问:
How can I stub the Properties.Settings object when the unit test is in a different assembly?
I have an object the references a bunch of Properties.Settings.Default... values and I need to stub these in the unit test for this object.

Unfortunately the type for the settings object is declared as internal and so I can't access it from the unit test project.

How can I stub up the return values for these properties? I'm using Rhino Mocks for mocking.

答:
I know this is an old question but I thought I would add in my solution as its simple and could help someone.

The settings class created is a partial class, we can leverage this to create our own implementation of Default.

Create a new file in the Properties folder

```<code>internal partial class Settings : ISettings
{
    private static ISettings _setInstance;

    internal static ISettings Get
    {
        get
        {
            return _setInstance = _setInstance  ?? Default;
        }
        set { _setInstance = value; }
    }
}
</code>```

Then when we use it elsewhere in the application we can call Settings.Get..
If you want to set the values from test, create a class that inherits from ISettings and set the new implementation.

If your tests are found in a separate project you will have to add another class to expose the setter to public.
We cant change the settings file to public as this would just be overwritten the next time we change or add a value.

Body:
I know this is an old question but I thought I would add in my solution as its simple and could help someone.

The settings class created is a partial class, we can leverage this to create our own implementation of Default.

Create a new file in the Properties folder

internal partial class Settings : ISettings
{
    private static ISettings _setInstance;

    internal static ISettings Get
    {
        get
        {
            return _setInstance = _setInstance  ?? Default;
        }
        set { _setInstance = value; }
    }
}

Then when we use it elsewhere in the application we can call Settings.Get..
If you want to set the values from test, create a class that inherits from ISettings and set the new implementation.

If your tests are found in a separate project you will have to add another class to expose the setter to public.
We cant change the settings file to public as this would just be overwritten the next time we change or add a value.


来源: stackexchange

问:
find count of element over multiple array
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?

my solution:
using dictionary:

```<code>from collections import defaultdict

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result
</code>```

My desired output would be:

```<code>['e', 'd', 'i', 'r']
</code>```

Can I get a better pythonic solution?

Thanks.

答:
You can use the collection's counter class to simplify the code:

```<code>from collections import Counter
...
d = Counter(L+K) #we are combining to process both at once
</code>```

Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array.

```<code>L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
print [k for k, v in Counter(L+K).iteritems() if v == 2]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given two list I need to make a third list which contains elements that occur only twice in over all list 1 and list 2.
How to do it efficienlty with reasonable time and space complexity ?

my solution:
using dictionary:

from collections import defaultdict

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']

d=defaultdict(int)

for i in L:
    d[i]+=1
for j in K:
    d[j]+=1

print d
result=[]
for key,val in d.iteritems():
  if val == 2:
     result.append(key)

print result

My desired output would be:

['e', 'd', 'i', 'r']

Can I get a better pythonic solution?

Thanks.

Body:
You can use the collection's counter class to simplify the code:

from collections import Counter
...
d = Counter(L+K) #we are combining to process both at once

Additionally, you can combine lines by doing a conditional for loop. So only if the value is 2, then we will append it to our array.

L=['a','b','c','d','a','d','e','e','g','h']
K=['a','g','i','g','g','i','r','r']
print [k for k, v in Counter(L+K).iteritems() if v == 2]


问:
why is the TcpSendingMessageHandler or TcpOuboundGateway expecting a reply?
The channel adapter is for one way communication.
But while using TcpSendingMessageHandler, the adapter is expecting a reply. and the following message is thrown same is the case with TcpOutboundGateway.

TcpNetConnection : Read Exception [Connection ID] Socket Exception : software caused connection abort: recv failed

Please help me to overcome this issue.

答:
The sending adapter is not expecting a reply; it is possible, however, that the application has collaborating channel adapters (a receiving adapter that uses the same connection).

Even if there is no listener, we have to read from the socket so we can log that an unexpected reply was received. If we don't read from the socket, the peer could end up blocking when the buffers fill up.

What problem is this causing you?

This is typically only logged at DEBUG or TRACE level.


问:
MS-Excel automatic increase number if text not same

As shown above picture i need put number on column B that automatic increase if text on column A not same so the the result would be

Can I do that with ms-excel?

答:
Put 1 on B1 and put below on B2 and drag down

```<code>=if(a2=a1, b1, b1+1)
</code>```

Body:
Put 1 on B1 and put below on B2 and drag down

=if(a2=a1, b1, b1+1)


问:
Presenting ViewController with TabBarController
Okay, so each time I try to present a ViewController (from the AppDelegate file's, "didFinishLaunchingWithOptions" function) using the following code, my tabBar with 4 items disappears, even though the ViewController I want is shown:

```<code>    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController? = tabBarController
</code>```

When I try the following code (also in the AppDelegate file's "didFinishLaunchingWithOptions" function), then I get nothing at all:

```<code>    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController?.tabBarController?.didMove(toParentViewController: tabBarController)
</code>```

I've tried several iterations of the two, but I still can't seem to get what I want...

Essentially, what I want is to programmatically press one of the buttons so that my third view controller becomes the first view the user sees in certain circumstances.

Any help would be greatly appreciated!

答:
It's unclear what exactly ThirdViewController is, but I'm guessing it's the view controller that's contained in the third tab of your tab controller.

The tab bar controller still needs to be the window's rootViewController.

If you just want to programmatically select a certain index of the tab bar controller, you can do something like this:

```<code>        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabVC = storyboard.instantiateViewController(withIdentifier: "tabVC") as! UITabBarController  // however you defined your UITabBarController.
        tabVC.selectedIndex = 2   // or whatever you want
        window?.rootViewController = tabVC
</code>```

And if the tab bar controller is already the root, then you could bypass the step where you instantiate it and set it to the root:

```<code>    if let tabVC = window?.rootViewController as? UITabBarController {
        tabVC.selectedIndex = 2
    }
</code>```

Body:
Okay, so each time I try to present a ViewController (from the AppDelegate file's, "didFinishLaunchingWithOptions" function) using the following code, my tabBar with 4 items disappears, even though the ViewController I want is shown:

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController? = tabBarController

When I try the following code (also in the AppDelegate file's "didFinishLaunchingWithOptions" function), then I get nothing at all:

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)

    let tabBarController = storyBoard.instantiateViewController(withIdentifier: "theEvents") as! ThirdViewController

    self.window?.rootViewController?.tabBarController?.didMove(toParentViewController: tabBarController)

I've tried several iterations of the two, but I still can't seem to get what I want...

Essentially, what I want is to programmatically press one of the buttons so that my third view controller becomes the first view the user sees in certain circumstances.

Any help would be greatly appreciated!

Body:
It's unclear what exactly ThirdViewController is, but I'm guessing it's the view controller that's contained in the third tab of your tab controller.

The tab bar controller still needs to be the window's rootViewController.

If you just want to programmatically select a certain index of the tab bar controller, you can do something like this:

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabVC = storyboard.instantiateViewController(withIdentifier: "tabVC") as! UITabBarController  // however you defined your UITabBarController.
        tabVC.selectedIndex = 2   // or whatever you want
        window?.rootViewController = tabVC

And if the tab bar controller is already the root, then you could bypass the step where you instantiate it and set it to the root:

    if let tabVC = window?.rootViewController as? UITabBarController {
        tabVC.selectedIndex = 2
    }


问:
AjaxToolkit Calendar Extender Programmatic change in value not reflected
There is a calendar image near to the text box for dropdown calendar. When I change the date value in text box by

$("#calendarTextBox").val("11/22/2004");

and then if user clicks on the image, the drop down calendar contains the old date value instead of the one set by the javascript.

Any clues will be helpful.

Calendar Demonstration for trying out.

答:
Got the solution.</p>

```<code>$find('<%CalenderExtenderContol.ClientID%>').set_selectedDate(new Date('11/22/2004'));
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Got the solution.

$find('<%CalenderExtenderContol.ClientID%>').set_selectedDate(new Date('11/22/2004'));


问:
Setting priority Firebase Messaging in Cloud Function for Firebase
I'm using Firebase Messaging to send notifications to users of my iPhone app. In order to not expose the app's messaging server key on the client side I'm using Cloud Function for Firebase to send the notifications to specific topics. Before this I did it from the client side on the app and was able to set the message's priority by making a JSON of this format:

```<code>// Swift code in iPhone app
let body: [String: Any] = ["to": "/topics/\(currentPet)",
                            "priority" : "high",
                            "notification" : [
                                "body" : "\(events[eventType]) for \(petsName.localizedCapitalized)",
                                "title" : "\(myName.localizedCapitalized) just logged an event",
                                "data" : ["personSent": myId]
                              ]
                           ]
</code>```

Now in my cloud function I'm trying to make a payload of the same general format, but keep running into the error:

Messaging payload contains an invalid "priority" property. Valid properties are "data" and "notification".

Here's my payload formatting and sending:

```<code>const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
        'sound': 'default',
        'data': userSent
      },
      'priority': 'high'
    };
admin.messaging().sendToTopic(pet_Id, payload);
</code>```

Does anybody know how I would accomplish setting the priority? Should I just manually do an HTTP POST instead of using admin.messaging().sendToTopic()?

答:
From the Firebase Cloud Messaging documentation on sending messages with the Admin SDK:

