问:
Core Data Migration error when migrating between non-consecutive versions

The Problem

I've got 13 versions of my core data model.

I've made 13 mapping models (V1-V2, V2-V3 etc)

I've got automatic migration switched on.

On migration between two consecutive versions (e.g. V12-V13) the migration works perfectly

On migration between two non-consecutive versions (e.g. V11-V13) the migration fails with the error:

Can't find mapping model for migration

What I've tried

Creating a mapping model for every possible combination of versions. This works, but it's a real hassle.

For version 14 I'll need to make 14 different mapping models. Manually. Ugh.

Code

Here's the options I pass in for migration:

```<code>[persistentStoreCoordinator addPersistentStoreWithType:[self storeType]
                                          configuration:nil
                                                    URL:url
                                                options:[NSDictionary dictionaryWithObjectsAndKeys:
                                                         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                                         [NSNumber numberWithBool:NO], NSReadOnlyPersistentStoreOption,
                                                         nil]
                                                  error:&error]){
</code>```

Data Model

My data model is pretty complex, but here it is: http://dl.dropbox.com/u/136780/Engine_V2_DataModel.xcdatamodeld.zip

I'm not using any version hash modifiers or renaming identifiers in my data model right now.

答:
See this Stack Overflow question: Core Data Migration Across Multiple Version Upgrades

Basically, the gist is that you don't need to create the complete set of mapping models.  You just need mapping models between each pair of successive models, and then you can progressively migrate any old model through the intermediate models to the newest model.

The performance may not be good depending on your store, because you're not doing the migration in one single step.  It may be good enough, though, and may be worth it to not have to create the complete set of mapping models.  You can also test out the performance of this method to determine whether you need to create maps between non-successive versions of your model.

Marcus Zarra (Core Data aficionado extraordinaire) has the code here: http://media.pragprog.com/titles/mzcd/code/ProgressiveMigration/AppDelegate.m

