问:
accessing reactiveValues in a reactiveValuesToList
Instead of specifying separate fileInput variables, I'd like to use reactiveValues to store uploaded CSV dataframes, manipulate them in some way, and then store them for accession later. My design is to name each dataframe by its filename and append to the reactiveValue rvTL. My questions are,

How can I access individual dataframes under the list I created using reactiveValuesToList(rvTL)?

Next step, how to create a selectInput menu to access the individual dataframes uploaded by fileInput

To learn this concept, I am piggybacking off the answer from Dean Attali and made rvTL the same as his values variable.
R shiny: How to get an reactive data frame updated each time pressing an actionButton without creating a new reactive data frame?

I've gone over many example codes on reactiveValues, yet still at an incomplete understanding. Most examples are using some sort variation on reactiveValuesToList(input) R Shiny: Keep/retain values of reactive inputs after modifying selection, I'm really not seeing the logic here. Any help/suggestions would be appreciated!

```<code>library(shiny)
runApp(shinyApp(
  ui=(fluidPage(
    titlePanel("amend data frame"),

    mainPanel(
      fileInput("file", "Upload file", multiple=T),
      tabsetPanel(type="tabs",
          tabPanel("tab1",
                    numericInput("Delete", "Delete row:", 1, step = 1),
                    actionButton("Go", "Delete!"),
                    verbatimTextOutput("df_data_files"),
                    verbatimTextOutput("values"),
                    verbatimTextOutput("rvTL"),
                   tableOutput("rvTL_out")
          ),
          tabPanel("tab2",
                  tableOutput("df_data_out")
          )
    )))),

  server = (function(input, output) {
    values <- reactiveValues(df_data = NULL) ##reactiveValues
    rvTL <- reactiveValues(rvTL = NULL)

    observeEvent(input$file, {
      values$df_data <- read.csv(input$file$datapath)
      rvTL[[input$file$name]] <- c(isolate(rvTL), read.csv(input$file$datapath))
    })

    observeEvent(input$Go, {
      temp <- values$df_data[-input$Delete, ]
      values$df_data <- temp
    })

    output$df_data_files <- renderPrint(input$file$name)
    output$values <- renderPrint(names(values))
    output$rvTL <- renderPrint(names(reactiveValuesToList(rvTL))[1] )
    output$rvTL_out <- renderTable(reactiveValuesToList(rvTL)[[1]])
    output$df_data_out <- renderTable(values$df_data)

    })
  ))
</code>```

答:
It really is as straightforward as you thought. You were close too, just fell into some syntax traps. I made the following changes:

that c(isolate(.. call was messing things up, I got rid of it. It was leading to those "Warning: Error in as.data.frame.default: cannot coerce class "c("ReactiveValues", "R6")" to a data.frame" errors.

Also you were reusing the rvTL name too often which is confusing and can lead to conflicts, so I renamed a couple of them.

I also added a loaded file name list (lfnamelist) to keep track of what was loaded. I could have used names(rvTL$dflist) for this but it didn't occur to me at the time  - and I also this is a useful example of how to organize related reactive values into one declaration.

And then I added rendered selectInput so you can inspect what is saved in the reactiveValue list.

So here is the adjusted code:

```<code>library(shiny)
runApp(shinyApp(
  ui=(fluidPage(
    titlePanel("amend data frame"),

    mainPanel(
      fileInput("file", "Upload file", multiple=T),
      tabsetPanel(type="tabs",
                  tabPanel("rvTL tab",
                           numericInput("Delete", "Delete row:", 1, step = 1),
                           uiOutput("filesloaded"),
                           actionButton("Go", "Delete!"),
                           verbatimTextOutput("df_data_files"),
                           verbatimTextOutput("values"),
                           verbatimTextOutput("rvTL_names"),
                           tableOutput("rvTL_out")
                  ),
                  tabPanel("values tab",
                           tableOutput("df_data_out")
                  )
      )))),

  server = (function(input, output) {
    values <- reactiveValues(df_data = NULL) ##reactiveValues
    rvTL <- reactiveValues(dflist=NULL,lfnamelist=NULL)

    observeEvent(input$file, {
      req(input$file)
      values$df_data <- read.csv(input$file$datapath)
      rvTL$dflist[[input$file$name]] <-read.csv(input$file$datapath)
      rvTL$lfnamelist <- c( rvTL$lfnamelist, input$file$name )
    })

    observeEvent(input$Go, {
      temp <- values$df_data[-input$Delete, ]
      values$df_data <- temp
    })

    output$df_data_files <- renderPrint(input$file$name)
    output$values <- renderPrint(names(values))
    output$rvTL_names <- renderPrint(names(rvTL$dflist))
    output$rvTL_out <- renderTable(rvTL$dflist[[input$lftoshow]])
    output$df_data_out <- renderTable(values$df_data)
    output$filesloaded <- renderUI(selectInput("lftoshow","File to show",choices=rvTL$lfnamelist))

  })
))
</code>```

And here is a screen shot:

Body:
Instead of specifying separate fileInput variables, I'd like to use reactiveValues to store uploaded CSV dataframes, manipulate them in some way, and then store them for accession later. My design is to name each dataframe by its filename and append to the reactiveValue rvTL. My questions are,

How can I access individual dataframes under the list I created using reactiveValuesToList(rvTL)?

Next step, how to create a selectInput menu to access the individual dataframes uploaded by fileInput

To learn this concept, I am piggybacking off the answer from Dean Attali and made rvTL the same as his values variable.
R shiny: How to get an reactive data frame updated each time pressing an actionButton without creating a new reactive data frame?

I've gone over many example codes on reactiveValues, yet still at an incomplete understanding. Most examples are using some sort variation on reactiveValuesToList(input) R Shiny: Keep/retain values of reactive inputs after modifying selection, I'm really not seeing the logic here. Any help/suggestions would be appreciated!

library(shiny)
runApp(shinyApp(
  ui=(fluidPage(
    titlePanel("amend data frame"),

    mainPanel(
      fileInput("file", "Upload file", multiple=T),
      tabsetPanel(type="tabs",
          tabPanel("tab1",
                    numericInput("Delete", "Delete row:", 1, step = 1),
                    actionButton("Go", "Delete!"),
                    verbatimTextOutput("df_data_files"),
                    verbatimTextOutput("values"),
                    verbatimTextOutput("rvTL"),
                   tableOutput("rvTL_out")
          ),
          tabPanel("tab2",
                  tableOutput("df_data_out")
          )
    )))),

  server = (function(input, output) {
    values <- reactiveValues(df_data = NULL) ##reactiveValues
    rvTL <- reactiveValues(rvTL = NULL)

    observeEvent(input$file, {
      values$df_data <- read.csv(input$file$datapath)
      rvTL[[input$file$name]] <- c(isolate(rvTL), read.csv(input$file$datapath))
    })

    observeEvent(input$Go, {
      temp <- values$df_data[-input$Delete, ]
      values$df_data <- temp
    })

    output$df_data_files <- renderPrint(input$file$name)
    output$values <- renderPrint(names(values))
    output$rvTL <- renderPrint(names(reactiveValuesToList(rvTL))[1] )
    output$rvTL_out <- renderTable(reactiveValuesToList(rvTL)[[1]])
    output$df_data_out <- renderTable(values$df_data)

    })
  ))

Body:
It really is as straightforward as you thought. You were close too, just fell into some syntax traps. I made the following changes:

that c(isolate(.. call was messing things up, I got rid of it. It was leading to those "Warning: Error in as.data.frame.default: cannot coerce class "c("ReactiveValues", "R6")" to a data.frame" errors.

Also you were reusing the rvTL name too often which is confusing and can lead to conflicts, so I renamed a couple of them.

I also added a loaded file name list (lfnamelist) to keep track of what was loaded. I could have used names(rvTL$dflist) for this but it didn't occur to me at the time  - and I also this is a useful example of how to organize related reactive values into one declaration.

And then I added rendered selectInput so you can inspect what is saved in the reactiveValue list.

So here is the adjusted code:

library(shiny)
runApp(shinyApp(
  ui=(fluidPage(
    titlePanel("amend data frame"),

    mainPanel(
      fileInput("file", "Upload file", multiple=T),
      tabsetPanel(type="tabs",
                  tabPanel("rvTL tab",
                           numericInput("Delete", "Delete row:", 1, step = 1),
                           uiOutput("filesloaded"),
                           actionButton("Go", "Delete!"),
                           verbatimTextOutput("df_data_files"),
                           verbatimTextOutput("values"),
                           verbatimTextOutput("rvTL_names"),
                           tableOutput("rvTL_out")
                  ),
                  tabPanel("values tab",
                           tableOutput("df_data_out")
                  )
      )))),

  server = (function(input, output) {
    values <- reactiveValues(df_data = NULL) ##reactiveValues
    rvTL <- reactiveValues(dflist=NULL,lfnamelist=NULL)

    observeEvent(input$file, {
      req(input$file)
      values$df_data <- read.csv(input$file$datapath)
      rvTL$dflist[[input$file$name]] <-read.csv(input$file$datapath)
      rvTL$lfnamelist <- c( rvTL$lfnamelist, input$file$name )
    })

    observeEvent(input$Go, {
      temp <- values$df_data[-input$Delete, ]
      values$df_data <- temp
    })

    output$df_data_files <- renderPrint(input$file$name)
    output$values <- renderPrint(names(values))
    output$rvTL_names <- renderPrint(names(rvTL$dflist))
    output$rvTL_out <- renderTable(rvTL$dflist[[input$lftoshow]])
    output$df_data_out <- renderTable(values$df_data)
    output$filesloaded <- renderUI(selectInput("lftoshow","File to show",choices=rvTL$lfnamelist))

  })
))

And here is a screen shot:


来源: stackexchange

问:
Visual Studio adding DLL as reference error
I'm adding a library to a project, and I get the following error:

Mixed mode assembly is built against
  version 'v2.0.50727' of the runtime
  and cannot be loaded in the 4.0
  runtime without additional
  configuration information.

I'm not too sure about what I have to tweak in order fro this to run. Anyone know what the changes should be?

Thanks,

PM

答:
I agree that stackoverflow is amazing, but google still does have a place in the world...

From copying and pasting your error into google:
http://social.msdn.microsoft.com/Forums/en/clr/thread/58271e39-beca-49ac-90f9-e116fa3dd3c0

Good luck.

ContentLicense: CC BY-SA 2.5


问:
Webpack - url-loader cannot resolve jpg
I have two folders in root directory of project - build and src. I would like to move images from src folder to build folder. However i'm getting error "Cannot resolve 'file'" despite i've included the url-loader plugin.

header.jsx

```<code>import {React, ReactDOM} from '../../build/react';

export default class Header extends React.Component {

  render() {
    return (
        <div className="header">
        <img className="logo" src={require("../src/content/images/program-brand-logo.jpg")} />
        </div>
      );
    }
  };
</code>```

Error log:

```<code>ERROR in ./src/components/header.jsx
Module not found: Error: Cannot resolve 'file' or 'directory' ../src/content/images/program-brand-logo.jpg in /Users/username/Desktop/Projects/Demo/Scorecard/SPA/React (Working Copy)/src/components
 @ ./src/components/header.jsx 45:68-123
</code>```

Webpack.config.js

```<code>var webpack = require('webpack');
var path = require('path');
require("babel-polyfill");

var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src');

module.exports = {
  entry: [
    // Set up an ES6-ish environment
    'babel-polyfill',
    'bootstrap-loader',
    'webpack/hot/dev-server',
    APP_DIR + '/import.js',
  ],
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel',

      exclude: /node_modules/,
      query: {
        plugins: ['transform-runtime'],
        presets: ['es2015', 'stage-0', 'react']
      }
    }, {
      test: /\.css$/,
      loader: "style-loader!css-loader"
    }, {
      test: /\.scss$/,
      loaders: ["style", "css", "sass"]
    }, {
      test: /\.(png|woff|woff2|eot|ttf|svg|jpg|gif)$/,
      loader: 'url-loader?limit=100000'
    }]
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
};
</code>```

答: Make sure this path ../src/content/images/program-brand-logo.jpg is relative to header.jsx file

ContentLicense: CC BY-SA 3.0

Title: Webpack - url-loader cannot resolve jpg

Body:
I have two folders in root directory of project - build and src. I would like to move images from src folder to build folder. However i'm getting error "Cannot resolve 'file'" despite i've included the url-loader plugin.

header.jsx

import {React, ReactDOM} from '../../build/react';

export default class Header extends React.Component {

  render() {
    return (

      );
    }
  };

Error log:

ERROR in ./src/components/header.jsx
Module not found: Error: Cannot resolve 'file' or 'directory' ../src/content/images/program-brand-logo.jpg in /Users/username/Desktop/Projects/Demo/Scorecard/SPA/React (Working Copy)/src/components
 @ ./src/components/header.jsx 45:68-123

Webpack.config.js

var webpack = require('webpack');
var path = require('path');
require("babel-polyfill");

var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'src');

module.exports = {
  entry: [
    // Set up an ES6-ish environment
    'babel-polyfill',
    'bootstrap-loader',
    'webpack/hot/dev-server',
    APP_DIR + '/import.js',
  ],
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  module: {
    loaders: [{
      test: /\.jsx?$/,
      loader: 'babel',

      exclude: /node_modules/,
      query: {
        plugins: ['transform-runtime'],
        presets: ['es2015', 'stage-0', 'react']
      }
    }, {
      test: /\.css$/,
      loader: "style-loader!css-loader"
    }, {
      test: /\.scss$/,
      loaders: ["style", "css", "sass"]
    }, {
      test: /\.(png|woff|woff2|eot|ttf|svg|jpg|gif)$/,
      loader: 'url-loader?limit=100000'
    }]
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
};


问:
Keep sap.m.MultiComboBox permanently open even after selecting an option
Is it possible to keep sap.m.MultiComboBox open by disabling the drop down toggle upon selecting a checkbox option or any other way of achieving the same.</p>

答:
The MultiComboBox is design to close if the on of the items is clicked. If you check one of the checkboxes it will remain open and just a selection will be triggered.

You can also try to modify the autoclose with something like:

```<code>oMultiComboBox.getPicker().oPopup.setAutoClose(false)
</code>```

But this is not a public API so it is not recommended

Body:
The MultiComboBox is design to close if the on of the items is clicked. If you check one of the checkboxes it will remain open and just a selection will be triggered.

You can also try to modify the autoclose with something like:

oMultiComboBox.getPicker().oPopup.setAutoClose(false)

But this is not a public API so it is not recommended


问:
Perl array vs list
I have two data structures in Perl:

An array:

```<code>my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}
</code>```

Giving me the following output:

```<code>1
2
3
</code>```

And a list:

```<code>my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}
</code>```

Giving the following output:

```<code>ARRAY(0x9c90818)
</code>```

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

答:
@array = ("1","2","3");
Here 1,2,3 is the element of @array variable. For ex. $array[0] is 1 , $array[1] is 2 and $array[2] is 3.

@array = ["1","2","3"];
Perl uses anonymous array references using [ ], so here basically only one element that you are storing, and that is the reference of an array ["1","2","3"] to the @array variable. for ex $array[0] is "ARRAY(0x9c90818)"

Hence while printing it is showing you the references.

Title: Perl array vs list

Body:
I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

Giving me the following output:

1
2
3

And a list:

my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}

Giving the following output:

ARRAY(0x9c90818)

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?


问:
How to add GMSMapView in Storyboard in IOS
https://developers.google.com/maps/documentation/ios-sdk/utility/marker-clustering

I am working for map clustering . In map clustering

```<code>private var mapView: GMSMapView!
</code>```

is used for mapView but couldn't find any  GMSMapView! in storyboard connection .

From Storyboard i found

```<code> @IBOutlet var mapView: MKMapView!
</code>```

that makes the problem . when i used exampled google map it throws error

this class is not key value coding-compliant for the key mapView.'

Here the complete code :

```<code>import UIKit
import MapKit
import GooglePlaces
import GoogleMaps

// Point of Interest Item which implements the GMUClusterItem protocol.
class POIItem: NSObject, GMUClusterItem {
    var position: CLLocationCoordinate2D
    var name: String!

    init(position: CLLocationCoordinate2D, name: String) {
        self.position = position
        self.name = name
    }
}

let kClusterItemCount = 10000
let kCameraLatitude = -33.8
let kCameraLongitude = 151.2

class FirstViewController: UIViewController , GMUClusterManagerDelegate,
GMSMapViewDelegate {

   // @IBOutlet var mapView: MKMapView!

    private var mapView: GMSMapView!

     private var clusterManager: GMUClusterManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set up the cluster manager with the supplied icon generator and
        // renderer.

        // Set up the cluster manager with default icon generator and renderer.
        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
        clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)

        // Generate and add random items to the cluster manager.
        generateClusterItems()

        // Call cluster() after items have been added to perform the clustering and rendering on map.
        clusterManager.cluster()

        // Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
        clusterManager.setDelegate(self, mapDelegate: self)

    }

//    override func loadView() {
//
//        // Create a GMSCameraPosition that tells the map to display the
//        // coordinate -33.86,151.20 at zoom level 6.
//        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
//        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
//        view = mapView
//
//        // Creates a marker in the center of the map.
//        let marker = GMSMarker()
//        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
//        marker.title = "Sydney"
//        marker.snippet = "Australia"
//        marker.map = mapView
//
//    }
//

    // MARK: - GMUClusterManagerDelegate
    func clusterManager(clusterManager: GMUClusterManager, didTapCluster cluster: GMUCluster) {
        let newCamera = GMSCameraPosition.camera(withTarget: cluster.position,
                                                           zoom: mapView.camera.zoom + 1)
        let update = GMSCameraUpdate.setCamera(newCamera)
        mapView.moveCamera(update)
    }

    // MARK: - GMUMapViewDelegate
    func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
        if let poiItem = marker.userData as? POIItem {
            NSLog("Did tap marker for cluster item \(poiItem.name)")
        } else {
            NSLog("Did tap a normal marker")
        }
        return false
    }

    // MARK: - Private
    /// Randomly generates cluster items within some extent of the camera and adds them to the
    /// cluster manager.
    private func generateClusterItems() {
        let extent = 0.2
        for index in 1...kClusterItemCount {
            let lat = kCameraLatitude + extent * randomScale()
            let lng = kCameraLongitude + extent * randomScale()
            let name = "Item \(index)"
            let item = POIItem(position: CLLocationCoordinate2DMake(lat, lng), name: name)
            clusterManager.add(item)
        }
    }

    /// Returns a random value between -1.0 and 1.0.
    private func randomScale() -> Double {
        return Double(arc4random()) / Double(UINT32_MAX) * 2.0 - 1.0
    }
}
</code>```

答:
First Take UIView:

Add UIView In UIViewController:

Assign class GMSMap View

And Now create outlet of GMSMapView.

```<code>@IBOutlet var mapView: GMSMapView!
</code>```

Body:
https://developers.google.com/maps/documentation/ios-sdk/utility/marker-clustering

I am working for map clustering . In map clustering

private var mapView: GMSMapView!

is used for mapView but couldn't find any  GMSMapView! in storyboard connection .

From Storyboard i found

 @IBOutlet var mapView: MKMapView!

that makes the problem . when i used exampled google map it throws error

this class is not key value coding-compliant for the key mapView.'

Here the complete code :

import UIKit
import MapKit
import GooglePlaces
import GoogleMaps

// Point of Interest Item which implements the GMUClusterItem protocol.
class POIItem: NSObject, GMUClusterItem {
    var position: CLLocationCoordinate2D
    var name: String!

    init(position: CLLocationCoordinate2D, name: String) {
        self.position = position
        self.name = name
    }
}

let kClusterItemCount = 10000
let kCameraLatitude = -33.8
let kCameraLongitude = 151.2

class FirstViewController: UIViewController , GMUClusterManagerDelegate,
GMSMapViewDelegate {

   // @IBOutlet var mapView: MKMapView!

    private var mapView: GMSMapView!

     private var clusterManager: GMUClusterManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set up the cluster manager with the supplied icon generator and
        // renderer.

        // Set up the cluster manager with default icon generator and renderer.
        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
        clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)

        // Generate and add random items to the cluster manager.
        generateClusterItems()

        // Call cluster() after items have been added to perform the clustering and rendering on map.
        clusterManager.cluster()

        // Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
        clusterManager.setDelegate(self, mapDelegate: self)

    }

//    override func loadView() {
//
//        // Create a GMSCameraPosition that tells the map to display the
//        // coordinate -33.86,151.20 at zoom level 6.
//        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
//        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
//        view = mapView
//
//        // Creates a marker in the center of the map.
//        let marker = GMSMarker()
//        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
//        marker.title = "Sydney"
//        marker.snippet = "Australia"
//        marker.map = mapView
//
//    }
//

    // MARK: - GMUClusterManagerDelegate
    func clusterManager(clusterManager: GMUClusterManager, didTapCluster cluster: GMUCluster) {
        let newCamera = GMSCameraPosition.camera(withTarget: cluster.position,
                                                           zoom: mapView.camera.zoom + 1)
        let update = GMSCameraUpdate.setCamera(newCamera)
        mapView.moveCamera(update)
    }

    // MARK: - GMUMapViewDelegate
    func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
        if let poiItem = marker.userData as? POIItem {
            NSLog("Did tap marker for cluster item \(poiItem.name)")
        } else {
            NSLog("Did tap a normal marker")
        }
        return false
    }

    // MARK: - Private
    /// Randomly generates cluster items within some extent of the camera and adds them to the
    /// cluster manager.
    private func generateClusterItems() {
        let extent = 0.2
        for index in 1...kClusterItemCount {
            let lat = kCameraLatitude + extent * randomScale()
            let lng = kCameraLongitude + extent * randomScale()
            let name = "Item \(index)"
            let item = POIItem(position: CLLocationCoordinate2DMake(lat, lng), name: name)
            clusterManager.add(item)
        }
    }

    /// Returns a random value between -1.0 and 1.0.
    private func randomScale() -> Double {
        return Double(arc4random()) / Double(UINT32_MAX) * 2.0 - 1.0
    }
}