```<code>// Set the message as high priority and have it expire after 24 hours.
var options = {
  priority: "high",
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
admin.messaging().sendToDevice(registrationToken, payload, options)
  .then(function(response) {
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });
</code>```

The difference is that the priority (and ttl in the example) is passed as a separate options argument instead of in the payload.

Body:
I'm using Firebase Messaging to send notifications to users of my iPhone app. In order to not expose the app's messaging server key on the client side I'm using Cloud Function for Firebase to send the notifications to specific topics. Before this I did it from the client side on the app and was able to set the message's priority by making a JSON of this format:

// Swift code in iPhone app
let body: [String: Any] = ["to": "/topics/\(currentPet)",
                            "priority" : "high",
                            "notification" : [
                                "body" : "\(events[eventType]) for \(petsName.localizedCapitalized)",
                                "title" : "\(myName.localizedCapitalized) just logged an event",
                                "data" : ["personSent": myId]
                              ]
                           ]

Now in my cloud function I'm trying to make a payload of the same general format, but keep running into the error:

Messaging payload contains an invalid "priority" property. Valid properties are "data" and "notification".

Here's my payload formatting and sending:

const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
        'sound': 'default',
        'data': userSent
      },
      'priority': 'high'
    };
admin.messaging().sendToTopic(pet_Id, payload);

Does anybody know how I would accomplish setting the priority? Should I just manually do an HTTP POST instead of using admin.messaging().sendToTopic()?

Body:
From the Firebase Cloud Messaging documentation on sending messages with the Admin SDK:

// Set the message as high priority and have it expire after 24 hours.
var options = {
  priority: "high",
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
admin.messaging().sendToDevice(registrationToken, payload, options)
  .then(function(response) {
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The difference is that the priority (and ttl in the example) is passed as a separate options argument instead of in the payload.


问:
Populate Table using DreamFactory API & Javascript
I am trying to populate a products table with products that belong to only one restaurant, so far I managed to populate the restaurant table, but when I click on the restaurant it doesn't show the products that belong to that place. I am following the code provided in here: https://github.com/dreamfactorysoftware/javascript-sdk

So far I got to this, regarding the products table

route.js

```<code>            case 'restaurantes':
                setButton('left', template, 'index', 'redirect', null);

                $.api.getRecords('restaurante', null, getToken('token'), populateRestaurantesTable);
                break;

            case 'produto_show':
                setButton('left', template, 'restaurantes', 'redirect', null);
                setButton('right', template, 'restaurantes/' + pathArray[1] + '/edit', 'redirect', null);

                var params = 'filter=id%3D' + pathArray[1] + '&fields=nomeRestaurante';
                $.api.getRecords('produto', params, getToken('token'), populateProdutoShowName);

                break;
</code>```

script.js

```<code>    var tableProduto = $('#table_produto').DataTable({
    "paging":   false,
    "info":     false,
    "order": [
        [2, "asc" ],
        [3, "asc"],
        [1, "asc"]
    ],
    "columnDefs": [
        { "visible": false, "targets": 0 },
        { "visible": false, "targets": 2 },
        { "visible": false, "targets": 3 }
    ],

    "drawCallback": function () {
        var api = this.api();
        var rows = api.rows( {page:'current'} ).nodes();
        var last=null;

        api.column(2, {page:'current'} ).data().each( function ( produto, i ) {
            if ( last !== produto) {
                $(rows).eq( i ).before(
                    '<tr class="produto info"><td colspan="4">'+produto+'</td></tr>'
                );

                last = produto;
            }
        } );

        $("#table_produto thead").remove();
        $("#table_produto tfoot").remove();
    }
});

var populateProdutoShowName = function(data) {
    $('#produto_show_name').text(data[0].name);
};

var populateProdutoTable = function(data) {
    var produtos = [];

    $.each(data, function(idProduto, produto){
        produtos.push([
            produto.idProduto,
            produto.nomeProduto + ' ' + produto.precoProduto,
            produto.nomeProduto.charAt(0).toUpperCase(),
            produto.precoProduto
        ])
    });

    $('#table_produto').dataTable().fnClearTable();
    $('#table_produto').dataTable().fnAddData(produtos);
    $('#table_produto').dataTable().fnDraw();
};

$('#table_produto tbody').on( 'click', 'tr', function () {
    var produtoId = $('#table_produto').DataTable().row(this).data();

    if (produtoId !== undefined)
        $.route('produto/' + produtoId[0]);
});

$('#table_produto_search').keyup(function(){
    $('#table_produto').DataTable().search($(this).val(), false, true).draw() ;
});
</code>```

index.html

```<code>   <div id="template_produto_show">
            <nav class="navbar navbar-fixed-top df-nav cen col-md-12" role="navigation" style="">
                <ul class="nav navbar-nav" style="width: 100%">
                    <li class="pull-left"><button type="button" id="produto_menu_left" class="btn btn-default btn-menu">Voltar</button></li>
                    <li class="pull-left"><button type="button" id="produto_menu_logout" class="btn btn-default btn-menu-logout">Sair</button></li>
                    <li style="float: none; display: inline-block; position: relative; text-align: center"><a href="#index"><img src="Leanline1503-Leanline1503/img/icone.png" height="25"></a></li>
                </ul>
            </nav>
            <div class="row vert-offset-top-30"></div>
            <div class="col-md-2"></div>
            <div class="col-md-8">

                <div style="text-align: center"><h2><span id="produto_show_name"></span></h2></div>
                <div class="input-group">
                    <div class="input-group-addon">
                        <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                    </div>
                    <input type="text" id="table_produto_search" class="form-control" placeholder="Procurar produtos">
                </div>
                <table class="table table-hover" id="table_produto">
                    <thead>
                    <tr>
                        <th></th>
                        <th></th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
            </div>
            <div class="col-md-2"></div>
        </div>
</code>```

The analogy I am making here is that the Groups are my "Restaurantes" and "Group_Show" is to show the Contacts inside the group, which for me is to show the "Produtos" inside the group.
I don't know if that's all the information one would need to help me, but please let me know if you need more info. Thank you everyone for the time and help!

答:
So I changed the route.js, now it is</p>

```<code>case 'produto_show':
            setButton('left', template, 'restaurantes', 'redirect', null);
            setButton('right', template, 'restaurantes/' + pathArray[1] + '/edit', 'redirect', null);

            var params = 'filter=restaurante_id_restaurante%3D' + pathArray[1] + '&fields=nomeProduto';
            $.api.getRecords('produto', params, getToken('token'), populateProdutoShowName);

            break;
</code>```

Body:
I am trying to populate a products table with products that belong to only one restaurant, so far I managed to populate the restaurant table, but when I click on the restaurant it doesn't show the products that belong to that place. I am following the code provided in here: https://github.com/dreamfactorysoftware/javascript-sdk

So far I got to this, regarding the products table

route.js

            case 'restaurantes':
                setButton('left', template, 'index', 'redirect', null);

                $.api.getRecords('restaurante', null, getToken('token'), populateRestaurantesTable);
                break;

            case 'produto_show':
                setButton('left', template, 'restaurantes', 'redirect', null);
                setButton('right', template, 'restaurantes/' + pathArray[1] + '/edit', 'redirect', null);

                var params = 'filter=id%3D' + pathArray[1] + '&fields=nomeRestaurante';
                $.api.getRecords('produto', params, getToken('token'), populateProdutoShowName);

                break;

script.js

    var tableProduto = $('#table_produto').DataTable({
    "paging":   false,
    "info":     false,
    "order": [
        [2, "asc" ],
        [3, "asc"],
        [1, "asc"]
    ],
    "columnDefs": [
        { "visible": false, "targets": 0 },
        { "visible": false, "targets": 2 },
        { "visible": false, "targets": 3 }
    ],

    "drawCallback": function () {
        var api = this.api();
        var rows = api.rows( {page:'current'} ).nodes();
        var last=null;

        api.column(2, {page:'current'} ).data().each( function ( produto, i ) {
            if ( last !== produto) {
                $(rows).eq( i ).before(
                    '
'+produto+'
'
                );

                last = produto;
            }
        } );

        $("#table_produto thead").remove();
        $("#table_produto tfoot").remove();
    }
});

var populateProdutoShowName = function(data) {
    $('#produto_show_name').text(data[0].name);
};

var populateProdutoTable = function(data) {
    var produtos = [];

    $.each(data, function(idProduto, produto){
        produtos.push([
            produto.idProduto,
            produto.nomeProduto + ' ' + produto.precoProduto,
            produto.nomeProduto.charAt(0).toUpperCase(),
            produto.precoProduto
        ])
    });

    $('#table_produto').dataTable().fnClearTable();
    $('#table_produto').dataTable().fnAddData(produtos);
    $('#table_produto').dataTable().fnDraw();
};

$('#table_produto tbody').on( 'click', 'tr', function () {
    var produtoId = $('#table_produto').DataTable().row(this).data();

    if (produtoId !== undefined)
        $.route('produto/' + produtoId[0]);
});

$('#table_produto_search').keyup(function(){
    $('#table_produto').DataTable().search($(this).val(), false, true).draw() ;
});

index.html

<button type="button" id="produto_menu_left" class="btn btn-default btn-menu">Voltar</button>

<button type="button" id="produto_menu_logout" class="btn btn-default btn-menu-logout">Sair</button>

                    <input type="text" id="table_produto_search" class="form-control" placeholder="Procurar produtos">

The analogy I am making here is that the Groups are my "Restaurantes" and "Group_Show" is to show the Contacts inside the group, which for me is to show the "Produtos" inside the group.
I don't know if that's all the information one would need to help me, but please let me know if you need more info. Thank you everyone for the time and help!

Body:
So I changed the route.js, now it is

case 'produto_show':
            setButton('left', template, 'restaurantes', 'redirect', null);
            setButton('right', template, 'restaurantes/' + pathArray[1] + '/edit', 'redirect', null);

            var params = 'filter=restaurante_id_restaurante%3D' + pathArray[1] + '&fields=nomeProduto';
            $.api.getRecords('produto', params, getToken('token'), populateProdutoShowName);

            break;


问:
Bootstrap button sizing and alignment
This is what I have so far http://www.bootply.com/SDIQQr0dZJ or    https://jsfiddle.net/sjgz57b8/

```<code><div class="panel panel-default">
 <div class="panel-heading">
           <strong>myusername</strong>
    <div class="btn-group btn-group-sm pull-right">
       <button type="button" class="btn btn-danger">Dislike</button>
       <button type="button" class="btn btn-success">Like</button>
    </div>
 </div>
     <div class="panel-body">
              Panel content
     </div>
 </div>
</code>```

I'm trying to make the buttons fit within that space and centered vertically, but I already added the btn-group-sm class so I'm not sure what else I can do. I'm also trying to make the dislike button the same width as the like button. Thanks for any help

答:
Just add your custom css. By adding additional padding you can make the buttons of same width. if you add a negative margin-top the buttons will align vertically.

Working snippet

#like {
  padding-left:16px;
  padding-right:16px;
}
#btn-vc
{
  margin-top: -5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
      <div class="panel-heading">
          <strong>myusername</strong>
        <div id="btn-vc" class="btn-group btn-group-sm pull-right">
                 <button type="button" class="btn btn-danger">Dislike</button>
                 <button id="like" type="button" class="btn btn-success">Like</button>
          </div>
      </div>
      <div class="panel-body">
         Panel content
      </div>
</div></code>```

Hope this helps!

Title: Bootstrap button sizing and alignment

Body:
This is what I have so far http://www.bootply.com/SDIQQr0dZJ or    https://jsfiddle.net/sjgz57b8/

           myusername

       <button type="button" class="btn btn-danger">Dislike</button>
       <button type="button" class="btn btn-success">Like</button>

              Panel content

I'm trying to make the buttons fit within that space and centered vertically, but I already added the btn-group-sm class so I'm not sure what else I can do. I'm also trying to make the dislike button the same width as the like button. Thanks for any help

Body:
Just add your custom css. By adding additional padding you can make the buttons of same width. if you add a negative margin-top the buttons will align vertically.

Working snippet

#like {
  padding-left:16px;
  padding-right:16px;
}
#btn-vc
{
  margin-top: -5px;
}

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="panel panel-default">
      <div class="panel-heading">
          <strong>myusername</strong>
        <div id="btn-vc" class="btn-group btn-group-sm pull-right">
                 <button type="button" class="btn btn-danger">Dislike</button>
                 <button id="like" type="button" class="btn btn-success">Like</button>
          </div>
      </div>
      <div class="panel-body">
         Panel content
      </div>
</div>

Hope this helps!


问:
How do I set the namespace URI in c#?
Im using a namespace in my xml (I need to use this for xsd validation purposes). Because of this my xpath is no longer working.

I have the code:

```<code>XmlDocument doc = new XmlDocument();
doc.Load(newXmlFilePath);
</code>```

And the XML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>
</code>```

But my xpath doesnt select the node. I tried to set the namespace using:

```<code>doc.NamespaceUR = "x";
</code>```

However its a get only accessor. Any ideas?

答:
Based on your other recent questions, I think you're trying to deal with a mixture of documents where some are in a particular namespace and some are not - so you're looking to be namespace-agnostic, right?

There are a couple of things you could do. You could use a hack to strip out the namespace - but that has always struck me as a bit fragile. There are other ways to express what is semantically the same document - e.g. the whole thing could use a namespace prefix on every single element - and that trick won't work.

Or you could write namespace-agnostic XPath queries. E.g. "/*[local-name()='video']/*[local-name()='subject']"

Title: How do I set the namespace URI in c#?

Body:
Im using a namespace in my xml (I need to use this for xsd validation purposes). Because of this my xpath is no longer working.

I have the code:

XmlDocument doc = new XmlDocument();
doc.Load(newXmlFilePath);

And the XML:

<?xml version="1.0" encoding="UTF-8"?>
<video xmlns="UploadXSD">
  <title>
    A vid with Pete
  </title>
  <description>
  Petes vid
  </description>
  <contributor>
    Pete
  </contributor>
  <subject>
    Cat 2
  </subject>
</video>

But my xpath doesnt select the node. I tried to set the namespace using:

doc.NamespaceUR = "x";

However its a get only accessor. Any ideas?


问:
My code should connect to http stream and rstp stream, but It isn't. any ideas?
So I am wondering why I can connect to this radio stream (http://51.255.127.128:8016/stream) but I cannot seem to connect to a VLC rtsp or rtp stream. I was under the impression that I could simply connect to rtp://hostaddress:port# but it seems that I can't get a connection. Is there any way I can avoid using the rtp classes and just do it directly using the method shown below? </p>

```<code>import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.Button;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

   Button button_stop;
   Button button_play;
   Uri stream_data= Uri.parse("http://51.255.127.128:8016/stream");
   //works for rtsp and http
   //private String STREAM_URL ="http://51.255.127.128:8016/stream";
   private MediaPlayer mPlayer;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       button_stop=(Button) findViewById(R.id.Stop_b);
       button_play=(Button) findViewById(R.id.Play_b);

       mPlayer=new MediaPlayer();

       button_play.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v){

               try{

                   mPlayer.reset();
                   mPlayer.setDataSource(MainActivity.this,stream_data);
                   mPlayer.prepare();
                   mPlayer.start();
                ;

              } catch (IOException e){
                  e.printStackTrace();

              }

           }

       });

     button_stop.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v){

               mPlayer.stop();

           }

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

答:
Use prepareAsync.</p>

```<code>    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
    mPlayer.prepareAsync();
</code>```

Body:
So I am wondering why I can connect to this radio stream (http://51.255.127.128:8016/stream) but I cannot seem to connect to a VLC rtsp or rtp stream. I was under the impression that I could simply connect to rtp://hostaddress:port# but it seems that I can't get a connection. Is there any way I can avoid using the rtp classes and just do it directly using the method shown below?

import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.Button;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

   Button button_stop;
   Button button_play;
   Uri stream_data= Uri.parse("http://51.255.127.128:8016/stream");
   //works for rtsp and http
   //private String STREAM_URL ="http://51.255.127.128:8016/stream";
   private MediaPlayer mPlayer;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       button_stop=(Button) findViewById(R.id.Stop_b);
       button_play=(Button) findViewById(R.id.Play_b);

       mPlayer=new MediaPlayer();

       button_play.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v){

               try{

                   mPlayer.reset();
                   mPlayer.setDataSource(MainActivity.this,stream_data);
                   mPlayer.prepare();
                   mPlayer.start();
                ;

              } catch (IOException e){
                  e.printStackTrace();

              }

           }

       });

     button_stop.setOnClickListener(new View.OnClickListener(){
           @Override
           public void onClick(View v){

               mPlayer.stop();

           }

       });
   }
}

Body:
Use prepareAsync.

    mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
    mPlayer.prepareAsync();


问:
Visual Studio core features fatal error during installation visual studio 2013 ultimate on windows 7
I have uninstalled VS 2012 all components and tried to install VS 2013.I have downloaded ISO file fully.I have turned off Firewall,Antivirus and started VS installation as admin.
Still I am getting this error.
VS installer snap of error

I have seen the log file but could not find how to fix it.
Any Sugestion?

答: Already tried it after installing .Net Entity Framework 4.5</p>


问:
how to write a single sql query based on combobox selection?
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

```<code>if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}
</code>```

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

答:
You can use the shorthand if only if you have two conditions:

```<code> string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);
</code>```

Hope it helps!

Body:
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

Body:
You can use the shorthand if only if you have two conditions:

 string query = string.Format("Select * from country{0}", string.IsNullOrEmpty(combobox1.text) ? "" : " where city_name = " + combobox1.text);

Hope it helps!


问:
Error trying to find most recent file and copy it
I'm getting "Object required" runtime error when trying to run the following code. I am trying to find the most recent file saved in a folder and copy/rename it to another file name. My issue is the If statement to "Check for most recent file in folder" is returning Object errors.

I have followed other suggestions on here, but I can't seem to get over the Object error hurdles. If anyone can provide help for this newbie, I would appreciate it.

```<code>Option Explicit
Dim FSO, FSO2, FLD, FIL
Dim strFolder, strContent, strPath, tmpName, tmpName2, mostRecent, newfile

strFolder = "C:\Users\username\Documents\Mockup"

'Create the filesystem object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO2 = CreateObject("Scripting.FileSystemObject")

'loop through the folder and get the files
For Each FLD in FSO.GetFolder(strFolder).SubFolders
    'Reset mostRecent to nothing
    Set mostRecent = Nothing
    Set mostRecent = CreateObject("Scripting.FileSystemObject")

    For Each Fil In FLD.Files
        If Fil = FLD & "\import.ARCHIVE" Then
            FSO2.DeleteFile FLD & "\import.ARCHIVE"
            Fil = FLD & "\import.tra"
        End If

        If Fil = FLD & "\import.tra" Then
            tmpName = Replace(Fil, "import.tra", "import.ARCHIVE")'Replace(String, thisString, toThisString)
            'Name Fil as tmpName
            FSO.MoveFile Fil, tmpName
        End If

        'Check for most recent file in folder
        If mostRecent Is Nothing Then
            Set mostRecent = Fil
        ElseIf Fil.DateCreated > mostRecent.DateCreated Then
            Set mostRecent = Fil
        End If

        tmpName2 = Replace(mostRecent, "*.*", "import.tra")'Replace(String, thisString, toThisString)
        FSO2.CopyFile mostRecent, tmpName2
    Next
Next

'Clean up
Set FLD = Nothing
Set FSO = Nothing
Set FSO2 = Nothing
Set mostRecent = Nothing
</code>```

答:
just mask Set mostRecent = CreateObject("Scripting.FileSystemObject") will do.

We don't need a File System Object to get the date created for a file. I think you just mean to create an object. In vbscript, since you already 'dim mostRecent', when using Set, it will automatically assigned to an object.

Hope this will help you :)

Body:
I'm getting "Object required" runtime error when trying to run the following code. I am trying to find the most recent file saved in a folder and copy/rename it to another file name. My issue is the If statement to "Check for most recent file in folder" is returning Object errors.

I have followed other suggestions on here, but I can't seem to get over the Object error hurdles. If anyone can provide help for this newbie, I would appreciate it.

Option Explicit
Dim FSO, FSO2, FLD, FIL
Dim strFolder, strContent, strPath, tmpName, tmpName2, mostRecent, newfile

strFolder = "C:\Users\username\Documents\Mockup"

'Create the filesystem object
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FSO2 = CreateObject("Scripting.FileSystemObject")

'loop through the folder and get the files
For Each FLD in FSO.GetFolder(strFolder).SubFolders
    'Reset mostRecent to nothing
    Set mostRecent = Nothing
    Set mostRecent = CreateObject("Scripting.FileSystemObject")

    For Each Fil In FLD.Files
        If Fil = FLD & "\import.ARCHIVE" Then
            FSO2.DeleteFile FLD & "\import.ARCHIVE"
            Fil = FLD & "\import.tra"
        End If

        If Fil = FLD & "\import.tra" Then
            tmpName = Replace(Fil, "import.tra", "import.ARCHIVE")'Replace(String, thisString, toThisString)
            'Name Fil as tmpName
            FSO.MoveFile Fil, tmpName
        End If

        'Check for most recent file in folder
        If mostRecent Is Nothing Then
            Set mostRecent = Fil
        ElseIf Fil.DateCreated > mostRecent.DateCreated Then
            Set mostRecent = Fil
        End If

        tmpName2 = Replace(mostRecent, "*.*", "import.tra")'Replace(String, thisString, toThisString)
        FSO2.CopyFile mostRecent, tmpName2
    Next
Next

'Clean up
Set FLD = Nothing
Set FSO = Nothing
Set FSO2 = Nothing
Set mostRecent = Nothing


问:
how to convert combination string to array like this?
I have already tried this problem, I have small question this below is my input:

```<code>AA-1001AB-1002
</code>```

my question this combination string with number, word and symbol on above, and convert to array or json:

```<code>["AA-1001","AB-1002"]
</code>```

thanks for help :)

答:
```<code><?php
$input = "AA-1001AB-1002";
$arr = str_split($input, 7);
print_r($arr);
</code>```

If you need JSON array, as possibly(?) indicated in your question:

```<code>$jarr = json_encode($arr);
echo $jarr;
</code>```

Body:
I have already tried this problem, I have small question this below is my input:

AA-1001AB-1002

my question this combination string with number, word and symbol on above, and convert to array or json:

["AA-1001","AB-1002"]

thanks for help :)

Body:
<?php
$input = "AA-1001AB-1002";
$arr = str_split($input, 7);
print_r($arr);

If you need JSON array, as possibly(?) indicated in your question:

$jarr = json_encode($arr);
echo $jarr;


问:
How would I direct all traffic that hasn't logged in to django allauth login
Want to direct all un-logged in traffic to the login page. How would I go about doing this? I don't want visitors to be able to see the site at all if they are not logged in. As well, the allauth signup page should not be able to be accessed either. Users will be pre-registered for the site. I'm fairly new to django and would not want to abandon allauth as I have it working.</p>

答:
You could also use something like this in your views.py</p>

```<code>from django.http import HttpResponseRedirect

 def index(request):
   if request.user.is_authenticated():
       return HttpResponseRedirect('/home/')
   else:
       return HttpResponseRedirect('/login/')
</code>```

Body:
You could also use something like this in your views.py

from django.http import HttpResponseRedirect

 def index(request):
   if request.user.is_authenticated():
       return HttpResponseRedirect('/home/')
   else:
       return HttpResponseRedirect('/login/')


问:
When are nested functions generally appropriate in JavaScript?
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

```<code>var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();
</code>```

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

```<code>function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}
</code>```

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

答:
One case when you might return a function like that is when creating multiple similar event listeners. For example, suppose you have buttons named button1, button2, and button3. You can add click listeners like this (using JQuery for brevity):

```<code>button1.click(() => console.log(1));
button2.click(() => console.log(5));
button1.click(() => console.log(42));
</code>```

This can be written instead as:

```<code>function makeLogger(x) {
    return () => console.log(x);
}

button1.click(makeLogger(1));
button2.click(makeLogger(5));
button1.click(makeLogger(42));
</code>```

This makes an even bigger difference if you can't use the arrow function for compatibility reasons (not using Babel).

Body:
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

Body:
One case when you might return a function like that is when creating multiple similar event listeners. For example, suppose you have buttons named button1, button2, and button3. You can add click listeners like this (using JQuery for brevity):

button1.click(() => console.log(1));
button2.click(() => console.log(5));
button1.click(() => console.log(42));

This can be written instead as:

function makeLogger(x) {
    return () => console.log(x);
}

button1.click(makeLogger(1));
button2.click(makeLogger(5));
button1.click(makeLogger(42));

This makes an even bigger difference if you can't use the arrow function for compatibility reasons (not using Babel).


问:
How to store text as paragraphs in SQLite database in a iPhone app?
In my iPhone app, I have a requirement to store a huge amount of text. I have paragraphs of text to be stored in my database along with the newline characters.

What should I do to store the text as paragraphs in SQLite database?

For example, I want to store paragraphs like the ones below in:

(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.

The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.'

Basically I want to save the paragraphs in database in the same format with carriage returns.

答:
i would use HTML to represent my paragraphs (i.e)

Saving the Text

```<code> <div>
 <p>(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true    like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.</p>
 <p>The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.</p>
</div>
</code>```

Loading the Paragraphs

I would load them inside a UIWebView as html, you can save the HTML into a file in the app sandbox let's say Paragraph1.HTML load it as the following:

```<code>// this is a user defined method
 -(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
    NSURL *url = [NSURL fileURLWithPath:sFilePath];// Path of the HTML File
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   [web loadRequest:request];
}
</code>```

dispose the File after loading it, this will save you much time and space.
Good luck.

ContentLicense: CC BY-SA 4.0

Body:
i would use HTML to represent my paragraphs (i.e)

Saving the Text

 <div>
 <p>(the mother of the faithful believers) The commencement of the Divine Inspiration to Allah's Apostle was in the form of good dreams which came true    like bright day light, and then the love of seclusion was bestowed upon him. He used to go in seclusion in the cave of Hira where he used to worship (Allah alone) continuously for many days before his desire to see his family. He used to take with him the journey food for the stay and then come back to (his wife) Khadija to take his food like-wise again till suddenly the Truth descended upon him while he was in the cave of Hira. The angel came to him and asked him to read. The Prophet replied, "I do not know how to read.</p>
 <p>The Prophet added, "The angel caught me (forcefully) and pressed me so hard that I could not bear it any more. He then released me and again asked me to read and I replied, 'I do not know how to read.</p>
</div>

Loading the Paragraphs

I would load them inside a UIWebView as html, you can save the HTML into a file in the app sandbox let's say Paragraph1.HTML load it as the following:

// this is a user defined method
 -(void)loadDocument:(NSString*)documentName inView:(UIWebView*)webView
{
    NSURL *url = [NSURL fileURLWithPath:sFilePath];// Path of the HTML File
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
   [web loadRequest:request];
}

dispose the File after loading it, this will save you much time and space.
Good luck.


问:
Why doesn't height automatically adjust to the width?
In CSS, if you set a width of 60%, the height will proportionally adjust. In React Native, that is not the case. If you set the width of an image to be '60%', and don't set the height, the height will be 0 and not show. How do I get the height to do the same as CSS?

```<code>thumbnail: {
    width: '60%',
    minHeight: 10,
}
</code>```

I tried setting a minHeight, and that makes it go to 10px. I want the height to change based on the image proportions. I looked at flex, but I don't think that's what I want.

答: I think you want to set the resizeMode to contain. It could be cover, it looks like there's currently a mistake in the docs... https://facebook.github.io/react-native/docs/image.html

Body:
In CSS, if you set a width of 60%, the height will proportionally adjust. In React Native, that is not the case. If you set the width of an image to be '60%', and don't set the height, the height will be 0 and not show. How do I get the height to do the same as CSS?

thumbnail: {
    width: '60%',
    minHeight: 10,
}

I tried setting a minHeight, and that makes it go to 10px. I want the height to change based on the image proportions. I looked at flex, but I don't think that's what I want.


问:
How to eliminate code repetition?
How can I reduce code repetition in the following snippet:

```<code>  if(motionIOS == 0)
  {
    if(character == 40)
    {
      previousMotion = character;
    }
      if(previousMotion == 40 && character == 50)
      {
        motionIOSValue = 50;
      }
    else
    {
    previousMotion = character;
    }
  }

  if(motionIOS == 1)
  {
    if(character == 60)
    {
      previousMotion = character;
    }
      if(previousMotion == 60 && character == 70)
      {
        motionIOSValue = 70;
      }
    else
    {
    previousMotion = character;
    }
  }
</code>```

In essence I am doing the same code twice, but with the values changes for some things. I will even need to use this code many more times too with variable numbers.

I think I should refactor it into a function, but do not know how.

答:
you can consolidate your condition checks.

```<code>if(motionIOS == 0 && previousMotion == 40 && character == 50) {
    motionIOSValue = 50;
} else if (motionIOS == 1 && previousMotion == 60 && character == 70){
    motionIOSValue = 70;
} else {
    previousMotion = character;
}
</code>```

You can extract the condition check to another class if you want.

```<code>bool updateIosValue(int previousMotion, int character, int testMotion, int testCharacter){
    //do your custom checks here.
    return previousMotion==testMotion && character== testCharacter;
}

if(motionIOS==0 && updateIosValue(previousMotion, character, 40, 50){
    motionIOSValue = 50;
}else if(motionIOS==1 && updateIosValue(previousMotion, character, 60, 70){
    motionIOSValue = 70;
}else{
    previousMotion = character;
}
</code>```

Title: How to eliminate code repetition?

Body:
How can I reduce code repetition in the following snippet:

  if(motionIOS == 0)
  {
    if(character == 40)
    {
      previousMotion = character;
    }
      if(previousMotion == 40 && character == 50)
      {
        motionIOSValue = 50;
      }
    else
    {
    previousMotion = character;
    }
  }

  if(motionIOS == 1)
  {
    if(character == 60)
    {
      previousMotion = character;
    }
      if(previousMotion == 60 && character == 70)
      {
        motionIOSValue = 70;
      }
    else
    {
    previousMotion = character;
    }
  }

In essence I am doing the same code twice, but with the values changes for some things. I will even need to use this code many more times too with variable numbers.

I think I should refactor it into a function, but do not know how.

Body:
you can consolidate your condition checks.

if(motionIOS == 0 && previousMotion == 40 && character == 50) {
    motionIOSValue = 50;
} else if (motionIOS == 1 && previousMotion == 60 && character == 70){
    motionIOSValue = 70;
} else {
    previousMotion = character;
}

You can extract the condition check to another class if you want.

bool updateIosValue(int previousMotion, int character, int testMotion, int testCharacter){
    //do your custom checks here.
    return previousMotion==testMotion && character== testCharacter;
}

if(motionIOS==0 && updateIosValue(previousMotion, character, 40, 50){
    motionIOSValue = 50;
}else if(motionIOS==1 && updateIosValue(previousMotion, character, 60, 70){
    motionIOSValue = 70;
}else{
    previousMotion = character;
}


问:
Calculate time difference in python
The datetime table field defined in postgresql:
 Column("created_on",DateTime(timezone=True),default=datetime.datetime.utcnow),

In python code, I have converted current time to aware-time as:

```<code>mcurr_time = datetime.datetime.now().replace(tzinfo=pytz.UTC)
</code>```

I get curr time as:

2017-03-30 21:44:51.394387+00:00

When I retrieve the time from the table using sqlalchemy I get:

mcreation_time = 2017-03-30 15:05:01.350078+05:30

How to find difference between the 2 or what conversion has to be used
to compare the difference with hours? All the tables have timezone
aware datetime. I need the exact code as I checked all examples and am confused.

The difference in the 2 dates is valid without any conversion. The result has to be compared with example 2 hours(variable var1) and based on the output, certain actions need to be taken.  This 2 hours I have converted as:

```<code>mcalc = datetime.timedelta(seconds=var1*60*60)
</code>```

So what I wish to do is,

```<code>diff_tm = (mcurr_time - mcreations_time)

if diff_tm > mcalc:
    do_some1()
else:
    do_some2()
</code>```

I do not know if any conversion is required in any of the dates, preferably the current time as all my tables are defined as mentioned above.
The time difference in the 2 dates should be correct from any client i.e from any place in the world

答:
Resolved it by removing timezone offset and using in calculation:</p>

```<code>mcurr_time = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
mcurr_time = mcurr_time.replace(
          tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))

mcreation_time = mcreation_time.replace(
          tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))
</code>```

Title: Calculate time difference in python

Body:
The datetime table field defined in postgresql:
 Column("created_on",DateTime(timezone=True),default=datetime.datetime.utcnow),

In python code, I have converted current time to aware-time as:

mcurr_time = datetime.datetime.now().replace(tzinfo=pytz.UTC)

I get curr time as:

2017-03-30 21:44:51.394387+00:00

When I retrieve the time from the table using sqlalchemy I get:

mcreation_time = 2017-03-30 15:05:01.350078+05:30

How to find difference between the 2 or what conversion has to be used
to compare the difference with hours? All the tables have timezone
aware datetime. I need the exact code as I checked all examples and am confused.

The difference in the 2 dates is valid without any conversion. The result has to be compared with example 2 hours(variable var1) and based on the output, certain actions need to be taken.  This 2 hours I have converted as:

mcalc = datetime.timedelta(seconds=var1*60*60)

So what I wish to do is,

diff_tm = (mcurr_time - mcreations_time)

if diff_tm > mcalc:
    do_some1()
else:
    do_some2()

I do not know if any conversion is required in any of the dates, preferably the current time as all my tables are defined as mentioned above.
The time difference in the 2 dates should be correct from any client i.e from any place in the world

Body:
Resolved it by removing timezone offset and using in calculation:

mcurr_time = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
mcurr_time = mcurr_time.replace(
          tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))

mcreation_time = mcreation_time.replace(
          tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))


答:
You can substr them and put two string into array:

```<code>$str = "AA-1001AB-1002";
$result = [ substr($str, 0, 7), substr($str, 7, 7) ];
var_dump($result);
</code>```

Hope this help you!

Title: how to convert combination string to array like this?

Body:
You can substr them and put two string into array:

$str = "AA-1001AB-1002";
$result = [ substr($str, 0, 7), substr($str, 7, 7) ];
var_dump($result);

Hope this help you!


问:
How to convert Binary Srtring into an integer array in java?
I am reading a file as byte and converting them into binary string using

```<code>String.format("%8s", Integer.toBinaryString(resultByteArray[i] & 0xFF)).replace(' ', '0')
</code>```

After that, using StringBuilder I have combined all strings into one string. Now I want to convert this string into an array like [1,0,1,0....].

Is there any way to do so?

答:
Since you've already compiled it into one big String, you can immediately convert it to a char array. There's a method called .toCharArray() that you can use to return a char array.

Here's an example of this:
http://www.javatpoint.com/java-string-tochararray

Additionally, if you want to convert it to a different type of array, you could iterate through and add it to an array that has the same size as the char array.

Best of luck!

Body:
I am reading a file as byte and converting them into binary string using

String.format("%8s", Integer.toBinaryString(resultByteArray[i] & 0xFF)).replace(' ', '0')

After that, using StringBuilder I have combined all strings into one string. Now I want to convert this string into an array like [1,0,1,0....].

Is there any way to do so?


问:
Importing PHP code in Joomla Component development
Can't figure out how to import php files into my joomla component- all of these fail:

require_once('code.php');

require_once(dirname(FILE).DS.'code.php');

require_once(JPATH_COMPONENT.DS.'code.php' );

Any ideas?  thanks

答:
Try jimport, see Joomla's docs on this: http://docs.joomla.org/Jimport

```<code>jimport('joomla.application.component.controller');
</code>```

This will include the php file "/libraries/joomla/application/component/controller.php".

Body:
Try jimport, see Joomla's docs on this: http://docs.joomla.org/Jimport

jimport('joomla.application.component.controller');

This will include the php file "/libraries/joomla/application/component/controller.php".


问:
SpringBoot @WebMvcTest, autowiring RestTemplateBuilder
I've got a problem while testing a Spring Controller.
I'm using the annotation @WebMvcTest in my test class.
When I run the test, I get this error:
No qualifying bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' available

I'm using RestTemplate for other classes in my project so I've defined a bean in my main class:

```<code>@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}
</code>```

To make it work, I have to define my restTemplate bean this way:

```<code>@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}
</code>```

Is it a problem with the annotation @WebMvcTest or did I miss something?

Thanks

答:
Yes, this does feel like a bug.

However you can solve it easily by adding @AutoConfigureWebClient to your test class along with the existing @WebMvcTest

Body:
I've got a problem while testing a Spring Controller.
I'm using the annotation @WebMvcTest in my test class.
When I run the test, I get this error:
No qualifying bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' available

I'm using RestTemplate for other classes in my project so I've defined a bean in my main class:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

To make it work, I have to define my restTemplate bean this way:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Is it a problem with the annotation @WebMvcTest or did I miss something?

Thanks


问:
XPath pulling more than one match

The (BaseX) error

I am running queries on a large dataset in BaseX, but one XQuery is crashing my programme with an error [XPTY0004] Item expected, sequence found: (attribute begin {"6"}, ...)..

In my query I am trying to make sure that one element comes before another by comparing begin - an attribute that is present in XML - with number(). But whenever I try the most basic of XQueries (return matching nodes) on my dataset (e.g. with this online tool) I get an error that resembles the one that I had before:

[Error] SaxonCE.XSLT20Processor 14:08:39.692 SEVERE: XPathException in
  invokeTransform: A sequence of more than one item is not allowed as
  the first argument of number() ("6", "10")

So I am guessing there is something going on with the node's siblings, i.e. that there are more than one of these nodes, and that it's unclear which should be compared. Examples follow below.

Why does the order matter?

The XPath is used in a query engine for treebanks: linguistically annotated corpora. In some cases we want nodes to match in order, and sometimes it does not matter. As a simplistic example: sometimes we want to match something as specific as the concerned man where the order article, adjective, noun matters. In other queries it doesn't matter, and we want to match phrases such as the time available as well, where the order of article, adjective, noun can be in any order.

In other words, in the first case the order of the elements should be respected, in the second one it shouldn't. Here is a possible XPath representation of such a construction that holds an article, an adjective, and a noun.

```<code>node[@cat="np" and node[@pt="art"] and node[@pt="adj"] and node[@pt="n"]]
</code>```

By default, XPath does not care about the order of these elements and does a greedy search, i.e. it will also match items such as the time available (art, n, adj). But I want to re-write the above XPath to make sure that the order of the nodes is respected, and so a construction such as the time available (art, n, adj) is not matched by the concerned man (art, adj, n) is.

```<code># Possible representation of *the time available*
<node id="0" begin="1" cat="np">
    <node id="1" begin="1" pt="art" text="the" />
    <node id="2" begin="2" pt="n" text="time" />
    <node id="3" begin="3" pt="adj" text="available" />