(I was just about to ask this question, but thanks to LazyTwitter I was pointed to this answer by Aaron Tuller: https://twitter.com/tullera/status/57708304683642880 )

Body:
The Problem

I've got 13 versions of my core data model.

I've made 13 mapping models (V1-V2, V2-V3 etc)

I've got automatic migration switched on.

On migration between two consecutive versions (e.g. V12-V13) the migration works perfectly

On migration between two non-consecutive versions (e.g. V11-V13) the migration fails with the error:

Can't find mapping model for migration

What I've tried

Creating a mapping model for every possible combination of versions. This works, but it's a real hassle.

For version 14 I'll need to make 14 different mapping models. Manually. Ugh.

Code

Here's the options I pass in for migration:

[persistentStoreCoordinator addPersistentStoreWithType:[self storeType]
                                          configuration:nil
                                                    URL:url
                                                options:[NSDictionary dictionaryWithObjectsAndKeys:
                                                         [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                                         [NSNumber numberWithBool:NO], NSReadOnlyPersistentStoreOption,
                                                         nil]
                                                  error:&error]){

Data Model

My data model is pretty complex, but here it is: http://dl.dropbox.com/u/136780/Engine_V2_DataModel.xcdatamodeld.zip

I'm not using any version hash modifiers or renaming identifiers in my data model right now.


来源: stackexchange

问:
SQL Server with Google Apps Script via JDBC
There seems to be an issue with Google Apps Script JDBC Connection in recent days, where connection via a hostname fails, but specifying an IP works.

Error:

Failed to establish a database connection. Check connection string,
  username and password.

```<code>    function SQLTOGOOGLOOGLESPREADSHEET(sqlQuery) {
    var address = 'http://127.0.0.1/phpmyadmin/:3306';
    var user = 'root';
    var userPwd = '';
    var db = 'employee';
    var msSqlUrlSyntax ='jdbc:sqlserver://'

    var dbUrl = msSqlUrlSyntax + address + ';databaseName=' + db;

    // msSqlUrlSyntax = 'youOptionalTestingQuery'
    var conn = Jdbc.getConnection(dbUrl, user, userPwd);

}
</code>```

答: You have done it right. Using an IP address instead of hostnames work as workaround. This is a known bug. Also, this issue was cited in this SO post.</p>

ContentLicense: CC BY-SA 4.0

Body:
There seems to be an issue with Google Apps Script JDBC Connection in recent days, where connection via a hostname fails, but specifying an IP works.

Error:

Failed to establish a database connection. Check connection string,
  username and password.

    function SQLTOGOOGLOOGLESPREADSHEET(sqlQuery) {
    var address = 'http://127.0.0.1/phpmyadmin/:3306';
    var user = 'root';
    var userPwd = '';
    var db = 'employee';
    var msSqlUrlSyntax ='jdbc:sqlserver://'

    var dbUrl = msSqlUrlSyntax + address + ';databaseName=' + db;

    // msSqlUrlSyntax = 'youOptionalTestingQuery'
    var conn = Jdbc.getConnection(dbUrl, user, userPwd);

}


问:
Dynamically give list items <li> a unique class with PHP
I am dynamically populating a list based on what is in the database, and I would like each list item to have a unique class name - something simple, for example the first <li> would have the class item-1, and the second <li> would have the class item-2.
This is the php code I am using to create the list: </p>

```<code> <?php
          $metas=trim(get_post_meta($post->ID,'hike_meta',true),'');
          $metas_arr=explode("\n",$metas);
          $metas1=array_slice($metas_arr,0,3);
          $metas2=array_slice($metas_arr,3,3);
?>

<div class="loca_meta">
    <ul>
       <?php foreach($metas1 as $meta){
             list($k, $v) = explode('|', $meta);
             echo "<li><span class='bold'>$k</span>:<br>$v</li>";
          }?>
     </ul>
     </div>
     <div class="loca_meta">
        <ul>
          <?php foreach($metas2 as $meta){
                list($k, $v) = explode('|', $meta);
                 echo "<li><span class='bold'>$k</span>:<br>$v</li>";
           }?>
        </ul>
     </div>
</code>```

<p>What extra code do I need, to give each list item a unique class? As a side note, I am very much a beginner when it comes to php, so please let me know if you need any more information. </p>

答:
You can use for loop:

   <?php for($i = 0; $i < count($metas1); $i++){
         list($k, $v) = explode('|', $metas[$i]);
         echo "
$k:
$v
";
      }?>
```

<p>Result will be:</p>

<pre class="lang-html prettyprint-override"><code><li><span class="bold item-1"><!-- content --></span>:<br><!-- content --></li>
<li><span class="bold item-2"><!-- content --></span>:<br><!-- content --></li>
<li><span class="bold item-3"><!-- content --></span>:<br><!-- content --></li>
</code>```

and so on.

Body:
I am dynamically populating a list based on what is in the database, and I would like each list item to have a unique class name - something simple, for example the first
 would have the class item-1, and the second
 would have the class item-2.
This is the php code I am using to create the list:

 <?php
          $metas=trim(get_post_meta($post->ID,'hike_meta',true),'');
          $metas_arr=explode("\n",$metas);
          $metas1=array_slice($metas_arr,0,3);
          $metas2=array_slice($metas_arr,3,3);
?>

       <?php foreach($metas1 as $meta){
             list($k, $v) = explode('|', $meta);
             echo "
$k:
$v
";
          }?>

          <?php foreach($metas2 as $meta){
                list($k, $v) = explode('|', $meta);
                 echo "
$k:
$v
";
           }?>

What extra code do I need, to give each list item a unique class? As a side note, I am very much a beginner when it comes to php, so please let me know if you need any more information.

Body:
You can use for loop:

   <?php for($i = 0; $i < count($metas1); $i++){
         list($k, $v) = explode('|', $metas[$i]);
         echo "<li><span class="bold item-".$i+1.">$k</span>:<br>$v</li>";
      }?>

Result will be:

<li><span class="bold item-1"><!-- content --></span>:<br><!-- content --></li>
<li><span class="bold item-2"><!-- content --></span>:<br><!-- content --></li>
<li><span class="bold item-3"><!-- content --></span>:<br><!-- content --></li>

and so on.


问:
AngularJS : Implementing token in $http
I am very new to angularJS.

My Backend is DRF and I have successfully implemented token.

this is my token:

```<code>{
    "key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
</code>```

Before I implement token in backend, it was working nice:

```<code>$scope.getAllContact = function() {
    var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
    .then(function(response) {
      $scope.contacts = response.data;
    });
  };
</code>```

But, now I am not getting how can I implement this token here

Can anyone help me in this case?

答:
Try to use this. You need to attach the token in the headers.

```<code>$http({
   url : "http://127.0.0.1:8000/api/v1/contact",
   method : 'GET',
  headers : {
      'Content-Type' : 'application/json',
      'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
  }
}).then(function(response){
    $scope.contacts = response.data;
});
</code>```

Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default

Title: AngularJS : Implementing token in $http

Body:
I am very new to angularJS.

My Backend is DRF and I have successfully implemented token.

this is my token:

{
    "key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}

Before I implement token in backend, it was working nice:

$scope.getAllContact = function() {
    var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
    .then(function(response) {
      $scope.contacts = response.data;
    });
  };

But, now I am not getting how can I implement this token here

Can anyone help me in this case?

Body:
Try to use this. You need to attach the token in the headers.

$http({
   url : "http://127.0.0.1:8000/api/v1/contact",
   method : 'GET',
  headers : {
      'Content-Type' : 'application/json',
      'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
  }
}).then(function(response){
    $scope.contacts = response.data;
});

Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default


问:
run synchronouse function in a promise
I am new to JS and async operations. In a router of nodeJS using express, I have aggregated some data from mongo using mongoose. The data is weather data collected from different sites every 15 minutes interval. I processed the data with mongoose aggregate pipeline to get hourly data and group by each site. But the data needs a further process to get periods where for example relative humidity over 90% and assign scores to each period so I wrote some synchronous functions that target each site (each geojson object).

Mongoose looks something like that:

```<code>module.exports.filteredData = function (collection, dateInput) {
return collection.aggregate([

    {
        $addFields :{
            DateObj: {
                $dateFromString: {
                    dateString: "$DateTime",
                    format: '%Y-%m-%d'
                }
            },
        }
    },

    {
        $addFields :{
            NewDateTimes: {
                $dateFromParts:{
                    'year': {$year: '$DateObj'},
                    'month':{$month: '$DateObj'},
                    'day':{$dayOfMonth: '$DateObj'},
                    'hour': {$toInt: "$Time"}
                }
            }
        }
    }

...
</code>```

synchronouse functions:

```<code>const calcDSV = function(featuresJSON){

    // featuresJSON
    const SVscore = [];
    const tuEval = featuresJSON.features.properties.TU90; // array
    const obArr = featuresJSON.features.properties.OB; // array
    const periodObj =  getPeriods(tuEval);// get period position
    const paramObj =  getParams(periodObj, obArr); // get parameters
    const periodDate =   getPeriodDate(featuresJSON, periodObj);
    const removeTime =  periodDate.beginDate.map(x=>x.split('T')[0]);

    let hourly = paramObj.hourCounts;
    let avgTemps = paramObj.avgTemps;

    for(let i = 0;i<hourly.length; i++){

        let score =  assignScore(avgTemps[i], hourly[i]);
        SVscore.push(score);

    }

    // output sv score for date

    const aggreScore =  accumScore(removeTime, SVscore);

    aggreScore.DSVdate = aggreScore.Date.map(x=>new Date(x));

    featuresJSON.features.properties.periodSV = SVscore;
    featuresJSON.features.properties.Periods = periodDate;
    featuresJSON.features.properties.DSVscore = aggreScore;

    return  featuresJSON;

}
</code>```

Now I am stuck on how to apply those function on each site return by the mongoose aggregate pipeline on a post request:

```<code>router.post('/form1', (req, res, next)=>{

const emdate = new Date(req.body.emdate);
const address = req.body.address;
const stationDataCursor = stationData.filteredData(instantData, emdate);

stationDataCursor.toArray((err, result)=>{
    if(err){
        res.status(400).send("An error occurred in Data aggregation")
    };

    res.json(result.map(x=>calcDSV.calcDSV(x)));

})

});
</code>```

I tried in the callback:

```<code>stationDataCursor.toArray((err, result)=>{
    if(err){
        res.status(400).send("An error occurred in Data aggregation")
    };

    res.json(result.map(async (x)=>await calcDSV.calcDSV(x))));

})
</code>```

and using then():

```<code>stationDataCursor.toArray().then((docArr)=>{

    let newfeature = await docArr.map(async (x)=> await calcDSV.calcDSV(x))));

    res.json(newfeature);

})
</code>```

or make calcDSV() returns new promise

```<code>    return  new Promise((rej, res)=>{
            resolve(featuresJSON);
     })
</code>```

I would expect to see all sites with a new feature added in the HTTP response output. But most of the time, I got ReferenceError: error is not defined.

答:
I think I have figured it out:

after all, have to make all synchronous functions asynchronous by prepending async to those functions;

rewrite this part in the post router function, especially the array map part. I read from this. and in the map() gonna have try...catch... in it, otherwise it won't work.

```<code>await stationDataCursor.toArray().then(async (docArr)=>{

        const newfeature = await Promise.all(docArr.map(async function(x){
            try{
                const feature = await calcDSV.calcDSV(x);

                return feature
            } catch(err){
                console.log("Error happened!!! ", err);

            }

        }));

        res.json(newfeature)

})
</code>```

Hope it helps.

Title: run synchronouse function in a promise

Body:
I am new to JS and async operations. In a router of nodeJS using express, I have aggregated some data from mongo using mongoose. The data is weather data collected from different sites every 15 minutes interval. I processed the data with mongoose aggregate pipeline to get hourly data and group by each site. But the data needs a further process to get periods where for example relative humidity over 90% and assign scores to each period so I wrote some synchronous functions that target each site (each geojson object).

Mongoose looks something like that:

module.exports.filteredData = function (collection, dateInput) {
return collection.aggregate([

    {
        $addFields :{
            DateObj: {
                $dateFromString: {
                    dateString: "$DateTime",
                    format: '%Y-%m-%d'
                }
            },
        }
    },

    {
        $addFields :{
            NewDateTimes: {
                $dateFromParts:{
                    'year': {$year: '$DateObj'},
                    'month':{$month: '$DateObj'},
                    'day':{$dayOfMonth: '$DateObj'},
                    'hour': {$toInt: "$Time"}
                }
            }
        }
    }

...

synchronouse functions:

const calcDSV = function(featuresJSON){

    // featuresJSON
    const SVscore = [];
    const tuEval = featuresJSON.features.properties.TU90; // array
    const obArr = featuresJSON.features.properties.OB; // array
    const periodObj =  getPeriods(tuEval);// get period position
    const paramObj =  getParams(periodObj, obArr); // get parameters
    const periodDate =   getPeriodDate(featuresJSON, periodObj);
    const removeTime =  periodDate.beginDate.map(x=>x.split('T')[0]);

    let hourly = paramObj.hourCounts;
    let avgTemps = paramObj.avgTemps;

    for(let i = 0;i<hourly.length; i++){

        let score =  assignScore(avgTemps[i], hourly[i]);
        SVscore.push(score);

    }

    // output sv score for date

    const aggreScore =  accumScore(removeTime, SVscore);

    aggreScore.DSVdate = aggreScore.Date.map(x=>new Date(x));

    featuresJSON.features.properties.periodSV = SVscore;
    featuresJSON.features.properties.Periods = periodDate;
    featuresJSON.features.properties.DSVscore = aggreScore;

    return  featuresJSON;

}

Now I am stuck on how to apply those function on each site return by the mongoose aggregate pipeline on a post request:

router.post('/form1', (req, res, next)=>{

const emdate = new Date(req.body.emdate);
const address = req.body.address;
const stationDataCursor = stationData.filteredData(instantData, emdate);

stationDataCursor.toArray((err, result)=>{
    if(err){
        res.status(400).send("An error occurred in Data aggregation")
    };

    res.json(result.map(x=>calcDSV.calcDSV(x)));

})

});

I tried in the callback:

stationDataCursor.toArray((err, result)=>{
    if(err){
        res.status(400).send("An error occurred in Data aggregation")
    };

    res.json(result.map(async (x)=>await calcDSV.calcDSV(x))));

})

and using then():

stationDataCursor.toArray().then((docArr)=>{

    let newfeature = await docArr.map(async (x)=> await calcDSV.calcDSV(x))));

    res.json(newfeature);

})

or make calcDSV() returns new promise

    return  new Promise((rej, res)=>{
            resolve(featuresJSON);
     })

I would expect to see all sites with a new feature added in the HTTP response output. But most of the time, I got ReferenceError: error is not defined.

Body:
I think I have figured it out:

after all, have to make all synchronous functions asynchronous by prepending async to those functions;

rewrite this part in the post router function, especially the array map part. I read from this. and in the map() gonna have try...catch... in it, otherwise it won't work.

await stationDataCursor.toArray().then(async (docArr)=>{

        const newfeature = await Promise.all(docArr.map(async function(x){
            try{
                const feature = await calcDSV.calcDSV(x);

                return feature
            } catch(err){
                console.log("Error happened!!! ", err);

            }

        }));

        res.json(newfeature)

})

Hope it helps.


问:
Remove the Open and close brackets from the string
I want to remove the [ ] brackets from list1 variable in python

```<code>list1 = ['Order No','Item']
</code>```

Expected :

```<code>>>> print (list1)
'Order No', 'Item'
</code>```

Actual :

```<code>>>> print (list1)
['Order No', 'Item']
</code>```

答:
Try the below code:

```<code>>>> list1 = ['Order No','Item']
>>> print(str(list1)[1:-1])
'Order No', 'Item'
>>>
</code>```

If you don't need the quotes, use:

```<code>>>> print(', '.join(list1))
Order No, Item
</code>```

Body:
I want to remove the [ ] brackets from list1 variable in python

list1 = ['Order No','Item']

Expected :

>>> print (list1)
'Order No', 'Item'

Actual :

>>> print (list1)
['Order No', 'Item']

Body:
Try the below code:

>>> list1 = ['Order No','Item']
>>> print(str(list1)[1:-1])
'Order No', 'Item'
>>>

If you don't need the quotes, use:

>>> print(', '.join(list1))
Order No, Item


问:
Create a Windows user for an IIS site and nothing else
I'd like to add basic authentication to a website in IIS, https only. For this I need to create a Windows user. It is important that this user can access nothing other than this website. So I need to add him to Deny log on locally & Deny log on through Remote Desktop Services in Local Computer Policy.

However I cannot add him to Deny access to this computer from the network or he can't access the website. Microsoft says about this permission:

Users who can log on to the device over the network can enumerate lists of account names, group names, and shared resources.

Users with permission to access shared folders and files can connect over the network and possibly view or modify data.

What can I do to create a user that I can be 100% sure can only access this website and absolutely nothing else?

答:
To address your concern about the "Deny access to this computer from the network" policy, that shouldn't prohibit the account from be used to authenticate with the website since "access from the network" doesn't include the HTTP/S protocol and WWW service.  Therefore, you can add the basic auth user account to the "deny access" policy as desired.

Sources...

https://www.itprotoday.com/compute-engines/understanding-access-computer-network-user-right

"Despite the broad-sounding name, the 'Access this computer from the network' user right applies only to the Server service and the resources it provides. The Server service primarily provides remote access to files and printers but also provides remote access to the resources you see in the Microsoft Management Console (MMC) Computer Management snap-in, including event logs, shared folders, local users and groups, logical disk management, and applications that use named pipes. However the Access this computer from the network user right has no effect on services such as World Wide Web Publishing, Telnet, and Terminal Services. To control access to these services, you must implement security settings specific to each service as necessary."

https://learn.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/access-this-computer-from-the-network

"The Access this computer from the network policy setting determines which users can connect to the device from the network. This capability is required by a number of network protocols, including Server Message Block (SMB)-based protocols, NetBIOS, Common Internet File System (CIFS), and Component Object Model Plus (COM+)."

Hope this helps.


问:
i have a project where i need to make special routing how i can make my own rule?
in my own site i need a thing that page are known by #topic.

it's need to look like

mywebsite.com#google [are this possible i need to pass google as parameter]
OR
mywebsite.com/#google [if first can not be done then how i can use it]

how i can apply this thing in my website. the thing i need to done that

if anyone open the site mywebsite.com#google that the content genrate dynamically through [passing google as parameter]

can anyone show how i can make routing for this

答: You can't use routing for this. The value that follows the # sign in an URL is NEVER sent to the server by the client browser. So for example if you request http://example.com/someaction#google the server can never fetch the value google simply because the browser never sends it. The only way is to use javascript (window.location.hash) and maybe send an AJAX request to the server by rewriting the url : http://example.com/someaction?param=google

OwnerDisplayName: delete my account

ContentLicense: CC BY-SA 3.0


问:
Struggling with HierarchicalDataTemplate in ContextMenu
I'd like to be able to bind the ItemsSource of a ContextMenu to a Collection in my view model, show Separators in the ContextMenu, and the ItemsSource has to be hierarchical (every level of the hierarchy will look the same).

In one of my other questions I managed to be able to show menu items and separators in a data bound ContextMenu, but now I struggle with making the ItemsSource hierarchical.

Right now I don't know what's going on, maybe you can enlighten me?

Here's my code again (simplified to be short, but working):

MenuItemViewModel.vb

```<code>Public Class MenuItemViewModel
    Implements ICommand

    Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

    Public Property IsSeparator As Boolean
    Public Property Caption As String
    Private ReadOnly _subItems As List(Of MenuItemViewModel)

    Public Sub New(createItems As Boolean, level As Byte)
        _subItems = New List(Of MenuItemViewModel)

        If createItems Then
            _subItems.Add(New MenuItemViewModel(level < 4, level + 1) With {.Caption = "SubItem 1"})
            _subItems.Add(New MenuItemViewModel(False, level + 1) With {.IsSeparator = True, .Caption = "SubSep 1"})
            _subItems.Add(New MenuItemViewModel(level < 4, level + 1) With {.Caption = "SubItem 2"})
        End If
    End Sub

    Public ReadOnly Property SubItems As List(Of MenuItemViewModel)
        Get
            Return _subItems
        End Get
    End Property

    Public ReadOnly Property Command As ICommand
        Get
            Return Me
        End Get
    End Property

    Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
        MessageBox.Show(Me.Caption)
    End Sub

    Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
        Return True
    End Function

End Class
</code>```

The view model for each menu item on each level has a Caption to show in the context menu, an IsSeparator flag to indicate whether it's a separator or a functional menu item, a Command to be bound to when being a functional menu item and of course a SubItems collection containing functional menu items and separators down to a certain hierarchy level.

MainViewModel.vb

```<code>Public Class MainViewModel
    Private ReadOnly _items As List(Of MenuItemViewModel)

    Public Sub New()
        _items = New List(Of MenuItemViewModel)
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 1"})
        _items.Add(New MenuItemViewModel(False, 0) With {.IsSeparator = True, .Caption = "Sep 1"})
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 2"})
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 3"})
        _items.Add(New MenuItemViewModel(False, 0) With {.IsSeparator = True, .Caption = "Sep 2"})
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 4"})
    End Sub

    Public ReadOnly Property Items As List(Of MenuItemViewModel)
        Get
            Return _items
        End Get
    End Property

End Class
</code>```

The main view model does only have an Items collection containing functional menu items as well as separators.

MainWindow.xaml

```<code><Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp3"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance local:MainViewModel, IsDesignTimeCreatable=True}"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>

    <Window.Resources>
        <ControlTemplate x:Key="mist" TargetType="{x:Type MenuItem}">
            <Separator />
        </ControlTemplate>

        <ControlTemplate x:Key="mict" TargetType="{x:Type MenuItem}">
            <MenuItem Header="{Binding Caption}" Command="{Binding Command}" ItemsSource="{Binding SubItems}" />
        </ControlTemplate>

        <Style x:Key="cmics" TargetType="{x:Type MenuItem}">
            <Setter Property="Template" Value="{StaticResource mict}" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsSeparator}" Value="True">
                    <Setter Property="Template" Value="{StaticResource mist}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>

    <Grid>
        <TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Text="Right click me">
            <TextBox.ContextMenu>
                <ContextMenu ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource cmics}">
                    <ContextMenu.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" ItemsSource="{Binding SubItems}" />
                    </ContextMenu.ItemTemplate>
                </ContextMenu>
            </TextBox.ContextMenu>
        </TextBox>
    </Grid>
</Window>
</code>```

The window resources contain two ControlTemplates "mist" and "mict" and a Style "cmics" that switches between the two ControlTemplates depending on the value of the IsSeparator flag. This works fine as long as the ItemsSource is not hierarchical (see my other question).

If my Style "cmics" is attached to the ItemContainerStyle of the ContextMenu only (as in my example code) then it looks like this:

The first level works but the others don't. This doesn't change when attaching my Style "cmics" to the ItemContainerStyle of the HierarchicalDataTemplate as well.

If I only attach my Style "cmics" to the HierarchicalDataTemplate then it looks like this:

The first level doesn't show captions and separators, the second level works and the other levels don't work.

So, how can I persuade the ContextMenu to use my Style "cmics" as the ItemContainerStyle for every hierarchy level?

答:
I found an answer here.

I had to create an empty view model just for the separators and a class that derives from ItemContainerTemplateSelector to return the DataTemplate that belongs to the type of the menu item ("MenuItemViewModel" or "SeparatorViewModel").

The linked article should be self explanatory.

Body:
I'd like to be able to bind the ItemsSource of a ContextMenu to a Collection in my view model, show Separators in the ContextMenu, and the ItemsSource has to be hierarchical (every level of the hierarchy will look the same).

In one of my other questions I managed to be able to show menu items and separators in a data bound ContextMenu, but now I struggle with making the ItemsSource hierarchical.

Right now I don't know what's going on, maybe you can enlighten me?

Here's my code again (simplified to be short, but working):

MenuItemViewModel.vb

Public Class MenuItemViewModel
    Implements ICommand

    Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged

    Public Property IsSeparator As Boolean
    Public Property Caption As String
    Private ReadOnly _subItems As List(Of MenuItemViewModel)

    Public Sub New(createItems As Boolean, level As Byte)
        _subItems = New List(Of MenuItemViewModel)

        If createItems Then
            _subItems.Add(New MenuItemViewModel(level < 4, level + 1) With {.Caption = "SubItem 1"})
            _subItems.Add(New MenuItemViewModel(False, level + 1) With {.IsSeparator = True, .Caption = "SubSep 1"})
            _subItems.Add(New MenuItemViewModel(level < 4, level + 1) With {.Caption = "SubItem 2"})
        End If
    End Sub

    Public ReadOnly Property SubItems As List(Of MenuItemViewModel)
        Get
            Return _subItems
        End Get
    End Property

    Public ReadOnly Property Command As ICommand
        Get
            Return Me
        End Get
    End Property

    Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
        MessageBox.Show(Me.Caption)
    End Sub

    Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
        Return True
    End Function

End Class

The view model for each menu item on each level has a Caption to show in the context menu, an IsSeparator flag to indicate whether it's a separator or a functional menu item, a Command to be bound to when being a functional menu item and of course a SubItems collection containing functional menu items and separators down to a certain hierarchy level.

MainViewModel.vb

Public Class MainViewModel
    Private ReadOnly _items As List(Of MenuItemViewModel)

    Public Sub New()
        _items = New List(Of MenuItemViewModel)
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 1"})
        _items.Add(New MenuItemViewModel(False, 0) With {.IsSeparator = True, .Caption = "Sep 1"})
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 2"})
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 3"})
        _items.Add(New MenuItemViewModel(False, 0) With {.IsSeparator = True, .Caption = "Sep 2"})
        _items.Add(New MenuItemViewModel(True, 0) With {.Caption = "Item 4"})
    End Sub

    Public ReadOnly Property Items As List(Of MenuItemViewModel)
        Get
            Return _items
        End Get
    End Property

End Class

The main view model does only have an Items collection containing functional menu items as well as separators.

MainWindow.xaml

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp3"
        mc:Ignorable="d"
        d:DataContext="{d:DesignInstance local:MainViewModel, IsDesignTimeCreatable=True}"
        Title="MainWindow" Height="450" Width="800">

    <Window.DataContext>
        <local:MainViewModel />
    </Window.DataContext>

    <Window.Resources>
        <ControlTemplate x:Key="mist" TargetType="{x:Type MenuItem}">
            <Separator />
        </ControlTemplate>

        <ControlTemplate x:Key="mict" TargetType="{x:Type MenuItem}">
            <MenuItem Header="{Binding Caption}" Command="{Binding Command}" ItemsSource="{Binding SubItems}" />
        </ControlTemplate>

        </Style>
    </Window.Resources>

    <Grid>
        <TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Text="Right click me">
            <TextBox.ContextMenu>
                <ContextMenu ItemsSource="{Binding Items}" ItemContainerStyle="{StaticResource cmics}">
                    <ContextMenu.ItemTemplate>
                        <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" ItemsSource="{Binding SubItems}" />
                    </ContextMenu.ItemTemplate>
                </ContextMenu>
            </TextBox.ContextMenu>
        </TextBox>
    </Grid>
</Window>

The window resources contain two ControlTemplates "mist" and "mict" and a Style "cmics" that switches between the two ControlTemplates depending on the value of the IsSeparator flag. This works fine as long as the ItemsSource is not hierarchical (see my other question).

If my Style "cmics" is attached to the ItemContainerStyle of the ContextMenu only (as in my example code) then it looks like this:

The first level works but the others don't. This doesn't change when attaching my Style "cmics" to the ItemContainerStyle of the HierarchicalDataTemplate as well.

If I only attach my Style "cmics" to the HierarchicalDataTemplate then it looks like this:

The first level doesn't show captions and separators, the second level works and the other levels don't work.

So, how can I persuade the ContextMenu to use my Style "cmics" as the ItemContainerStyle for every hierarchy level?


问:
import encrypted private key to jks
I need use ssl(2 way handshake) socket for connection in my project.
So for creating keys, i used openssl with this comands :

for server :

```<code>req -x509 -days 3650 -nodes -newkey rsa:2048 -keyout a_private.key -out a_certificate.cert

rsa -in a_private.key -des3 -out a_private_des.key

rsa -in a_private_des.key -pubout -out a_pub.key
</code>```

for client :

```<code>req -x509 -days 3650 -nodes -newkey rsa:2048 -keyout b_private.key -out b_certificate.cert

rsa -in b_private.key -des3 -out b_private_des.key

rsa -in b_private_des.key -pubout -out b_pub.key
</code>```

for import to jks file i used keytool:

```<code>keytool -import -alias a_private -file a_private_des.key -keystore a.jks

keytool error: java.lang.Exception: Input not an X.509 certificate
</code>```

after that, I made der file with this command :

```<code>pkcs8 -topk8 -in a_private_des.key -out a_private_des.der -outform DER
</code>```

and retry to import key to jks file:

```<code>keytool -import -alias a_private -file a_private_des.der -keystore a.jks

keytool error: java.lang.Exception: Input not an X.509 certificate
</code>```

and I get same exception with b_pub.key

how can I import encrypted private key and public key in jks file ?

tanx alot.

答:
To import a key pair (key and cert) into a java keystore, you first need to create a p12 file. Whilst the question is "import encrypted private key to jks", I don't actually believe the key in question is encrypted as the "nodes" option is used.

So to import a key, and cert into a JKS use:

```<code># create p12
openssl pkcs12 -export \
  -name a_private \
  -out a_private.p12 \
  -inkey a_private.key \
  -in a_certificate.cert \
  -passin "pass:changeit" \
  -passout "pass:changeit"

# create jks
keytool -v -importkeystore -deststoretype pkcs12 -destkeystore \
  "a.jks" \
  -srckeystore "a_private.p12" -srcstoretype pkcs12 \
  -alias "a_private" -srcstorepass "changeit" \
  -deststorepass "changeit" -destkeypass "changeit"
</code>```

Actually change the password "changeit" as well.

Title: import encrypted private key to jks

Body:
I need use ssl(2 way handshake) socket for connection in my project.
So for creating keys, i used openssl with this comands :

for server :

req -x509 -days 3650 -nodes -newkey rsa:2048 -keyout a_private.key -out a_certificate.cert

rsa -in a_private.key -des3 -out a_private_des.key

rsa -in a_private_des.key -pubout -out a_pub.key

for client :

req -x509 -days 3650 -nodes -newkey rsa:2048 -keyout b_private.key -out b_certificate.cert

rsa -in b_private.key -des3 -out b_private_des.key

rsa -in b_private_des.key -pubout -out b_pub.key

for import to jks file i used keytool:

keytool -import -alias a_private -file a_private_des.key -keystore a.jks

keytool error: java.lang.Exception: Input not an X.509 certificate

after that, I made der file with this command :

pkcs8 -topk8 -in a_private_des.key -out a_private_des.der -outform DER

and retry to import key to jks file:

keytool -import -alias a_private -file a_private_des.der -keystore a.jks

keytool error: java.lang.Exception: Input not an X.509 certificate

and I get same exception with b_pub.key

how can I import encrypted private key and public key in jks file ?

tanx alot.

Body:
To import a key pair (key and cert) into a java keystore, you first need to create a p12 file. Whilst the question is "import encrypted private key to jks", I don't actually believe the key in question is encrypted as the "nodes" option is used.

So to import a key, and cert into a JKS use:

# create p12
openssl pkcs12 -export \
  -name a_private \
  -out a_private.p12 \
  -inkey a_private.key \
  -in a_certificate.cert \
  -passin "pass:changeit" \
  -passout "pass:changeit"

# create jks
keytool -v -importkeystore -deststoretype pkcs12 -destkeystore \
  "a.jks" \
  -srckeystore "a_private.p12" -srcstoretype pkcs12 \
  -alias "a_private" -srcstorepass "changeit" \
  -deststorepass "changeit" -destkeypass "changeit"

Actually change the password "changeit" as well.


问:
tag <c:forEach/> si not doing anything
I am trying to show through JSP code the value of some variables stored in in ArrayList money.
I am using Java for this project.
The thing is that when I try to do:

```<code><c:forEach var="pos" items="${yourGame.money}">
    <c:out value="${pos.nombre}"/>
     ${pos.nombre}: <a href="${pos.url}"><b>${pos.precio}</b></a>
<br/>
</c:forEach>
</code>```

It shows nothing, and I have made sure that yourGame.money isn't empty so I don't know what's going on. I am new to JSP and have run out of ideas; could anyone please help me?

This are the structures I am using:

```<code>public class Juego{
    String nombre;
    String plataforma;
    String edicion;
    ArrayList<Precios> money = new ArrayList();
}

public class Precios{
    String precio;
    String url;
    String nombre;
}
</code>```

The JSP class recieves a "Juego" object, and I am trying to print the values of the "money" atribute. I know the class JSP is recieving the "Juego" object fine since I have already printed some other variables of this class such as :

```<code><h3>The ultimate edition: ${yourGame.edicion}</h3>
</code>```

And it works just fine ...enter code here

答: Please modify your variables to use private access and generate get and set methods for all of them. The issue will be resolved.  </p>

Title: tag <c:forEach/> si not doing anything

Body:
I am trying to show through JSP code the value of some variables stored in in ArrayList money.
I am using Java for this project.
The thing is that when I try to do:

<c:forEach var="pos" items="${yourGame.money}">
    <c:out value="${pos.nombre}"/>
     ${pos.nombre}: ${pos.precio}

</c:forEach>

It shows nothing, and I have made sure that yourGame.money isn't empty so I don't know what's going on. I am new to JSP and have run out of ideas; could anyone please help me?

This are the structures I am using:

public class Juego{
    String nombre;
    String plataforma;
    String edicion;
    ArrayList<Precios> money = new ArrayList();
}

public class Precios{
    String precio;
    String url;
    String nombre;
}

The JSP class recieves a "Juego" object, and I am trying to print the values of the "money" atribute. I know the class JSP is recieving the "Juego" object fine since I have already printed some other variables of this class such as :

The ultimate edition: ${yourGame.edicion}

And it works just fine ...enter code here


问:
error while loading shared libraries: libX11.so.6: cannot open shared object file: No such file or directory in linux docker container
I am trying to run my chromedriver selenium tests within my docker image (java).

ChromeDriver - linux 64

Here is my Dockerfile

```<code># Dockerfile
FROM openjdk

ENV MAVEN_VERSION 3.3.9

RUN mkdir -p /usr/share/maven \
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz \
    | tar -xzC /usr/share/maven --strip-components=1 \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven

VOLUME /root/.m2

CMD ["mvn"]
</code>```

After building the image, when i run the docker - i get the error while loading shared libraries: libX11.so.6: cannot open shared object file - though chromedriver is present in the root folder.

答:
For all practical purposes a docker container is a headless server, without an X11-server. Therefore docker images usually does not have the X11 libraries needed for graphical clients to run. </p>

<p>Either install them or use another Docker image which has them. </p>

Body:
I am trying to run my chromedriver selenium tests within my docker image (java).

ChromeDriver - linux 64

Here is my Dockerfile

# Dockerfile
FROM openjdk

ENV MAVEN_VERSION 3.3.9

RUN mkdir -p /usr/share/maven \
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz \
    | tar -xzC /usr/share/maven --strip-components=1 \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven

VOLUME /root/.m2

CMD ["mvn"]

After building the image, when i run the docker - i get the error while loading shared libraries: libX11.so.6: cannot open shared object file - though chromedriver is present in the root folder.

Body:
For all practical purposes a docker container is a headless server, without an X11-server. Therefore docker images usually does not have the X11 libraries needed for graphical clients to run.

Either install them or use another Docker image which has them.


问:
Passing data from CollectionView to DetailVC in Swift 4
My CollectionView should pass a class model to DetailViewController, but when I tap on a cell I get the nil error.

Fatal error: Unexpectedly found nil while implicitly unwrapping an
  Optional value

The CollectionViewController is embedded programmatically on a TabBarController.

Collection View

```<code>
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return soundArray.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SoundCell", for: indexPath) as? SoundCell {
    let SoundClass = soundArray[indexPath.row]
    cell.updateUI(SoundClass: SoundClass)
    return cell

    } else {
    return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "seguetosound", sender: self)

  }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "seguetosound" {
    if let detailVC = segue.destination as? DetailSecondVC
    let sound = sender as? SoundClass {
    detailVC.SoundClass = sound

    }
 }
</code>```

Detail View Controller

```<code>class DetailSecondVC: UIViewController, UIWebViewDelegate {

private var _SoundClass: SoundClass!

var SoundClass: SoundClass {
        get {
            return _SoundClass
        } set {
            _SoundClass = newValue
        }
    }
</code>```

Do you know what I am missing here? I tested the segue with a simple white screen and it works but when I try to pass the data, it fails.

答:
The correct approach is this. First, figure out how you want to trigger the segue. One option is, in didSelect, trigger the segue in code:

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "seguetosound", sender: self)
}
</code>```

But even better, just delete didSelectItemAt completely and have the segue in the storyboard come from the cell. That way the segue is triggered automatically when the user taps the cell.

Then, in prepare, find out what index path was selected, and pull out the data from the model and pass it to the destination view controller (this might not compile, because your variable names are so atrocious that I can't read your code, but it is the correct approach generally):

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "DetailSecondVC" {
        if let detailVC = segue.destination as? DetailSecondVC {
            if let paths = collectionView?.indexPathsForSelectedItems {
                let row = paths[0].row
                detailVC.SoundClass = SoundClasss[row]
            }
        }
    }
}
</code>```

Body:
My CollectionView should pass a class model to DetailViewController, but when I tap on a cell I get the nil error.

Fatal error: Unexpectedly found nil while implicitly unwrapping an
  Optional value

The CollectionViewController is embedded programmatically on a TabBarController.

Collection View

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return soundArray.count
    }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SoundCell", for: indexPath) as? SoundCell {
    let SoundClass = soundArray[indexPath.row]
    cell.updateUI(SoundClass: SoundClass)
    return cell

    } else {
    return UICollectionViewCell()
    }
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    self.performSegue(withIdentifier: "seguetosound", sender: self)

  }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "seguetosound" {
    if let detailVC = segue.destination as? DetailSecondVC
    let sound = sender as? SoundClass {
    detailVC.SoundClass = sound

    }
 }