Body:
First Take UIView:

Add UIView In UIViewController:

Assign class GMSMap View

And Now create outlet of GMSMapView.

@IBOutlet var mapView: GMSMapView!


问:
Java- Getting variables from method into other method
I am struggling with getting variables (all kinds: arrays, Strings, int) from a method (the method where I create the my GUI fields) into another method (the method where i manage my keypress events) I managed to get the fields, via their names, but I don't know how to get some variables.

Example: In the Field Method i got this part:
I manage My timestuff and put it into the input field(s) (rest is cut out)

```<code>DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
long todayDateUnix = Instant.now().getEpochSecond();;
String reportDate = df.format(todayDate);
String CustomDate = "meinDatum";
String[] parts = reportDate.split("/");
String DateDay = parts[0];
String DateMonth = parts[1];
String DateYear = parts[2];

JTextField input_day =new JTextField(DateDay);
//  input_day.setFocusTraversalKeysEnabled(false);
input_day.setName("input_day");
input_day.setBounds(102, 37, 25, 20);
input_day.setColumns(10);
</code>```

and in the other method I need these variables:

```<code>input_datum.setText(reportDate);
if(check_datum.isSelected()){
    CustomDateFinal[0] = datumvar;
    input_datum.setText(CustomDateFinal[0]);

}
</code>```

Don't care for the others but how for example do I get "reportDate"?
Thanks in advance :)

EDIT:
I want the variables from "createFields" to "customKeyevent"
PICTURE

答:
It's a design problem:
The objet containing the methods createFields and customKeyEvent has to exchange some values between those.

Then, you could create a structure (class) return by createFields, that contains your created field and the values customKeyEvent needs.
Or, you could externalize values and create type's properties. During the call of createFields, set the properties value, and after, you could get it from customKeyEvent. But take care of possibly multithreading access: choose the good accessibility of your properties for your problem.

I think the second choice is the best ; these solution respect the role suggested by the name of createFields method.

It could be a good practice to you to learn about design patterns. That's some classics of basic design problem resolution.

It still helps me every day.

Body:
I am struggling with getting variables (all kinds: arrays, Strings, int) from a method (the method where I create the my GUI fields) into another method (the method where i manage my keypress events) I managed to get the fields, via their names, but I don't know how to get some variables.

Example: In the Field Method i got this part:
I manage My timestuff and put it into the input field(s) (rest is cut out)

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
long todayDateUnix = Instant.now().getEpochSecond();;
String reportDate = df.format(todayDate);
String CustomDate = "meinDatum";
String[] parts = reportDate.split("/");
String DateDay = parts[0];
String DateMonth = parts[1];
String DateYear = parts[2];

JTextField input_day =new JTextField(DateDay);
//  input_day.setFocusTraversalKeysEnabled(false);
input_day.setName("input_day");
input_day.setBounds(102, 37, 25, 20);
input_day.setColumns(10);

and in the other method I need these variables:

input_datum.setText(reportDate);
if(check_datum.isSelected()){
    CustomDateFinal[0] = datumvar;
    input_datum.setText(CustomDateFinal[0]);

}

Don't care for the others but how for example do I get "reportDate"?
Thanks in advance :)

EDIT:
I want the variables from "createFields" to "customKeyevent"
PICTURE


问:
Email address Input from Form to Table
I am trying to have a form take the input of a username and have the @domain.com automatically added to the table.
My code for the form is:

```<code><th>Owner Emaill: *  <td><input type="text" name="email" value="<?php echo $email; ?>" />@informatica.com </td></tr>
</code>```

and the table is:

```<code>echo '<td><a href="mailto:'.$row['email'].'">' . $row['email'].'</a></td>';
</code>```

any help is greatly appreciated.

答:
If you want to display it too:</p>

```<code>echo '<td><a href="mailto:'.$row['email'].'@informatica.com">' . $row['email'].'@informatica.com</a></td>';
</code>```

Title: Email address Input from Form to Table

Body:
I am trying to have a form take the input of a username and have the @domain.com automatically added to the table.
My code for the form is:

Owner Emaill: *  <input type="text" name="email" value="<?php echo $email; ?>" />@informatica.com

and the table is:

echo '' . $row['email'].'	';

any help is greatly appreciated.

Body:
If you want to display it too:

echo '<td><a href="mailto:'.$row['email'].'@informatica.com">' . $row['email'].'@informatica.com</a></td>';


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
Functions as a programming construct.  No matter how big the problem, I could break it down into sensible calls to a set of functions.  If the problem to be solved by any one function was too big, I could break it down as well (we didn't call it refactoring then).  Sooner or later, I thought, I could solve anything by just finishing the functions.

More generally, I was hooked on development when I realized that I could create processes that determined how a team, a department, a business, or even an entire industry would work.  And that I could help them work better and faster.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych


问:
XML parser error: entity not defined
I have searched stackoverflow on this problem and did find a few topics, but I feel like there isn't really a solid answer for me on this.

I have a form that users submit and the field's value is stored in a XML file. The XML is set to be encoded with UTF-8.

Every now and then a user will copy/paste text from somewhere and that's when I get the "entity not defined error".

I realize XML only supports a select few entities and anything beyond that is not recognized - hence the parser error.

From what I gather, there's a few options I've seen:

I can find and replace all   and swap them out with   or an actual space.

I can place the code in question within a CDATA section.

I can include these entities within the XML file.

What I'm doing with the XML file is that the user can enter content into a form, it gets stored in a XML file, and that content then gets displayed as XHTML on a Web page (parsed with SimpleXML).

Of the three options, or any other option(s) I'm not aware of, what's really the best way to deal with these entities?

Thanks,
Ryan

UPDATE

I want to thank everyone for the great feedback. I actually determined what caused my entity errors. All the suggestions made me look into it more deeply!

Some textboxes where plain old textboxes, but my textareas were enhanced with TinyMCE. It turns out, while taking a closer look, that the PHP warnings always referenced data from the TinyMCE enhanced textareas. Later I noticed on a PC that all the characters were taken out (because it couldn't read them), but on a MAC you could see little square boxes referencing the unicode number of that character. The reason it showed up in squares on a MAC in the first place, is because I used utf8_encode to encode data that wasn't in UTF to prevent other parsing errors (which is somehow also related to TinyMCE).

The solution to all this was quite simple:

I added this line entity_encoding : "utf-8" in my tinyMCE.init. Now, all the characters show up the way they are supposed to.

I guess the only thing I don't understand is why the characters still show up when placed in textboxes, because nothing converts them to UTF, but with TinyMCE it was a problem.

答:
I agree that it is purely an encoding issue. In PHP, this is how I solved this problem:

Before passing the html-fragment to SimpleXMLElement constructor I decoded it by using html_entity_decode.

Then further encoded it using utf8_encode().

$headerDoc = '<temp>' . utf8_encode(html_entity_decode($headerFragment)) . '</temp>';
$xmlHeader = new SimpleXMLElement($headerDoc);
```

Now the above code does not throw any undefined entity errors.

Title: XML parser error: entity not defined

Body:
I agree that it is purely an encoding issue. In PHP, this is how I solved this problem:

Before passing the html-fragment to SimpleXMLElement constructor I decoded it by using html_entity_decode.

Then further encoded it using utf8_encode().

$headerDoc = '<temp>' . utf8_encode(html_entity_decode($headerFragment)) . '</temp>';
$xmlHeader = new SimpleXMLElement($headerDoc);

Now the above code does not throw any undefined entity errors.

ContentLicense: CC BY-SA 4.0


问:
Adding "more-information"-button to woocommerce product
In standard Woocommerce on the products page of the shop has a nice "add-to-cart"-button. I wanted to add a "more-information"-button to it in the same style.

Using the code from this page I managed to add a button by placing this code in my functions.php:

add_action('woocommerce_after_shop_loop_item_title','more_information');

function more_information() {
 global $product;
 $link = $product->get_permalink();
 echo do_shortcode('
[button class="meer-informatie" link="' . esc_attr($link) . '"]meer informatie[/button]');
}```

It's crucial I add a class to the button I want to add so I can style it. Point is I added the button (see image) but the link isn't working. It needs to link to the productdetail-page. So, where does it go wrong? I can't seem to figure it out (but then again: I only speak PHP a little).

Thanks in advance for any help!

答:
Still don't really know what is wrong with the code I posted in my question but I found something that actually works. Someone might someday be looking for this or encounter the same issue so I'm going to post this as an answer to my own question. After seeking help in all kinds of directions I came up with the following code:

function more_information() {
global $product;
if ($product){
$url = esc_url($product->get_permalink() );
echo 'meer informatie';
}
}
add_action('woocommerce_after_shop_loop_item_title','more_information');```

It works like a charm!

Body:
In standard Woocommerce on the products page of the shop has a nice "add-to-cart"-button. I wanted to add a "more-information"-button to it in the same style.

Using the code from this page I managed to add a button by placing this code in my functions.php:

add_action('woocommerce_after_shop_loop_item_title','more_information');

function more_information() {
 global $product;
 $link = $product->get_permalink();
 echo do_shortcode('
[button class="meer-informatie" link="' . esc_attr($link) . '"]meer informatie[/button]');
}

It's crucial I add a class to the button I want to add so I can style it. Point is I added the button (see image) but the link isn't working. It needs to link to the productdetail-page. So, where does it go wrong? I can't seem to figure it out (but then again: I only speak PHP a little).

Thanks in advance for any help!

Body:
Still don't really know what is wrong with the code I posted in my question but I found something that actually works. Someone might someday be looking for this or encounter the same issue so I'm going to post this as an answer to my own question. After seeking help in all kinds of directions I came up with the following code:

function more_information() {
global $product;
if ($product){
$url = esc_url($product->get_permalink() );
echo '<a rel="nofollow" href="' .$url .'" class="meer-informatie">meer informatie</a>';
}
}
add_action('woocommerce_after_shop_loop_item_title','more_information');

It works like a charm!


问:
Trying to understand extern in C
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

```<code>extern int global_counter;

int file_counter;
</code>```

extern.c

```<code>#include "extern.h"

int global_counter = 5;
</code>```

incrementor1.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

incrementor2.c

```<code>#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}
</code>```

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

```<code>void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}
</code>```

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

```<code>CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o
</code>```

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

```<code>From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2
</code>```

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.

答:
So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter

This is incorrect. Both global_counter and file_counter are global variables. This is because you declare file_counter outside any function.

If you declare file_counter separately inside the functions incrementor1_local and incrementor2_local and remove it from extern.h, then it will be a local variable and will have separate copies in each function.

Title: Trying to understand extern in C

Body:
By the answer given here, I am trying to construct a working example and try to understand behavior of the extern linkage.

Here is my example:

extern.h

extern int global_counter;

int file_counter;

extern.c

#include "extern.h"

int global_counter = 5;

incrementor1.c

#include "extern.h"
#include <stdio.h>

void incrementor1_global()
{
    global_counter++;
    printf("From Incrementor1...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor1_local()
{
    file_counter++;
    printf("From Incrementor1...\n");
    printf("File counter is: %d\n", file_counter);
}

incrementor2.c

#include "extern.h"
#include <stdio.h>

void incrementor2_global()
{
    global_counter++;
    printf("From Incrementor2...\n");
    printf("Global counter is: %d\n", global_counter);
}

void incrementor2_local()
{
    file_counter++;
    printf("From Incrementor2...\n");
    printf("File counter is: %d\n", file_counter);
}

You can yourself put these into separate files as depicted. Here is my main.c now:

main.c

void incrementor1_global();
void incrementor1_local();

void incrementor2_global();
void incrementor2_local();

int main(char argc, char* argv[])
{
    incrementor1_global();
    incrementor2_global();

    incrementor1_local();
    incrementor2_local();
}

Since I link .o files to my main, I am just declaring the functions and since they are extern by default, they are linked by the linker as I understood. And lastly, here is a makefile if you want to try it yourself.

CC=gcc

CFLAGS=-I.

DEPS = extern.h

OBJ = main.o extern.o incrementor1.o incrementor2.o

%.o: %.c $(DEPS)
    $(CC) -c -o $@ $< $(CFLAGS)

main: $(OBJ)
    gcc -o $@ $^ $(CFLAGS)

.PHONY: clean

clean:
    rm -f *.o

So by the answer linked above, I think global_counter should be shared by all translation units while each should have their own copy of file_counter. But the output I get is:

From Incrementor1...
Global counter is: 6
From Incrementor2...
Global counter is: 7
From Incrementor1...
File counter is: 1
From Incrementor2...
File counter is: 2

So, I think both incrementor have a one copy of file_counter and that is a global variable. But now I don't know how I can replicate the answer given and make them have their own copy. Any suggestions?

By the way, If I want to give a definition to file_counter in extern.h, since it is included in both incrementors I am getting multiple definitions error. This confuses me further on how could I make them have a shared copy.


问:
add an icon to django crispy form submit button
I am struggling with the Button on a crispy form. Instead of just the default button I would like to have an icon inside

The form I am currently using is like

```<code>class MyForm(forms.ModelForm):

helper = FormHelper()
helper.layout = Layout(
    Div(
        Div(PrependedText('source_text', '<span class="fa fa-user"></span>'), css_class='col-md-6'),
        Div(PrependedText('destination_text','<span class="fa fa-flag-checkered"></span>'), css_class='col-md-6'),
        css_class='row-fluid'),
    Div(
        Div(PrependedText('departure', '<span class="fa fa-clock-o"></span>'), css_class='col-md-3'),
        Div('departure_delta', css_class='col-md-2'),
        Div(Submit('submit', "Neue Fahrt starten", css_class="btn"), css_class="col-md2"),
        css_class='row-fluid'),
)
helper.form_show_labels = False
helper.form_id = 'id_travelshare'

class Meta:

    model = MyModel
    fields = ['source', 'source_text', 'destination',
              'destination_text', 'departure', 'departure_delta']

    widgets = {
        'source': forms.HiddenInput(),
        'destination': forms.HiddenInput(),
        'departure' : forms.DateTimeInput(attrs={'class':'datetimepicker'}),
    }
</code>```

What I want is a button with an icon inside. I did not find an example for this. Maybe somebody has one.

Kind regads

Michael

答:
I can live with an ordinary link and submit the form with JS. Now it looks like :

```<code><a href="#" class="btn btn-primary">
        <i class="fa fa-plus" aria-hidden="true"></i>
        Hinzufuegen
</a>
</code>```

Regards

Michael

Body:
I am struggling with the Button on a crispy form. Instead of just the default button I would like to have an icon inside

The form I am currently using is like

class MyForm(forms.ModelForm):

helper = FormHelper()
helper.layout = Layout(
    Div(
        Div(PrependedText('source_text', ''), css_class='col-md-6'),
        Div(PrependedText('destination_text',''), css_class='col-md-6'),
        css_class='row-fluid'),
    Div(
        Div(PrependedText('departure', ''), css_class='col-md-3'),
        Div('departure_delta', css_class='col-md-2'),
        Div(Submit('submit', "Neue Fahrt starten", css_class="btn"), css_class="col-md2"),
        css_class='row-fluid'),
)
helper.form_show_labels = False
helper.form_id = 'id_travelshare'

class Meta:

    model = MyModel
    fields = ['source', 'source_text', 'destination',
              'destination_text', 'departure', 'departure_delta']

    widgets = {
        'source': forms.HiddenInput(),
        'destination': forms.HiddenInput(),
        'departure' : forms.DateTimeInput(attrs={'class':'datetimepicker'}),
    }

What I want is a button with an icon inside. I did not find an example for this. Maybe somebody has one.

Kind regads

Michael

Body:
I can live with an ordinary link and submit the form with JS. Now it looks like :

<a href="#" class="btn btn-primary">
        <i class="fa fa-plus" aria-hidden="true"></i>
        Hinzufuegen
</a>

Regards

Michael


问:
Is there a way to rebuild Dexie keys?
I had a working app that uses Dexie.  After upgrading to iOS 10.3, lookups by key are not working.  (This is actually an indexeddb problem, not Dexie per se, I'm sure.)  I'm still in shock but I have been able to confirm that the data is there by doing db.table.each(function(p) {}, and the fields used in keys are there and correct.  But if I do
db.table.get(primarykey, function(p) {}
or
db.table.where("somekey").equals(nonprimarykey).first(function(p) {}
p is undefined.

I tried doing .db.table.each and then putting each retrieved object back to see if that would rebuild the keys, and it worked in Firefox, but doesn't work in Safari or Chrome (still can't retrieve by key).

I also tried specifying a new version with the same key structure and an empty upgrade, and that didn't do anything (but I only tried it in Chrome).

Everything is fine if the database is created AFTER installing 10.3 but I'm hoping that my customers won't have to delete their databases.

Is there any way to repair this without losing data?

答:
This seems to be an upgrade bug in Safari and should really be filed on bugs.webkit.org. Assume this is something that will be fixed there as the Safari team is very responsive when it comes to critical bugs. Please file it!

As for a workaround, I would suggest to recreate the database. Copy the database to a new database, delete it, then copy back and delete the intermediate copy. I've not verified the code below, so you have to test it.

```<code>function check_and_fix_IOS_10_3_upgrade_issue () {
    return (somehowCheckIfWeNeedToDoThis) ?
        recreateDatabase() : Promise.resolve();
}

function recreateDatabase () {
    copyDatabase("dbName", "dbName_tmp").then(()=>{
        return Dexie.delete("dbName");
    }).then(()=>{
        return copyDatabase("dbName_tmp", "dbName");
    }).then(()=>{
        return Dexie.delete("dbName_tmp");
    });
}

function copyDatabase(fromDbName, toDbName) {
    return new Dexie(fromDbName).open().then(db => {
        let schema = db.tables.reduce((schema, table) => {
            schema[table.name] = [table.schema.primKey.src]
                .concat(table.schema.indexes.map(idx => idx.src))
                .join(',');
        }, {});

        let dbCopy = new Dexie(toDbName);
        dbCopy.version(db.verno).stores(schema);

        return dbCopy.open().then(()=>{
            // dbCopy is now successfully created with same version and schema as source db.
            // Now also copy the data
            return Promise.all(
                db.tables.map(table =>
                    table.toArray().then(rows => dbCopy.table(table.name).bulkAdd(rows))));
        }).finally(()=>{
             db.close();
             dbCopy.close();
        });
    })
}
</code>```

Regarding "somehowCheckIfWeNeedToDoThis", I can't answer exactly how to do it. Maybe user-agent sniff + cookie (set persistent cookie when fixed, so that it wont be recreated over and over). Maybe you'll find a better solution.

Then before you open your database (maybe before your app is launched) you'd need to do something like:

```<code>check_and_fix_IOS_10_3_upgrade_issue()
    .then(()=>app.start())
    .catch(err => {
        // Display error, to user
    });
</code>```

Title: Is there a way to rebuild Dexie keys?

Body:
This seems to be an upgrade bug in Safari and should really be filed on bugs.webkit.org. Assume this is something that will be fixed there as the Safari team is very responsive when it comes to critical bugs. Please file it!

As for a workaround, I would suggest to recreate the database. Copy the database to a new database, delete it, then copy back and delete the intermediate copy. I've not verified the code below, so you have to test it.

function check_and_fix_IOS_10_3_upgrade_issue () {
    return (somehowCheckIfWeNeedToDoThis) ?
        recreateDatabase() : Promise.resolve();
}

function recreateDatabase () {
    copyDatabase("dbName", "dbName_tmp").then(()=>{
        return Dexie.delete("dbName");
    }).then(()=>{
        return copyDatabase("dbName_tmp", "dbName");
    }).then(()=>{
        return Dexie.delete("dbName_tmp");
    });
}

function copyDatabase(fromDbName, toDbName) {
    return new Dexie(fromDbName).open().then(db => {
        let schema = db.tables.reduce((schema, table) => {
            schema[table.name] = [table.schema.primKey.src]
                .concat(table.schema.indexes.map(idx => idx.src))
                .join(',');
        }, {});

        let dbCopy = new Dexie(toDbName);
        dbCopy.version(db.verno).stores(schema);

        return dbCopy.open().then(()=>{
            // dbCopy is now successfully created with same version and schema as source db.
            // Now also copy the data
            return Promise.all(
                db.tables.map(table =>
                    table.toArray().then(rows => dbCopy.table(table.name).bulkAdd(rows))));
        }).finally(()=>{
             db.close();
             dbCopy.close();
        });
    })
}

Regarding "somehowCheckIfWeNeedToDoThis", I can't answer exactly how to do it. Maybe user-agent sniff + cookie (set persistent cookie when fixed, so that it wont be recreated over and over). Maybe you'll find a better solution.

Then before you open your database (maybe before your app is launched) you'd need to do something like:

check_and_fix_IOS_10_3_upgrade_issue()
    .then(()=>app.start())
    .catch(err => {
        // Display error, to user
    });


问:
How to modify a link?
I need to modify this link to go to

```<code>channels/params[:channel_id]/messages
</code>```

here is the current link

```<code><%= link_to pluralize(@channel.messages.size, 'message') %>
</code>```

result of rake routes

```<code>{:action=>"index", :controller=>"messages"}  POST   /channels/:channel_id/messages(.:format)
{:action=>"create", :controller=>"messages"}new_channel_message GET    /channels/:channel_id/messages/new(.:format)
{:action=>"new", :controller=>"messages"} edit_channel_message GET    /channels/:channel_id/messages/:id/edit(.:format)
{:action=>"edit", :controller=>"messages"}channel_message GET    /channels/:channel_id/messages/:id(.:format)
{:action=>"show", :controller=>"messages"} PUT    /channels/:channel_id/messages/:id(.:format)
{:action=>"update", :controller=>"messages"} DELETE /channels/:channel_id/messages/:id(.:format)
{:action=>"destroy", :controller=>"messages"} channels GET    /channels(.:format)
{:action=>"index", :controller=>"channels"} POST   /channels(.:format)
{:action=>"create", :controller=>"channels"}  new_channel GET    /channels/new(.:format)
{:action=>"new", :controller=>"channels"} edit_channel GET    /channels/:id/edit(.:format)
{:action=>"edit", :controller=>"channels"}channel GET    /channels/:id(.:format)
{:action=>"show", :controller=>"channels"}PUT    /channels/:id(.:format)
{:action=>"update", :controller=>"channels"} DELETE /channels/:id(.:format)
</code>```

答:
If you would have used nested routes and if you redirect that link to index action in messages controller, then you can define your link like this:

<%= link_to pluralize(@channel.messages.size, 'message'), channel_messages_path(@channel) %>

Title: How to modify a link?

Body:
I need to modify this link to go to

channels/params[:channel_id]/messages

here is the current link

<%= link_to pluralize(@channel.messages.size, 'message') %>

result of rake routes

{:action=>"index", :controller=>"messages"}  POST   /channels/:channel_id/messages(.:format)
{:action=>"create", :controller=>"messages"}new_channel_message GET    /channels/:channel_id/messages/new(.:format)
{:action=>"new", :controller=>"messages"} edit_channel_message GET    /channels/:channel_id/messages/:id/edit(.:format)
{:action=>"edit", :controller=>"messages"}channel_message GET    /channels/:channel_id/messages/:id(.:format)
{:action=>"show", :controller=>"messages"} PUT    /channels/:channel_id/messages/:id(.:format)
{:action=>"update", :controller=>"messages"} DELETE /channels/:channel_id/messages/:id(.:format)
{:action=>"destroy", :controller=>"messages"} channels GET    /channels(.:format)
{:action=>"index", :controller=>"channels"} POST   /channels(.:format)
{:action=>"create", :controller=>"channels"}  new_channel GET    /channels/new(.:format)
{:action=>"new", :controller=>"channels"} edit_channel GET    /channels/:id/edit(.:format)
{:action=>"edit", :controller=>"channels"}channel GET    /channels/:id(.:format)
{:action=>"show", :controller=>"channels"}PUT    /channels/:id(.:format)
{:action=>"update", :controller=>"channels"} DELETE /channels/:id(.:format)


问:
Not able to update 2 items using php and mysqli
I have a table where I want to update data in 2 rows.

Heres my code:

```<code><?php
   include("includes/conn.php");
   session_start();
    if(!isset($_SESSION['username']))
    {
        header('Location: login.php');
    }
else{
?>
    <?php
            $page_title = 'Update Order';
            include("includes/header.inc.php");
    ?>

    <?php if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update-order']) ){
        if( !empty($_POST['productname']) && !empty($_POST['quantity']) && !empty($_POST['price']) && !empty($_POST['amount']) ){

            $total = 0;
            $pid = mysqli_real_escape_string($db,$_POST['pid']);
            $advance = mysqli_real_escape_string($db,$_POST['advance_paid']);
            $dod = mysqli_real_escape_string($db,$_POST['dod']);
            $dod = date('Y-m-d', strtotime($dod));
            $mop = mysqli_real_escape_string($db,$_POST['mop']);

            for($i = 0; $i<count($_POST['productname']); $i++)
            {
                $total = $total + $_POST['amount'][$i];

                $query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$pid}' ";
                mysqli_query($db, $query);

                $update_stock = "UPDATE `item` SET added_by = '{$_SESSION['id']}', total_stock = total_stock + '{$_SESSION['quant']}' - '{$_POST['quantity'][$i]}' WHERE id = '{$_POST['productname'][$i]}'";
                mysqli_query($db, $update_stock);

            }

                $query_orders = "UPDATE `orders` SET amount = '{$total}', dod = '{$dod}', mop = '{$mop}', advance = '{$advance}', added_by = '{$_SESSION['id']}' WHERE order_id = '{$_POST['orderid']}' ";
                mysqli_query($db, $query_orders);

        }
    }
    ?>

    <div id="alteration-form">
        <div style="width: 90%; margin: 0 auto;">
            <form method="GET" action="">
                <label for="update_orderno" >Order NO.</label>
                <input type="text" name="orderno" class="input-field" id="update_orderno" />
                <input type="submit" name="find-order" value="Search Order" class="btn-all-submit" id="btn-order" />
            </form>
         </div>
    </div>
    <?php if( $_SERVER["REQUEST_METHOD"] == "GET" ){ ?>

    <?php
        if( !empty($_GET['orderno']) ){

            $orderno = $_GET['orderno'];

            $sql_cust = "SELECT cust_id FROM `orders` where order_id = '$orderno' ";
            $result_cust = mysqli_query($db, $sql_cust);

            if( mysqli_num_rows($result_cust) > 0 ){
                while( $row_cust = mysqli_fetch_array($result_cust, MYSQLI_ASSOC) ){
                    $cust_id = $row_cust['cust_id'];
                }

                $sql_name = "SELECT * FROM `users` WHERE id = '$cust_id' ";
                $result_name = mysqli_query($db, $sql_name);

                if( mysqli_num_rows($result_name) > 0 ){
                    while( $row_name = mysqli_fetch_array($result_name, MYSQLI_ASSOC) ){
                        $name = $row_name['name'];
                        $phone = $row_name['phone'];
                        $address = $row_name['address'];
                        $city = $row_name['city'];
                        $state = $row_name['state'];
                    }
                }

            }
    ?>
    <div class="result-table-div">
        <div class="divRow">
            <div class="divCell" ><strong>Name:</strong></div>
            <div class="divCell" ><?php echo $name; ?></div>
            <?php if(!empty($phone)){ ?>
                <div class="divCell" ><strong>Phone:</strong></div>
                <div class="divCell" ><?php echo $phone; ?></div>
            <?php } ?>
        </div>
        <div class="divRow">
            <?php if(!empty($address)){ ?>
                <div class="divCell" ><strong>Address:</strong></div>
                <div class="divCell" ><?php echo $address; ?></div>
            <?php } ?>
            <?php if(!empty($city)){ ?>
                <div class="divCell" ><strong>City:</strong></div>
                <div class="divCell" ><?php echo $city; ?></div>
            <?php } ?>
        </div>
        <div class="divRow">
            <?php if(!empty($state)){ ?>
                <div class="divCell" ><strong>State:</strong></div>
                <div class="divCell" ><?php echo $state; ?></div>
            <?php } ?>
        </div>
    </div>
    <div class="result-table-div">
    <form method="POST" action="">
    <div class="divRow">
        <div class="divCell" ><strong>Date of Delivery:</strong></div>
        <div class="divCell" ><input type="text" name="dod" id="dod" value="<?php echo date("m/d/Y"); ?>"/></div>
        <div class="divCell" ><strong>Mode of Payment:</strong></div>
        <div class="divCell" >
            <select name="mop">
                <option value="cash">Cash</option>
                <option value="card/cheque/online banking">Card/Cheque/Online Banking</option>
            </select>
        </div>
    </div>
    <table id="invoice-table">
    <thead>
        <tr>
            <th>S No.</th>
            <th>Item</th>
            <th>Quantity</th>
            <th>Price</th>
            <th>Discount</th>
            <th>Amount</th>
        </tr>
    </thead>
    <tbody>
    <?php

                    $sql = "SELECT * FROM invoice where order_id = '$orderno' ";

                    $result = mysqli_query($db, $sql);

                    if( mysqli_num_rows($result) > 0 ){
                    $count = 1;
                        while( $row = mysqli_fetch_array($result,MYSQLI_ASSOC) ){
                            $id = $row['id'];
                            $product_name = $row['product_name'];
                            $quantity = $row['quantity'];
                            $price = $row['price'];
                            $discount = $row['discount'];
                            $amount = $row['amount'];
                            $_SESSION['cust_id'] = $row['cust_id'];
                            $_SESSION['quant'] = $quantity;
    ?>
    <tr>
        <input type="hidden" name="pid" value="<?php echo $id; ?>" />
        <td><?php echo $count++; ?></td>
        <!--<td><input type="text" name="productname[]" value="?php echo $product_name ?>"></td>-->
        <td>
            <select name="productname[]">
                <option value="1" <?php if( isset($product_name) && strtolower($product_name) == "bags" ) echo "selected"; ?> >Bags</option>
                <option value="2" <?php if( isset($product_name) && strtolower($product_name) == "shoes" ) echo "selected"; ?> >Shoes</option>
                <option value="3" <?php if( isset($product_name) && strtolower($product_name) == "suit" ) echo "selected"; ?> >Suit</option>
                <option value="4" <?php if( isset($product_name) && strtolower($product_name) == "belts" ) echo "selected"; ?> >Belts</option>
                <option value="5" <?php if( isset($product_name) && strtolower($product_name) == "t-shirts" ) echo "selected"; ?> >T-shirts</option>
                <option value="6" <?php if( isset($product_name) && strtolower($product_name) == "others" ) echo "selected"; ?> >Others</option>
            </select>
        </td>
        <td><input type="text" class="quantity" name="quantity[]" value="<?php echo $quantity ?>"></td>
        <td><input type="text" class="price" name="price[]" value="<?php echo $price ?>"></td>
        <td><input type="text" class="discount" name="discount[]" value="<?php echo $discount ?>"></td>
        <td><input type="text" class="amount" name="amount[]" value="<?php echo $amount ?>"></td>
    </tr>
      <?php
                    }
        ?>
            <input type="hidden" name="orderid" value="<?php echo $orderno; ?>">
        <?php
                }
    ?>
    </tbody>
    </table>
    <p style="text-align: center;">Advanced Paid:  <input type="text" name="advance_paid" /></p>
    <div class="btn-div">
        <input type="submit" class="btn-all-submit" name="update-order" value="Update Order">
    </div>
    </form>
    </div>
    <?php } } ?>
    <script>
        $('body').delegate('.quantity,.price,.discount','keyup',function()
        {
        var tr=$(this).parent().parent();
        var qty=tr.find('.quantity').val();
        var price=tr.find('.price').val();

        var dis=tr.find('.discount').val();
        var amt =(qty * price)-(qty * price *dis)/100;
        tr.find('.amount').val(amt);
        });
    </script>
    <?php include("includes/footer.inc.php"); ?>
