问:
How should I approach the logic for writing the code for a more complex ng-model feature?
First, let me explain the effect I am looking for:

Layout:

Header at the top of the page that says "Choose between...".

Two input boxes below, input1 and input2

Effect

If the user begins typing first in [choice1] in input1, the header auto-updates and says "Choose between [choice 1] and..."

If the user begins typing first in [choice2] in input2, the header auto-updates and says "Choose between ___ and [choice2]"

If the user has already written in one input and begins writing in the other input, the header auto-updates and says "Choose between [choice1] and [choice2]".

Now, I have already written the angular-js code to achieve this. I am not looking for an answer on how to achieve the effect. Instead, I want to know the logic for the best way to achieve this effect because I think the way I did it could be improved.

Finally, here is the logic I used:

Create 4 divs with 4 ng-switch-when properties. Each div contains a header. First div contains header with "Choose between..." written on it. Second div contains header with "Choose between [input1text] and..." written on it. Third div contains a header with "Choose between ___ and [input2text]" written on it. Final div has "Choose between [input1text] and [input2text]" written on it. Each div has an ng-switch-when property, they are: "not-pressed", "first-pressed", "second-pressed", and "both-pressed", respectively

If someone starts typing in input1, I see if either second-pressed state or both-pressed state is currently active. If one is, I set the state to both-pressed. Otherwise, I set the state to first-pressed.

If someone starts typing in input2, I see if either first-pressed state or both-pressed state is currently active. If one is, I set the state to both-pressed. Otherwise, I set the state to second-pressed.

I think the way I wrote it is really clunky and messy and I'd like an opinion on if there is a better way to apprach the logic to this feature. Again, I am not looking for code. I just want to see if there is better logic.

答:
I would only have 2 'div', in the ng-switch-when block.

choice1 and choice2 are part of ng-model

ng-switch on checks whether choice1 or choice2 is not an empty string. This means: choice1 is not empty, or choice2 is not empty, or choice1 and choice2 are not empty

ng-switch-when = true then renders. Note as least one of the choices is entered.

```<code><div>
  <h2> Choose between {{choice1 === "" ? "____" : choice1}} and {{choice2 === "" ? "..." : choice2}} </h2>
</div>
</code>```

ng-switch-default would render the header as Choose between ...

Edit:
Actually, I think it's better to have a div as a wrapper outside the ng-switch, then renders only inner element. It seems like regardless of of the values of the inputs, you will always show the header.

Body:
I would only have 2 'div', in the ng-switch-when block.

choice1 and choice2 are part of ng-model

ng-switch on checks whether choice1 or choice2 is not an empty string. This means: choice1 is not empty, or choice2 is not empty, or choice1 and choice2 are not empty

ng-switch-when = true then renders. Note as least one of the choices is entered.

<div>
  <h2> Choose between {{choice1 === "" ? "____" : choice1}} and {{choice2 === "" ? "..." : choice2}} </h2>
</div>

ng-switch-default would render the header as Choose between ...

Edit:
Actually, I think it's better to have a div as a wrapper outside the ng-switch, then renders only inner element. It seems like regardless of of the values of the inputs, you will always show the header.


来源: stackexchange

问:
npm start Microsoft JScript runtime error 800A138F object expected
Getting started with NPM...

I can run the following command to start my app.

```<code>node app
</code>```

But when I run the following command, I get the following error:

```<code>npm start
</code>```

Windows Script Host
  Object expected

Line 2

800A138F

Microsoft JScript runtime error

App.js:

```<code>var port = 5000;
var express = require('express');
</code>```

Package.json:

```<code>{
  "name": "2",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.3"
  }
}
</code>```

And I've run this command of course:

```<code>npm install express --save
</code>```

Seems like NPM can't find the express package? Why not?

答:
Use >node app.js instead of >app.js

Then it will work

ContentLicense: CC BY-SA 3.0

Body:
Getting started with NPM...

I can run the following command to start my app.

node app

But when I run the following command, I get the following error:

npm start

Windows Script Host
  Object expected

Line 2

800A138F

Microsoft JScript runtime error

App.js:

var port = 5000;
var express = require('express');

Package.json:

{
  "name": "2",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.3"
  }
}

And I've run this command of course:

npm install express --save

Seems like NPM can't find the express package? Why not?


问:
ARM Disassembly - confused about "LDR r7, [pc, #0x14]"
I am attempting to learn ARM assembly.  I decided to disassembly the "read" function and this is what I get.  From the looks of it, it seems to be making a system call (svc #0) using the R7 register as the system call number.

```<code>mov ip, r7            # save R7
ldr r7, [pc, #0x14]   # get system call number and put it into R7 ??
svc #0                # make system call
mov r7, ip            # restore R7
cmn r0, #0x1000
bxls lr
rsb r0, r0, #0        # R0 = 0
b #2976848216
</code>```

I am a bit confused though on why it is loading the system call number the way it is ("LDR r7, [PC, #0x14]").  Isn't this just doing in C code r7 = *(pc + 0x14)? I looked at other functions that might also use system calls (e.g. kill, wait, etc.) and they use a very similar convention (i.e. LDR R7, [PC, #0x14]).

This is on Android if it helps at all.

Thanks!

答:
```<code>mov ip, r7            @# save R7
ldr r7, [pc, #0x14]   @# get system call number and put it into R7 ??
svc #0                @# make system call
mov r7, ip            @# restore R7
cmn r0, #0x1000       @
bxls lr               @
rsb r0, r0, #0        @# R0 = 0
.word 0x1234
.word 0xABCD
</code>```

you pretty much left out the most important parts so had to improvise

```<code>00000000 <.text>:
   0:   e1a0c007    mov ip, r7
   4:   e59f7014    ldr r7, [pc, #20]   ; 20 <.text+0x20>
   8:   ef000000    svc 0x00000000
   c:   e1a0700c    mov r7, ip
  10:   e3700a01    cmn r0, #4096   ; 0x1000
  14:   912fff1e    bxls    lr
  18:   e2600000    rsb r0, r0, #0
  1c:   00001234    andeq   r1, r0, r4, lsr r2
  20:   0000abcd    andeq   sl, r0, sp, asr #23
</code>```

And yes it is doing what you say it is doing, it is loading some value in r7 before making the system call, now what value is it as to why it is using a pc relative load (likely a constant that wont fit as an immediate, and/or a link time resolved value rather than compile time) and are there different values for different system calls and is r7 a parameter or not?  Well you didnt provide enough information to talk about that.  Once you have/see that information then that should be pretty obvious what those answers are...if any of those are is your question.

Body:
I am attempting to learn ARM assembly.  I decided to disassembly the "read" function and this is what I get.  From the looks of it, it seems to be making a system call (svc #0) using the R7 register as the system call number.

mov ip, r7            # save R7
ldr r7, [pc, #0x14]   # get system call number and put it into R7 ??
svc #0                # make system call
mov r7, ip            # restore R7
cmn r0, #0x1000
bxls lr
rsb r0, r0, #0        # R0 = 0
b #2976848216

I am a bit confused though on why it is loading the system call number the way it is ("LDR r7, [PC, #0x14]").  Isn't this just doing in C code r7 = *(pc + 0x14)? I looked at other functions that might also use system calls (e.g. kill, wait, etc.) and they use a very similar convention (i.e. LDR R7, [PC, #0x14]).

This is on Android if it helps at all.

Thanks!

Body:
mov ip, r7            @# save R7
ldr r7, [pc, #0x14]   @# get system call number and put it into R7 ??
svc #0                @# make system call
mov r7, ip            @# restore R7
cmn r0, #0x1000       @
bxls lr               @
rsb r0, r0, #0        @# R0 = 0
.word 0x1234
.word 0xABCD

you pretty much left out the most important parts so had to improvise

00000000 <.text>:
   0:   e1a0c007    mov ip, r7
   4:   e59f7014    ldr r7, [pc, #20]   ; 20 <.text+0x20>
   8:   ef000000    svc 0x00000000
   c:   e1a0700c    mov r7, ip
  10:   e3700a01    cmn r0, #4096   ; 0x1000
  14:   912fff1e    bxls    lr
  18:   e2600000    rsb r0, r0, #0
  1c:   00001234    andeq   r1, r0, r4, lsr r2
  20:   0000abcd    andeq   sl, r0, sp, asr #23

And yes it is doing what you say it is doing, it is loading some value in r7 before making the system call, now what value is it as to why it is using a pc relative load (likely a constant that wont fit as an immediate, and/or a link time resolved value rather than compile time) and are there different values for different system calls and is r7 a parameter or not?  Well you didnt provide enough information to talk about that.  Once you have/see that information then that should be pretty obvious what those answers are...if any of those are is your question.


问:
PyDev tells "error == cudaSuccess (35 vs. 0)CUDA driver version is insufficient for CUDA runtime version",but command line works fine
My configuration like this:

```<code>Ubuntu        16.04
Java          1.8
Python        2.7.12
Caffe         1.0
Cuda          8.0
Nvidia driver 375-66
PyDev         5.7.0.201704111357

And I tried to run this in bash:
</code>```

https://github.com/ZheC/Realtime_Multi-Person_Pose_Estimation/tree/master/testing/python

by

```<code>python -m Demo
</code>```

It works fine,but when try to run from eclipse-pydev,got this error:

```<code>WARNING: Logging before InitGoogleLogging() is written to STDERR
E0606 09:34:43.905447 15924 common.cpp:114] Cannot create Cublas handle. Cublas won't be available.
0
E0606 09:34:43.905640 15924 common.cpp:121] Cannot create Curand generator. Curand won't be available.
F0606 09:34:43.905845 15924 common.cpp:152] Check failed: error == cudaSuccess (35 vs. 0)  CUDA driver version is insufficient for CUDA runtime version
*** Check failure stack trace: ***
</code>```

I think this problem comes from that I start up OS with nvidia driver then switchs to intel like this:

This is what I want due to hope to use embeded intel VC to handle OS related work,and leave Nvidia VC for caffe(a deep learning framework) jobs.The
question is :

Why,for same python wrapped caffe job,does command line work fine but PyDev give the these error?

答:
Thanks the tips from @Fabio Zadrozny

Window->Preferences->PyDev->Interpreters->Python Interpreter->Click Environment->New

```<code>create a env variable:
Name:LD_LIBRARY_PATH   Value:as in you system env
</code>```

Body:
My configuration like this:

Ubuntu        16.04
Java          1.8
Python        2.7.12
Caffe         1.0
Cuda          8.0
Nvidia driver 375-66
PyDev         5.7.0.201704111357

And I tried to run this in bash:

https://github.com/ZheC/Realtime_Multi-Person_Pose_Estimation/tree/master/testing/python

by

python -m Demo

It works fine,but when try to run from eclipse-pydev,got this error:

WARNING: Logging before InitGoogleLogging() is written to STDERR
E0606 09:34:43.905447 15924 common.cpp:114] Cannot create Cublas handle. Cublas won't be available.
0
E0606 09:34:43.905640 15924 common.cpp:121] Cannot create Curand generator. Curand won't be available.
F0606 09:34:43.905845 15924 common.cpp:152] Check failed: error == cudaSuccess (35 vs. 0)  CUDA driver version is insufficient for CUDA runtime version
*** Check failure stack trace: ***

I think this problem comes from that I start up OS with nvidia driver then switchs to intel like this:

This is what I want due to hope to use embeded intel VC to handle OS related work,and leave Nvidia VC for caffe(a deep learning framework) jobs.The
question is :

Why,for same python wrapped caffe job,does command line work fine but PyDev give the these error?

Body:
Thanks the tips from @Fabio Zadrozny

Window->Preferences->PyDev->Interpreters->Python Interpreter->Click Environment->New

create a env variable:
Name:LD_LIBRARY_PATH   Value:as in you system env


问:
Importing/exporting the Express router using ES6 import + export keywords and Babel
I have an old test project originally built with Express 2.X. I am moving it to Express 4.x and trying to insert Babel 6.x to experiment with ES6 features server-side.

The update to Express 4.x went OK. The original app works fine. The problems arise when I start adding ES6 features.

In particular, I want to substitute all require and module.export instructions with ES6 import {...} from... and export {...}.

Problem: I seem unable to import routes from external files into the main app.js file.

My app.js loads routes like so:

```<code>import { indexRoute } from './routes/index_route';
app.use('/', indexRoute);
</code>```

Inside index_route.js I have:

```<code>"use strict";
import express from 'express';
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index_view', { title: 'Express' });
});

export { router }
</code>```

This source code is OK for Babel, but node complains at startup:

```<code>Router.use() requires middleware function but got a undefined
</code>```

I have two files like index_route.js, each one for a group of routes, and AFAIS they both import + modify + export the same router object. In any case, the export+import done using ES6 keywords returns undefined.

What am I doing wrong? Am I using the ES6 keywords on the wrong objects? Am I using obsolete instructions to configure the routes inside app.js?

答:
Try this:</p>

```<code>export default router;
</code>```

Body:
I have an old test project originally built with Express 2.X. I am moving it to Express 4.x and trying to insert Babel 6.x to experiment with ES6 features server-side.

The update to Express 4.x went OK. The original app works fine. The problems arise when I start adding ES6 features.

In particular, I want to substitute all require and module.export instructions with ES6 import {...} from... and export {...}.

Problem: I seem unable to import routes from external files into the main app.js file.

My app.js loads routes like so:

import { indexRoute } from './routes/index_route';
app.use('/', indexRoute);

Inside index_route.js I have:

"use strict";
import express from 'express';
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index_view', { title: 'Express' });
});