Detail View Controller

class DetailSecondVC: UIViewController, UIWebViewDelegate {

private var _SoundClass: SoundClass!

var SoundClass: SoundClass {
        get {
            return _SoundClass
        } set {
            _SoundClass = newValue
        }
    }

Do you know what I am missing here? I tested the segue with a simple white screen and it works but when I try to pass the data, it fails.

Body:
The correct approach is this. First, figure out how you want to trigger the segue. One option is, in didSelect, trigger the segue in code:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.performSegue(withIdentifier: "seguetosound", sender: self)
}

But even better, just delete didSelectItemAt completely and have the segue in the storyboard come from the cell. That way the segue is triggered automatically when the user taps the cell.

Then, in prepare, find out what index path was selected, and pull out the data from the model and pass it to the destination view controller (this might not compile, because your variable names are so atrocious that I can't read your code, but it is the correct approach generally):

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "DetailSecondVC" {
        if let detailVC = segue.destination as? DetailSecondVC {
            if let paths = collectionView?.indexPathsForSelectedItems {
                let row = paths[0].row
                detailVC.SoundClass = SoundClasss[row]
            }
        }
    }
}


答:
You can add $counter variable to get the incremented value and assign it to class.

```<code><div class="loca_meta">
    <ul>
       <?php $counter = 0; foreach($metas1 as $meta){
             list($k, $v) = explode('|', $meta);
             echo "<li><span class='bold <?php echo "item_".$counter ?>'>$k</span>:<br>$v</li>";
          $counter++;
        }?>
     </ul>
     </div>
     <div class="loca_meta">
        <ul>
          <?php foreach($metas2 as $meta){
                list($k, $v) = explode('|', $meta);
                 echo "<li><span class='bold <?php echo "item_".$counter ?>'>$k</span>:<br>$v</li>";
           $counter++;
          }?>
        </ul>
     </div>
</code>```