<?php } ?>
</code>```

I am using for loop to update the data but if I have 2 items to update, it is only updating second item and not the first one. Can someone please help me with this.
Problem occurs while updating invoice table.

答:
I found the solution for my problem.
Query should be</p>

```<code>$query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$_POST['pid'][$i]}' ";
                mysqli_query($db, $query);
</code>```

Body:
I have a table where I want to update data in 2 rows.

Heres my code:

<?php
   include("includes/conn.php");
   session_start();
    if(!isset($_SESSION['username']))
    {
        header('Location: login.php');
    }
else{
?>
    <?php
            $page_title = 'Update Order';
            include("includes/header.inc.php");
    ?>

    <?php if( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update-order']) ){
        if( !empty($_POST['productname']) && !empty($_POST['quantity']) && !empty($_POST['price']) && !empty($_POST['amount']) ){

            $total = 0;
            $pid = mysqli_real_escape_string($db,$_POST['pid']);
            $advance = mysqli_real_escape_string($db,$_POST['advance_paid']);
            $dod = mysqli_real_escape_string($db,$_POST['dod']);
            $dod = date('Y-m-d', strtotime($dod));
            $mop = mysqli_real_escape_string($db,$_POST['mop']);

            for($i = 0; $i<count($_POST['productname']); $i++)
            {
                $total = $total + $_POST['amount'][$i];

                $query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$pid}' ";
                mysqli_query($db, $query);

                $update_stock = "UPDATE `item` SET added_by = '{$_SESSION['id']}', total_stock = total_stock + '{$_SESSION['quant']}' - '{$_POST['quantity'][$i]}' WHERE id = '{$_POST['productname'][$i]}'";
                mysqli_query($db, $update_stock);

            }

                $query_orders = "UPDATE `orders` SET amount = '{$total}', dod = '{$dod}', mop = '{$mop}', advance = '{$advance}', added_by = '{$_SESSION['id']}' WHERE order_id = '{$_POST['orderid']}' ";
                mysqli_query($db, $query_orders);

        }
    }
    ?>

            <form method="GET" action="">
                Order NO.
                <input type="text" name="orderno" class="input-field" id="update_orderno" />
                <input type="submit" name="find-order" value="Search Order" class="btn-all-submit" id="btn-order" />
            </form>

    <?php if( $_SERVER["REQUEST_METHOD"] == "GET" ){ ?>

    <?php
        if( !empty($_GET['orderno']) ){

            $orderno = $_GET['orderno'];

            $sql_cust = "SELECT cust_id FROM `orders` where order_id = '$orderno' ";
            $result_cust = mysqli_query($db, $sql_cust);

            if( mysqli_num_rows($result_cust) > 0 ){
                while( $row_cust = mysqli_fetch_array($result_cust, MYSQLI_ASSOC) ){
                    $cust_id = $row_cust['cust_id'];
                }

                $sql_name = "SELECT * FROM `users` WHERE id = '$cust_id' ";
                $result_name = mysqli_query($db, $sql_name);

                if( mysqli_num_rows($result_name) > 0 ){
                    while( $row_name = mysqli_fetch_array($result_name, MYSQLI_ASSOC) ){
                        $name = $row_name['name'];
                        $phone = $row_name['phone'];
                        $address = $row_name['address'];
                        $city = $row_name['city'];
                        $state = $row_name['state'];
                    }
                }

            }
    ?>

Name:

<?php echo $name; ?>

            <?php if(!empty($phone)){ ?>

Phone:

<?php echo $phone; ?>

            <?php } ?>

            <?php if(!empty($address)){ ?>

Address:

<?php echo $address; ?>

            <?php } ?>
            <?php if(!empty($city)){ ?>

City:

<?php echo $city; ?>

            <?php } ?>

            <?php if(!empty($state)){ ?>

State:

<?php echo $state; ?>

            <?php } ?>

    <form method="POST" action="">

Date of Delivery:

<input type="text" name="dod" id="dod" value="<?php echo date("m/d/Y"); ?>"/>

Mode of Payment:

            <select name="mop">
                <option value="cash">Cash</option>
                <option value="card/cheque/online banking">Card/Cheque/Online Banking</option>
            </select>

            S No.
            Item
            Quantity
            Price
            Discount
            Amount

    <?php

                    $sql = "SELECT * FROM invoice where order_id = '$orderno' ";

                    $result = mysqli_query($db, $sql);

                    if( mysqli_num_rows($result) > 0 ){
                    $count = 1;
                        while( $row = mysqli_fetch_array($result,MYSQLI_ASSOC) ){
                            $id = $row['id'];
                            $product_name = $row['product_name'];
                            $quantity = $row['quantity'];
                            $price = $row['price'];
                            $discount = $row['discount'];
                            $amount = $row['amount'];
                            $_SESSION['cust_id'] = $row['cust_id'];
                            $_SESSION['quant'] = $quantity;
    ?>

        <input type="hidden" name="pid" value="<?php echo $id; ?>" />
        <?php echo $count++; ?>

            <select name="productname[]">
                <option value="1" <?php if( isset($product_name) && strtolower($product_name) == "bags" ) echo "selected"; ?> >Bags</option>
                <option value="2" <?php if( isset($product_name) && strtolower($product_name) == "shoes" ) echo "selected"; ?> >Shoes</option>
                <option value="3" <?php if( isset($product_name) && strtolower($product_name) == "suit" ) echo "selected"; ?> >Suit</option>
                <option value="4" <?php if( isset($product_name) && strtolower($product_name) == "belts" ) echo "selected"; ?> >Belts</option>
                <option value="5" <?php if( isset($product_name) && strtolower($product_name) == "t-shirts" ) echo "selected"; ?> >T-shirts</option>
                <option value="6" <?php if( isset($product_name) && strtolower($product_name) == "others" ) echo "selected"; ?> >Others</option>
            </select>

        <input type="text" class="quantity" name="quantity[]" value="<?php echo $quantity ?>">
        <input type="text" class="price" name="price[]" value="<?php echo $price ?>">
        <input type="text" class="discount" name="discount[]" value="<?php echo $discount ?>">
        <input type="text" class="amount" name="amount[]" value="<?php echo $amount ?>">

      <?php
                    }
        ?>
            <input type="hidden" name="orderid" value="<?php echo $orderno; ?>">
        <?php
                }
    ?>

Advanced Paid:  <input type="text" name="advance_paid" />

        <input type="submit" class="btn-all-submit" name="update-order" value="Update Order">

    </form>

    <?php } } ?>

    <?php include("includes/footer.inc.php"); ?>
<?php } ?>

I am using for loop to update the data but if I have 2 items to update, it is only updating second item and not the first one. Can someone please help me with this.
Problem occurs while updating invoice table.

Body:
I found the solution for my problem.
Query should be

$query = "UPDATE `invoice` SET product_name = (select name from item where id = '{$_POST['productname'][$i]}'), quantity = '{$_POST['quantity'][$i]}', price = '{$_POST['price'][$i]}', discount = '{$_POST['discount'][$i]}', amount = '{$_POST['amount'][$i]}', dod = '{$dod}', added_by = '{$_SESSION['id']}' WHERE id = '{$_POST['pid'][$i]}' ";
                mysqli_query($db, $query);


问:
Calculating duration by subtracting two datetime columns in string format
I have a Spark Dataframe in that consists of a series of dates:

```<code>from pyspark.sql import SQLContext
from pyspark.sql import Row
from pyspark.sql.types import *
sqlContext = SQLContext(sc)
import pandas as pd