</node>

# Possible representation of *the concerned man*
<node id="0" begin="1" cat="np">
    <node id="1" begin="1" pt="art" text="the" />
    <node id="2" begin="2" pt="adj" text="concerned" />
    <node id="3" begin="3" pt="n" text="man" />
</node>
</code>```

One way to go about is to use a numeric comparison of the begin attribute that is available in the corpus. It is numerical ascending, so if we want to ensure the order of XPath is intact, we can say that the numeric value of each child node of @cat="np" should be less than the next by using number(). But as I showed above, this leads to an error - an error that would not occur in the simple example code that I just showed.

Another example.

```<code><node id="0" begin="2">
    <node id="1" begin="2">
        <node id="2" begin="2"/>
        <node id="3" begin="3"/>
    </node>
    <node id="4" begin="5">
        <node id="5" begin="5"/>
    </node>
    <node id="6" begin="6"/>
</node>
</code>```

This XPath should match:

```<code>/node/node[number(@begin) < number(../node/@begin)]
</code>```

But when put through an XQuery processor you'd get the error described above. A sequence of more than one item is not allowed as the first argument of number() ("2", "5", ...).

I tried the solution provided by @Michael Kay but the same issue seems to play.

XQuery

```<code>for $node in node[every $n in node[position() lt last()] satisfies (number($n/@begin) lt number($n/following-sibling::node/@begin))]
return $node
</code>```

Data

```<code><node id="0" begin="2">
    <node id="1" begin="2">
        <node id="2" begin="2"/>
        <node id="3" begin="3"/>
    </node>
    <node id="4" begin="5">
        <node id="5" begin="5"/>
    </node>
    <node id="6" begin="6"/>