Title: Dynamically give list items <li> a unique class with PHP

Body:
You can add $counter variable to get the incremented value and assign it to class.

<div class="loca_meta">
    <ul>
       <?php $counter = 0; foreach($metas1 as $meta){
             list($k, $v) = explode('|', $meta);
             echo "<li><span class='bold <?php echo "item_".$counter ?>'>$k</span>:<br>$v</li>";
          $counter++;
        }?>
     </ul>
     </div>
     <div class="loca_meta">
        <ul>
          <?php foreach($metas2 as $meta){
                list($k, $v) = explode('|', $meta);
                 echo "<li><span class='bold <?php echo "item_".$counter ?>'>$k</span>:<br>$v</li>";
           $counter++;
          }?>
        </ul>
     </div>


问:
How can I save queries using broadcastreceiver for Android?
I want to save the history of queries made between my application and my database using a broadcastreceiver . How can I do that?</p>

答:
Ignoring the fact that this task is too weird, in order to do that you need to create a custom BroadcastRicever ,

```<code>public class DatabaseRecever extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("database")) {
                   saveLogs();
                }
            }
    }
and
</code>```

and send a sendBroadcast intent every time you communicate with your local database and then in your receiver save the log you want

Body:
Ignoring the fact that this task is too weird, in order to do that you need to create a custom BroadcastRicever ,