export { router }

This source code is OK for Babel, but node complains at startup:

Router.use() requires middleware function but got a undefined

I have two files like index_route.js, each one for a group of routes, and AFAIS they both import + modify + export the same router object. In any case, the export+import done using ES6 keywords returns undefined.

What am I doing wrong? Am I using the ES6 keywords on the wrong objects? Am I using obsolete instructions to configure the routes inside app.js?

Body:
Try this:

export default router;


问:
Cakephp read() on a non-object in session when I call another Controller
I'm working with Cakephp and I get a error with sessions when I call a method from another Controller.

Error
Error: Call to a member function read() on a non-object

Controller Hotels

```<code>App::import('Controller', 'Reports');
$Report = new ReportsController;
$Report->hotelsActivity($cabecera, $data, "Actividad Hotels Report");
</code>```

Method of Controller Reports

```<code>function hotelsActivity($cabecera, $data, $nombre){
  $this->layout = false;
  $this->autoRender = false;
  $size = parent::excel($cabecera, $data, $nombre);

  $this->set('filesize',CakeNumber::toReadableSize($size));
  $this->set('counter',count($data));

  $this->render('new_reports');
}
</code>```

Header appController

```<code>App::uses('Controller', 'Controller');

class AppController extends Controller {
    public $components = array(
      'Session'
    );

    public $helpers = array(
        'Session'
    );

    public function beforeFilter() {
        parent::beforeFilter();

        //$this->Auth->allow();
        //$this->Auth->allow("*");
    }

    public function breadcump(){

        $model = $this->name;

        $breadcump = Array();
        foreach($_GET as $key => $value){
            switch($key){
              case "hotels_id":
                $breadcump_model = "Hotel";
                $breadcump_name = "Hotel";
                $breadcump_field = "name";
              break;
              case "medics_id":
                $breadcump_model = "Medic";
                $breadcump_name = "Médico";
                $breadcump_field = "name";
              break;
              case "users_id":
                $breadcump_model = "User";
                $breadcump_name = "Usuario";
                $breadcump_field = "user_name";
              break;
              case "manager_id":
                $breadcump_model = "User";
                $breadcump_name = "Manager";
                $breadcump_field = "user_name";
              break;
              case "group_id":
                $breadcump_model = "Group";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "nightusers_id":
                $breadcump_model = "User";
                $breadcump_name = "Responsable de noche";
                $breadcump_field = "user_name";
              break;
              case "hotelstypes_id":
                $breadcump_model = "Hotelstype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "hotelsgroups_id":
                $breadcump_model = "Hotelsgroup";
                $breadcump_name = "Cadena";
                $breadcump_field = "name";
              break;
              case "regions_id":
                $breadcump_model = "Region";
                $breadcump_name = "Region";
                $breadcump_field = "name";
              break;
              case "zones_id":
                $breadcump_model = "Zone";
                $breadcump_name = "Zona";
                $breadcump_field = "name";
              break;
              case "subzones_id":
                $breadcump_model = "Subzone";
                $breadcump_name = "Subzona";
                $breadcump_field = "name";
              break;
              case "centres_id":
                $breadcump_model = "Centre";
                $breadcump_name = "Centro";
                $breadcump_field = "name";
              break;
              case "ttoos_id":
                $breadcump_model = "Ttoo";
                $breadcump_name = "Tour Operador";
                $breadcump_field = "name";
              break;
              case "incidencestypes_id":
                $breadcump_model = "Incidencestype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "origins_id":
                $breadcump_model = "Origin";
                $breadcump_name = "Origen";
                $breadcump_field = "name";
              break;
              case "ttoogroups_id":
                $breadcump_model = "Ttoogroup";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "ttoonationalities_id":
                $breadcump_model = "Ttoonationality";
                $breadcump_name = "Nacionalidad";
                $breadcump_field = "name";
              break;
              default:
                $breadcump_model = null;
            }

            // Condición para las búsquedas belongsto
            if($breadcump_model){
              if($value != ""){
                $breadcump[$key] = $value;
                $this->loadModel($breadcump_model);
                $conditions = array('conditions' => array($breadcump_model.'.id =' => $value), 'fields' => array($breadcump_model.'.'.$breadcump_field));
                $hotel = $this->$breadcump_model->find('all', $conditions);
                if($breadcump_name == "Responsable de noche"){
                  $breadcump[$breadcump_model."2"]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model."2"]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model."2"]['id'] = $value;
                }
                else{
                  $breadcump[$breadcump_model]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model]['id'] = $value;
                }
              }
            }
            // Condición para las búsquedas fijas tipo fecha inicio, fecha fin, status..
            else{
              if($value != ""){
                if($key == "status"){
                    if ($model=="Incidences") {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Activa"; break;
                          case 2: $value = "Finalizada"; break;
                        }
                    } else {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Aceptada"; break;
                          case 2: $value = "Asignada"; break;
                          case 3: $value = "Registrada"; break;
                          case 4: $value = "Anulada"; break;
                        }
                    }
                }
                if($key == "colaborator"){
                  switch($value){
                    case 'y': $value = "Sí"; break;
                    case 'n': $value = "No"; break;
                  }
                }
                if($key == "priority"){
                  $key = "Prioridad médico";
                }
                if($key =="dpd1"){
                    $key = "Fecha Inicio";
                }
                if($key =="dpd2"){
                    $key = "Fecha Fin";
                }

                $breadcump[$key] = $value;
                $breadcump[$key] = array('data_name' => $key, 'data' => $value);
              }
            }
        }

        return $breadcump;
    }

    public function excel($cabecera, $data, $report_type){

      $counter = count($data);
      $celdas = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

      // Importamos la clase PHPExcel
      App::import('Vendor', 'Classes/PHPExcel');
      App::uses('CakeTime', 'Utility');
      App::uses('CakeNumber', 'Utility');

      $objPHPExcel = new PHPExcel();
      $objPHPExcel->setActiveSheetIndex(0);

      $session = $this->request->session();
      $session->read('auth_user.User.user_name');

      // Set properties
      $objPHPExcel->getProperties()->setCreator($session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setLastModifiedBy($this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setTitle("FreepApp ".$report_type);
      $objPHPExcel->getProperties()->setSubject("Autogenerated Excel File");
      $objPHPExcel->getProperties()->setDescription("This is an automated excel file generated by IMS FreepApp Application");

      $filename = WWW_ROOT.'/files/tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx';

      $this->set('filename','tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx');

      //Sheet rename
      $objPHPExcel->getActiveSheet()->setTitle($report_type);

      //Creating Header
      $objPHPExcel->getActiveSheet()->SetCellValue('A1', Configure::read('title') . ' ' . Configure::read('Ver') . ' Report System');
      $objPHPExcel->getActiveSheet()->SetCellValue('A2', 'Type');
      $objPHPExcel->getActiveSheet()->SetCellValue('B2', $report_type);
      $objPHPExcel->getActiveSheet()->SetCellValue('A3', 'Records');
      $objPHPExcel->getActiveSheet()->SetCellValue('B3', $counter);
      $objPHPExcel->getActiveSheet()->SetCellValue('A4', 'Date');
      $objPHPExcel->getActiveSheet()->SetCellValue('B4', date('d/m/Y H:i:s', time()));
      $objPHPExcel->getActiveSheet()->SetCellValue('A5', 'User');
      $objPHPExcel->getActiveSheet()->SetCellValue('B5', $this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getActiveSheet()->mergeCells('A1:X1');
      $objPHPExcel->getActiveSheet()->mergeCells('B2:X2');
      $objPHPExcel->getActiveSheet()->mergeCells('B3:X3');
      $objPHPExcel->getActiveSheet()->mergeCells('B4:X4');
      $objPHPExcel->getActiveSheet()->mergeCells('B5:X5');

      //Header styles
      $style1 = array(
          'font' => array(
              'bold' => true,
              'size' => '18',
              'color' => array('rgb' => 'ffffff')

          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $style2 = array(
          'font' => array(
              'bold' => true,
              'size' => '14',
              'color' => array('rgb' => 'ffffff')
          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle('A1:X1')->applyFromArray($style1);
      $objPHPExcel->getActiveSheet()->getStyle('A2:B5')->applyFromArray($style2);

      //Title Bars
      for ($i=0; $i < count($cabecera); $i++) {
        if($i == 0){ $primeraCelda = "$celdas[$i]7"; }
        elseif( $i == (count($cabecera)-1) ){ $ultimaCelda = "$celdas[$i]7"; }
        $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$i]7", "$cabecera[$i]");
      }

      $header = "$primeraCelda:$ultimaCelda";
      $style = array(
          'font' => array('bold' => true,),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => 'E0E0E0')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle($header)->applyFromArray($style);
      $objPHPExcel->getActiveSheet()->setAutoFilter("$primeraCelda:$ultimaCelda");

      $rowCount = 8;
      for ($i=0; $i < count($data); $i++) {
        $contadorCeldas = 0;
        foreach ($data[$i] as $key => $arrayFinal) {
          $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$contadorCeldas]$rowCount", $data[$i][$key]);
              $contadorCeldas++;
        }
        $rowCount++;
      }

      //Set column autosize
      for($col = 'A'; $col !== 'AA'; $col++) {
          $objPHPExcel->getActiveSheet()
              ->getColumnDimension($col)
              ->setAutoSize(true);
      }
      $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
      $objWriter->save($filename);

      $f = fopen($filename, 'r+');
      $stat = fstat($f);
      return $size = $stat['size'];

    }

}
</code>```