rdd = sc.parallelizesc.parallelize([('X01','2014-02-13T12:36:14.899','2014-02-13T12:31:56.876','sip:4534454450'),
                                    ('X02','2014-02-13T12:35:37.405','2014-02-13T12:32:13.321','sip:6413445440'),
                                    ('X03','2014-02-13T12:36:03.825','2014-02-13T12:32:15.229','sip:4534437492'),
                                    ('XO4','2014-02-13T12:37:05.460','2014-02-13T12:32:36.881','sip:6474454453'),
                                    ('XO5','2014-02-13T12:36:52.721','2014-02-13T12:33:30.323','sip:8874458555')])
schema = StructType([StructField('ID', StringType(), True),
                     StructField('EndDateTime', StringType(), True),
                     StructField('StartDateTime', StringType(), True)])
df = sqlContext.createDataFrame(rdd, schema)
</code>```

What I want to do is find duration by subtracting EndDateTime and StartDateTime. I figured I'd try and do this using a function:

```<code># Function to calculate time delta
def time_delta(y,x):
    end = pd.to_datetime(y)
    start = pd.to_datetime(x)
    delta = (end-start)
    return delta

# create new RDD and add new column 'Duration' by applying time_delta function
df2 = df.withColumn('Duration', time_delta(df.EndDateTime, df.StartDateTime))
</code>```

However this just gives me:

```<code>>>> df2.show()
ID  EndDateTime          StartDateTime        ANI            Duration
X01 2014-02-13T12:36:... 2014-02-13T12:31:... sip:4534454450 null
X02 2014-02-13T12:35:... 2014-02-13T12:32:... sip:6413445440 null
X03 2014-02-13T12:36:... 2014-02-13T12:32:... sip:4534437492 null
XO4 2014-02-13T12:37:... 2014-02-13T12:32:... sip:6474454453 null
XO5 2014-02-13T12:36:... 2014-02-13T12:33:... sip:8874458555 null
</code>```

I'm not sure if my approach is correct or not. If not, I'd gladly accept another suggested way to achieve this.

答:
Here is a working version for spark 2.x derived from jason's answer</p>

```<code>from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession,SQLContext
from pyspark.sql.types import StringType, StructType, StructField