public class DatabaseRecever extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals("database")) {
                   saveLogs();
                }
            }
    }
and

and send a sendBroadcast intent every time you communicate with your local database and then in your receiver save the log you want


问:
Implement 'Select All' option in reactive shiny
I'm building a shiny app which displays a table based on user selections. I have a table called 'stat' and it is of the form

```<code>Team      Season   wins  loss  draws
Arsenal   1992-93   18    12    14
Arsenal   1993-94   21    10    7
Liverpool 1992-93   22    6     12
Liverpool 1993-94   19    13    10
 All        All     0     0     0
</code>```

I need to filter the data based on the team and season selected. The table should display all season's data when 'All' is selected for season and vice versa for team.

I had tried some of the code below but it's not working as expected.

```<code>#UI part
selectInput("club", "Select Club", choices = stat$Team),
                 selectInput("season", "Select Season", choices =
 stat$Season)

#server part
server <- output$statdata <- renderTable({
  teamfilter <- subset(stat, (stat$Team == input$club) &
                         (stat$Season==input$season))
})

  observe({
    if("Select All" %in% input$club)
      selected_choices = stat$Team[-1]
    else
      selected_choices = input$club
    updateSelectInput(session, "club", selected = selected_choices)

})
</code>```

Can some suggest me a correct code or tell me if any changes are required to make the code working.

答:
Here's a full-working example showing how one might incorporate "All" into a selectInput:

library(shiny)
dat <- mtcars
app <- shinyApp(
  ui = shinyUI(
    pageWithSidebar(
      headerPanel("Simple Test"),
      sidebarPanel(
        selectInput("cyl", "Cylinders", choices = c("All", sort(unique(dat$cyl)))),
        selectInput("gear", "Gears", choices = c("All", sort(unique(dat$gear))))
      ),
      mainPanel(
        shiny::tableOutput("out")
      )
    )
  ),
  server = function(input, output, session) {
    filtered <- reactive({
      rows <- (input$cyl == "All" | dat$cyl == input$cyl) &
        (input$gear == "All" | dat$gear == input$gear)
      dat[rows,,drop = FALSE]
    })
    output$out <- renderTable(filtered())
  }
)
```

<p>This takes advantage of R's recycling: while <code>input$gear == "All"</code> returns a single logical, <code>dat$gear == input$gear</code> returns a vector as long as the number of rows in the table. Because the first logical is length 1, it is recycled as long as the second vector. This means that <code>input$gear == "All"</code> is effectively a vector of length "nrow(dat)", and is always all <code>TRUE</code> or all <code>FALSE</code>. When true, none of the other <code>$gear</code> comparisons matter (I'm glossing over <code>NA</code> comparisons); when false, the other <code>$gear</code> comparisons are relevant.</p>

<p>Demonstration of recycling:</p>

<pre class="lang-r prettyprint-override"><code>1 == 1
# [1] TRUE
1 == 2
# [1] FALSE

1 == 1:5
# [1]  TRUE FALSE FALSE FALSE FALSE

1 == 1 | 1 == 1:5
# [1] TRUE TRUE TRUE TRUE TRUE
1 == 2 | 1 == 1:5
# [1]  TRUE FALSE FALSE FALSE FALSE
</code>```

Body:
I'm building a shiny app which displays a table based on user selections. I have a table called 'stat' and it is of the form

Team      Season   wins  loss  draws
Arsenal   1992-93   18    12    14
Arsenal   1993-94   21    10    7
Liverpool 1992-93   22    6     12
Liverpool 1993-94   19    13    10
 All        All     0     0     0

I need to filter the data based on the team and season selected. The table should display all season's data when 'All' is selected for season and vice versa for team.

I had tried some of the code below but it's not working as expected.

#UI part
selectInput("club", "Select Club", choices = stat$Team),
                 selectInput("season", "Select Season", choices =
 stat$Season)

#server part
server <- output$statdata <- renderTable({
  teamfilter <- subset(stat, (stat$Team == input$club) &
                         (stat$Season==input$season))
})

  observe({
    if("Select All" %in% input$club)
      selected_choices = stat$Team[-1]
    else
      selected_choices = input$club
    updateSelectInput(session, "club", selected = selected_choices)

})

Can some suggest me a correct code or tell me if any changes are required to make the code working.

Body:
Here's a full-working example showing how one might incorporate "All" into a selectInput:

library(shiny)
dat <- mtcars
app <- shinyApp(
  ui = shinyUI(
    pageWithSidebar(
      headerPanel("Simple Test"),
      sidebarPanel(
        selectInput("cyl", "Cylinders", choices = c("All", sort(unique(dat$cyl)))),
        selectInput("gear", "Gears", choices = c("All", sort(unique(dat$gear))))
      ),
      mainPanel(
        shiny::tableOutput("out")
      )
    )
  ),
  server = function(input, output, session) {
    filtered <- reactive({
      rows <- (input$cyl == "All" | dat$cyl == input$cyl) &
        (input$gear == "All" | dat$gear == input$gear)
      dat[rows,,drop = FALSE]
    })
    output$out <- renderTable(filtered())
  }
)

This takes advantage of R's recycling: while input$gear == "All" returns a single logical, dat$gear == input$gear returns a vector as long as the number of rows in the table. Because the first logical is length 1, it is recycled as long as the second vector. This means that input$gear == "All" is effectively a vector of length "nrow(dat)", and is always all TRUE or all FALSE. When true, none of the other $gear comparisons matter (I'm glossing over NA comparisons); when false, the other $gear comparisons are relevant.

Demonstration of recycling:

1 == 1
# [1] TRUE
1 == 2
# [1] FALSE

1 == 1:5
# [1]  TRUE FALSE FALSE FALSE FALSE

1 == 1 | 1 == 1:5
# [1] TRUE TRUE TRUE TRUE TRUE
1 == 2 | 1 == 1:5
# [1]  TRUE FALSE FALSE FALSE FALSE


问:
How to take a few values in column of a CSV file and export it to an python array
I have an CSV file something like:

```<code>Total Energy                 Pump        Diswasher      Freezer
2015-04-15T13:00:00+0200     70          50             80
2015-04-15T14:00:00+0400     80          40             80
2015-04-15T15:00:00+0300     30          90             80
2015-04-15T16:00:00+0600     40          80             80
2015-04-15T17:00:00+0700     50          70             80
</code>```

I want to take only the first 3 values of each column and export to different Python arrays. But for the total energy, I want to take only the value after "+" sign only.

```<code>The result is expected something like:
Total_energy = [200, 400, 300]
Pump = [70, 80, 30]
Diswasher = [50, 40, 90]
Freezer = [80, 80, 80]
</code>```