Line on get the error in parent Controller

```<code>$this->Session->read('auth_user.User.user_name')
</code>```

答:
Define sessionhelper in app controller :

```<code>class AppController extends Controller {

public $components = array(
    'Session'
);

public $helpers = array(
    'Session'
);
}
</code>```

Then try it:

```<code>$session = $this->request->session();
$session->read('auth_user.User.user_name');
</code>```

Body:
I'm working with Cakephp and I get a error with sessions when I call a method from another Controller.

Error
Error: Call to a member function read() on a non-object

Controller Hotels

App::import('Controller', 'Reports');
$Report = new ReportsController;
$Report->hotelsActivity($cabecera, $data, "Actividad Hotels Report");

Method of Controller Reports

function hotelsActivity($cabecera, $data, $nombre){
  $this->layout = false;
  $this->autoRender = false;
  $size = parent::excel($cabecera, $data, $nombre);

  $this->set('filesize',CakeNumber::toReadableSize($size));
  $this->set('counter',count($data));

  $this->render('new_reports');
}

Header appController

App::uses('Controller', 'Controller');

class AppController extends Controller {
    public $components = array(
      'Session'
    );

    public $helpers = array(
        'Session'
    );

    public function beforeFilter() {
        parent::beforeFilter();

        //$this->Auth->allow();
        //$this->Auth->allow("*");
    }