</node>
</code>```

Error

SaxonCE.XSLT20Processor 14:48:49.809 SEVERE: XPathException in
  invokeTransform: A sequence of more than one item is not allowed as
  the first argument of number() ("5", "6")

Update April 19th, 2017

I bumped into some unexpected behaviour today, which makes the solution provided by @har07 not sufficient any more. I had wrongly assumed that the not() clause had only an effect on the nodes in the XPath (and not all the nodes in XML). In other words, when the not() clause is added to the topmost node of the XPath, all its children in XML will have a fixed, sorted word order. (Now that I read it like this, it seems only normal.) However, what I actually want is that the word order is only set on the nodes specified in XPath, and not possible other nodes in matching XML. Hopefully and example will make this more clear.

Let's say that I want to match the following XPath, a cat="np" that contains rel="det" pt="vnw" lemma="die" and at least two times rel="mod" pt="adj".

```<code>//node[@cat="np" and node[@rel="det" and @pt="vnw" and @lemma="die"] and count(node[@rel="mod" and @pt="adj"]) > 1]
</code>```

but with the added requirement that the order of this XPath is followed, i.e.

```<code>//node[
    @cat="np" and
    not(node[
        position() < last()
    ][number(@begin) > following-sibling::node/number(@begin)]) and
    node[
        @rel="det" and
        @pt="vnw" and
        @lemma="die"
    ] and
    count(node[
        @rel="mod" and
        @pt="adj"
    ]) > 1
]
</code>```

So rel="det" has to occur before the two rel="mod"s in XML. This works fine, and all matches are correct, but not all expected matches are found. The cause is that the not() line obviously targets all the XML nodes rather than the XPath-specified nodes. In case where down the line a node is found that does not adhere to the not rule, there won't be a match - even if that node is not specified in XPath. The above XPath, for instance, will not match the following XML because inside cat="np" there is a node whose begin attribute is larger than its next sibling, which is not allowed by the not rule.

```<code><node begin="4" cat="np" id="8" rel="obj1">
    <node begin="4" id="9" pos="det" pt="vnw" rel="det" word="die" lemma="die" />
    <node begin="5" id="10" pos="adj" pt="adj" rel="mod" word="veelzijdige" />
    <node begin="6" id="11" pos="adj" pt="adj" rel="mod" word="getalenteerde" />
    <node begin="7" id="12" pos="noun" pt="n" rel="hd" word="figuren" />
    <node begin="8" id="31" index="1" rel="obj1" />
    <node begin="2" id="32" index="2" rel="obj2" />