I have two issue:
1. Only take the first three values in each column and I do not want to take the whole column.
2. First column(Total Energy) I only need the value after "+" sign

```<code>import pandas
colnames = ['Total_energy', 'Pump', 'Diswasher',]
data = pandas.read_csv('Data_60min.csv', names=colnames)
names = data.name.tolist()
Total_energy = data.Total_energy.tolist()
Pump = data.Pump.tolist()
Diswasher = data.Diswasher.tolist()
</code>```

I can do something like above but it takes for the whole column and also I do not know how to take the value after the "+" sign only.enter image description here

答:
You can get the result you want by using:

```<code>Total_energy = data.loc[:2, "Total Energy"].apply(lambda x: int(x.split("+")[1])).tolist()
Pump = data.loc[:2, "Pump"].tolist()
Diswasher = data.loc[:2, "Diswasher"].tolist()
</code>```

Use loc to select the rows and column you want and split to get the value after the "+" sign for Total Energy.

Body:
I have an CSV file something like:

Total Energy                 Pump        Diswasher      Freezer
2015-04-15T13:00:00+0200     70          50             80
2015-04-15T14:00:00+0400     80          40             80
2015-04-15T15:00:00+0300     30          90             80
2015-04-15T16:00:00+0600     40          80             80
2015-04-15T17:00:00+0700     50          70             80

I want to take only the first 3 values of each column and export to different Python arrays. But for the total energy, I want to take only the value after "+" sign only.

The result is expected something like:
Total_energy = [200, 400, 300]
Pump = [70, 80, 30]
Diswasher = [50, 40, 90]
Freezer = [80, 80, 80]

I have two issue:
1. Only take the first three values in each column and I do not want to take the whole column.
2. First column(Total Energy) I only need the value after "+" sign

import pandas
colnames = ['Total_energy', 'Pump', 'Diswasher',]
data = pandas.read_csv('Data_60min.csv', names=colnames)
names = data.name.tolist()
Total_energy = data.Total_energy.tolist()
Pump = data.Pump.tolist()
Diswasher = data.Diswasher.tolist()

I can do something like above but it takes for the whole column and also I do not know how to take the value after the "+" sign only.enter image description here

Body:
You can get the result you want by using:

Total_energy = data.loc[:2, "Total Energy"].apply(lambda x: int(x.split("+")[1])).tolist()
Pump = data.loc[:2, "Pump"].tolist()
Diswasher = data.loc[:2, "Diswasher"].tolist()

Use loc to select the rows and column you want and split to get the value after the "+" sign for Total Energy.


问:
System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentNullException
I've been getting the error:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentNullException

When I try to call my webservice using the following code:

```<code>{
//Create an echoSync request - set the services.
ServiceNameType sourceService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Source"};
ServiceNameType destService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Destination"};

//Create the request.
SDD2RequestType request = new SDD2RequestType
                  {
                      AppId = "echoSync",
                      SourceService = sourceService,
                      DestService = destService,
                      RequestId = "1",
                      RequestBody = "Ping"
                  };

//Create the originator.
originator originator = new originator {id = "123456789"};

//Create the transport.
SDD2Transport transport = new SDD2Transport {originatorValue = originator};

//Send the request.
SDD2ResponseType response = null;
response = transport.SDD2TransportOp(request);

//Write out the response.
System.Console.WriteLine(response.ResponseBody.ToString());
}
</code>```

My webservice method is quite simple and it looks like this:

```<code>    [System.Web.Services.Protocols.SoapHeaderAttribute("originatorValue", Direction = System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://memberdirect.net/SDD2/Transport", RequestElementName = "SDD2Transport", RequestNamespace = "http://cucbc.com/sdd2/transport/", ResponseElementName = "SDD2TransportResponse", ResponseNamespace = "http://cucbc.com/sdd2/transport/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Default)]
    [return: System.Xml.Serialization.XmlElementAttribute("SDD2Response", Namespace = "http://cucbc.com/sdd2/")]
    public override SDD2ResponseType SDD2TransportOp(SDD2RequestType SDD2Request)
    {
        if (SDD2Request == null) throw new ArgumentNullException("SDD2Request");
        var response = new SDD2ResponseType();

        switch (SDD2Request.AppId)
        {
            case "echoSync":
                response.AppId = SDD2Request.AppId;
                response.ProcessingStatus = ProcessingStatusType.Complete;
                response.RequestId = SDD2Request.RequestId;
                response.ResponseBody = "Pong";
                break;
            default:
                throw new System.NotImplementedException();
                break;
        }

        return response;
    }
</code>```

When I make the call I know the request is not NULL but when it arrives at the webservice it is always received as null.  I generated the webservice from WSDL using the wsdl.exe utility and clearly I don't understand all the details of SOAP that I should.  Has anyone else run into this issue?

答:
I have no idea what causes this so this is not an answer to your question, but only a suggestion for a way to look further into the problem

Try using a sniffer to look at the actual data being sent between the machines and find out on which side the problem is. I've used Wireshark successfully once.

OwnerDisplayName: Daver

Body:
I've been getting the error:

System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.ArgumentNullException

When I try to call my webservice using the following code:

{
//Create an echoSync request - set the services.
ServiceNameType sourceService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Source"};
ServiceNameType destService = new ServiceNameType {Service = "echoSync", OnBehalfOf = "Destination"};

//Create the request.
SDD2RequestType request = new SDD2RequestType
                  {
                      AppId = "echoSync",
                      SourceService = sourceService,
                      DestService = destService,
                      RequestId = "1",
                      RequestBody = "Ping"
                  };

//Create the originator.
originator originator = new originator {id = "123456789"};

//Create the transport.
SDD2Transport transport = new SDD2Transport {originatorValue = originator};

//Send the request.
SDD2ResponseType response = null;
response = transport.SDD2TransportOp(request);

//Write out the response.
System.Console.WriteLine(response.ResponseBody.ToString());
}

My webservice method is quite simple and it looks like this:

    [System.Web.Services.Protocols.SoapHeaderAttribute("originatorValue", Direction = System.Web.Services.Protocols.SoapHeaderDirection.InOut)]
    [System.Web.Services.WebMethodAttribute()]
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://memberdirect.net/SDD2/Transport", RequestElementName = "SDD2Transport", RequestNamespace = "http://cucbc.com/sdd2/transport/", ResponseElementName = "SDD2TransportResponse", ResponseNamespace = "http://cucbc.com/sdd2/transport/", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Default)]
    [return: System.Xml.Serialization.XmlElementAttribute("SDD2Response", Namespace = "http://cucbc.com/sdd2/")]
    public override SDD2ResponseType SDD2TransportOp(SDD2RequestType SDD2Request)
    {
        if (SDD2Request == null) throw new ArgumentNullException("SDD2Request");
        var response = new SDD2ResponseType();

        switch (SDD2Request.AppId)
        {
            case "echoSync":
                response.AppId = SDD2Request.AppId;
                response.ProcessingStatus = ProcessingStatusType.Complete;
                response.RequestId = SDD2Request.RequestId;
                response.ResponseBody = "Pong";
                break;
            default:
                throw new System.NotImplementedException();
                break;
        }

        return response;
    }

When I make the call I know the request is not NULL but when it arrives at the webservice it is always received as null.  I generated the webservice from WSDL using the wsdl.exe utility and clearly I don't understand all the details of SOAP that I should.  Has anyone else run into this issue?

OwnerDisplayName: configurator

ContentLicense: CC BY-SA 2.5


问:
How to reduce Entity Framework 4 query compile time?
Summary: We're having problems with EF4 query compilation times of 12+ seconds. Cached queries will only get us so far; are there any ways we can actually reduce the compilation time? Is there anything we might be doing wrong we can look for? Thanks!

We have an EF4 model which is exposed over the WCF services. For each of our entity types we expose a method to fetch and return the whole entity for display / edit including a number of referenced child objects.

For one particular entity we have to .Include() 31 tables / sub-tables to return all relevant data. Unfortunately this makes the EF query compilation prohibitively slow: it takes 12-15 seconds to compile and builds a 7,800-line, 300K query. This is the back-end of a web UI which will need to be snappier than that.

Is there anything we can do to improve this? We can CompiledQuery.Compile this - that doesn't do any work until first use and so helps the second and subsequent executions but our customer is nervous that the first usage shouldn't be slow either. Similarly if the IIS app pool hosting the web service gets recycled we'll lose the cached plan, although we can increase lifetimes to minimise this. Also I can't see a way to precompile this ahead of time and / or to serialise out the EF compiled query cache (short of reflection tricks). The CompiledQuery object only contains a GUID reference into the cache so it's the cache we really care about. (Writing this out it occurs to me I can kick off something in the background from app_startup to execute all queries to get them compiled - is that safe?)

However even if we do solve that problem, we build up our search queries dynamically with LINQ-to-Entities clauses based on which parameters we're searching on: I don't think the SQL generator does a good enough job that we can move all that logic into the SQL layer so I don't think we can pre-compile our search queries. This is less serious because the search data results use fewer tables and so it's only 3-4 seconds compile not 12-15 but the customer thinks that still won't really be acceptable to end-users.

So we really need to reduce the query compilation time somehow. Any ideas?

Profiling points to ELinqQueryState.GetExecutionPlan as the place to start and I have attempted to step into that but without the real .NET 4 source available I couldn't get very far, and the source generated by Reflector won't let me step into some functions or set breakpoints in them.

The project was upgraded from .NET 3.5 so I have tried regenerating the EDMX from scratch in EF4 in case there was something wrong with it but that didn't help.

I have tried the EFProf utility advertised here but it doesn't look like it would help with this. My large query crashes its data collector anyway.

I have run the generated query through SQL performance tuning and it already has 100% index usage. I can't see anything wrong with the database that would cause the query generator problems.

Is there something O(n^2) in the execution plan compiler - is breaking this down into blocks of separate data loads rather than all 32 tables at once likely to help? Setting EF to lazy-load didn't help.

I've bought the pre-release O'Reilly Julie Lerman EF4 book but I can't find anything in there to help beyond 'compile your queries'.