    public function breadcump(){

        $model = $this->name;

        $breadcump = Array();
        foreach($_GET as $key => $value){
            switch($key){
              case "hotels_id":
                $breadcump_model = "Hotel";
                $breadcump_name = "Hotel";
                $breadcump_field = "name";
              break;
              case "medics_id":
                $breadcump_model = "Medic";
                $breadcump_name = "Médico";
                $breadcump_field = "name";
              break;
              case "users_id":
                $breadcump_model = "User";
                $breadcump_name = "Usuario";
                $breadcump_field = "user_name";
              break;
              case "manager_id":
                $breadcump_model = "User";
                $breadcump_name = "Manager";
                $breadcump_field = "user_name";
              break;
              case "group_id":
                $breadcump_model = "Group";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "nightusers_id":
                $breadcump_model = "User";
                $breadcump_name = "Responsable de noche";
                $breadcump_field = "user_name";
              break;
              case "hotelstypes_id":
                $breadcump_model = "Hotelstype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "hotelsgroups_id":
                $breadcump_model = "Hotelsgroup";
                $breadcump_name = "Cadena";
                $breadcump_field = "name";
              break;
              case "regions_id":
                $breadcump_model = "Region";
                $breadcump_name = "Region";
                $breadcump_field = "name";
              break;
              case "zones_id":
                $breadcump_model = "Zone";
                $breadcump_name = "Zona";
                $breadcump_field = "name";
              break;
              case "subzones_id":
                $breadcump_model = "Subzone";
                $breadcump_name = "Subzona";
                $breadcump_field = "name";
              break;
              case "centres_id":
                $breadcump_model = "Centre";
                $breadcump_name = "Centro";
                $breadcump_field = "name";
              break;
              case "ttoos_id":
                $breadcump_model = "Ttoo";
                $breadcump_name = "Tour Operador";
                $breadcump_field = "name";
              break;
              case "incidencestypes_id":
                $breadcump_model = "Incidencestype";
                $breadcump_name = "Tipo";
                $breadcump_field = "name";
              break;
              case "origins_id":
                $breadcump_model = "Origin";
                $breadcump_name = "Origen";
                $breadcump_field = "name";
              break;
              case "ttoogroups_id":
                $breadcump_model = "Ttoogroup";
                $breadcump_name = "Grupo";
                $breadcump_field = "name";
              break;
              case "ttoonationalities_id":
                $breadcump_model = "Ttoonationality";
                $breadcump_name = "Nacionalidad";
                $breadcump_field = "name";
              break;
              default:
                $breadcump_model = null;
            }

            // Condición para las búsquedas belongsto
            if($breadcump_model){
              if($value != ""){
                $breadcump[$key] = $value;
                $this->loadModel($breadcump_model);
                $conditions = array('conditions' => array($breadcump_model.'.id =' => $value), 'fields' => array($breadcump_model.'.'.$breadcump_field));
                $hotel = $this->$breadcump_model->find('all', $conditions);
                if($breadcump_name == "Responsable de noche"){
                  $breadcump[$breadcump_model."2"]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model."2"]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model."2"]['id'] = $value;
                }
                else{
                  $breadcump[$breadcump_model]['data_name'] = $breadcump_name;
                  $breadcump[$breadcump_model]['data'] = $hotel[0][$breadcump_model][$breadcump_field];
                  $breadcump[$breadcump_model]['id'] = $value;
                }
              }
            }
            // Condición para las búsquedas fijas tipo fecha inicio, fecha fin, status..
            else{
              if($value != ""){
                if($key == "status"){
                    if ($model=="Incidences") {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Activa"; break;
                          case 2: $value = "Finalizada"; break;
                        }
                    } else {
                        $key = "Estado";
                        switch($value){
                          case 1: $value = "Aceptada"; break;
                          case 2: $value = "Asignada"; break;
                          case 3: $value = "Registrada"; break;
                          case 4: $value = "Anulada"; break;
                        }
                    }
                }
                if($key == "colaborator"){
                  switch($value){
                    case 'y': $value = "Sí"; break;
                    case 'n': $value = "No"; break;
                  }
                }
                if($key == "priority"){
                  $key = "Prioridad médico";
                }
                if($key =="dpd1"){
                    $key = "Fecha Inicio";
                }
                if($key =="dpd2"){
                    $key = "Fecha Fin";
                }

                $breadcump[$key] = $value;
                $breadcump[$key] = array('data_name' => $key, 'data' => $value);
              }
            }
        }

        return $breadcump;
    }

    public function excel($cabecera, $data, $report_type){

      $counter = count($data);
      $celdas = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

      // Importamos la clase PHPExcel
      App::import('Vendor', 'Classes/PHPExcel');
      App::uses('CakeTime', 'Utility');
      App::uses('CakeNumber', 'Utility');

      $objPHPExcel = new PHPExcel();
      $objPHPExcel->setActiveSheetIndex(0);

      $session = $this->request->session();
      $session->read('auth_user.User.user_name');

      // Set properties
      $objPHPExcel->getProperties()->setCreator($session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setLastModifiedBy($this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getProperties()->setTitle("FreepApp ".$report_type);
      $objPHPExcel->getProperties()->setSubject("Autogenerated Excel File");
      $objPHPExcel->getProperties()->setDescription("This is an automated excel file generated by IMS FreepApp Application");

      $filename = WWW_ROOT.'/files/tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx';

      $this->set('filename','tmp_report_'.$this->Session->read('auth_user.User.id').'.xlsx');

      //Sheet rename
      $objPHPExcel->getActiveSheet()->setTitle($report_type);

      //Creating Header
      $objPHPExcel->getActiveSheet()->SetCellValue('A1', Configure::read('title') . ' ' . Configure::read('Ver') . ' Report System');
      $objPHPExcel->getActiveSheet()->SetCellValue('A2', 'Type');
      $objPHPExcel->getActiveSheet()->SetCellValue('B2', $report_type);
      $objPHPExcel->getActiveSheet()->SetCellValue('A3', 'Records');
      $objPHPExcel->getActiveSheet()->SetCellValue('B3', $counter);
      $objPHPExcel->getActiveSheet()->SetCellValue('A4', 'Date');
      $objPHPExcel->getActiveSheet()->SetCellValue('B4', date('d/m/Y H:i:s', time()));
      $objPHPExcel->getActiveSheet()->SetCellValue('A5', 'User');
      $objPHPExcel->getActiveSheet()->SetCellValue('B5', $this->Session->read('auth_user.User.user_name'));
      $objPHPExcel->getActiveSheet()->mergeCells('A1:X1');
      $objPHPExcel->getActiveSheet()->mergeCells('B2:X2');
      $objPHPExcel->getActiveSheet()->mergeCells('B3:X3');
      $objPHPExcel->getActiveSheet()->mergeCells('B4:X4');
      $objPHPExcel->getActiveSheet()->mergeCells('B5:X5');

      //Header styles
      $style1 = array(
          'font' => array(
              'bold' => true,
              'size' => '18',
              'color' => array('rgb' => 'ffffff')

          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $style2 = array(
          'font' => array(
              'bold' => true,
              'size' => '14',
              'color' => array('rgb' => 'ffffff')
          ),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_LEFT,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => '428bca')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle('A1:X1')->applyFromArray($style1);
      $objPHPExcel->getActiveSheet()->getStyle('A2:B5')->applyFromArray($style2);

      //Title Bars
      for ($i=0; $i < count($cabecera); $i++) {
        if($i == 0){ $primeraCelda = "$celdas[$i]7"; }
        elseif( $i == (count($cabecera)-1) ){ $ultimaCelda = "$celdas[$i]7"; }
        $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$i]7", "$cabecera[$i]");
      }

      $header = "$primeraCelda:$ultimaCelda";
      $style = array(
          'font' => array('bold' => true,),
          'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
          'fill' => array(
              'type' => PHPExcel_Style_Fill::FILL_SOLID,
              'color' => array('rgb' => 'E0E0E0')
          )
      );
      $objPHPExcel->getActiveSheet()->getStyle($header)->applyFromArray($style);
      $objPHPExcel->getActiveSheet()->setAutoFilter("$primeraCelda:$ultimaCelda");

      $rowCount = 8;
      for ($i=0; $i < count($data); $i++) {
        $contadorCeldas = 0;
        foreach ($data[$i] as $key => $arrayFinal) {
          $objPHPExcel->getActiveSheet()->SetCellValue("$celdas[$contadorCeldas]$rowCount", $data[$i][$key]);
              $contadorCeldas++;
        }
        $rowCount++;
      }

      //Set column autosize
      for($col = 'A'; $col !== 'AA'; $col++) {
          $objPHPExcel->getActiveSheet()
              ->getColumnDimension($col)
              ->setAutoSize(true);
      }
      $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
      $objWriter->save($filename);

      $f = fopen($filename, 'r+');
      $stat = fstat($f);
      return $size = $stat['size'];

    }

}

Line on get the error in parent Controller

$this->Session->read('auth_user.User.user_name')

Body:
Define sessionhelper in app controller :

class AppController extends Controller {

public $components = array(
    'Session'
);

public $helpers = array(
    'Session'
);
}

Then try it:

$session = $this->request->session();
$session->read('auth_user.User.user_name');


问:
Difference between using [] and list() in Python when using with set() function
Could anyone tell me why this function work:

```<code>def findDisappearedNumbers(self, nums):
    return list(set(range(1,len(nums)+1)) - set(nums))
</code>```

but this function doesn't work:

```<code>def findDisappearedNums(self, nums):
    return [set(range(1, len(nums)+1)) - set(nums)]
</code>```

I would like to use [] instead of list() because [] has a better performance, but using [] with set() function would give me an error while list() with set() function works fine. Thanks.

```<code>>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718enter code here
</code>```

答:
It's not quite the same.  When you use [] as you are using it, you get a list with a single element, in this case a set of numbers.  When you cast it with list(), you're saying 'take all the elements of the set and make a list out of them'.  You can do this with list comprehensions if you like, by doing:

```<code>[x for x in set(range(1, len(nums)+1)) - set(nums)]
</code>```

but I think most pythonistas would just use list() in a case like this.

Body:
Could anyone tell me why this function work:

def findDisappearedNumbers(self, nums):
    return list(set(range(1,len(nums)+1)) - set(nums))

but this function doesn't work:

def findDisappearedNums(self, nums):
    return [set(range(1, len(nums)+1)) - set(nums)]

I would like to use [] instead of list() because [] has a better performance, but using [] with set() function would give me an error while list() with set() function works fine. Thanks.

>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718enter code here

Body:
It's not quite the same.  When you use [] as you are using it, you get a list with a single element, in this case a set of numbers.  When you cast it with list(), you're saying 'take all the elements of the set and make a list out of them'.  You can do this with list comprehensions if you like, by doing:

[x for x in set(range(1, len(nums)+1)) - set(nums)]

but I think most pythonistas would just use list() in a case like this.


问:
"call" for calling MySQL function work on JDBC but not on MySQL itself
I have a function in Java that uses a callable statement and calls a function of an schema in MySQL with the word "call". It works fine.

But if in MySQL I write:

```<code>call myFunction(); ( in this case :call getNumberOfIdeasDB();)
</code>```

It won't work, I get:

PROCEDURE ... doesnt exist.

It's weird to me that it works in Java but not in MySQL. Could you please help me understand why.

Here is my function in Java even though I don't believe it is relevant.

```<code>public static double getNumberOfIdeasDB() {
    Connection co = riverManager.getConnection("jdbc:...");
    CallableStatement ps = co.prepareCall("{?= call getNumberOfIdeasThisWeek()}"); //10

    ps.registerOutParameter(1, java.sql.Types.DOUBLE);

    ps.execute();

    return ps.getDouble(1);
}
</code>```

It is inside a try-catch and works fine I just don't know why here that word "call" works.

答:
The {?= call ...} is a JDBC escape (it is defined in the JDBC specification) to execute stored procedures. This escape allows you to write stored procedure calls in a - relatively - database-independent way.

The JDBC driver then has to translate that to the right statement for the underlying database.

Whether functions should be callable is a totally different matter, but the implementation of MySQL Connector/J thinks it does, and provides a translation (likely to something like select getNumberOfIdeasThisWeek()). If instead you had used call getNumberOfIdeasThisWeek() (that is, without the {?= and }), you would likely have received the same error you get when querying MySQL directly.

ContentLicense: CC BY-SA 4.0

Body:
I have a function in Java that uses a callable statement and calls a function of an schema in MySQL with the word "call". It works fine.

But if in MySQL I write:

call myFunction(); ( in this case :call getNumberOfIdeasDB();)

It won't work, I get:

PROCEDURE ... doesnt exist.

It's weird to me that it works in Java but not in MySQL. Could you please help me understand why.

Here is my function in Java even though I don't believe it is relevant.

public static double getNumberOfIdeasDB() {
    Connection co = riverManager.getConnection("jdbc:...");
    CallableStatement ps = co.prepareCall("{?= call getNumberOfIdeasThisWeek()}"); //10

    ps.registerOutParameter(1, java.sql.Types.DOUBLE);

    ps.execute();

    return ps.getDouble(1);
}

It is inside a try-catch and works fine I just don't know why here that word "call" works.


问:
How can i get ongoing project count in each month using MYSQL?
I have the table like this

```<code>Title    | start_date |end_date   |
------   | ---------- |---------  |
Test_pro1 | 2017-06-06 |2017-08-06 |
Test_pro2 | 2017-07-06 |2017-11-06 |
</code>```

I need the ongoing project count in each month.

```<code>Example 1 : 2017-06-06 project count = 1
Example 2 : 2017-07-06 project count = 2
Example 3 : 2017-11-06 project count = 0
</code>```

How can i write a query in MYSQL?

答:
May be your are looking for something like this (change YOUR_DATE with the value you want to check)?</p>

```<code>SELECT  COUNT(*) AS RC
FROM  YOUR_TABLE
WHERE   START_DATE <= YOUR_DATE AND END_DATE >= YOUR_DATE
</code>```

Body:
I have the table like this

Title    | start_date |end_date   |
------   | ---------- |---------  |
Test_pro1 | 2017-06-06 |2017-08-06 |
Test_pro2 | 2017-07-06 |2017-11-06 |

I need the ongoing project count in each month.

Example 1 : 2017-06-06 project count = 1
Example 2 : 2017-07-06 project count = 2
Example 3 : 2017-11-06 project count = 0

How can i write a query in MYSQL?

Body:
May be your are looking for something like this (change YOUR_DATE with the value you want to check)?

SELECT  COUNT(*) AS RC
FROM  YOUR_TABLE
WHERE   START_DATE <= YOUR_DATE AND END_DATE >= YOUR_DATE


问:
Android Data binding Error:Could not find com.android.databindig:databinder:1.0.-rc1
I have been trying for hours now to enable data binding in Android. Here is my gradle:

```<code>buildscript {
    repositories {
        mavenCentral()
        maven { url 'http://download.crashlytics.com/maven' }
        maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
    }

    dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
        classpath 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'

        classpath "com.android.databinding:dataBinder:1.0-rc0"
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

apply plugin: 'com.android.application'
apply plugin: 'crashlytics'

repositories {
    maven { url 'http://download.crashlytics.com/maven' }
    maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}

android {
    compileSdkVersion 16
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "ts.kiosk.app.checkout"
        minSdkVersion 16
        targetSdkVersion 16
        versionCode 2
        versionName "0.0.2.258"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        abortOnError false
    }

    sourceSets {
        main {
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        }
    }

    sourceSets {
        androidTest.setRoot('src/test')
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:support-v4:20.0.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'net.danlew:android.joda:2.7.2'
    compile 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'
    compile 'com.squareup.retrofit:retrofit:1.6.1'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
    compile 'com.squareup.okhttp:okhttp:2.0.0'

    compile project(':asterixmodule')
    compile project(':servicemodule')
    compile project(':sdfclient')

    // Robolectric
    testCompile 'junit:junit:4.12'
    testCompile 'org.hamcrest:hamcrest-library:1.3'
    testCompile 'org.apache.maven:maven-ant-tasks:2.1.3' // fixes issue on linux/mac
    testCompile 'org.robolectric:robolectric:3.0'
}
</code>```

I keep getting the error:

```<code>Error:Could not find com.android.databindig:databinder:1.0.-rc1   .
</code>```

I have also read similar posts on SO stating that you also have to add:

```<code>classpath 'com.android.tools.build:gradle:1.3.0-beta1'
</code>```

but my gradle is 2.4 so I'm thinking I don't need that and of course if I do add that statement, gradle cannot find that version of gradle  (1.3.0)

答:
check your gradle version, i resolved it by upgrading :

previously :

classpath "com.android.tools.build:gradle:1.3.0"

I updated to :

```<code>classpath "com.android.tools.build:gradle:2.2.0"
</code>```

Or 1.5.0 and newer.

Body:
I have been trying for hours now to enable data binding in Android. Here is my gradle:

buildscript {
    repositories {
        mavenCentral()
        maven { url 'http://download.crashlytics.com/maven' }
        maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
    }

    dependencies {
        classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+'
        classpath 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'

        classpath "com.android.databinding:dataBinder:1.0-rc0"
    }
}

allprojects {
    repositories {
        jcenter()
        mavenCentral()
    }
}

apply plugin: 'com.android.application'
apply plugin: 'crashlytics'

repositories {
    maven { url 'http://download.crashlytics.com/maven' }
    maven { url 'https://oss.sonatype.org/content/repositories/ksoap2-android-releases/' }
}

android {
    compileSdkVersion 16
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "ts.kiosk.app.checkout"
        minSdkVersion 16
        targetSdkVersion 16
        versionCode 2
        versionName "0.0.2.258"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    lintOptions {
        abortOnError false
    }

    sourceSets {
        main {
            assets.srcDirs = ['src/main/assets', 'src/main/assets/']
        }
    }

    sourceSets {
        androidTest.setRoot('src/test')
    }

    dataBinding {
        enabled = true
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:support-v4:20.0.0'
    compile 'com.crashlytics.android:crashlytics:1.+'
    compile 'net.danlew:android.joda:2.7.2'
    compile 'com.google.code.ksoap2-android:ksoap2-android:3.1.1'
    compile 'com.squareup.retrofit:retrofit:1.6.1'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
    compile 'com.squareup.okhttp:okhttp:2.0.0'

    compile project(':asterixmodule')
    compile project(':servicemodule')
    compile project(':sdfclient')

    // Robolectric
    testCompile 'junit:junit:4.12'
    testCompile 'org.hamcrest:hamcrest-library:1.3'
    testCompile 'org.apache.maven:maven-ant-tasks:2.1.3' // fixes issue on linux/mac
    testCompile 'org.robolectric:robolectric:3.0'
}

I keep getting the error:

Error:Could not find com.android.databindig:databinder:1.0.-rc1   .

I have also read similar posts on SO stating that you also have to add:

classpath 'com.android.tools.build:gradle:1.3.0-beta1'

but my gradle is 2.4 so I'm thinking I don't need that and of course if I do add that statement, gradle cannot find that version of gradle  (1.3.0)

Body:
check your gradle version, i resolved it by upgrading :

previously :

classpath "com.android.tools.build:gradle:1.3.0"

I updated to :

classpath "com.android.tools.build:gradle:2.2.0"

Or 1.5.0 and newer.


问:
Get Max and Min of 2 Columns SQL Server 2008 R2
This query is the final part of a store procedure that manages to show me the results in this way:

```<code>;with final_comparativo as (
                    select s.CeEmplazamiento, avg(s.Totales) TotalGeneral , s2.TotGral, @Mes as Mes
                    from tmpSemanas s
                        cross join ( select avg(Totales) TotGral from tmpSemanas s2 where Totales >0) s2
                    group by s.CeEmplazamiento , s2.TotGral
            union all
                    select ss.CeEmplazamiento, avg(ss.Totales) TotalGeneral , ss2.TotGral, @Mes_comparar as Mes
                    from tmpSemanas_comparar ss
                        cross join ( select avg(Totales) TotGral from tmpSemanas_comparar ss2 where Totales >0) ss2
                    group by ss.CeEmplazamiento , ss2.TotGral
        )

        --insert #tmpDatos
        , maximo_minimo as (
            select CeEmplazamiento,
                max(case when Mes  = @Mes then TotalGeneral else 0 end) as Mes_actual,
                max(case when Mes  = @Mes_comparar then TotalGeneral else 0 end) as Mes_comparar
            from final_comparativo
            where TotalGeneral <> 0
            group by CeEmplazamiento
            )

            select * from maximo_minimo
            drop table #tmpDatos
</code>```

This is the current result table

```<code>CeEmplazamiento Month_current Month_compare
Celaya          76.500000       75.600000
Coecillo        79.000000       79.800000
Irapuato        77.500000       75.400000
León Sur        85.750000       87.600000
Oriente León    86.250000       85.200000
</code>```

The store procedure asks you for 2 arguments corresponding to month_current (month of origin) month_compare (against which month you want to compare the month_current) so it is already a final calculation. But my problem lies in the following, I want this table to take the maximum and minimum of the current month and likewise for the column "Month_compare", I hope I have explained. More briefly, I would like it to remain this way.

```<code>CeEmplazamiento       Month_current Month_compare
Leon Sur              85.75        87.60
Celaya                76.50         null
Irapuato               null        75.40
</code>```

As far as you can tell, it is not the same amount for all CeEsmplazamiento, those that are not in the current Month, are not shown but are taken into account for a graphic that is being done. I hope you can help me

答:
Smth like this:</p>

```<code>    declare @t table(CeEmplazamiento varchar(100),  Month_current money, Month_compare money);
    insert into @t values
    ('Celaya',          76.500000,       75.600000),
    ('Coecillo',        79.000000,       79.800000),
    ('Irapuato',        77.500000,       75.400000),
    ('León Sur',        85.750000,       87.600000),
    ('Oriente León',    86.250000,       85.200000);

    with cte1 as
    (
    select top 1 CeEmplazamiento, Month_current, null as Month_compare
    from @t
    order by  Month_current asc
    )

    ,cte2 as
    (
    select top 1 CeEmplazamiento, Month_current, null as Month_compare
    from @t
    order by  Month_current desc
    )

    ,cte3 as
    (
    select top 1 CeEmplazamiento, null as Month_current, Month_compare
    from @t
    order by  Month_compare asc
    )

    ,cte4 as
    (
    select top 1 CeEmplazamiento, null as Month_current, Month_compare
    from @t
    order by  Month_compare desc
    )

    select *
    from cte1
    union all
    select *
    from cte2
    union all
    select *
    from cte3
    union all
    select *
    from cte4
</code>```

Body:
This query is the final part of a store procedure that manages to show me the results in this way:

;with final_comparativo as (
                    select s.CeEmplazamiento, avg(s.Totales) TotalGeneral , s2.TotGral, @Mes as Mes
                    from tmpSemanas s
                        cross join ( select avg(Totales) TotGral from tmpSemanas s2 where Totales >0) s2
                    group by s.CeEmplazamiento , s2.TotGral
            union all
                    select ss.CeEmplazamiento, avg(ss.Totales) TotalGeneral , ss2.TotGral, @Mes_comparar as Mes
                    from tmpSemanas_comparar ss
                        cross join ( select avg(Totales) TotGral from tmpSemanas_comparar ss2 where Totales >0) ss2
                    group by ss.CeEmplazamiento , ss2.TotGral
        )

        --insert #tmpDatos
        , maximo_minimo as (
            select CeEmplazamiento,
                max(case when Mes  = @Mes then TotalGeneral else 0 end) as Mes_actual,
                max(case when Mes  = @Mes_comparar then TotalGeneral else 0 end) as Mes_comparar
            from final_comparativo
            where TotalGeneral <> 0
            group by CeEmplazamiento
            )

            select * from maximo_minimo
            drop table #tmpDatos

This is the current result table

CeEmplazamiento Month_current Month_compare
Celaya          76.500000       75.600000
Coecillo        79.000000       79.800000
Irapuato        77.500000       75.400000
León Sur        85.750000       87.600000
Oriente León    86.250000       85.200000

The store procedure asks you for 2 arguments corresponding to month_current (month of origin) month_compare (against which month you want to compare the month_current) so it is already a final calculation. But my problem lies in the following, I want this table to take the maximum and minimum of the current month and likewise for the column "Month_compare", I hope I have explained. More briefly, I would like it to remain this way.

CeEmplazamiento       Month_current Month_compare
Leon Sur              85.75        87.60
Celaya                76.50         null
Irapuato               null        75.40

As far as you can tell, it is not the same amount for all CeEsmplazamiento, those that are not in the current Month, are not shown but are taken into account for a graphic that is being done. I hope you can help me

Body:
Smth like this:

    declare @t table(CeEmplazamiento varchar(100),  Month_current money, Month_compare money);
    insert into @t values
    ('Celaya',          76.500000,       75.600000),
    ('Coecillo',        79.000000,       79.800000),
    ('Irapuato',        77.500000,       75.400000),
    ('León Sur',        85.750000,       87.600000),
    ('Oriente León',    86.250000,       85.200000);

    with cte1 as
    (
    select top 1 CeEmplazamiento, Month_current, null as Month_compare
    from @t
    order by  Month_current asc
    )

    ,cte2 as
    (
    select top 1 CeEmplazamiento, Month_current, null as Month_compare
    from @t
    order by  Month_current desc
    )

    ,cte3 as
    (
    select top 1 CeEmplazamiento, null as Month_current, Month_compare
    from @t
    order by  Month_compare asc
    )

    ,cte4 as
    (
    select top 1 CeEmplazamiento, null as Month_current, Month_compare
    from @t
    order by  Month_compare desc
    )

    select *
    from cte1
    union all
    select *
    from cte2
    union all
    select *
    from cte3
    union all
    select *
    from cte4


问:
creating time series with seq and lubridate
Hi i have a data set with all character data type

```<code>col1        min_date        max_date
Minutes     2016-06-01    2016-06-27 11:15:00
15_minutes  2016-06-01    2016-06-27 11:15:00
</code>```

Now i trying to make time series according to values in "col1"
for Minutes :

```<code>time_index <- seq(from = ymd(df$min_date),
                  to = ymd_hms(df$max_date), by = "minute")
</code>```

for 15_minutes :

```<code>time_index <- seq(from = ymd(df$min_date),
                  to = ymd_hms(df$max_date), by = "15 minute")
</code>```

then i am getting error

Error in seq.Date(from = ymd(df$min_date),
                    to = ymd_hms(df$max_date), by = "minute",  :
    'from' must be of length 1

how do we solve ,thanks in advance

答:
We can use Map to do this as seq is not vectorized to take multiple ranges of dates.  With Map, we specify the input arguments as the dataset columns in the same order as from, to and by and apply the seq.  The 'col1' substring is taken for the by argument

```<code>df1$col1 <-  sub("utes", "", sub("_", " ", tolower(df1$col1)))

lst <- Map(seq, as.POSIXct(df1$min_date),
        as.POSIXct(df1$max_date), df1$col1)
lapply(lst, head, 2)
#[[1]]
#[1] "2016-06-01 00:00:00 IST" "2016-06-01 00:01:00 IST"

#[[2]]
#[1] "2016-06-01 00:00:00 IST" "2016-06-01 00:15:00 IST"
</code>```

Body:
Hi i have a data set with all character data type

col1        min_date        max_date
Minutes     2016-06-01    2016-06-27 11:15:00
15_minutes  2016-06-01    2016-06-27 11:15:00

Now i trying to make time series according to values in "col1"
for Minutes :

time_index <- seq(from = ymd(df$min_date),
                  to = ymd_hms(df$max_date), by = "minute")

for 15_minutes :

time_index <- seq(from = ymd(df$min_date),
                  to = ymd_hms(df$max_date), by = "15 minute")

then i am getting error

Error in seq.Date(from = ymd(df$min_date),
                    to = ymd_hms(df$max_date), by = "minute",  :
    'from' must be of length 1

how do we solve ,thanks in advance

Body:
We can use Map to do this as seq is not vectorized to take multiple ranges of dates.  With Map, we specify the input arguments as the dataset columns in the same order as from, to and by and apply the seq.  The 'col1' substring is taken for the by argument

df1$col1 <-  sub("utes", "", sub("_", " ", tolower(df1$col1)))

lst <- Map(seq, as.POSIXct(df1$min_date),
        as.POSIXct(df1$max_date), df1$col1)
lapply(lst, head, 2)
#[[1]]
#[1] "2016-06-01 00:00:00 IST" "2016-06-01 00:01:00 IST"

#[[2]]
#[1] "2016-06-01 00:00:00 IST" "2016-06-01 00:15:00 IST"


问:
Managing third party javascript libraries with bundled jQuery
I am working on a website globalization project, which involves (us the vendor) asking our clients to insert a script tag on their home/origin site. The script tag is necessary for helping our clients go global, and part of the solution embodies a UI that gets triggered based on certain end user criteria.

The UI is built through the help of jQuery, which we really can't expect our clients to insert on their pages, not to mention version mismatches will be hard to resolve. Therefore, our third party library downloads its own jQuery version, albeit namespaced differently to avoid any conflicts.

However, such a mechanism requires us to rename all instances of jQuery to something that will help us avoid name clashes with another jQuery instance (if present), and makes the our mangled jQuery (MY_Query in examples below) very hard to manage, let alone upgrade.

For example

```<code>jQuery = window.jQuery = window.$ = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
},
.
.
.
jQuery.fn = jQuery.prototype = ...
</code>```

becomes

```<code>MY_JQuery = window.MY_JQuery = window.MY_Q = function( selector, context ) {
    // The MY_JQuery object is actually just the init constructor 'enhanced'
    return new MY_JQuery.fn.init( selector, context );
},
.
.
.
MP_JQuery.fn = MP_JQuery.prototype = ...
</code>```

In an ideal world, both us and the client would have a single version of jQuery on the site, and we both would use it to our advantage. But that would mean an upgrade of jQuery would require heavy testing on both sides (while the mangled jQuery version is contained) and that any plugin wanted would require the client to add appropriate script tags to their site, spurring a political debate between the two parties on what versions win.

So, can I manage our jQuery version (with plugins) on a client site without having to rename all instances of jQuery with something like MY_Query with the constraints mentioned above?

答: Have you tried to use JQuery.noConflict(). This sounds like it could help you.</p>

ContentLicense: CC BY-SA 2.5

Body:
I am working on a website globalization project, which involves (us the vendor) asking our clients to insert a script tag on their home/origin site. The script tag is necessary for helping our clients go global, and part of the solution embodies a UI that gets triggered based on certain end user criteria.

The UI is built through the help of jQuery, which we really can't expect our clients to insert on their pages, not to mention version mismatches will be hard to resolve. Therefore, our third party library downloads its own jQuery version, albeit namespaced differently to avoid any conflicts.

However, such a mechanism requires us to rename all instances of jQuery to something that will help us avoid name clashes with another jQuery instance (if present), and makes the our mangled jQuery (MY_Query in examples below) very hard to manage, let alone upgrade.

For example

jQuery = window.jQuery = window.$ = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
},
.
.
.
jQuery.fn = jQuery.prototype = ...

becomes

MY_JQuery = window.MY_JQuery = window.MY_Q = function( selector, context ) {
    // The MY_JQuery object is actually just the init constructor 'enhanced'
    return new MY_JQuery.fn.init( selector, context );
},
.
.
.
MP_JQuery.fn = MP_JQuery.prototype = ...

In an ideal world, both us and the client would have a single version of jQuery on the site, and we both would use it to our advantage. But that would mean an upgrade of jQuery would require heavy testing on both sides (while the mangled jQuery version is contained) and that any plugin wanted would require the client to add appropriate script tags to their site, spurring a political debate between the two parties on what versions win.

So, can I manage our jQuery version (with plugins) on a client site without having to rename all instances of jQuery with something like MY_Query with the constraints mentioned above?


问:
Azure Media Services Status Disconnected
I move one AMS (Azure Media Service) and their Storage Account to another subscription at Azure Portal Tool. The migration was complete sucessfully. But before the migration the AMS was Active and now is is Disconnected.

Why? How can turn Active again ?

答: The portal shows Disconnected when the Storage attached to the AMS is new (not the classic). So this is by design and you can manage your AMS account from the new portal.</p>


问:
WCAG Compliance - Element with role="button" and no content
I'm trying to develop a WCAG compliant web app, currently codesniffer is giving me lots of:

This element has a role of "button" but does not have a name available
  to an accessibility API. Valid names are: element content.

From this HTML:

```<code><span unselectable="on" class="k-select" aria-label="abcd" role="button"  alt="abcd" title="abcd" value="abcd">
  <span class="k-icon k-i-calendar"></span>
</span>
</code>```

Setting alt, value, title and aria-label seem to do no good.
How can I have a WCAG compliant element with role="button" with no text inside it?

答:
You can use a button element with the aria-label and title attributes :

```<code> <button class="k-select" role="button"
        aria-label="alternative for screen readers"
        title="alternative for other users"
        value="abcd">
   <span class="k-icon k-i-calendar"></span>
 </button>
</code>```

Body:
I'm trying to develop a WCAG compliant web app, currently codesniffer is giving me lots of:

This element has a role of "button" but does not have a name available
  to an accessibility API. Valid names are: element content.

From this HTML:

Setting alt, value, title and aria-label seem to do no good.
How can I have a WCAG compliant element with role="button" with no text inside it?

Body:
You can use a button element with the aria-label and title attributes :

 <button class="k-select" role="button"
        aria-label="alternative for screen readers"
        title="alternative for other users"
        value="abcd">
   <span class="k-icon k-i-calendar"></span>
 </button>


问:
how append date build to versionNameSuffix on gradle
I am using Android Studio and I need to append a suffix to the versionNameSuffix on my Android build.gradle file. I have three different build types and I only need to append the datetime to my "beta" release. My actual file is:

defaultConfig {
    versionCode 14
    versionName "0.7.5"
    minSdkVersion 9
    targetSdkVersion 18
}
buildTypes {
    beta {
        packageNameSuffix ".beta"
        versionNameSuffix "-beta"
        signingConfig signingConfigs.debug
    }
    ....
}
```

For testing and automatic deploy, I need to get a final versionName like: 0.7.5-beta-build20131004, 0.7.5-beta-build1380855996 or something like that. Any ideas?

答:
You can test

```<code>task timenow {
    println(new Date().getTime())
}
</code>```

Run gradle: gradle timenow

See details. Place it on the top-level build

```<code>ext {
    configuration = [
            appName          : "vBulletin",
            applicationId    : "com.vbulletin",
            minSdkVersion    : 14,
            targetSdkVersion : 19,
            compileSdkVersion: 19,
            versionCode      : 6,
            versionName      : "1.3.6",
            buildToolsVersion: "25.0.0",
    ]

}

task createBrand {
    appConfig.applicationId = appConfig.applicationId + ".${brand}"
    appConfig.versionCode = new Date().getTime()
    appConfig.versionName = version
}
</code>```

Body:
I am using Android Studio and I need to append a suffix to the versionNameSuffix on my Android build.gradle file. I have three different build types and I only need to append the datetime to my "beta" release. My actual file is:

defaultConfig {
    versionCode 14
    versionName "0.7.5"
    minSdkVersion 9
    targetSdkVersion 18
}
buildTypes {
    beta {
        packageNameSuffix ".beta"
        versionNameSuffix "-beta"
        signingConfig signingConfigs.debug
    }
    ....
}

For testing and automatic deploy, I need to get a final versionName like: 0.7.5-beta-build20131004, 0.7.5-beta-build1380855996 or something like that. Any ideas?

Body:
You can test

task timenow {
    println(new Date().getTime())
}

Run gradle: gradle timenow

See details. Place it on the top-level build

ext {
    configuration = [
            appName          : "vBulletin",
            applicationId    : "com.vbulletin",
            minSdkVersion    : 14,
            targetSdkVersion : 19,
            compileSdkVersion: 19,
            versionCode      : 6,
            versionName      : "1.3.6",
            buildToolsVersion: "25.0.0",
    ]

}

task createBrand {
    appConfig.applicationId = appConfig.applicationId + ".${brand}"
    appConfig.versionCode = new Date().getTime()
    appConfig.versionName = version
}


问:
Can't create new simulator in xcode 9 beta
I have just installed xcode 9.0 beta. And I'm trying create a new simulator, but it no response when I click Create button (image below). Any idea?

答: Restart xcode resolved my issue.</p>

Body: Restart xcode resolved my issue.


问:
GROUP BY & ORDER BY - Ordering by a specific field
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

```<code>SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

```<code>SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC
</code>```

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

答:
You are not selecting anything from classes, so don't need that table:

```<code>select i.*
from (
    SELECT class_id, max(popularity) as MaxPopularity
    FROM items
    GROUP BY class_id
) ip
inner join items i on ip.class_id = i.class_id
    and ip.MaxPopularity = i.popularity
</code>```

Note: You may get duplicates if there is more than one item in a class with the same popularity.

Body:
I need to write a query which returns a list of unique 'classes' ordered by the most popular item in that class. Here's an example query:

SELECT items.title, items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

This query returns the correct class but the item it returns is the first that appears in the table rather than the most popular.

Similarly I have tried:

SELECT MAX(items.title), items.popularity
FROM items, classes
WHERE class_id = classes.id
GROUP BY class_id
ORDER BY MAX(items.popularity) DESC

And all variations - this just returns the most recent added and not the most popular.

I've read lots and lots of other answers.

I'm sure there's a simple answer, please help!

Body:
You are not selecting anything from classes, so don't need that table:

select i.*
from (
    SELECT class_id, max(popularity) as MaxPopularity
    FROM items
    GROUP BY class_id
) ip
inner join items i on ip.class_id = i.class_id
    and ip.MaxPopularity = i.popularity

Note: You may get duplicates if there is more than one item in a class with the same popularity.


问:
Webpack and Bootstrap with variable path
Migrating to Webpack I had some issues with import sass or css.

I have Bootstrap installed in my node_modules and inside my file structure I' trying to do this:

```<code>// folder scss
- vendor
   - bootstrap
   - pickadate
- views
- components
- base
</code>```

Inside the bootstrap scss, I have the import for bootstrap files and since the path is big, I'm trying to use a variable to reuse:

```<code>$path: '../../../node_modules/bootstrap-sass/assets/stylesheets/bootstrap/';
@import '#{$path}variables';
@import '#{$path}grid';
@import '#{$path}responsive-utilities';
</code>```

With the code above I'm getting this error:

```<code>Module build failed:
@import '#{$path}';
^
      File to import not found or unreadable: #{$path}.
</code>```

Anyone knows why?

Thanks :)

答:
Possible duplicate: Import path using variable SASS

Interpolation in @import urls is not support.

Additionally, you could import like so:

```<code>@import '~bootstrap-sass/assets/stylesheets/bootstrap/variables';
</code>```

Body:
Migrating to Webpack I had some issues with import sass or css.

I have Bootstrap installed in my node_modules and inside my file structure I' trying to do this:

// folder scss
- vendor
   - bootstrap
   - pickadate
- views
- components
- base

Inside the bootstrap scss, I have the import for bootstrap files and since the path is big, I'm trying to use a variable to reuse:

$path: '../../../node_modules/bootstrap-sass/assets/stylesheets/bootstrap/';
@import '#{$path}variables';
@import '#{$path}grid';
@import '#{$path}responsive-utilities';

With the code above I'm getting this error:

Module build failed:
@import '#{$path}';
^
      File to import not found or unreadable: #{$path}.

Anyone knows why?

Thanks :)

Body:
Possible duplicate: Import path using variable SASS

Interpolation in @import urls is not support.

Additionally, you could import like so:

@import '~bootstrap-sass/assets/stylesheets/bootstrap/variables';


问:
How to display records based on selected year from dropdown dynamically without any submit button
I am working on PHP code-igniter.

My view code goes like below:

```<code><form method="post" action="">
    <div class="col-md-4 col-sm-4 ">
        <div class="form-group">
            <label class="h5" for="Mode"><b>See year wise commitments</b></label>
            <select class="form-control" name="Year" id="Year"  onchange="this.form.submit()">
                <option value="">Select Year</option>
                <option value="2015">2015</option>
                <option value="2016">2016</option>
                <option value="2017">2017</option>
            </select>
        </div>
    </div>
</form>
</code>```

Just by selecting any year from dropdown, I have to pass the selected year to my controller and inturn to model and get the query results based on the selected year.

In my controller I am receiving the posted value like:

```<code>$selectedYear = $this->input->post('Year');
</code>```

And before selecting any dropdown value the records in my view has to be of Current year.

My ajax code is

```<code>$( "#year" ).change(function() {
    year = $(this).val();
    $.ajax({
          url : "controllerfilename/controllername",
          data : {"year": year},
          type : "post",
          success: function(data){
             console.log(data);
          }
   });
</code>```

});