sc = SparkContext()
sqlContext = SQLContext(sc)
spark = SparkSession.builder.appName("Python Spark SQL basic example").getOrCreate()

rdd = sc.parallelize([('X01','2014-02-13T12:36:14.899','2014-02-13T12:31:56.876'),
                      ('X02','2014-02-13T12:35:37.405','2014-02-13T12:32:13.321'),
                      ('X03','2014-02-13T12:36:03.825','2014-02-13T12:32:15.229'),
                      ('XO4','2014-02-13T12:37:05.460','2014-02-13T12:32:36.881'),
                      ('XO5','2014-02-13T12:36:52.721','2014-02-13T12:33:30.323')])
schema = StructType([StructField('ID', StringType(), True),
                     StructField('EndDateTime', StringType(), True),
                     StructField('StartDateTime', StringType(), True)])
df = sqlContext.createDataFrame(rdd, schema)

# register as a UDF
from datetime import datetime
sqlContext.registerFunction("time_delta", lambda y,x:(datetime.strptime(y, '%Y-%m-%dT%H:%M:%S.%f')-datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f')).total_seconds())

df.createOrReplaceTempView("Test_table")

spark.sql("SELECT ID,EndDateTime,StartDateTime,time_delta(EndDateTime,StartDateTime) as time_delta FROM Test_table").show()

sc.stop()
</code>```

Body:
I have a Spark Dataframe in that consists of a series of dates:

from pyspark.sql import SQLContext
from pyspark.sql import Row
from pyspark.sql.types import *
sqlContext = SQLContext(sc)
import pandas as pd

rdd = sc.parallelizesc.parallelize([('X01','2014-02-13T12:36:14.899','2014-02-13T12:31:56.876','sip:4534454450'),
                                    ('X02','2014-02-13T12:35:37.405','2014-02-13T12:32:13.321','sip:6413445440'),
                                    ('X03','2014-02-13T12:36:03.825','2014-02-13T12:32:15.229','sip:4534437492'),
                                    ('XO4','2014-02-13T12:37:05.460','2014-02-13T12:32:36.881','sip:6474454453'),
                                    ('XO5','2014-02-13T12:36:52.721','2014-02-13T12:33:30.323','sip:8874458555')])
schema = StructType([StructField('ID', StringType(), True),
                     StructField('EndDateTime', StringType(), True),
                     StructField('StartDateTime', StringType(), True)])
df = sqlContext.createDataFrame(rdd, schema)

What I want to do is find duration by subtracting EndDateTime and StartDateTime. I figured I'd try and do this using a function:

# Function to calculate time delta
def time_delta(y,x):
    end = pd.to_datetime(y)
    start = pd.to_datetime(x)
    delta = (end-start)
    return delta

# create new RDD and add new column 'Duration' by applying time_delta function
df2 = df.withColumn('Duration', time_delta(df.EndDateTime, df.StartDateTime))

However this just gives me:

>>> df2.show()
ID  EndDateTime          StartDateTime        ANI            Duration
X01 2014-02-13T12:36:... 2014-02-13T12:31:... sip:4534454450 null
X02 2014-02-13T12:35:... 2014-02-13T12:32:... sip:6413445440 null
X03 2014-02-13T12:36:... 2014-02-13T12:32:... sip:4534437492 null
XO4 2014-02-13T12:37:... 2014-02-13T12:32:... sip:6474454453 null
XO5 2014-02-13T12:36:... 2014-02-13T12:33:... sip:8874458555 null

I'm not sure if my approach is correct or not. If not, I'd gladly accept another suggested way to achieve this.

Body:
Here is a working version for spark 2.x derived from jason's answer

from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession,SQLContext
from pyspark.sql.types import StringType, StructType, StructField

sc = SparkContext()
sqlContext = SQLContext(sc)
spark = SparkSession.builder.appName("Python Spark SQL basic example").getOrCreate()

rdd = sc.parallelize([('X01','2014-02-13T12:36:14.899','2014-02-13T12:31:56.876'),
                      ('X02','2014-02-13T12:35:37.405','2014-02-13T12:32:13.321'),
                      ('X03','2014-02-13T12:36:03.825','2014-02-13T12:32:15.229'),
                      ('XO4','2014-02-13T12:37:05.460','2014-02-13T12:32:36.881'),
                      ('XO5','2014-02-13T12:36:52.721','2014-02-13T12:33:30.323')])
schema = StructType([StructField('ID', StringType(), True),
                     StructField('EndDateTime', StringType(), True),
                     StructField('StartDateTime', StringType(), True)])
df = sqlContext.createDataFrame(rdd, schema)

# register as a UDF
from datetime import datetime
sqlContext.registerFunction("time_delta", lambda y,x:(datetime.strptime(y, '%Y-%m-%dT%H:%M:%S.%f')-datetime.strptime(x, '%Y-%m-%dT%H:%M:%S.%f')).total_seconds())

df.createOrReplaceTempView("Test_table")

spark.sql("SELECT ID,EndDateTime,StartDateTime,time_delta(EndDateTime,StartDateTime) as time_delta FROM Test_table").show()

sc.stop()


问:
mysql change innodb_large_prefix
I just setup debian 8.3 on a VM and installed xampp after this Tutorial. Everything is working, until I tried to create a new table:

```<code>create table testtable
(
  id int(10) not null auto_increment,
  firstname varchar(255) collate utf8mb4_german2_ci not null,
  lastname varchar(255) collate utf8mb4_german2_ci not null,
  primary key (id),
  unique key (lastname)
)engine = innodb default charset=utf8mb4, collate=utf8mb4_german2_ci
</code>```

I got the error: #1709 - Index column size too large. The maximum column size is 767 bytes.
Then I found out this comes from the prefix limitation which is limited to 767Byte in Innodb and I can fix this by set the innodb_large_prefix in the my.cnf file. But I can't find the file, its not under /etc/ and theres no /etc/mysql/-folder, the only my.cnf I found is in /opt/lampp/etc/, however, after I added the innodb_large_prefix=1 to the file and restarted lampp. I stil get the same error. What did I do wrong?

edit: SELECT version() returns 5.6.14, so innodb_large_prefix should be supported.

edit2: I know I can work around this by only set part of the the key as index to get under 767Byte. But I want to know here how to config the mysql correctly.

答:
Go to your xampp and add this query:</p>

```<code>`mysql>` set global innodb_file_format = `BARRACUDA`;
`mysql>` set global innodb_large_prefix = `ON`;
</code>```

Title: mysql change innodb_large_prefix

Body:
I just setup debian 8.3 on a VM and installed xampp after this Tutorial. Everything is working, until I tried to create a new table:

create table testtable
(
  id int(10) not null auto_increment,
  firstname varchar(255) collate utf8mb4_german2_ci not null,
  lastname varchar(255) collate utf8mb4_german2_ci not null,
  primary key (id),
  unique key (lastname)
)engine = innodb default charset=utf8mb4, collate=utf8mb4_german2_ci

I got the error: #1709 - Index column size too large. The maximum column size is 767 bytes.
Then I found out this comes from the prefix limitation which is limited to 767Byte in Innodb and I can fix this by set the innodb_large_prefix in the my.cnf file. But I can't find the file, its not under /etc/ and theres no /etc/mysql/-folder, the only my.cnf I found is in /opt/lampp/etc/, however, after I added the innodb_large_prefix=1 to the file and restarted lampp. I stil get the same error. What did I do wrong?

edit: SELECT version() returns 5.6.14, so innodb_large_prefix should be supported.

edit2: I know I can work around this by only set part of the the key as index to get under 767Byte. But I want to know here how to config the mysql correctly.

Body:
Go to your xampp and add this query:

`mysql>` set global innodb_file_format = `BARRACUDA`;
`mysql>` set global innodb_large_prefix = `ON`;


问:
Python Optimized Comparison Between List of Dict
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.

I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].

The size of both lists can run upwards of 100,000 items each.

My current code is posted below, but it's very inefficient.

```<code>    filteredList = []
    for i in range(len(sList)):

            minx = (sList[i]['x']) - (sList[i]['radius'])
            maxx = (sList[i]['x']) + (sList[i]['radius'])
            miny = (sList[i]['y']) - (sList[i]['radius'])
            maxy = (sList[i]['y']) + (sList[i]['radius'])
            minz = (sList[i]['z']) - (sList[i]['radius'])
            maxz = (sList[i]['z']) + (sList[i]['radius'])

            for j in range(len(nList)):
                    if minx <= nList[j]['x'] <= maxx:
                            if miny <= nList[j]['y'] <= maxy:
                                    if minz <= nList[j]['z'] <= maxz:
                                            tmpRad = findRadius(sList[i],nList[j])
                                            if tmpRad <= sList[i]['radius']:
                                                    filteredList.append(int(nList[j]['num']))
</code>```

I'm at a loss and appreciate any ideas.

Edit: Adding extra information about the data format.

List A (nList) -- defines nodes, with locations x,y,z, and identifier num

[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},

{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},

{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},

{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},

{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},

{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},

{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},

{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},

{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},

{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]

List B (sList) -- defines spheres using x,y,z, radius

[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},

{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},

{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},

{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},

{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},

{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},

{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},

{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},

{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},

{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]

答:
(AFAICT, the following solution is algorithmically faster than any other answer posted so far: approximately O(N log N) vs O(N²). Caveat: this assumes that you don't have massive amounts of overlap between bounding boxes.)

If you are allowed to pre-compute an index structure:

Push all the min/max x values into a set and sort them, thus creating a list of vertical regions spanning the x-axis. Associate each region with the set of bounding boxes that contain it.

Repeat this procedure for min/max y values, to create a list of horizontal regions, and associate each region with the set of bounding boxes it contains.

For each point being tested:

Use a binary chop to find the horizontal region that contains the point's x coordinate. What you really want, though, is the set of bounding boxes associated with the region.

Likewise, find the set of bounding boxes associated with the y coordinate.

Find the intersection of these two sets.

Test the bounding boxes in this residue set using Pythagoras.

Body:
I'm trying to see whether nodes reside within the volume of a sphere, and add the node id to a list. However, the efficiency of the algorithm is incredibly slow and I'm not sure how to improve it.

I have two lists. List A has the format [{'num': ID, 'x': VALUE, 'y': VALUE, 'z': VALUE] while List B has the format [{'x': VALUE, 'y': VALUE, 'z': VALUE, 'rad': VALUE}].

The size of both lists can run upwards of 100,000 items each.

My current code is posted below, but it's very inefficient.

    filteredList = []
    for i in range(len(sList)):

            minx = (sList[i]['x']) - (sList[i]['radius'])
            maxx = (sList[i]['x']) + (sList[i]['radius'])
            miny = (sList[i]['y']) - (sList[i]['radius'])
            maxy = (sList[i]['y']) + (sList[i]['radius'])
            minz = (sList[i]['z']) - (sList[i]['radius'])
            maxz = (sList[i]['z']) + (sList[i]['radius'])

            for j in range(len(nList)):
                    if minx <= nList[j]['x'] <= maxx:
                            if miny <= nList[j]['y'] <= maxy:
                                    if minz <= nList[j]['z'] <= maxz:
                                            tmpRad = findRadius(sList[i],nList[j])
                                            if tmpRad <= sList[i]['radius']:
                                                    filteredList.append(int(nList[j]['num']))

I'm at a loss and appreciate any ideas.

Edit: Adding extra information about the data format.

List A (nList) -- defines nodes, with locations x,y,z, and identifier num

[{'y': 0.0, 'x': 0.0, 'num': 1.0, 'z': 0.0},

{'y': 0.0, 'x': 1.0, 'num': 2.0, 'z': 0.0},

{'y': 0.0, 'x': 2.0, 'num': 3.0, 'z': 0.0},

{'y': 0.0, 'x': 3.0, 'num': 4.0, 'z': 0.0},

{'y': 0.0, 'x': 4.0, 'num': 5.0, 'z': 0.0},

{'y': 0.0, 'x': 5.0, 'num': 6.0, 'z': 0.0},

{'y': 0.0, 'x': 6.0, 'num': 7.0, 'z': 0.0},

{'y': 0.0, 'x': 7.0, 'num': 8.0, 'z': 0.0},

{'y': 0.0, 'x': 8.0, 'num': 9.0, 'z': 0.0},

{'y': 0.0, 'x': 9.0, 'num': 10.0, 'z': 0.0}]

List B (sList) -- defines spheres using x,y,z, radius

[{'y': 18.0, 'x': 25.0, 'z': 26.0, 'radius': 0.0056470000000000001},

{'y': 29.0, 'x': 23.0, 'z': 45.0, 'radius': 0.0066280000000000002},

{'y': 46.0, 'x': 29.0, 'z': 13.0, 'radius': 0.014350999999999999},

{'y': 0.0, 'x': 20.0, 'z': 25.0, 'radius': 0.014866000000000001},

{'y': 27.0, 'x': 31.0, 'z': 18.0, 'radius': 0.018311999999999998},

{'y': 10.0, 'x': 36.0, 'z': 46.0, 'radius': 0.024702000000000002},

{'y': 27.0, 'x': 13.0, 'z': 48.0, 'radius': 0.027300999999999999},

{'y': 14.0, 'x': 1.0, 'z': 13.0, 'radius': 0.033889000000000002},

{'y': 31.0, 'x': 20.0, 'z': 11.0, 'radius': 0.034118999999999997},

{'y': 23.0, 'x': 28.0, 'z': 8.0, 'radius': 0.036683}]


问:
Why does XCTestCase override the setup method of XCTest?
I'd like to think that I understand the idea of inheritance but apparently I don't because I'm confused as to why there a setup method in XCTestCase if XCTest provides the setup method in its class?  XCTestCase is a subclass of XCTest but after reading the Apple docs, it doesn't look any different between the two.</p>

```<code>import XCTest
@testable import FirstDemo

class FirstDemoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}
</code>```

答:
You can override a method in a subclass to add more functionality to what the superclass has.

You can override the superclass's implementation completely or you can call super.setUp() in the overriding method to execute the superclass's implementation before anything that you add in the override.

In tests, it's common for an XCTestCase subclass to override setUp() to add common setup actions for that class, whereas the superclass's implementation will execute common setup actions for your whole suite. For example, one XCTestCase subclass will have a setUp() method which launches the app, and a subclass of that class will have a setUp() method which calls its superclass setup and then initializes the area under test in that class. In a unit test, this could mean creating an object, or in a UI test, this could mean navigating to a particular page in your app.

You need to override XCTestCase's setUp() when you subclass it if you want something to happen during the setup stage of your tests as it has an empty implementation by default.

The reason that XCTest has a setUp() method defined (even though it does nothing) is to enable other methods on XCTest to call setUp(), for example, invokeTest() on XCTestCase calls setUp(). This enables users of the framework to specify actions to be done at the beginning of each test by overriding the setUp() method, which does not require any test invocation logic, instead of having to override methods with other logic in them, which we wouldn't necessarily know about and may not implement correctly or at all when overriding the method. This model makes setUp() a safe place for you to execute code entirely of your choosing, without needing to worry about whether you have broken the entire test framework.

Body:
I'd like to think that I understand the idea of inheritance but apparently I don't because I'm confused as to why there a setup method in XCTestCase if XCTest provides the setup method in its class?  XCTestCase is a subclass of XCTest but after reading the Apple docs, it doesn't look any different between the two.

import XCTest
@testable import FirstDemo

class FirstDemoTests: XCTestCase {

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }

    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }

    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }

}


问:
Jquery/Ajax Modal is not loading
I am having a problem opening up my modal. I am not sure where the problem lies. rental_id is the primary key for the table in database.</p>

```<code><script>
    function detailsmodal(rental_id){
        var data = {"rental_id" : rental_id};
        jQuery.ajax({
            url : <?=BASEURL;?>+'includes/detailsmodal.php',
            method : "post",
            data : data,
            success: function(data){
                jQuery('body').append(data);
                jQuery('#quote').modal('toggle');
            },
            error: function(){
                alert("Something went wrong!");
            }
        });
    }
</script>
</code>```

答:
Bootstrap has a few functions that can be called manually on modals:

```<code>$('#quote').modal('toggle');//"toggle" not working sometimes
$('#quote').modal('show');
$('#quote').modal('hide');
</code>```

You can see more from here: http://getbootstrap.com/javascript/#modals

Title: Jquery/Ajax Modal is not loading

Body:
Bootstrap has a few functions that can be called manually on modals:

$('#quote').modal('toggle');//"toggle" not working sometimes
$('#quote').modal('show');
$('#quote').modal('hide');

You can see more from here: http://getbootstrap.com/javascript/#modals


问:
WindowsError: [Error 2] The system cannot find the file specified in pexpect.popen_spawn.PopenSpawn
I was trying to open telnet connection using pexpect.popen_spawn.PopenSpawn on Windows as pexpect.spawn is only available on Linux platform. I have tested the same python script with pexpect.spawn on Linux and it works fine. However, I am unable to open telnet using pexpect.popen_spawn.PopenSpawn on Windows. The line pexpect.popen_spawn.PopenSpawn("C:/Windows/System32/telnet.exe <IP> <PORT>") shows following error

```<code>    console = popen_spawn.PopenSpawn(mycommand)
  File "C:\Python27\lib\site-packages\pexpect\popen_spawn.py", line 45, in __ini
t__
    self.proc = subprocess.Popen(cmd, **kwargs)
  File "C:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code>```

Now telnet.exe is available at the C:/Windows/System32 and I have successfully tested the same command using telnet on command prompt. What am I doing wrong? Any idea? I am using python 2.7

答:
Consider using an absolute path for your command-execution.
To find out where  telnet resides, run the following in cmd.exe: where  telnet and that should give you the absolute path.

Then simply do:

popen_spawn.PopenSpawn('C:/Windows/System32/telnet ***')

Body:
I was trying to open telnet connection using pexpect.popen_spawn.PopenSpawn on Windows as pexpect.spawn is only available on Linux platform. I have tested the same python script with pexpect.spawn on Linux and it works fine. However, I am unable to open telnet using pexpect.popen_spawn.PopenSpawn on Windows. The line pexpect.popen_spawn.PopenSpawn("C:/Windows/System32/telnet.exe <IP> <PORT>") shows following error

    console = popen_spawn.PopenSpawn(mycommand)
  File "C:\Python27\lib\site-packages\pexpect\popen_spawn.py", line 45, in __ini
t__
    self.proc = subprocess.Popen(cmd, **kwargs)
  File "C:\Python27\lib\subprocess.py", line 710, in __init__
    errread, errwrite)
  File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

Now telnet.exe is available at the C:/Windows/System32 and I have successfully tested the same command using telnet on command prompt. What am I doing wrong? Any idea? I am using python 2.7


问:
connection.getCatalog() returns null for Oracle
When using oracle.jdbc.driver.OracleDriver to connect an Oracle database, connection.getCatalog() returns null. For MySql database, it returns the database name. Is there any way to get oracle database name easily?</p>

答:
Because in Oracle a user equals a "schema". So try

DatabaseMetaData.getUserName()