I don't understand why it's taking 12-15 seconds to generate a single select across 32 tables so I'm optimistic there's some scope for improvement!

Thanks for any suggestions! We're running against SQL Server 2008 in case that matters and XP / 7 / server 2008 R2 using RTM VS2010.

答:
Take a look at nqueries, it uses precompiled queries, that are generated during application startup.

Edit:
Since the switch to EF5, NQueries does no longer support compiled queries as it switched to DbContext, if you still would like to take a look, take the 1.03 release source code, which is still ObjectContext based and supports compiled queries.


问:
Getting letters in a string. Why my code didn't work well?
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

```<code>Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }
</code>```

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

答:
That's how .next() works. It takes string until first space.
This will work for you:

```<code>String a;
while(qx.hasNext){
a = a + qx.next();
}
</code>```

And then continue with your loop.

Body:
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

Body:
That's how .next() works. It takes string until first space.
This will work for you:

String a;
while(qx.hasNext){
a = a + qx.next();
}

And then continue with your loop.


问:
aws s3 boto3 copy()
I am trying to execute the following program and facing this issue

botocore.exceptions.ClientError: An error occurred (404) when calling
  the HeadObject operation: Not Found

```<code>import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'forw',
    'Key': 'test'
}
s3.meta.client.copy(copy_source,Bucket='copybucket0526',Key='tet')
</code>```

答:
Try this code it will work

```<code>import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'source_bucket',
    'Key': 'dirname/subdirname/filename.gz'
}
s3.meta.client.copy(copy_source,Bucket='destination_bucket',Key='somedirname/new_or_same_filename.gz')
</code>```

This is working I guess you are wrong in providing the path, means here you need to provide file complete path

Title: aws s3 boto3 copy()

Body:
I am trying to execute the following program and facing this issue

botocore.exceptions.ClientError: An error occurred (404) when calling
  the HeadObject operation: Not Found

import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'forw',
    'Key': 'test'
}
s3.meta.client.copy(copy_source,Bucket='copybucket0526',Key='tet')

Body:
Try this code it will work

import boto3
s3 = boto3.resource('s3')
copy_source = {
    'Bucket': 'source_bucket',
    'Key': 'dirname/subdirname/filename.gz'
}
s3.meta.client.copy(copy_source,Bucket='destination_bucket',Key='somedirname/new_or_same_filename.gz')

This is working I guess you are wrong in providing the path, means here you need to provide file complete path


问:
How to drop columns in a compressed table?
After compressing a table, it's not possible to drop a column any more:

```<code>CREATE TABLE foo (p NUMBER, i NUMBER, j NUMBER) COMPRESS BASIC;

ALTER TABLE foo DROP COLUMN j;
ORA-39726: unsupported add/drop column operation on compressed tables
</code>```

It is possible if advance compression is used:

```<code>CREATE TABLE foo (p NUMBER, i NUMBER, j NUMBER) COMPRESS FOR OLTP;

ALTER TABLE foo DROP COLUMN j;
Table FOO altered.
</code>```

However, the column is not really dropped, just hidden:

```<code>SELECT column_name, data_type, hidden_column
  FROM user_tab_cols WHERE table_name = 'FOO';

COLUMN_NAME                 DATA_TYPE  HIDDEN_COLUMN
P                           NUMBER     NO
I                           NUMBER     NO
SYS_C00002_18030204:09:26$  NUMBER     YES
</code>```

This causes an error when partitions are exchanged:

```<code>CREATE TABLE par (p NUMBER, i NUMBER)
 PARTITION BY LIST(p)(
 PARTITION p1 VALUES(1),
 PARTITION p2 VALUES(2)
);

ALTER TABLE par EXCHANGE PARTITION p1 WITH TABLE foo;
ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION
</code>```

How can the hidden column be removed? I tried

```<code>ALTER TABLE foo DROP UNUSED COLUMNS;
</code>```

but it doesn't help:

```<code>SELECT column_name, data_type, hidden_column
  FROM user_tab_cols WHERE table_name = 'BAR';

COLUMN_NAME                 DATA_TYPE  HIDDEN_COLUMN
P                           NUMBER     NO
I                           NUMBER     NO
SYS_C00002_18030204:09:26$  NUMBER     YES
</code>```

答:
```<code>update foo set j = null;
commit;
alter table foo set unused column j;
</code>```

Read more

Body:
After compressing a table, it's not possible to drop a column any more:

CREATE TABLE foo (p NUMBER, i NUMBER, j NUMBER) COMPRESS BASIC;

ALTER TABLE foo DROP COLUMN j;
ORA-39726: unsupported add/drop column operation on compressed tables

It is possible if advance compression is used:

CREATE TABLE foo (p NUMBER, i NUMBER, j NUMBER) COMPRESS FOR OLTP;

ALTER TABLE foo DROP COLUMN j;
Table FOO altered.

However, the column is not really dropped, just hidden:

SELECT column_name, data_type, hidden_column
  FROM user_tab_cols WHERE table_name = 'FOO';

COLUMN_NAME                 DATA_TYPE  HIDDEN_COLUMN
P                           NUMBER     NO
I                           NUMBER     NO
SYS_C00002_18030204:09:26$  NUMBER     YES

This causes an error when partitions are exchanged:

CREATE TABLE par (p NUMBER, i NUMBER)
 PARTITION BY LIST(p)(
 PARTITION p1 VALUES(1),
 PARTITION p2 VALUES(2)
);

ALTER TABLE par EXCHANGE PARTITION p1 WITH TABLE foo;
ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE PARTITION

How can the hidden column be removed? I tried

ALTER TABLE foo DROP UNUSED COLUMNS;

but it doesn't help:

SELECT column_name, data_type, hidden_column
  FROM user_tab_cols WHERE table_name = 'BAR';

COLUMN_NAME                 DATA_TYPE  HIDDEN_COLUMN
P                           NUMBER     NO
I                           NUMBER     NO
SYS_C00002_18030204:09:26$  NUMBER     YES

Body:
update foo set j = null;
commit;
alter table foo set unused column j;

Read more


问:
how to clear data of a table before each ajax call
Table data is not cleared after each ajax call. New data is appended below the previous data

$('#show_data').remove();
I have tried this but its not working

View

```<code><table id="example2" class="table table-bordered table-hover">
                        <thead>
                        <tr>
                            <th>Title</th>
                            <th>Description</th>
                            <th>Date</th>
                            <th>Time</th>
                            <th>Action</th>
                        </tr>
                        </thead>
                        <tbody id="show_data">

                        </tbody>
                    </table>
</code>```

Script

```<code><script>
    $(document).ready(function () {

        //Date picker
        $('#datepicker').datepicker({
            autoclose: true,
            format: 'yyyy-mm-dd',
        });

        $("#datepicker").attr("autocomplete", "off");

    $(document).on('submit','#myform',function(){
        event.preventDefault();
        var date = $('#datepicker').val();
        console.log(date);
        $('#show_data').remove();
        $.ajax({
            type:"POST",
            url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
            data:{date:date},
            dataType: "json",
            success:function(data) {
                console.log(data[0].blog_id);
                let i;

                for(i=0;i<data.length;i++){

                    $('#show_data').append('<tr><td>' + data[i].article_name + '</td>' +
                        '<td>' + data[i].description + '</td>' +
                        '<td>' + data[i].date + '</td>' +
                        '<td>' + data[i].time + '</td>' +
                        '</tr>');
                }
            },
            error: function() {
                alert("oops...");
            },

        });
    });
 });

</script>
</code>```

Present Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 1
         Data 2
         Data 3

Expected Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 3

答:
Its because you append your response to previous data. Try this way</p>

```<code>$.ajax({
    type:"POST",
    url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
    data:{date:date},
    dataType: "json",
    success:function(data) {
        console.log(data[0].blog_id);
        let i;

        let html= '';

        for(i=0;i<data.length;i++){

            html += '<tr><td>' + data[i].article_name + '</td>' +
                '<td>' + data[i].description + '</td>' +
                '<td>' + data[i].date + '</td>' +
                '<td>' + data[i].time + '</td>' +
                '</tr>');
        }

        $('#show_data').html(html);
    },
    error: function() {
        alert("oops...");
    },

});
</code>```

Body:
Table data is not cleared after each ajax call. New data is appended below the previous data

$('#show_data').remove();
I have tried this but its not working

View

                            Title
                            Description
                            Date
                            Time
                            Action

Script

Present Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 1
         Data 2
         Data 3

Expected Output

Input-> 2019-05-25 -> Submit

Output-> Data 1
         Data 2

Input-> 2019-05-24 -> Submit

Output-> Data 3

Body:
Its because you append your response to previous data. Try this way

$.ajax({
    type:"POST",
    url:"<?php echo base_url().'admin/Dashboard/get_blog'; ?>",
    data:{date:date},
    dataType: "json",
    success:function(data) {
        console.log(data[0].blog_id);
        let i;

        let html= '';

        for(i=0;i<data.length;i++){

            html += '<tr><td>' + data[i].article_name + '</td>' +
                '<td>' + data[i].description + '</td>' +
                '<td>' + data[i].date + '</td>' +
                '<td>' + data[i].time + '</td>' +
                '</tr>');
        }

        $('#show_data').html(html);
    },
    error: function() {
        alert("oops...");
    },

});


问:
MVC and EF 5 scaffolding project giving HTTP Error 400.0 - Bad Request
I have created an MVC and EF5 scaffolding project. All the views for all tables are working except for one where it shows the index and list all entries and I am able to create new records as well but when I click on edit, details, or delete links it shows error page saying

HTTP Error 400.0 - Bad Request Bad Request

and below that

Most likely causes:

has nothing but a dot point in it.

I am new to this and dont know what I can do to make it work just like other pages. I did not do any programming and everything else is working fine.

The error comes on localhost as well as on remote server where I uploaded this.