答:
You defined id as id="Year" but in the ajax you call it like $( "#year" ).change(function() {. Means In ajax its year and in view its Year (uppercase).

Try this code:

```<code>$("#Year").change(function() {
year = $(this).val();
$.ajax({
      url : "<?php echo base_url('controllerfilename/controllername') ?>",
      data : {"year": year},
      type : "post",
      success: function(data){
         console.log(data);
      }
});
});
</code>```

Body:
I am working on PHP code-igniter.

My view code goes like below:

<form method="post" action="">

            See year wise commitments
            <select class="form-control" name="Year" id="Year"  onchange="this.form.submit()">
                <option value="">Select Year</option>
                <option value="2015">2015</option>
                <option value="2016">2016</option>
                <option value="2017">2017</option>
            </select>

</form>

Just by selecting any year from dropdown, I have to pass the selected year to my controller and inturn to model and get the query results based on the selected year.

In my controller I am receiving the posted value like:

$selectedYear = $this->input->post('Year');

And before selecting any dropdown value the records in my view has to be of Current year.

My ajax code is

$( "#year" ).change(function() {
    year = $(this).val();
    $.ajax({
          url : "controllerfilename/controllername",
          data : {"year": year},
          type : "post",
          success: function(data){
             console.log(data);
          }
   });

});

Body:
You defined id as id="Year" but in the ajax you call it like $( "#year" ).change(function() {. Means In ajax its year and in view its Year (uppercase).

Try this code:

$("#Year").change(function() {
year = $(this).val();
$.ajax({
      url : "<?php echo base_url('controllerfilename/controllername') ?>",
      data : {"year": year},
      type : "post",
      success: function(data){
         console.log(data);
      }
});
});


问:
how to update vue object value inside this object
I create Vue object and need update some data when get response

```<code>new Vue({
    el: "#app",
    data: {
        message: [1,2,3,]
    },
    methods: {
        getList: function () {
            var myGet = axios.get('/api/guests/.json')
                .then(function (response) {
// ????????? message = response.data;

                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    },
    created:function () {
        this.getList();
    }
});
</code>```

how to update vue object value inside this object?
how to update 'message'  ?

答:
You need to bind the correct context to your then callback and access this.message. You will have to do something like this

```<code>new Vue({
    el: "#app",
    data: {
        message: [1,2,3,]
    },
    methods: {
        getList: function () {
            var myGet = axios.get('/api/guests/.json')
                .then(function (response) {
                    this.message = response.data;
                }.bind(this))
                .catch(function (error) {
                    console.log(error);
                });
        }
    },
    created:function () {
        this.getList();
    }
});
</code>```

Body:
I create Vue object and need update some data when get response

new Vue({
    el: "#app",
    data: {
        message: [1,2,3,]
    },
    methods: {
        getList: function () {
            var myGet = axios.get('/api/guests/.json')
                .then(function (response) {
// ????????? message = response.data;

                })
                .catch(function (error) {
                    console.log(error);
                });
        }
    },
    created:function () {
        this.getList();
    }
});

how to update vue object value inside this object?
how to update 'message'  ?

Body:
You need to bind the correct context to your then callback and access this.message. You will have to do something like this

new Vue({
    el: "#app",
    data: {
        message: [1,2,3,]
    },
    methods: {
        getList: function () {
            var myGet = axios.get('/api/guests/.json')
                .then(function (response) {
                    this.message = response.data;
                }.bind(this))
                .catch(function (error) {
                    console.log(error);
                });
        }
    },
    created:function () {
        this.getList();
    }
});


问:
How to generate simpler xml in c#?
if there any way to generate xml file in c# with form like this:

```<code><data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>
</code>```

I tried

```<code>System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")
</code>```

and my xml has body like:

```<code><tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>
</code>```

答:
You can use XDocument to create a new xml:</p>

```<code>XDocument doc = new XDocument(
    new XElement("data",
        new XElement("tableName",
            new XElement("filename", yourfilename),
            new XElement("time", yourTime),
            new XElement("message", yourMessage)
        )
    ));
doc.Save(yourFileName);
</code>```

Title: How to generate simpler xml in c#?

Body:
if there any way to generate xml file in c# with form like this:

<data>
<tableName fieldname="value" fieldname2="value2" fieldname3="value3" />
</data>

I tried

System.Data.DataTable datatable = new System.Data.DataTable("tableName");
datatable.Columns.Add("filename", typeof(string));
datatable.Columns.Add("time", typeof(string));
datatable.Columns.Add("message", typeof(string));
.
.
datatable.WriteXml("Raports.xml")

and my xml has body like:

<tableName>
<filename>Raport_1201_1</filename>
<time>15:21:11.343</time>
<message>START</message>
</tableName>

Body:
You can use XDocument to create a new xml:

XDocument doc = new XDocument(
    new XElement("data",
        new XElement("tableName",
            new XElement("filename", yourfilename),
            new XElement("time", yourTime),
            new XElement("message", yourMessage)
        )
    ));
doc.Save(yourFileName);


问:
Why is my PHP code not displaying in my web browser? it just appears as a blank white page
So I am trying to connect to my database and display the Vehicles on the web page. However it is just coming up with a blank page, and not displaying anything.

Below is the code for the page I was to display the contents of vehicles on from my database

Any Ideas?

```<code><?php
   $conn = @mysqli_connect("localhost", "root", "2401", "taylor_callaghan_wca");

$query = "SELECT * FROM vehicle";
$results = mysqli_query($conn, $query);
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}

else {
// Fetch and display the results of the select query
while ($row = mysqli_fetch_array($results)) {
echo "<p>VIN_#: $row[vin]</p>";
echo "<p>Stock Number: $row[stockno]</p>";
echo "<p>Manufacturer Number: $row[man_num] </p>";
echo "<p>Model: $row[model] </p>";
echo "<p>Colour: Id $row[col_id] </p>";
echo "<p>Year: $row[year] </p>";
echo "<p>Price: $row[price] </p>";
echo "<p>Kilometres: $row[kms] </p>";
echo "<p>Registration: $row[rego] </p>";
echo "<p>Cylinders: $row[cylinders] </p>";
echo "<p>Fuel: $row[fuel] </p>";
echo "<p>Transmission: $row[transmission] </p>";
echo "<p>Category Id: $row[cat_id] </p>";
echo "<p>Vehicle On Special: $row[special] </p>";
echo "<p>Standard Used Vehicle: $row[standardusedvehicle] </p>";
}
}

?>
</code>```

答:
It's not really an answer but I can't post this code in comment. Try addind echos to see what it does and what it doesn't:

```<code><?php
echo '1';
$conn = @mysqli_connect("localhost", "root", "2401", "taylor_callaghan_wca");

$query = "SELECT * FROM vehicle";
$results = mysqli_query($conn, $query);
if(!$results) {
    echo '2';
    echo ("Query error: " . mysqli_error($conn));
}

else {
    echo '3';
    // Fetch and display the results of the select query
    while ($row = mysqli_fetch_array($results)) {
        echo '4';
        echo "<p>VIN_#: $row[vin]</p>";
        echo "<p>Stock Number: $row[stockno]</p>";
        echo "<p>Manufacturer Number: $row[man_num] </p>";
        echo "<p>Model: $row[model] </p>";
        echo "<p>Colour: Id $row[col_id] </p>";
        echo "<p>Year: $row[year] </p>";
        echo "<p>Price: $row[price] </p>";
        echo "<p>Kilometres: $row[kms] </p>";
        echo "<p>Registration: $row[rego] </p>";
        echo "<p>Cylinders: $row[cylinders] </p>";
        echo "<p>Fuel: $row[fuel] </p>";
        echo "<p>Transmission: $row[transmission] </p>";
        echo "<p>Category Id: $row[cat_id] </p>";
        echo "<p>Vehicle On Special: $row[special] </p>";
        echo "<p>Standard Used Vehicle: $row[standardusedvehicle] </p>";
    }
}
echo '5';
?>
</code>```

Body:
So I am trying to connect to my database and display the Vehicles on the web page. However it is just coming up with a blank page, and not displaying anything.

Below is the code for the page I was to display the contents of vehicles on from my database

Any Ideas?

<?php
   $conn = @mysqli_connect("localhost", "root", "2401", "taylor_callaghan_wca");

$query = "SELECT * FROM vehicle";
$results = mysqli_query($conn, $query);
if(!$results) {
echo ("Query error: " . mysqli_error($conn));
}

else {
// Fetch and display the results of the select query
while ($row = mysqli_fetch_array($results)) {
echo "
VIN_#: $row[vin]
";
echo "
Stock Number: $row[stockno]
";
echo "
Manufacturer Number: $row[man_num]
";
echo "
Model: $row[model]
";
echo "
Colour: Id $row[col_id]
";
echo "
Year: $row[year]
";
echo "
Price: $row[price]
";
echo "
Kilometres: $row[kms]
";
echo "
Registration: $row[rego]
";
echo "
Cylinders: $row[cylinders]
";
echo "
Fuel: $row[fuel]
";
echo "
Transmission: $row[transmission]
";
echo "
Category Id: $row[cat_id]
";
echo "
Vehicle On Special: $row[special]
";
echo "
Standard Used Vehicle: $row[standardusedvehicle]
";
}
}

?>

Body:
It's not really an answer but I can't post this code in comment. Try addind echos to see what it does and what it doesn't:

<?php
echo '1';
$conn = @mysqli_connect("localhost", "root", "2401", "taylor_callaghan_wca");

$query = "SELECT * FROM vehicle";
$results = mysqli_query($conn, $query);
if(!$results) {
    echo '2';
    echo ("Query error: " . mysqli_error($conn));
}

else {
    echo '3';
    // Fetch and display the results of the select query
    while ($row = mysqli_fetch_array($results)) {
        echo '4';
        echo "<p>VIN_#: $row[vin]</p>";
        echo "<p>Stock Number: $row[stockno]</p>";
        echo "<p>Manufacturer Number: $row[man_num] </p>";
        echo "<p>Model: $row[model] </p>";
        echo "<p>Colour: Id $row[col_id] </p>";
        echo "<p>Year: $row[year] </p>";
        echo "<p>Price: $row[price] </p>";
        echo "<p>Kilometres: $row[kms] </p>";
        echo "<p>Registration: $row[rego] </p>";
        echo "<p>Cylinders: $row[cylinders] </p>";
        echo "<p>Fuel: $row[fuel] </p>";
        echo "<p>Transmission: $row[transmission] </p>";
        echo "<p>Category Id: $row[cat_id] </p>";
        echo "<p>Vehicle On Special: $row[special] </p>";
        echo "<p>Standard Used Vehicle: $row[standardusedvehicle] </p>";
    }
}
echo '5';
?>


问:
S4 missing or NULL arguments to methods?
Is there a way to define what happens when the argument of a method is missing or NULL?

In the example below, I'd like to call the same function no matter whether I type foo() or foo(NULL). Of course I know that I can have a method setMethod("foo","NULL",function(x) foo())  but that that's code replication and a possible source of mistakes.

Thanks!

```<code>setGeneric("foo",function(x) standardGeneric("foo"))
setMethod("foo","numeric",function(x) "numeric")
setMethod("foo","NULL",function(x) "NULL")
setMethod("foo","missing",function(x) "missing")

R> foo(1)
[1] "numeric"
R> foo()
[1] "missing"
R> foo(NULL)
[1] "NULL"
</code>```

答: Using setMethod("foo","NULL",function(x) foo()) is not a code replication, since you don't replicate code but put a call to it. I would say it is a very good way of solving your problem.

Body:
Is there a way to define what happens when the argument of a method is missing or NULL?

In the example below, I'd like to call the same function no matter whether I type foo() or foo(NULL). Of course I know that I can have a method setMethod("foo","NULL",function(x) foo())  but that that's code replication and a possible source of mistakes.

Thanks!

setGeneric("foo",function(x) standardGeneric("foo"))
setMethod("foo","numeric",function(x) "numeric")
setMethod("foo","NULL",function(x) "NULL")
setMethod("foo","missing",function(x) "missing")

R> foo(1)
[1] "numeric"
R> foo()
[1] "missing"
R> foo(NULL)
[1] "NULL"


问:
How to find prevoius Http Get request from Browser history using Javascript
I  want to find the previous Get request from browser history using javascript</p>

答:
You cannot access the browser history using javascript, it is usually blocked by the browser. You can however use some APIs provided by some browsers in order to get the history.

Access my entire browsing history via Javascript

Now since you asked for only the previous get request, the simple logic would be to write a tracing code within your httprequest function

How to view the last GET HTTP request in JavaScript


问:
How to run a .class file that is part of a package from cmd?
I keep getting errors when I make my .class part of a package and try to run it from cmd.

Here's the code that works after using javac and then java:

```<code>class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
</code>```

and then the code that does not work:

```<code>package com;

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
</code>```

giving me this error after trying to run the program via the command: java HelloWorld:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong nam
e: com/HelloWorld)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
</code>```

Here's what I've tried doing so far:

```<code>java -cp . HelloWorld
java -cp . com.HelloWorld
java -cp . com/HelloWorld
java HelloWorld
java com.HelloWorld
java com/HelloWorld
</code>```

Keep in mind that javac returns with no errors and that simply removing package com; solves the problem. Sometimes in other scenarios I get an error that says the main class file cannot be found or something along those lines.

What am I doing wrong?

答:
Suppose the file locates at  C:/projects/com/HelloWorld
and you can try the following ways.

1.java -cp c:/projects com.HelloWorld

2.cd c:/projects

   java com.HelloWorld

(The example 2 is not working in many situation,such as java process.)

if there is no package declaration and there will be a little change.

1.java -cp c:/projects/com HelloWorld

2.cd c:/projects/com

   java HelloWorld

(It's not good with the same reason.)

alternatively,relative path will be ok but has some risk.
Last remember put the class file in end of cmd.

Body:
I keep getting errors when I make my .class part of a package and try to run it from cmd.

Here's the code that works after using javac and then java:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

and then the code that does not work:

package com;

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

giving me this error after trying to run the program via the command: java HelloWorld:

Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld (wrong nam
e: com/HelloWorld)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)

Here's what I've tried doing so far:

java -cp . HelloWorld
java -cp . com.HelloWorld
java -cp . com/HelloWorld
java HelloWorld
java com.HelloWorld
java com/HelloWorld

Keep in mind that javac returns with no errors and that simply removing package com; solves the problem. Sometimes in other scenarios I get an error that says the main class file cannot be found or something along those lines.

What am I doing wrong?


问:
PrimeNg DropDown - User can't clear the value
I'm implementing primeNg dropdown component in my Angular2 application.

```<code><p-dropdown [options]="listCustomers_itm" placeholder="Selezionare" [(ngModel)]="Customer_itm" [ngModelOptions]="{standalone: true}" [style]="{'width':'225px'}" filter="filter"  (onChange)="onCustomerSelect($event.value)">
</p-dropdown>
</code>```

All works fine except one annoing thing:

Once time the user has selected an option, he can't clear the selected value...

Can you help me?

答:
Since the component is not allowing reset value function, I have implemented a button in the form the clear all the values...

It works properly

Body:
I'm implementing primeNg dropdown component in my Angular2 application.

All works fine except one annoing thing:

Once time the user has selected an option, he can't clear the selected value...

Can you help me?


问:
How to create SQL multiple count count query by date?
I have a query that selects counts group by department.

```<code>select department, count(*) group by department
</code>```

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

```<code>Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11
</code>```

答:
@SimarjeetSingh has already answered this.

except the comparison with datecolumn should happen with datepart only, GETDATE() retuns time with it.

```<code>select department, count(*) as Total,
sum(case when cast(datecolumn as date)= cast(GETDATE() as date)  then 1 else 0 end) as Today,
sum(case when month(datecolumn) =month(GETDATE()) and year(datecolumn) = year(GETDATE()) then 1 else 0 end) as ThisMonth
from YourTable
group by department
</code>```

Body:
I have a query that selects counts group by department.

select department, count(*) group by department

This returns two columns data result. I wonder if select cout, count by today and count by this month same query.

Department  Total  Today  ThisMonth
AAA         40     8      23
BBB         20     6      11

Body:
@SimarjeetSingh has already answered this.

except the comparison with datecolumn should happen with datepart only, GETDATE() retuns time with it.

select department, count(*) as Total,
sum(case when cast(datecolumn as date)= cast(GETDATE() as date)  then 1 else 0 end) as Today,
sum(case when month(datecolumn) =month(GETDATE()) and year(datecolumn) = year(GETDATE()) then 1 else 0 end) as ThisMonth
from YourTable
group by department