</node>
</code>```

However, I would like this cat="np" to match, and make the not() function less aggressive, i.e. only require that nodes specified in XPath (in this example rel="det" pt="vnw" lemma="die", and the two rel="mod" pt="adj" nodes) follow the order requirement where the begin attribute should be smaller than the next item of the XPath structure. Other items inside cat="np" that have not been specified in XPath are allowed to have an attribute that is larger than its next sibling.

Note that the last item of the XPath structure (which would match id="11" in the example XML) does not necessarily have to have a begin attribute that is lower than its following node in XML (which is not specified in the XPath).

As before, I am especially interested in how to solve this with a pure XPath option, but XQuery alternatives are also welcome. Preferably as a function that takes an XPath structure as input, and applies the 'word order' to its topmost node and all its descendants. Example code and usage with the XPath shown here as an example is encouraged.

答:
in terms of your recursive search request:

Using //node[@pt=("art" or "adj" or "n")]/ancestor::* searches from the inner levels of your xml tree. In your sample xml this will return (per element group) each top level in a recursive manner.

For more info: http://www.w3.org/TR/xpath-30/

Title: XPath pulling more than one match

Body:
The (BaseX) error

I am running queries on a large dataset in BaseX, but one XQuery is crashing my programme with an error [XPTY0004] Item expected, sequence found: (attribute begin {"6"}, ...)..

In my query I am trying to make sure that one element comes before another by comparing begin - an attribute that is present in XML - with number(). But whenever I try the most basic of XQueries (return matching nodes) on my dataset (e.g. with this online tool) I get an error that resembles the one that I had before:

[Error] SaxonCE.XSLT20Processor 14:08:39.692 SEVERE: XPathException in
  invokeTransform: A sequence of more than one item is not allowed as
  the first argument of number() ("6", "10")

So I am guessing there is something going on with the node's siblings, i.e. that there are more than one of these nodes, and that it's unclear which should be compared. Examples follow below.

Why does the order matter?

The XPath is used in a query engine for treebanks: linguistically annotated corpora. In some cases we want nodes to match in order, and sometimes it does not matter. As a simplistic example: sometimes we want to match something as specific as the concerned man where the order article, adjective, noun matters. In other queries it doesn't matter, and we want to match phrases such as the time available as well, where the order of article, adjective, noun can be in any order.

In other words, in the first case the order of the elements should be respected, in the second one it shouldn't. Here is a possible XPath representation of such a construction that holds an article, an adjective, and a noun.

node[@cat="np" and node[@pt="art"] and node[@pt="adj"] and node[@pt="n"]]

By default, XPath does not care about the order of these elements and does a greedy search, i.e. it will also match items such as the time available (art, n, adj). But I want to re-write the above XPath to make sure that the order of the nodes is respected, and so a construction such as the time available (art, n, adj) is not matched by the concerned man (art, adj, n) is.

# Possible representation of *the time available*
<node id="0" begin="1" cat="np">
    <node id="1" begin="1" pt="art" text="the" />
    <node id="2" begin="2" pt="n" text="time" />
    <node id="3" begin="3" pt="adj" text="available" />
</node>

# Possible representation of *the concerned man*
<node id="0" begin="1" cat="np">
    <node id="1" begin="1" pt="art" text="the" />
    <node id="2" begin="2" pt="adj" text="concerned" />
    <node id="3" begin="3" pt="n" text="man" />
</node>

One way to go about is to use a numeric comparison of the begin attribute that is available in the corpus. It is numerical ascending, so if we want to ensure the order of XPath is intact, we can say that the numeric value of each child node of @cat="np" should be less than the next by using number(). But as I showed above, this leads to an error - an error that would not occur in the simple example code that I just showed.

Another example.

<node id="0" begin="2">
    <node id="1" begin="2">
        <node id="2" begin="2"/>
        <node id="3" begin="3"/>
    </node>
    <node id="4" begin="5">
        <node id="5" begin="5"/>
    </node>
    <node id="6" begin="6"/>
</node>

This XPath should match:

/node/node[number(@begin) < number(../node/@begin)]

But when put through an XQuery processor you'd get the error described above. A sequence of more than one item is not allowed as the first argument of number() ("2", "5", ...).

I tried the solution provided by @Michael Kay but the same issue seems to play.

XQuery

for $node in node[every $n in node[position() lt last()] satisfies (number($n/@begin) lt number($n/following-sibling::node/@begin))]
return $node

Data

<node id="0" begin="2">
    <node id="1" begin="2">
        <node id="2" begin="2"/>
        <node id="3" begin="3"/>
    </node>
    <node id="4" begin="5">
        <node id="5" begin="5"/>
    </node>
    <node id="6" begin="6"/>
</node>

Error

SaxonCE.XSLT20Processor 14:48:49.809 SEVERE: XPathException in
  invokeTransform: A sequence of more than one item is not allowed as
  the first argument of number() ("5", "6")

Update April 19th, 2017

I bumped into some unexpected behaviour today, which makes the solution provided by @har07 not sufficient any more. I had wrongly assumed that the not() clause had only an effect on the nodes in the XPath (and not all the nodes in XML). In other words, when the not() clause is added to the topmost node of the XPath, all its children in XML will have a fixed, sorted word order. (Now that I read it like this, it seems only normal.) However, what I actually want is that the word order is only set on the nodes specified in XPath, and not possible other nodes in matching XML. Hopefully and example will make this more clear.

Let's say that I want to match the following XPath, a cat="np" that contains rel="det" pt="vnw" lemma="die" and at least two times rel="mod" pt="adj".

//node[@cat="np" and node[@rel="det" and @pt="vnw" and @lemma="die"] and count(node[@rel="mod" and @pt="adj"]) > 1]

but with the added requirement that the order of this XPath is followed, i.e.

//node[
    @cat="np" and
    not(node[
        position() < last()
    ][number(@begin) > following-sibling::node/number(@begin)]) and
    node[
        @rel="det" and
        @pt="vnw" and
        @lemma="die"
    ] and
    count(node[
        @rel="mod" and
        @pt="adj"
    ]) > 1
]

So rel="det" has to occur before the two rel="mod"s in XML. This works fine, and all matches are correct, but not all expected matches are found. The cause is that the not() line obviously targets all the XML nodes rather than the XPath-specified nodes. In case where down the line a node is found that does not adhere to the not rule, there won't be a match - even if that node is not specified in XPath. The above XPath, for instance, will not match the following XML because inside cat="np" there is a node whose begin attribute is larger than its next sibling, which is not allowed by the not rule.

<node begin="4" cat="np" id="8" rel="obj1">
    <node begin="4" id="9" pos="det" pt="vnw" rel="det" word="die" lemma="die" />
    <node begin="5" id="10" pos="adj" pt="adj" rel="mod" word="veelzijdige" />
    <node begin="6" id="11" pos="adj" pt="adj" rel="mod" word="getalenteerde" />
    <node begin="7" id="12" pos="noun" pt="n" rel="hd" word="figuren" />
    <node begin="8" id="31" index="1" rel="obj1" />
    <node begin="2" id="32" index="2" rel="obj2" />
</node>

However, I would like this cat="np" to match, and make the not() function less aggressive, i.e. only require that nodes specified in XPath (in this example rel="det" pt="vnw" lemma="die", and the two rel="mod" pt="adj" nodes) follow the order requirement where the begin attribute should be smaller than the next item of the XPath structure. Other items inside cat="np" that have not been specified in XPath are allowed to have an attribute that is larger than its next sibling.

Note that the last item of the XPath structure (which would match id="11" in the example XML) does not necessarily have to have a begin attribute that is lower than its following node in XML (which is not specified in the XPath).

As before, I am especially interested in how to solve this with a pure XPath option, but XQuery alternatives are also welcome. Preferably as a function that takes an XPath structure as input, and applies the 'word order' to its topmost node and all its descendants. Example code and usage with the XPath shown here as an example is encouraged.


问:
Casting fails for core data codegen subclasses implemented in both app and framework
I'm trying to use the new Xcode automatic codegen of NSManagedObject subclasses (set to "Class Definition" in this case because I don't need any custom logic) in a project that has a "Cocoa Touch Framework" target.

I created this Cocoa Touch Framework target (let's call it "CoreDataFramework") to contain all code related to core data handling (creating entities, updating entities, etc.) so both the app and an app extension can use this same code (the app extension has not been added yet).

When the app starts, this error message appears:

"Class X is implemented in both .../DerivedData/.../CoreDataFramework and .../AppName.app/AppName".

I assume this is because the automatically generated files have both the app and the framework set in their "target membership".

In an older version I had created the NSManagedObject subclasses manually and was somehow able to fix this error by setting the target membership of those classes to only the framework, the error disappeared and the app was still able to use these classes.

But now that the subclasses files are generated automatically, I cannot change their target membership, so both app and framework have a definition for the same subclass.

The big problem here is when the app uses the framework code to obtain one of these subclasses: let's say the app asks for a new "User" entity, the framework code returns the new "User" but then the app code crashes with the error:

"Could not cast value of type 'CoreDataFramework.User' to 'AppName.User'"

Assuming that I want to use the codegen to keep generating in "Class Definition" mode, and that I don't want to type "CoreDataFramework.User" or "AppName.User" instead of just "User" everywhere, how can I fix this casting problem? Or even if I switched the codegen to "Category/Extension" how could I fix the problem? The goal here is to not go back to "Manual/None".

Update:

Core data stack code, after moving data model to the framework only as suggested by Dave Weston:

```<code>{
    let persistentContainer = NSPersistentContainer(name: "DataModel")
    persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error (error), (error.userInfo)")
        }
    })
}
</code>```

Currently both this code and data model file are in the framework. For some reason the line that attempts to create the container is the one that prints this error: CoreData: error: Failed to load model named DataModel, so the fatal error from the code is never shown.

Solution:

Thanks to Dave Weston who led me in the right path. The solution that worked for me was moving the data model file to the framework and changing its target membership to the framework only (this causes the subclasses to only exist in the framework and not be implemented in both sides). Then I changed the core data stack initialization code so it would load the data model properly by accessing the framework bundle instead of the main bundle, like so:

```<code>{
    let frameworkBundle = Bundle.init(identifier: "bundle.id.of.framework")
    let dataModelURL = frameworkBundle!.url(forResource: "DataModelName", withExtension: "momd")!
    let managedObjectModel = NSManagedObjectModel(contentsOf: dataModelURL)
    let persistentContainer = NSPersistentContainer(name: "DataModelName", managedObjectModel: managedObjectModel!)
    persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
    }
}
</code>```

答: Generate the model classes in the framework only and then just import the framework when you want to reference those classes. </p>

Body:
I'm trying to use the new Xcode automatic codegen of NSManagedObject subclasses (set to "Class Definition" in this case because I don't need any custom logic) in a project that has a "Cocoa Touch Framework" target.

I created this Cocoa Touch Framework target (let's call it "CoreDataFramework") to contain all code related to core data handling (creating entities, updating entities, etc.) so both the app and an app extension can use this same code (the app extension has not been added yet).

When the app starts, this error message appears:

"Class X is implemented in both .../DerivedData/.../CoreDataFramework and .../AppName.app/AppName".

I assume this is because the automatically generated files have both the app and the framework set in their "target membership".

In an older version I had created the NSManagedObject subclasses manually and was somehow able to fix this error by setting the target membership of those classes to only the framework, the error disappeared and the app was still able to use these classes.

But now that the subclasses files are generated automatically, I cannot change their target membership, so both app and framework have a definition for the same subclass.

The big problem here is when the app uses the framework code to obtain one of these subclasses: let's say the app asks for a new "User" entity, the framework code returns the new "User" but then the app code crashes with the error:

"Could not cast value of type 'CoreDataFramework.User' to 'AppName.User'"

Assuming that I want to use the codegen to keep generating in "Class Definition" mode, and that I don't want to type "CoreDataFramework.User" or "AppName.User" instead of just "User" everywhere, how can I fix this casting problem? Or even if I switched the codegen to "Category/Extension" how could I fix the problem? The goal here is to not go back to "Manual/None".

Update:

Core data stack code, after moving data model to the framework only as suggested by Dave Weston:

{
    let persistentContainer = NSPersistentContainer(name: "DataModel")
    persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error (error), (error.userInfo)")
        }
    })
}

Currently both this code and data model file are in the framework. For some reason the line that attempts to create the container is the one that prints this error: CoreData: error: Failed to load model named DataModel, so the fatal error from the code is never shown.

Solution:

Thanks to Dave Weston who led me in the right path. The solution that worked for me was moving the data model file to the framework and changing its target membership to the framework only (this causes the subclasses to only exist in the framework and not be implemented in both sides). Then I changed the core data stack initialization code so it would load the data model properly by accessing the framework bundle instead of the main bundle, like so:

{
    let frameworkBundle = Bundle.init(identifier: "bundle.id.of.framework")
    let dataModelURL = frameworkBundle!.url(forResource: "DataModelName", withExtension: "momd")!
    let managedObjectModel = NSManagedObjectModel(contentsOf: dataModelURL)
    let persistentContainer = NSPersistentContainer(name: "DataModelName", managedObjectModel: managedObjectModel!)
    persistentContainer.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
    }
}


问:
HTML Position Fixed in a mobile version
I hope you can give me a hand.
What I'm Trying to do in a mobile version it's to leve the menu bar always visible using position fixed to the visitor and it work's fine, the issue is that the second div called aside it shows behind the menu bar and I really do not know how to show it after the menu bar.

I'm working in a 500px mobile version.

How can I fix this ?
I hope you can help me

....

```<code><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin título</title>
<style type="text/css">
body {
    margin-top: 0px;
    margin-right: 0px;
    margin-bottom: 0px;
    margin-left: 0px;
    height: 1000px;
    font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.container {
    width: 95%;
    margin-right: auto;
    margin-left: auto;
    background-color: #f1f1f1;
    height: 1000px;
    max-width: 950px;
}
header{
    height: 150px;
    border-color: red;
    border-style: dotted;
    margin-bottom: 5px;
    }
aside{
    height: 200px;
    border-color: blue;
    border-style: dotted;
    margin-bottom: 5px;

    }
section{
    height: 200px;
    border-color: yellow;
    border-style: dotted;
    margin-bottom: 5px;
    }
article{
    height: 200px;
    border-color: deeppink;
    border-style: dotted;
    margin-bottom: 5px;
}
footer{
    height: 200px;
    background-color: green;
    border-style: dotted;

}

nav{
    width: 100%;
    float: left;
}

nav ul{
    list-style: none;
    padding: 0;
    overflow: hidden;
    margin-top: 56px;
}

nav ul li{
    padding: 10px;
    display: inline-block;
    overflow: hidden;
}

nav ul li a{
    color: red;
}

.menu {
    display: none;
}

@media screen and (max-width:700px){

    .container{
        background-color: deeppink;
    }
}

@media screen and (max-width:500px){

    body{
        margin: 0;

    }
    .container{
        background-color: #CCCCCC;
        width: 100%;

    }
    header{
        margin-bottom: 5px;
        border-style:none;
        height: auto;

    }

    .menu{
        display: block;
        background-color: black;
        width: 100%;
        height: auto;
        margin-top: 0px;
        position: fixed;

    }

    .menu .icon-menu{
        color: #fff;
        padding: 10px;
        font-size: 28px;

    }

    .menu .menu_txt{
        color: #fff;
        float: right;
        padding: 10px;
        font-size: 18px;
        margin-top: 5px;
        margin-right: 5px;
    }

    nav{
        background-color: #595959;
        height: 100%;
        position: fixed;
        width: 90%;
        display: none;
    }

    nav ul{
        border-color: deeppink;
        margin-top: 0px;

    }

    nav ul li{
        background-color: #3E3E3E;
        display: block;
        margin-top: 0px;
        width: 100%

    }

    aside{
        margin-top: 0px;
    }
}
</style>
<link href="fonts.css" rel="stylesheet" type="text/css">
</head>

<body>
<div class="container">

    <header>

        <div class="menu">
            <div class="menu_txt">MENU</div>
            <div class="icon-menu"></div>
        </div>

        <nav>
            <ul>
                <li><a href="#">page</a></li>
                <li><a href="#">page</a></li>
                <li><a href="#">page</a></li>
                <li><a href="#">page</a></li>
                <li><a href="#">page</a></li>
            </ul>
        </nav>

    </header>

    <aside>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id excepturi nesciunt in modi ratione alias vero ipsam optio quod quaerat fugiat est nihil temporibus, earum, necessitatibus ducimus hic cumque inventore?</aside>
    <section>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic, incidunt necessitatibus asperiores quibusdam voluptas eos doloremque vitae consectetur earum facilis repudiandae ullam quisquam perferendis tempora. Illo, officia atque natus itaque.</section>
    <article>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis necessitatibus explicabo obcaecati cum minima mollitia quam assumenda perferendis dicta. Cumque placeat, aliquam itaque ad quia accusamus autem tempora ex fugit.</article>
    <footer>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus at natus pariatur eligendi possimus ipsa corporis rem rerum omnis, perferendis, earum vero dolorum optio, nihil odit dolores autem asperiores recusandae!</footer>

</div>
</body>
</html>
</code>```

答:
In your media query, add margin top or padding top to your body to push the content below the menu then add top: 0; to your menu to make sure it stays at the top.
http://codepen.io/anon/pen/JWwRmN</p>

```<code>@media screen and (max-width:500px){
    body{
        margin: 0;
        margin-top: 50px;
    }
      .menu{
        display: block;
        background-color: black;
        width: 100%;
        height: auto;
        margin-top: 0px;
        position: fixed;
        top: 0;
    }
</code>```

Title: HTML Position Fixed in a mobile version

Body:
I hope you can give me a hand.
What I'm Trying to do in a mobile version it's to leve the menu bar always visible using position fixed to the visitor and it work's fine, the issue is that the second div called aside it shows behind the menu bar and I really do not know how to show it after the menu bar.

I'm working in a 500px mobile version.

How can I fix this ?
I hope you can help me

....

<!doctype html>

<meta charset="utf-8">
<title>Documento sin título</title>

<link href="fonts.css" rel="stylesheet" type="text/css">

MENU

page

page

page

page

page

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id excepturi nesciunt in modi ratione alias vero ipsam optio quod quaerat fugiat est nihil temporibus, earum, necessitatibus ducimus hic cumque inventore?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic, incidunt necessitatibus asperiores quibusdam voluptas eos doloremque vitae consectetur earum facilis repudiandae ullam quisquam perferendis tempora. Illo, officia atque natus itaque.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis necessitatibus explicabo obcaecati cum minima mollitia quam assumenda perferendis dicta. Cumque placeat, aliquam itaque ad quia accusamus autem tempora ex fugit.

    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus at natus pariatur eligendi possimus ipsa corporis rem rerum omnis, perferendis, earum vero dolorum optio, nihil odit dolores autem asperiores recusandae!

Body:
In your media query, add margin top or padding top to your body to push the content below the menu then add top: 0; to your menu to make sure it stays at the top.
http://codepen.io/anon/pen/JWwRmN

@media screen and (max-width:500px){
    body{
        margin: 0;
        margin-top: 50px;
    }
      .menu{
        display: block;
        background-color: black;
        width: 100%;
        height: auto;
        margin-top: 0px;
        position: fixed;
        top: 0;
    }


问:
PHP Fatal error: Class 'Vinkla\Hashids\HashidsServiceProvider' not found
I was developing on my dev machine using Homestead. I committed both my composer.lock and composer.json. During this branch, I added Hashid and LaravelDebugBar to composer for development purposes. Everything worked fine on the development machine.

Once I pulled from master to my production machine, and ran composer update, and I get the following error:

When I type in php artisan migrate or composer update, I get the following error:

```<code>  PHP Fatal error:  Class 'Vinkla\Hashids\HashidsServiceProvider' not found in /var/www/schedulizer/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 146

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'Vinkla\Hashids\HashidsServiceProvider' not found
</code>```

I tried composer clear-compiled, composer dump-autoload tried manually requiring the Hashid package, and removing the offending lines in config/app.php and running composer update

I checked the service provider, and it is in my config/app.php..

答:
I tried php artisan config:clear then I ran composer update and composer install but I got the same error message.

in my case, the problem was in bootstrap/cache/config.php
So I deleted the file manually and mission accomplished.

Body:
I was developing on my dev machine using Homestead. I committed both my composer.lock and composer.json. During this branch, I added Hashid and LaravelDebugBar to composer for development purposes. Everything worked fine on the development machine.

Once I pulled from master to my production machine, and ran composer update, and I get the following error:

When I type in php artisan migrate or composer update, I get the following error:

  PHP Fatal error:  Class 'Vinkla\Hashids\HashidsServiceProvider' not found in /var/www/schedulizer/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php on line 146

  [Symfony\Component\Debug\Exception\FatalErrorException]
  Class 'Vinkla\Hashids\HashidsServiceProvider' not found

I tried composer clear-compiled, composer dump-autoload tried manually requiring the Hashid package, and removing the offending lines in config/app.php and running composer update

I checked the service provider, and it is in my config/app.php..