EDIT:
Upon further investigation I found that index view has the following lines at the end, which clearly says that there is no ID being passed to the controller. Not sure what does it mean by commenting the ID part and what will go in there. My table has a composite primary key (made up of two foreign keys.

```<code>    @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */}) |
    @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
    @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</code>```

答:
Please check your Primary Key Attribute in your database. Make sure it has one primary key attribute.

If it's missing, add it and try to regenerate the scaffolding items.

Body:
I have created an MVC and EF5 scaffolding project. All the views for all tables are working except for one where it shows the index and list all entries and I am able to create new records as well but when I click on edit, details, or delete links it shows error page saying

HTTP Error 400.0 - Bad Request Bad Request

and below that

Most likely causes:

has nothing but a dot point in it.

I am new to this and dont know what I can do to make it work just like other pages. I did not do any programming and everything else is working fine.

The error comes on localhost as well as on remote server where I uploaded this.

EDIT:
Upon further investigation I found that index view has the following lines at the end, which clearly says that there is no ID being passed to the controller. Not sure what does it mean by commenting the ID part and what will go in there. My table has a composite primary key (made up of two foreign keys.

    @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */}) |
    @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
    @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })


问:
Codeigniter & HMVC Callback shows first
On my codeigniter Version 3.1.4 / hmvc login if the form validation password input is empty for some reason the callback function shows first rather than the required message?

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

As shown on message it should show the password required message first rather than callback

Question how can I make sure it shows the correct validation messages
  first.

Autoloaded form_validation

```<code>$autoload['libraries'] = array('database', 'form_validation');
</code>```

Controller

```<code><?php

class Login extends MX_Controller {

    public $CI;

    public function __construct() {
        parent::__construct();
        $this->load->model('catalog/user/user_model');

        $this->form_validation->CI =& $this;
    }

    public function index() {
        $data['type'] = $this->input->post('type');
        $data['password'] = $this->input->post('password');

        $this->form_validation->set_rules('type', 'Username Or Email', 'trim|required');
        $this->form_validation->set_rules('password', 'password', 'required|callback_validatePassword[password]');

        if ($this->form_validation->run() == false) {

            $data['header'] = Modules::run('catalog/common/header/index');
            $data['footer'] = Modules::run('catalog/common/footer/index');

            $this->load->view('template/account/login', $data);

        } else {

            $user_info = $this->user_model->get_user($user_id = '', $this->input->post('type', true));

            if ($user_info) {

                $remember = $this->input->post('remember') ? TRUE : FALSE;

                $this->user->login($user_info['user_id'], $remember);

                redirect(base_url("users") .'/'. $user_info['user_id'] .'/'. $user_info['username']);
            }
        }
    }

    public function validatePassword($str) {
        if ($this->user_model->validate_password($str, $this->input->post('type',  true))) {
            return TRUE;
        } else {
            $this->form_validation->set_message('validatePassword', 'Opp\'s somthing wrong with login!');
            return FALSE;
        }
    }
}
</code>```

application > libraries >  MY_Form_validation.php

```<code><?php

class MY_Form_validation extends CI_Form_validation {

    public $CI;

}
</code>```

答:
Instead of this -

```<code>$this->form_validation->set_rules('password', 'password', 'required|callback_validatePassword[password]');
</code>```

kindly use the callback function like this -

```<code>$this->form_validation->set_rules('password', 'password', 'required', 'callback_validatePassword');
</code>```

Title: Codeigniter & HMVC Callback shows first

Body:
On my codeigniter Version 3.1.4 / hmvc login if the form validation password input is empty for some reason the callback function shows first rather than the required message?

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc

As shown on message it should show the password required message first rather than callback

Question how can I make sure it shows the correct validation messages
  first.

Autoloaded form_validation

$autoload['libraries'] = array('database', 'form_validation');

Controller

<?php

class Login extends MX_Controller {

    public $CI;

    public function __construct() {
        parent::__construct();
        $this->load->model('catalog/user/user_model');

        $this->form_validation->CI =& $this;
    }

    public function index() {
        $data['type'] = $this->input->post('type');
        $data['password'] = $this->input->post('password');

        $this->form_validation->set_rules('type', 'Username Or Email', 'trim|required');
        $this->form_validation->set_rules('password', 'password', 'required|callback_validatePassword[password]');

        if ($this->form_validation->run() == false) {

            $data['header'] = Modules::run('catalog/common/header/index');
            $data['footer'] = Modules::run('catalog/common/footer/index');

            $this->load->view('template/account/login', $data);

        } else {

            $user_info = $this->user_model->get_user($user_id = '', $this->input->post('type', true));

            if ($user_info) {

                $remember = $this->input->post('remember') ? TRUE : FALSE;

                $this->user->login($user_info['user_id'], $remember);

                redirect(base_url("users") .'/'. $user_info['user_id'] .'/'. $user_info['username']);
            }
        }
    }

    public function validatePassword($str) {
        if ($this->user_model->validate_password($str, $this->input->post('type',  true))) {
            return TRUE;
        } else {
            $this->form_validation->set_message('validatePassword', 'Opp\'s somthing wrong with login!');
            return FALSE;
        }
    }
}

application > libraries >  MY_Form_validation.php

<?php

class MY_Form_validation extends CI_Form_validation {

    public $CI;

}

Body:
Instead of this -

$this->form_validation->set_rules('password', 'password', 'required|callback_validatePassword[password]');

kindly use the callback function like this -

$this->form_validation->set_rules('password', 'password', 'required', 'callback_validatePassword');


问:
How to play video in HTML page
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

```<code><video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>
</code>```

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

```<code><video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>
</code>```

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

答:
you need to put an alternative text like this to check of your browser or smartphone supports video autoplay.

like this:

```<code><video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

```
```

Title: How to play video in HTML page

Body:
I am trying to play a mp4 video on my HTML page, I have searched the web and found that in HTML5 I can do this with video tag like this below

<video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
</video>

Issue I am facing

My main issue is my video is stored in my local computer in some location, So how can I call that from that path

In my system it is located in D drive so I want to call it from there

I am new to this so I don't know if I am doing it the right way; is my approach correct?

My requirement is to auto-play video on my web page

I am doing like this

<video width="320" height="240" autoplay>
  <source src="D:\Video\samplevideo.mp4" type="video/mp4">
</video>

D:\Video\samplevideo.mp4 is the path of my file and samplevideo.mp4 is the name of the video

On Chrome it show error Not allowed to load local resource: file:///D:/Video/samplevideo.mp4

And on Firefox All candidate resources failed to load. Media load paused.

Edit

My main focus is to play video on webpage.

I need to play a video on the web (HTML page) when page is loaded I have that video in my system at D:\Video\samplevideo.mp4 this path, how can I play that video when page is loaded.

Body:
you need to put an alternative text like this to check of your browser or smartphone supports video autoplay.

like this:

<video width="320" height="240" autoplay>
  <source src="movie.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

```


问:
Mac bash split cannot split by line-bytes
I'd like to split a file by bytes while maintaining full lines via

```<code>split -C <bytes> filename
</code>```

However, the default split doesn't accept -C

```<code>split: illegal option -- C
usage: split [-a sufflen] [-b byte_count] [-l line_count] [-p pattern]
             [file [prefix]]
</code>```

I've brew install coreutils, which looks like it should support what I want.

How do I change split to use coreutils?

答:
Please go to the path of the file and execute the following command
split -b 500m  inputFile output_files.split.txt

Example

split -b 500m  sample.txt output_files.split.txt

Body:
I'd like to split a file by bytes while maintaining full lines via

split -C <bytes> filename

However, the default split doesn't accept -C

split: illegal option -- C
usage: split [-a sufflen] [-b byte_count] [-l line_count] [-p pattern]
             [file [prefix]]

I've brew install coreutils, which looks like it should support what I want.

How do I change split to use coreutils?


问:
Get website's contents from a list of URLs in a text-file
I have a list of URLs in a text file as below:

File URL.txt

```<code>https://url2.html
https://url3.html
...
https://urln.html
</code>```

I want to get content of those URLs into a text file line by line as shown below

Expected file Content.txt:

```<code>Content of web from url2.html
Content of web from url3.html
...
Content of web from urln.html
</code>```

Please help me to find a solution for my problem, can I use Python or Java code for this.

Thank you for consideration!

答:
You can try out the follwing python script.</p>

```<code>import requests
filepath = 'url.txt'
cnt=0
f= open("content.txt","w+")
with open(filepath) as fp:
    for line in fp
        file_url = fp.readline()
        cnt = cnt+1
        f.write("Content of web from url%d.html\n ",cnt)
        r = requests.get(file_url)
        f.write(r.content)
</code>```

Body:
I have a list of URLs in a text file as below:

File URL.txt

https://url2.html
https://url3.html
...
https://urln.html

I want to get content of those URLs into a text file line by line as shown below

Expected file Content.txt:

Content of web from url2.html
Content of web from url3.html
...
Content of web from urln.html

Please help me to find a solution for my problem, can I use Python or Java code for this.

Thank you for consideration!

Body:
You can try out the follwing python script.

import requests
filepath = 'url.txt'
cnt=0
f= open("content.txt","w+")
with open(filepath) as fp:
    for line in fp
        file_url = fp.readline()
        cnt = cnt+1
        f.write("Content of web from url%d.html\n ",cnt)
        r = requests.get(file_url)
        f.write(r.content)


问:
replace single slash with double slash, php
how replace single slash with double slash?
I have this text:

```<code>"/data/folder/"

 and i need get

"//data//folder//"
</code>```

i try with replace, but get error:

```<code>$data = str_replace("\", "\\", $data);
</code>```

答:
You're talking about backslashes or normal slashes ? anyway check the code below for both of them :</p>

```<code>$str = '\dada\dsadsa';
var_dump(str_replace('\\', '\\\\', $str));
$str = '/dada/dadda';
var_dump(str_replace('/', '//', $str));
</code>```

Body:
how replace single slash with double slash?
I have this text:

"/data/folder/"

 and i need get

"//data//folder//"

i try with replace, but get error:

$data = str_replace("\", "\\", $data);

Body:
You're talking about backslashes or normal slashes ? anyway check the code below for both of them :

$str = '\dada\dsadsa';
var_dump(str_replace('\\', '\\\\', $str));
$str = '/dada/dadda';
var_dump(str_replace('/', '//', $str));