问:
Babelify ParseError 'import' and 'export' may appear only with 'sourceType: module'
I'm trying to build a project with this simple structure:

```<code>app
 |-- components
 |       |-- App.jsx
 |       |-- Root.jsx
 |-- index.jsx
</code>```

index.jsx looks like this:

```<code>import React from 'react';
import { createStore } from 'redux';
import { render } from 'react-dom';

import Root from 'app/components/core/Root';

const store = createStore();

render(<Root store={ store } />, document.getElementById('root'));
</code>```

and Root.jsx looks like this:

```<code>import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter, Route } from 'react-router-dom';

import App from 'app/components/core/App';

const Root = ({ store }) => {
    return <Provider store={ store }>
        <BrowserRouter>
            <Route path='/' component={ App } />
        </BrowserRouter>
    </Provider>
};

Root.propTypes = {
    store: React.PropTypes.object.isRequired,
};

export default Root;
</code>```

I create a gulp file this way, specifying the (I think) correct processors for Babelify:

```<code>var gulp = require('gulp'),
buffer = require('vinyl-buffer'),
browserify = require('browserify'),
babelify = require('babelify'),
source = require('vinyl-source-stream'),
gutil = require('gulp-util');

gulp.task('build', function () {
    var browserifyOptions = {
        debug: true,
        entries: './app/index.jsx',
        extensions: ['.jsx', '.js'],
    };

    return browserify(browserifyOptions)
        .transform(babelify.configure({
            presets: ['es2015', 'react']
        }))
        .bundle()
        .on('error', gutil.log)
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(gulp.dest('./lima/static'));
});

gulp.task('default', ['build']);
</code>```

Now the strange thing is I get this:

```<code>Root.jsx:1
import React from 'react';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'
</code>```

The weird thing is that index.jsx seems to work just fine and if I remove any of the babel presets I get errors in that file instead. What can be wrong about Root.jsx or my gulpfile?

答:
You need to add { modules: false } to your gulpfile:

```<code>presets: [['es2015', { modules: false }], 'react']
</code>```

Body:
I'm trying to build a project with this simple structure:

app
 |-- components
 |       |-- App.jsx
 |       |-- Root.jsx
 |-- index.jsx

index.jsx looks like this:

import React from 'react';
import { createStore } from 'redux';
import { render } from 'react-dom';

import Root from 'app/components/core/Root';

const store = createStore();

render(<Root store={ store } />, document.getElementById('root'));

and Root.jsx looks like this:

import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter, Route } from 'react-router-dom';

import App from 'app/components/core/App';

const Root = ({ store }) => {
    return <Provider store={ store }>
        <BrowserRouter>
            <Route path='/' component={ App } />
        </BrowserRouter>
    </Provider>
};

Root.propTypes = {
    store: React.PropTypes.object.isRequired,
};

export default Root;

I create a gulp file this way, specifying the (I think) correct processors for Babelify:

var gulp = require('gulp'),
buffer = require('vinyl-buffer'),
browserify = require('browserify'),
babelify = require('babelify'),
source = require('vinyl-source-stream'),
gutil = require('gulp-util');

gulp.task('build', function () {
    var browserifyOptions = {
        debug: true,
        entries: './app/index.jsx',
        extensions: ['.jsx', '.js'],
    };

    return browserify(browserifyOptions)
        .transform(babelify.configure({
            presets: ['es2015', 'react']
        }))
        .bundle()
        .on('error', gutil.log)
        .pipe(source('app.js'))
        .pipe(buffer())
        .pipe(gulp.dest('./lima/static'));
});

gulp.task('default', ['build']);

Now the strange thing is I get this:

Root.jsx:1
import React from 'react';
^
ParseError: 'import' and 'export' may appear only with 'sourceType: module'

The weird thing is that index.jsx seems to work just fine and if I remove any of the babel presets I get errors in that file instead. What can be wrong about Root.jsx or my gulpfile?

Body:
You need to add { modules: false } to your gulpfile:

presets: [['es2015', { modules: false }], 'react']


来源: stackexchange

问:
How many subnets required in a VPC
I wish to implement my website in AWS virtual private cloud (VPC) with the following requirement:

The web tier will use an Auto Scaling group across multiple Availability Zones (AZs).

The database will use Multi-AZ RDS MySQL and should not be publicly accessible.

What is the minimal number of subnets required?

I assume one subnet = one AZ. Having said that, I will be needing 2 subnets for the RDS instance and one for my web tier which might have to sit in the public subnets? so total 3 minimal?

答:
There is no requirement for 3 subnet.

If you put 2 subnet in different AZ and 1 is public and 1 is private that is also able to communicate with each other because of in 1 VPC multi-pal instance can calumniate with each other and different.

But if you put 3 subnet in different AZ as you said that is better for security and accessibility from web-server.

ContentLicense: CC BY-SA 3.0

Title: How many subnets required in a VPC


问:
Square an array's size with the same pattern repeated
Given an array int X[x_size], I'd like to make a new array int Y[x_size * x_size] and copy the values of X in order.

For example, given X = {0, 1, 2}, I'd like array Y to be {0, 1, 2, 0, 1, 2, 0, 1, 2}.

```<code>int main(int argc, const char * argv[]) {
    int x[3] = [0,1,2];
    int * y = makeY(a,3);
}
int * makeY(int x[], int size) {
    int *y = new int[size * size];
    for(int i = 0; i < size; size+=2)
        for(int j = i; j < j + (size - 1); j++)
            for (int i = 0; i < size; i++)
                y[j+i] = x[i];
    return y;
}
</code>```

答:
If you want to work with pointers, I suggest passing the pointer of y instead of returning it since it is a local variable.

```<code>void makeY(int * x, int * y, int size){
     for(int i=0; i<size; i++){
      for(int j = 0; j < (size); j++){
       y[j*size + i] = x[i];
      }
     }
}
</code>```

Now you can use it like this:

```<code>int main()
{
  int size = 3;
  int x[size] = {0, 1, 2};
  int y[size * size];
  makeY(x, y, size);
}
</code>```

Body:
Given an array int X[x_size], I'd like to make a new array int Y[x_size * x_size] and copy the values of X in order.

For example, given X = {0, 1, 2}, I'd like array Y to be {0, 1, 2, 0, 1, 2, 0, 1, 2}.

int main(int argc, const char * argv[]) {
    int x[3] = [0,1,2];
    int * y = makeY(a,3);
}
int * makeY(int x[], int size) {
    int *y = new int[size * size];
    for(int i = 0; i < size; size+=2)
        for(int j = i; j < j + (size - 1); j++)
            for (int i = 0; i < size; i++)
                y[j+i] = x[i];
    return y;
}

Body:
If you want to work with pointers, I suggest passing the pointer of y instead of returning it since it is a local variable.

void makeY(int * x, int * y, int size){
     for(int i=0; i<size; i++){
      for(int j = 0; j < (size); j++){
       y[j*size + i] = x[i];
      }
     }
}

Now you can use it like this:

int main()
{
  int size = 3;
  int x[size] = {0, 1, 2};
  int y[size * size];
  makeY(x, y, size);
}


问:
Override core files using module prestashop
Actually I'm a newbie to prestashop,

and I have changes in the following file in these locations

classes/Product.php

src/PrestaShopBundle/Controller/Admin/ProductController.php

src/PrestaShopBundle/Resources/views/Admin/Product/form.html.twig

I have created a module named as My Kit while this module is configured all these changes should work..If the module is set to be disabled these changes should not affect in front end(I mean in admin panel)

For this I've created an override folder in my_kit module and place all those above mentioned files into this my_kit\override path..

like

my_kit\override\classes/Product.php

my_kit\override\src/PrestaShopBundle/Controller/Admin/ProductController.php

my_kit\override\src/PrestaShopBundle/Resources/views/Admin/Product/form.html.twig

But it won't work for me :(

how should I do this one..

Someone help me out of this..

答:
You can use php default copy function in your main file install function like below.

```<code>public function install()
{

copy(_PS_ROOT_DIR_."/modules/your module name/classes/Product.php",_PS_ROOT_DIR_."/override/classes/Product.php");

unlink(_PS_ROOT_DIR_."/cache/class_index.php");//because you need to delete this file after override

//Do same like this all other file.

}
</code>```

Thanks,

Body:
You can use php default copy function in your main file install function like below.

public function install()
{

copy(_PS_ROOT_DIR_."/modules/your module name/classes/Product.php",_PS_ROOT_DIR_."/override/classes/Product.php");

unlink(_PS_ROOT_DIR_."/cache/class_index.php");//because you need to delete this file after override

//Do same like this all other file.

}

Thanks,


问:
Create JWTAuth token in Factory Laravel
I have model User and need create db seeder with faker lib, but i have record _token using JWT. Now how to create _token with JWT?</p>

```<code>$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => $faker->randomElement(['seller', 'buyer']),
        'birthday' => $faker->dateTimeThisCentury,
        'avatar' => $faker->imageUrl($width = 400, $height = 400),
        'cover' => $faker->imageUrl($width = 851, $height = 315),
        'gender' => $faker->randomElement(['male', 'female']),
        'country' => $faker->country,
        '_token' => JWTAuth::fromUser() // ???,

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

答:
That's not how JWT works.

How do you expect the library to generate a token for the user when the user itself hasn't been created? The token needs to have at least one claim to identify the user.

JWT is meant to be used as a non persistent token. They're stored only when you want to blacklist or invalidate tokens.

What you're looking for might be a simple token based authentication and not JWT in this case.

Title: Create JWTAuth token in Factory Laravel

Body:
I have model User and need create db seeder with faker lib, but i have record _token using JWT. Now how to create _token with JWT?

$factory->define(App\User::class, function (Faker\Generator $faker) {
    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => $faker->randomElement(['seller', 'buyer']),
        'birthday' => $faker->dateTimeThisCentury,
        'avatar' => $faker->imageUrl($width = 400, $height = 400),
        'cover' => $faker->imageUrl($width = 851, $height = 315),
        'gender' => $faker->randomElement(['male', 'female']),
        'country' => $faker->country,
        '_token' => JWTAuth::fromUser() // ???,

    ];
});


问:
Boost interprocess string without shared memory
So, this question is linked to a previous one (std::string without copying from char*).

Now I've come across boost:interprocess::string, which allows the construction of strings inside a shared memory address space. Since I've already got my char* memory, I was wondering if I could reuse the boost:interprocess::string to avoid copying.

However, every single document I'm reading uses boost::interprocess::managed_shared_memory and its siblings.

Is anyone using a boost managed string without shared memory? How?

Thanks!

答:
The problem is your char * points to the memory of your process ( heap ), when process no longer running this memory is invalid. Shared memory is shared between processes.
You have to copy from char * into shared memory segment, in my opinion it's the only option. Please tell me where your char * points to on heap ?

But reading from shared memory or memory mapped file can be done without copying , you can use containers like string_view either  boost::string_ref or boost::string_view or in C++17 std::string_view include <experimental/string_view>. These are containers without ownership and allow you to refer to memory by {char * ,  size} , however since shared memory is shared it would be hard to imagine if it could ever be production quality code since any process can change your memory, unless you never write but only read from SHM.
In my humble opinion the answer is NO. However I will wait for more experienced developers.


问:
Does Android Market Accept app using WebViewClient?
I developing a web icon application.I used the below code to launch my url

Uri uri = Uri.parse("http://www.myurl.com");
 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
 startActivity(intent);

Does Android Market accept this type of application?

答: Yes, This is acceptable. No restrictions on this.</p>

ContentLicense: CC BY-SA 2.5


问:
Java method override - parent method is called when a parameter is used
Here is the code I wrote:

https://pastebin.com/raw/0iBrGJR4

Most relevant parts:

```<code>    A a = new A();
    B b = new B();

    System.out.println(((A) b).a());
    System.out.println(((A) b).b(3));

  static class A {
    Object a() {
      System.out.println("A.a()");
    }

    Object b(Number x) {
      System.out.println("A.b()");
    }
  }

  static class B extends A {
    String a() {
      System.out.println("B.a()");
      return "hello";
    }

    String b(Integer x) {
      System.out.println("B.b()");
      return "hola" + x;
    }
  }
</code>```

When I run this, the first print displays

```<code>B.a()
hello
</code>```

which is what I expected, since even though we cast to A, the call goes through to the object's actual type which is B.

But the second print, the ((A) b).b(3) call, prints

```<code>A.b()
3
</code>```

(i.e. it calls the method in A). Force casting 3 to Integer doesn't do anything either. Can someone explain this behavior to me? I don't understand what the reason is. I would've expected ((A) b).b(3) to print B.() \n hola3 rather than use the parent class method.

答:
In Java, what makes a method override another method in a parent class is if it has the same name but different number and/or types of arguments.

In your case class A has a method b(Number x) and class B that extends A has a method b(Integer x) ==> B.b() doesn't override A.b() ==> when executing ((A) b).b(b), A.b(3) is executed.

On the contrary, B.a() does override A.a() ==> when executing ((A) b).a(), B.a() is executed.

The return value of the methods doesn't matter when overriding, only name and arguments.

Body:
Here is the code I wrote:

https://pastebin.com/raw/0iBrGJR4

Most relevant parts:

    A a = new A();
    B b = new B();

    System.out.println(((A) b).a());
    System.out.println(((A) b).b(3));

  static class A {
    Object a() {
      System.out.println("A.a()");
    }

    Object b(Number x) {
      System.out.println("A.b()");
    }
  }

  static class B extends A {
    String a() {
      System.out.println("B.a()");
      return "hello";
    }

    String b(Integer x) {
      System.out.println("B.b()");
      return "hola" + x;
    }
  }

When I run this, the first print displays

B.a()
hello

which is what I expected, since even though we cast to A, the call goes through to the object's actual type which is B.

But the second print, the ((A) b).b(3) call, prints

A.b()
3

(i.e. it calls the method in A). Force casting 3 to Integer doesn't do anything either. Can someone explain this behavior to me? I don't understand what the reason is. I would've expected ((A) b).b(3) to print B.() \n hola3 rather than use the parent class method.


问:
Building memory game minigame in JQuery (Javascript)
I am making a set of minigames for my major project, have being following a tutorial on the internet to make a memory game for one of them.

The code works up to where I generate a new board but the rest of the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?

This is my code for the memory minigame.

$(document).ready(function() {

  //speech
  var progress = 0;
  var txt;
  $('#complete, #speech').hide();

  function eventHandler() {
    switch (progress) {
      case 0:
        txt = "Complete";
        break;
      case 1:
        txt = "Move on the the next game";
        $('#speech').click(function() {
          window.location.href = "minigame4.html"; //next minigame
        });
        break;
    }
    progress++;
    $('#speech').html(txt);
  }

  $('#speech').click(eventHandler);

  // Memory Game //

  var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'];
  var memory_values = [];
  var memory_tile_ids = [];
  var tiles_flipped = 0;

  //shuffle method
  Array.prototype.memory_tile_shuffle = function() {
    var i = this.length,
      j, temp;
    while (--i > 0) {
      j = Math.floor(Math.random() * (i + 1));
      temp = this[j];
      this[j] = this[i];
      this[i] = temp;
    }
  }

  //generate new board
  function newBoard() {
    tiles_flipped = 0;
    var output = '';
    memory_array.memory_tile_shuffle();
    for (var i = 0; i < memory_array.length; i++) {
      output += '

';
    }
    $('#memory_board').html(output);
  }

  newBoard();

  //
  // all code works up to here

  function memoryFlipTile(tile, val) {
    // When tile is clicked, change colour to white along with its letter
    if (tile.html == "" && memory_values.length < 2) {
      tile.style.background = '#FFF';
      tile.html = val;
      // If no tiles are flipped
      if (memory_values.length == 0) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // If one tile is already flipped
      } else if (memory_values.length == 1) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // See if both tiles are a match
        if (memory_values[0] == memory_values[1]) {
          tiles_flipped += 2;
          // Clear both arrays
          memory_values = [];
          memory_tile_ids = [];
          // Check to see if the whole board is cleared
          // then display complete
          if (tiles_flipped == memory_array.length) {
            $("#complete").show(0, function() {
              eventHandler()
              $('#speech').show();
            });
          }
        } else {
          function flip2Back() {
            // Flip the 2 tiles back over
            var tile_1 = document.getElementById(memory_tile_ids[0]);
            var tile_2 = document.getElementById(memory_tile_ids[1]);
            tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_1.html = "";
            tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_2.html = "";
            // Clear both arrays
            memory_values = [];
            memory_tile_ids = [];
          }
          setTimeout(flip2Back, 700);
        }
      }
    }
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div#memory_board {
  padding: 24px;
  margin: 0px auto;
  width: 456px;
  height: 300px;
}

div#memory_board div {
  float: left;
  margin: 10px;
  padding: 28px;
  font-size: 50px;
  cursor: pointer;
  text-align: center;
  background-image: url(images/puzzle5/blank.png);
}

#complete {
  position: absolute;
  width: 105px;
  height: 25px;
  top: 240px;
  left: 289px;
  background-color: black;
  color: white;
  font-size: 20px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 5;
}

#speech {
  position: absolute;
  width: 655px;
  height: 100px;
  top: 330px;
  left: 15px;
  background-color: black;
  color: white;
  font-size: 25px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 99;
}</code>```

<!doctype html>

  <meta charset="utf-8">
  <title>MAS340</title>
  <link href="styles.css" rel="stylesheet" />

```

答:
You have syntax errors in line 93 and 95. In addition, html should be innerHTML
Change

```<code>tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';

tile_1.html = "";

tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';

tile_2.html = "";
</code>```

To

```<code>tile_1.style.['background-image'] = 'url(images/puzzle5/blank.png) no-repeat';

tile_1.innerHTML = "";

tile_2.style.['background-image'] = 'url(images/puzzle5/blank.png) no-repeat';

tile_2.innerHTML = "";
</code>```

Body:
I am making a set of minigames for my major project, have being following a tutorial on the internet to make a memory game for one of them.

The code works up to where I generate a new board but the rest of the code doesn't seem to work. Have I done something wrong in my scipting? Can anyone tell me where I'm going wrong?

This is my code for the memory minigame.

$(document).ready(function() {

  //speech
  var progress = 0;
  var txt;
  $('#complete, #speech').hide();

  function eventHandler() {
    switch (progress) {
      case 0:
        txt = "Complete";
        break;
      case 1:
        txt = "Move on the the next game";
        $('#speech').click(function() {
          window.location.href = "minigame4.html"; //next minigame
        });
        break;
    }
    progress++;
    $('#speech').html(txt);
  }

  $('#speech').click(eventHandler);

  // Memory Game //

  var memory_array = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L'];
  var memory_values = [];
  var memory_tile_ids = [];
  var tiles_flipped = 0;

  //shuffle method
  Array.prototype.memory_tile_shuffle = function() {
    var i = this.length,
      j, temp;
    while (--i > 0) {
      j = Math.floor(Math.random() * (i + 1));
      temp = this[j];
      this[j] = this[i];
      this[i] = temp;
    }
  }

  //generate new board
  function newBoard() {
    tiles_flipped = 0;
    var output = '';
    memory_array.memory_tile_shuffle();
    for (var i = 0; i < memory_array.length; i++) {
      output += '

';
    }
    $('#memory_board').html(output);
  }

  newBoard();

  //
  // all code works up to here

  function memoryFlipTile(tile, val) {
    // When tile is clicked, change colour to white along with its letter
    if (tile.html == "" && memory_values.length < 2) {
      tile.style.background = '#FFF';
      tile.html = val;
      // If no tiles are flipped
      if (memory_values.length == 0) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // If one tile is already flipped
      } else if (memory_values.length == 1) {
        memory_values.push(val);
        memory_tile_ids.push(tile.id);
        // See if both tiles are a match
        if (memory_values[0] == memory_values[1]) {
          tiles_flipped += 2;
          // Clear both arrays
          memory_values = [];
          memory_tile_ids = [];
          // Check to see if the whole board is cleared
          // then display complete
          if (tiles_flipped == memory_array.length) {
            $("#complete").show(0, function() {
              eventHandler()
              $('#speech').show();
            });
          }
        } else {
          function flip2Back() {
            // Flip the 2 tiles back over
            var tile_1 = document.getElementById(memory_tile_ids[0]);
            var tile_2 = document.getElementById(memory_tile_ids[1]);
            tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_1.html = "";
            tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';
            tile_2.html = "";
            // Clear both arrays
            memory_values = [];
            memory_tile_ids = [];
          }
          setTimeout(flip2Back, 700);
        }
      }
    }
  }
});

div#memory_board {
  padding: 24px;
  margin: 0px auto;
  width: 456px;
  height: 300px;
}

div#memory_board div {
  float: left;
  margin: 10px;
  padding: 28px;
  font-size: 50px;
  cursor: pointer;
  text-align: center;
  background-image: url(images/puzzle5/blank.png);
}

#complete {
  position: absolute;
  width: 105px;
  height: 25px;
  top: 240px;
  left: 289px;
  background-color: black;
  color: white;
  font-size: 20px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 5;
}

#speech {
  position: absolute;
  width: 655px;
  height: 100px;
  top: 330px;
  left: 15px;
  background-color: black;
  color: white;
  font-size: 25px;
  padding: 10px;
  border-style: solid;
  border-width: 5px;
  border-color: white;
  z-index: 99;
}

<!doctype html>

  <meta charset="utf-8">
  <title>MAS340</title>
  <link href="styles.css" rel="stylesheet" />

Body:
You have syntax errors in line 93 and 95. In addition, html should be innerHTML
Change

tile_1.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';

tile_1.html = "";

tile_2.style.background - image = 'url(images/puzzle5/blank.png) no-repeat';

tile_2.html = "";

To

tile_1.style.['background-image'] = 'url(images/puzzle5/blank.png) no-repeat';

tile_1.innerHTML = "";

tile_2.style.['background-image'] = 'url(images/puzzle5/blank.png) no-repeat';

tile_2.innerHTML = "";


问:
Yii2 Database Connection - PDOException
I tried to change mysql to ms sql server dbms in yii but encounter PDO Exception,
"Caused by: PDOException could not find driver". What is the issue there?

This is db.php file.

```<code>'class' => 'yii\db\Connection',
'dsn' => 'sqlsrv:Server=localhost;Database=mydb',
'username' => 'myusername',
'password' => 'myps',
'charset' => 'utf8'
</code>```

This is config.php.

```<code>'components' => [
    'db' => [
        'dsn' => 'sqlsrv:Server=localhost;Database=mydb',
    ],
</code>```

答:
You need to install PDO driver for your database type.

Before proceeding, make sure you have installed both the PDO PHP extension and the PDO driver for the database you are using (e.g. pdo_mysql for MySQL). This is a basic requirement if your application uses a relational database.

Please refer these links for detail:

Guide Start Databases - Configuring a DB Connection Section

MSSQL PDO

Title: Yii2 Database Connection - PDOException

Body:
I tried to change mysql to ms sql server dbms in yii but encounter PDO Exception,
"Caused by: PDOException could not find driver". What is the issue there?

This is db.php file.

'class' => 'yii\db\Connection',
'dsn' => 'sqlsrv:Server=localhost;Database=mydb',
'username' => 'myusername',
'password' => 'myps',
'charset' => 'utf8'

This is config.php.

'components' => [
    'db' => [
        'dsn' => 'sqlsrv:Server=localhost;Database=mydb',
    ],


问:
How do i unit test a class that uses IoC container classes
I am using Autofac in my project,but i am unable to do a unit test on one particular class.

Consider the following Scenario :

```<code>//Class to be tested
public Class A
{
  private SomeAutoFacClass B;

  public void DoSomething()
  {
    B = scope.Resolve<ClassName>();// Resolve the object needed
    // Do something with instance B
  }
}

// Test class
public Class ATest
{
  private A a;

  [test]
  public void TestMethod()
  {
    a.DoSomething();//*This method causes a null reference exception as it tries to resolve the objects*
  }
}
</code>```

In the code above,i am not able to unit test case due to the dependency injection which is only specific to that particular class.
how do i solve this? I also tried creating a autofaccontainer using Moq.
But that too fails.

答:
Using an IoC container you should aim to use IoC. Normally this is either constructor injection or property injection depending on what your container can support for auto-injection.

A pattern I use for this I call "lazy property injection" where I constructor-inject my container to act as a registry, then use the lazy resolution on property use..

What it looks like:

```<code>private readonly IoCContainer _container = null;

private IMyService _myService = null;
public IMyService MyService
{
   get { return _myService ?? (_myService = _container.Resolve<IMyService>()); }
   set { _myService = value; }
}

public MyClass( IoCContainer container)
{
   if (container == null)
      throw new ArgumentNullException("container");

   _container = container;
}
</code>```

Now when you go to test a method of this class, your test initializes your MyService with a Mock.  When running under test, I have the IoCContainer initialized to a Mock() that throws if any .Resolve<> calls are made. This catches scenarios where your code under test might be modified to use a new dependency that hasn't been mocked out.

The benefit of this approach is that often a class will have several single-purpose methods, and by extension need a number of dependencies. In applications like web requests where maybe only one method is called, needing one dependency, the dependency resolution only retrieves the dependencies from the container that are needed, not all of them. (I.e. if you use constructor injection with 8 dependencies, all 8 need to be resolved at runtime, even if only 1 will be used.) This also simplifies unit testing to only mock out what you know will be needed rather than everything.

Body:
I am using Autofac in my project,but i am unable to do a unit test on one particular class.

Consider the following Scenario :

//Class to be tested
public Class A
{
  private SomeAutoFacClass B;

  public void DoSomething()
  {
    B = scope.Resolve<ClassName>();// Resolve the object needed
    // Do something with instance B
  }
}

// Test class
public Class ATest
{
  private A a;

  [test]
  public void TestMethod()
  {
    a.DoSomething();//*This method causes a null reference exception as it tries to resolve the objects*
  }
}

In the code above,i am not able to unit test case due to the dependency injection which is only specific to that particular class.
how do i solve this? I also tried creating a autofaccontainer using Moq.
But that too fails.

Body:
Using an IoC container you should aim to use IoC. Normally this is either constructor injection or property injection depending on what your container can support for auto-injection.

A pattern I use for this I call "lazy property injection" where I constructor-inject my container to act as a registry, then use the lazy resolution on property use..

What it looks like:

private readonly IoCContainer _container = null;

private IMyService _myService = null;
public IMyService MyService
{
   get { return _myService ?? (_myService = _container.Resolve<IMyService>()); }
   set { _myService = value; }
}

public MyClass( IoCContainer container)
{
   if (container == null)
      throw new ArgumentNullException("container");

   _container = container;
}

Now when you go to test a method of this class, your test initializes your MyService with a Mock.  When running under test, I have the IoCContainer initialized to a Mock() that throws if any .Resolve<> calls are made. This catches scenarios where your code under test might be modified to use a new dependency that hasn't been mocked out.

The benefit of this approach is that often a class will have several single-purpose methods, and by extension need a number of dependencies. In applications like web requests where maybe only one method is called, needing one dependency, the dependency resolution only retrieves the dependencies from the container that are needed, not all of them. (I.e. if you use constructor injection with 8 dependencies, all 8 need to be resolved at runtime, even if only 1 will be used.) This also simplifies unit testing to only mock out what you know will be needed rather than everything.


问:
how to call a string from a method from another class Android
Hello I am new to android,java and I want to use the string from a method from another class. Specifically  I want to use the String s from to class Test to class MainActivity. I tried to call it like

```<code>Test.AnswerQ1
</code>```

but it says that cannot resolve symbol "AnswerQ1"

This is my Test class

```<code>public class Test extends Activity {

 private RadioGroup radioGroupQuestion1;
 private RadioButton radioButtonQuestion1;

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

   radioGroupQuestion1 = (RadioGroup) findViewById(R.id.radioGroupQ1);

   Button NextButton = (Button) findViewById(R.id.Q1NextButton);
    NextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

           int selectedId =  radioGroupQuestion1.getCheckedRadioButtonId();
            radioButtonQuestion1 = (RadioButton) findViewById(selectedId);
            String AnswerQ1 = radioButtonQuestion1.getText().toString();
            String Question1 = getString(R.string.Q1);
            System.out.println(Question1);

           System.out.println(AnswerQ1);

           Intent myIntent = new Intent(view.getContext(),  Question2.class);
            startActivityForResult(myIntent, 0);
        }
    });
}
</code>```

And this is my MainActivity class

```<code>public class MainActivity extends Activity{

String myData = Test.s;

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

   System.out.println(myData);

   }
}
</code>```

答: You can make s public static But there are many other solution. Dependent on your need, You can use Shared Preference, Broadcast Listener, Interface etc.

Body:
Hello I am new to android,java and I want to use the string from a method from another class. Specifically  I want to use the String s from to class Test to class MainActivity. I tried to call it like

Test.AnswerQ1

but it says that cannot resolve symbol "AnswerQ1"

This is my Test class

public class Test extends Activity {

 private RadioGroup radioGroupQuestion1;
 private RadioButton radioButtonQuestion1;

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

   radioGroupQuestion1 = (RadioGroup) findViewById(R.id.radioGroupQ1);

   Button NextButton = (Button) findViewById(R.id.Q1NextButton);
    NextButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

           int selectedId =  radioGroupQuestion1.getCheckedRadioButtonId();
            radioButtonQuestion1 = (RadioButton) findViewById(selectedId);
            String AnswerQ1 = radioButtonQuestion1.getText().toString();
            String Question1 = getString(R.string.Q1);
            System.out.println(Question1);

           System.out.println(AnswerQ1);

           Intent myIntent = new Intent(view.getContext(),  Question2.class);
            startActivityForResult(myIntent, 0);
        }
    });
}

And this is my MainActivity class

public class MainActivity extends Activity{

String myData = Test.s;

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

   System.out.println(myData);

   }
}


问:
Get text using selenium PhantomJS inside Span
I tried to get text inside span using Seleniung webdriver PhantomJS. My code is like this :

```<code>href = driver.find_elements_by_xpath("//a[@class='_8mlbc _vbtk2 _t5r8b']")
for rt in href:
    rt.click()
    if href:
        name = driver.find_elements_by_xpath("//*[@class='_99ch8']/span").text
        # name = driver.find_element_by_xpath("//li[a[@title='nike']]/span").text
        print(name)
</code>```

In HTML :

```<code><li class="_99ch8"><a class="_4zhc5 notranslate _ebg8h" title="nike" href="/nike/">nike</a><span><span>Nobody believed a boy from Madeira would make it to the stars. Except the boy from Madeira. </span><br><a href="/explore/tags/nike/">#nike</a><span> </span><a href="/explore/tags/soccer/">#soccer</a><span> </span><a href="/explore/tags/football/">#football</a><span> </span><a href="/explore/tags/cr7/">#CR7</a><span> </span><a href="/explore/tags/cristiano/">#Cristiano</a><span> </span><a href="/explore/tags/cristianoronaldo/">#CristianoRonaldo</a><span> </span><a href="/explore/tags/mercurial/">#Mercurial</a><span> </span><a href="/explore/tags/justdoit/">#justdoit</a></span></li>
</code>```

I want try to get text inside span.

答:
I think first of all, if you want to go for a single element, you need to use find_element_by_xpath() method instead of find_elements_by_xpath() method to get to the element.

If you're using find_elements_by_xpath() then you need to use a looping statement for printing all the names that comes in the name variable.

Also, using the .text property of an element would give you the desired result.

Try this

```<code>   name = driver.find_element_by_xpath(//li[@class='_69ch8']/span).text
   print(name)
</code>```

Body:
I tried to get text inside span using Seleniung webdriver PhantomJS. My code is like this :

href = driver.find_elements_by_xpath("//a[@class='_8mlbc _vbtk2 _t5r8b']")
for rt in href:
    rt.click()
    if href:
        name = driver.find_elements_by_xpath("//*[@class='_99ch8']/span").text
        # name = driver.find_element_by_xpath("//li[a[@title='nike']]/span").text
        print(name)

In HTML :

nikeNobody believed a boy from Madeira would make it to the stars. Except the boy from Madeira.
#nike #soccer #football #CR7 #Cristiano #CristianoRonaldo #Mercurial #justdoit

I want try to get text inside span.

Body:
I think first of all, if you want to go for a single element, you need to use find_element_by_xpath() method instead of find_elements_by_xpath() method to get to the element.

If you're using find_elements_by_xpath() then you need to use a looping statement for printing all the names that comes in the name variable.

Also, using the .text property of an element would give you the desired result.

Try this

   name = driver.find_element_by_xpath(//li[@class='_69ch8']/span).text
   print(name)


问:
How do I access Firebase storage from within a Database-triggered Cloud Function?
I would like to perform file manipulation using firebase cloud functions by listening to an event triggered by functions.database.ref().onWrite() (instead of functions.storage.object().onChange()).

I noticed most of the sample using cloud functions functions.storage.object().onChange() to trigger a cloud functions for file manipulation. Is there a way to get a storageRef from within functions.database.ref() and perform file manipulation from there?

答:
To access Firebase Storage from within your database triggered Cloud Function, you can use the Google Cloud SDK.

From one of my apps:

const gcs = require('@google-cloud/storage')();

...
exports
.emojifyStory = functions.database.ref('/stories/{storyId}')
.onWrite(function(event) {
    const filePath = event.data.val().filePath;
    const file = gcs.bucket(bucket).file(filePath);

    // Use the Vision API to detect labels
    return visionClient.detectLabels(file)
      .then(data => {
      ...
```


问:
Picker View displaces objects
I'm making an app with a picker view, and when a button is pressed, the picker view pops up, and when another button is pressed, it disappears. In the storyboard, the picker view covers the bottom half of the screen, including two buttons, but when I run the simulator, the buttons and other objects that are on the screen (such as labels and text fields) get shifted to seemingly random places, including the objects that are not covered by the picker view. What exactly is the problem, and how do I fix it?</p>

答:
Go to the story board, select that particular view controller on which you have placed the picker view and open document outline window(which appear on the left side of story board). After that you will get the list of components present on that view. Drag the labels and the buttons to the bottom of the picker view. By doing this you will get the labels and the buttons on the top of the picker view and add the constraints to the components.
Another reason might be that you have selected other model at the bottom and ran on other model.
Just set the constraints it will solve the problems. And delete suggested constraints.</p>

Title: Picker View displaces objects


问:
How to get the returned value in a Windows batch file
In Windows batch file I want the return value i.e. the apkVerison number. When I run gulp getVersion on the command line or inside a batch file it works fine. I want save the version number to a variable inside the batch file.

```<code>gulpfile.js:
  gulp.task('getVersion', function () {
      var data = require('./package.json')
      console.log('Version = ' + data.apkDependencies.apkVersion)
      return data.apkDependencies.apkVersion;
    });

abc.bat:
    set x=gulp getVersion
    echo %x%
</code>```

The batch file does not work. echo just echos "gulp getVersion"

Sorry I should have mentioned when I run gulp this is its output

```<code>gulp getVersion
[22:16:44] Using gulpfile ~\CareWheelsCorp\CareWheels\gulpfile.js
[22:16:44] Starting 'getVersion'...
Version = 9.1.13
[22:16:44] Finished 'getVersion' after 1.91 ms
</code>```

As you can see Version is hidden inside, I need that 9.1.13 number

答:
It works perfectly happily - just as you have asked it to do, to echo the contents of x.

If you want to execute the contents of x, you need

```<code>%x%
</code>```

and if you want to get the return value, you need

```<code>for /f "delims=" %%r in ('%x%') do set "return=%%r"
echo %return%
</code>```

(assuming that the executable responds with a result from stdout)

Given the clarification,

```<code>for /f "tokens=1*delims== " %%r in ('%x%') do if "%%r"=="Version" set "return=%%s"
echo %return%
</code>```

Body:
In Windows batch file I want the return value i.e. the apkVerison number. When I run gulp getVersion on the command line or inside a batch file it works fine. I want save the version number to a variable inside the batch file.

gulpfile.js:
  gulp.task('getVersion', function () {
      var data = require('./package.json')
      console.log('Version = ' + data.apkDependencies.apkVersion)
      return data.apkDependencies.apkVersion;
    });

abc.bat:
    set x=gulp getVersion
    echo %x%

The batch file does not work. echo just echos "gulp getVersion"

Sorry I should have mentioned when I run gulp this is its output

gulp getVersion
[22:16:44] Using gulpfile ~\CareWheelsCorp\CareWheels\gulpfile.js
[22:16:44] Starting 'getVersion'...
Version = 9.1.13
[22:16:44] Finished 'getVersion' after 1.91 ms

As you can see Version is hidden inside, I need that 9.1.13 number

Body:
It works perfectly happily - just as you have asked it to do, to echo the contents of x.

If you want to execute the contents of x, you need

%x%

and if you want to get the return value, you need

for /f "delims=" %%r in ('%x%') do set "return=%%r"
echo %return%

(assuming that the executable responds with a result from stdout)

Given the clarification,

for /f "tokens=1*delims== " %%r in ('%x%') do if "%%r"=="Version" set "return=%%s"
echo %return%


问:
Undefined constant in Laravel 5.4
I am migrating an old code from 4.2 to 5.4.
My index.php is triggering the error: undefined constant CURRENCY_BEFORE assumed 'CURRENCY_BEFORE

from this line:

```<code><select name="curreny_position">
    <option value="BEFORE"
    <?php if ($curr_pos['value'] == CURRENCY_BEFORE) echo "selected"; ?>>
     Before
    </option>
    <option value="AFTER" <?php if ($curr_pos['value'] == CURRENCY_AFTER) echo "selected"; ?>>After
    </option>
</code>```

I am not sure if this would help, but this is the callout in my settings.php file:

```<code>{
    $currency_position = self::param('site', 'curr_position')['value'];
    $currency = self::param('site', 'currency')['value'];
    switch ($currency_position) {
        case CURRENCY_BEFORE:
            return implode(' ', [$currency, number_format($amount, 2)]);
            break;
        case CURRENCY_AFTER:
            return implode(' ', [number_format($amount, 2), $currency]);
            break;
 }
</code>```

what would be the proper way to define CURRENCY_BEFORE above?

答:
I would suggest moving the definition of your constant to a config file

```<code><?php
/**
 *  file: app/config/constants.php
 */

return [
    'CURRENCY_BEFORE' => 'BEFORE'
];
</code>```

then you can call anywhere in the application by Config::get('constants.CURRENCY_BEFORE')

Title: Undefined constant in Laravel 5.4

Body:
I am migrating an old code from 4.2 to 5.4.
My index.php is triggering the error: undefined constant CURRENCY_BEFORE assumed 'CURRENCY_BEFORE

from this line:

<select name="curreny_position">
    <option value="BEFORE"
    <?php if ($curr_pos['value'] == CURRENCY_BEFORE) echo "selected"; ?>>
     Before
    </option>
    <option value="AFTER" <?php if ($curr_pos['value'] == CURRENCY_AFTER) echo "selected"; ?>>After
    </option>

I am not sure if this would help, but this is the callout in my settings.php file:

{
    $currency_position = self::param('site', 'curr_position')['value'];
    $currency = self::param('site', 'currency')['value'];
    switch ($currency_position) {
        case CURRENCY_BEFORE:
            return implode(' ', [$currency, number_format($amount, 2)]);
            break;
        case CURRENCY_AFTER:
            return implode(' ', [number_format($amount, 2), $currency]);
            break;
 }

what would be the proper way to define CURRENCY_BEFORE above?

Body:
I would suggest moving the definition of your constant to a config file

<?php
/**
 *  file: app/config/constants.php
 */

return [
    'CURRENCY_BEFORE' => 'BEFORE'
];

then you can call anywhere in the application by Config::get('constants.CURRENCY_BEFORE')


问:
Type casting with pointers in C
Does the following type cast create a new variable in memory?
It is referenced in the printf function below, and it prints 1.23 as the answer.</p>

```<code>#include<stdio.h>
int main(){
    int num;
    num = 1.23456;
    printf("num = %.2f \n", (float)num);
    *((float*) &num) = 1.23456;
    printf("num = %.2f \n", *((float*)&num));
    return 0;
}
</code>```

答:
When you declare a variable as an integer and then initialise it as a float, the program, in the background, will store it as an integer as 1 in this case, truncating all the decimal places. It should be declared as a float first.

For the case of the pointer, it is displayed as a float because it has been declared and initialised as a float and you are modifying(type casting) and displaying the value at it's memory location which is calling by reference. This means that the data type will change as well.

Title: Type casting with pointers in C

Body:
Does the following type cast create a new variable in memory?
It is referenced in the printf function below, and it prints 1.23 as the answer.

#include<stdio.h>
int main(){
    int num;
    num = 1.23456;
    printf("num = %.2f \n", (float)num);
    *((float*) &num) = 1.23456;
    printf("num = %.2f \n", *((float*)&num));
    return 0;
}


问:
How do I filter and count objects in a javascript array?
I'm trying to implement the filter method on an array in which every element is an object like this:

```<code>{
  "start": 1234,
  "end": 4321,
  "count": 0
}
</code>```

I want to remove duplicates from my array while incrementing the count property.

At the moment I only managed to filter the array by the start property using this code:

```<code> var temp = {};
 myArray = myArray.filter(function(obj) {
     if (obj.start in temp) {
         return false;
     } else {
         temp[obj.start] = true;
         return true;
     }
 });
</code>```

What I want to achieve is a filter that works on these conditions (for better explaining, I will refer to elements in temp as tempObj and the current object as obj):

if obj.start === tempObj.start && obj.end === tempObj.end, obj.count += 1

if obj.start === tempObj.start || obj.end === tempObj.end, obj.count = tempObj.count + 1

if obj.start > tempObj.start && obj.end < tempObj.end, obj.count = tempObj.count + 1

else add a new element to temp with count = 1

Is it possible using the filter method? If not, what is the correct way? I would rather not use any framework.

EDIT: as per RobG request, to make the question more clear I'm adding an input and output example.

Example input:

```<code>myArray = [{
  "start": 1105,
  "end": 1501,
  "count": 0
},

{
  "start": 1105,
  "end": 1003,
  "count": 0
},

{
  "start": 1110,
  "end": 1120,
  "count": 0
},

{
  "start": 1105,
  "end": 1003,
  "count": 0
},

{
  "start": 1115,
  "end": 1120,
  "count": 0
}]
</code>```

Desired output:

```<code>myArray = [{
  "start": 1105,
  "end": 1501,
  "count": 1
},

{
  "start": 1105,
  "end": 1003,
  "count": 3
},

{
  "start": 1110,
  "end": 1120,
  "count": 1
}

{
  "start": 1115,
  "end": 1120,
  "count": 1
}]
</code>```

答:
Is this what you are looking for?

myArray = [{
    "start": 1105,
    "end": 1501,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1110,
    "end": 1120,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1115,
    "end": 1120,
    "count": 0
  }
]

var obj = {};

for (var i = 0, len = myArray.length; i < len; i++) {
  obj[myArray[i]['start']] = myArray[i];
}

myArray = new Array();
var count = 0;
for (var key in obj) {
  obj[key].count = count++;
  myArray.push(obj[key]);
}

console.log(myArray)```
</div>
</div>
</p>

<p>updated answer. </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>myArray = [{
    "start": 1105,
    "end": 1501,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },
  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1110,
    "end": 1120,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1115,
    "end": 1120,
    "count": 0
  }
]

function removeDoopCount(myArray) {
  const start = x => myArray[x].start;
  const end = x => myArray[x].end;
  let hash = new Map();
  for (var i = 0, len = myArray.length; i < len; i++) {
    let key = start(i) + ':' + end(i);
    let item = myArray[i];
    let values = hash.get(key);
    if (values) values.push(item);
    else hash.set(key, [item]);
  }
  let ar = [];
  hash.forEach((v, k, m) => (count = 1, v.forEach(i => i.count += count++), ar.push(v[v.length - 1])));
  return ar;
}
console.log(removeDoopCount(myArray));</code>```

Body:
I'm trying to implement the filter method on an array in which every element is an object like this:

{
  "start": 1234,
  "end": 4321,
  "count": 0
}

I want to remove duplicates from my array while incrementing the count property.

At the moment I only managed to filter the array by the start property using this code:

 var temp = {};
 myArray = myArray.filter(function(obj) {
     if (obj.start in temp) {
         return false;
     } else {
         temp[obj.start] = true;
         return true;
     }
 });

What I want to achieve is a filter that works on these conditions (for better explaining, I will refer to elements in temp as tempObj and the current object as obj):

if obj.start === tempObj.start && obj.end === tempObj.end, obj.count += 1

if obj.start === tempObj.start || obj.end === tempObj.end, obj.count = tempObj.count + 1

if obj.start > tempObj.start && obj.end < tempObj.end, obj.count = tempObj.count + 1

else add a new element to temp with count = 1

Is it possible using the filter method? If not, what is the correct way? I would rather not use any framework.

EDIT: as per RobG request, to make the question more clear I'm adding an input and output example.

Example input:

myArray = [{
  "start": 1105,
  "end": 1501,
  "count": 0
},

{
  "start": 1105,
  "end": 1003,
  "count": 0
},

{
  "start": 1110,
  "end": 1120,
  "count": 0
},

{
  "start": 1105,
  "end": 1003,
  "count": 0
},

{
  "start": 1115,
  "end": 1120,
  "count": 0
}]

Desired output:

myArray = [{
  "start": 1105,
  "end": 1501,
  "count": 1
},

{
  "start": 1105,
  "end": 1003,
  "count": 3
},

{
  "start": 1110,
  "end": 1120,
  "count": 1
}

{
  "start": 1115,
  "end": 1120,
  "count": 1
}]

Body:
Is this what you are looking for?

myArray = [{
    "start": 1105,
    "end": 1501,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1110,
    "end": 1120,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1115,
    "end": 1120,
    "count": 0
  }
]

var obj = {};

for (var i = 0, len = myArray.length; i < len; i++) {
  obj[myArray[i]['start']] = myArray[i];
}

myArray = new Array();
var count = 0;
for (var key in obj) {
  obj[key].count = count++;
  myArray.push(obj[key]);
}

console.log(myArray)

updated answer.

myArray = [{
    "start": 1105,
    "end": 1501,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },
  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1110,
    "end": 1120,
    "count": 0
  },

  {
    "start": 1105,
    "end": 1003,
    "count": 0
  },

  {
    "start": 1115,
    "end": 1120,
    "count": 0
  }
]

function removeDoopCount(myArray) {
  const start = x => myArray[x].start;
  const end = x => myArray[x].end;
  let hash = new Map();
  for (var i = 0, len = myArray.length; i < len; i++) {
    let key = start(i) + ':' + end(i);
    let item = myArray[i];
    let values = hash.get(key);
    if (values) values.push(item);
    else hash.set(key, [item]);
  }
  let ar = [];
  hash.forEach((v, k, m) => (count = 1, v.forEach(i => i.count += count++), ar.push(v[v.length - 1])));
  return ar;
}
console.log(removeDoopCount(myArray));


问:
Get all push notifications received since app was last open
I'm creating an iOS 10 app using Xcode 8 and CloudKit. When the app loads, is there any way to read all push notification that have been sent since the last time the app was running?</p>

答:
from ios 10.x we can get pending and delivered notification information using UNUserNotificationCenter

you with a list of the app’s notifications that are still displayed in Notification Center using below function

func getDeliveredNotifications(completionHandler: @escaping ([UNNotification]) -> Void)

refrer below link for more details


问:
How to overcome the effect of navigation bar
In my application i want to hide the navigation bar when i m going to previous view and i m hiding navigation bar in viewwiilldisaapper method but the effect is remaining mean it gives the white screen at the time of pop..

so can any one tell me the solution for it.

Thanks to all.

答:
(void) viewWillDisappear:(BOOL)animated
{

if (self.navigationController.topViewController != self)

{

```<code>[self.navigationController setNavigationBarHidden:NO animated:animated];
</code>```

}

[super viewWillDisappear:animated];
}

Body:
(void) viewWillDisappear:(BOOL)animated
{

if (self.navigationController.topViewController != self)

{

[self.navigationController setNavigationBarHidden:NO animated:animated];

}

[super viewWillDisappear:animated];
}


问:
What difference between
I have first query

```<code>select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Created_at BETWEEN '2017-05-01' AND '2017-05-31')
</code>```

and result is 1050

i also have second query :

```<code>select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Month(Created_at) =5 and Year(Created_at) = 2017)
</code>```

and result is 1111

I think 2 query have same meaning but it return 2 different result.
Info about column "Created_at": COLUMN_NAME Created_at,  COLUMN_TYPE timestamp,  IS_NULLABLE NO,  COLUMN_KEY ,  COLUMN_DEFAULT CURRENT_TIMESTAMP

Please help what difference between 2 query?

答:
If you consider the time within a day, the first query only returns results before 2017-05-31 00:00:00.
If you have any results after 2017-05-31 00:00:00 and before 2017-05-31 23:59:59 (maybe down to milliseconds too), they only show up in the second query.</p>

Title: What difference between

Body:
I have first query

select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Created_at BETWEEN '2017-05-01' AND '2017-05-31')

and result is 1050

i also have second query :

select count(*)
from `order`
where marketer_id = 75 and
      HandleStatus != -1 and
      (Month(Created_at) =5 and Year(Created_at) = 2017)

and result is 1111

I think 2 query have same meaning but it return 2 different result.
Info about column "Created_at": COLUMN_NAME Created_at,  COLUMN_TYPE timestamp,  IS_NULLABLE NO,  COLUMN_KEY ,  COLUMN_DEFAULT CURRENT_TIMESTAMP

Please help what difference between 2 query?


问:
How to pass large number of parameters from Angular js to rest service
I am trying to fetch parameters from angular JS $http service to rest service using **@queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with @QueryParam makes the code look pretty bad .I am using GET.

How can I optimize this ?

Example what I am doing -

Angular Js code -

```<code>$http({
    url: someUrl,
    method: "GET",
    params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
 });
</code>```

Java side -

```<code>@path("/getAllData")
@GET
@Produces({..}
public response getAllData(@QueryParam("filter1") final String filter1,
                           @QueryParam("filter2") final String filter2,
                           @QueryParam("filter3") final String filter3){
}
</code>```

Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with @PathParam

```<code>$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
           '&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
           '&filter4='$scope.filter4)
</code>```

I am able to do it by passing individually in @QueryParam . I am looking for optimized code when we a large number of parameters.

答:
You can do it in 2 ways:

1) org.json.simple.JSONObject.

2) Bean or POJO Class.

AngularJS Controller:

```<code>var URL = appURL+'/adm/addCollProcess.do';
var json = {"col_pro_id":$scope.col_pro_id, "col_code": $scope.col_code, "exam_type_ids": $scope.exam_types.toString().replace("[","").replace("]",""),
    "created_by" : "admin", "file_path" : $scope.file_path, "website" : $scope.website, "facebook" : $scope.facebook};

// using JSONObject
$http.post(URL, json).then(function(response){
    if(response.data){
       // Code
    }
});

// using Bean Class
 $http.post(URL, JSON.stringify(json)).then(function(response){
    if(response.data){
       // Code
    }
});
</code>```

Java Controller:

```<code>// using JSONObject
@RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public boolean addCollProcess(@RequestBody JSONObject json){
    // Code
}

// using Bean Class:
@RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public @ResponseBody boolean addCollProcess(@RequestBody AdmissionProcessBean processBean) {
    // Code
}
</code>```

Body:
I am trying to fetch parameters from angular JS $http service to rest service using **@queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with @QueryParam makes the code look pretty bad .I am using GET.

How can I optimize this ?

Example what I am doing -

Angular Js code -

$http({
    url: someUrl,
    method: "GET",
    params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
 });

Java side -

@path("/getAllData")
@GET
@Produces({..}
public response getAllData(@QueryParam("filter1") final String filter1,
                           @QueryParam("filter2") final String filter2,
                           @QueryParam("filter3") final String filter3){
}

Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with @PathParam

$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
           '&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
           '&filter4='$scope.filter4)

I am able to do it by passing individually in @QueryParam . I am looking for optimized code when we a large number of parameters.

Body:
You can do it in 2 ways:

1) org.json.simple.JSONObject.

2) Bean or POJO Class.

AngularJS Controller:

var URL = appURL+'/adm/addCollProcess.do';
var json = {"col_pro_id":$scope.col_pro_id, "col_code": $scope.col_code, "exam_type_ids": $scope.exam_types.toString().replace("[","").replace("]",""),
    "created_by" : "admin", "file_path" : $scope.file_path, "website" : $scope.website, "facebook" : $scope.facebook};

// using JSONObject
$http.post(URL, json).then(function(response){
    if(response.data){
       // Code
    }
});

// using Bean Class
 $http.post(URL, JSON.stringify(json)).then(function(response){
    if(response.data){
       // Code
    }
});

Java Controller:

// using JSONObject
@RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public boolean addCollProcess(@RequestBody JSONObject json){
    // Code
}

// using Bean Class:
@RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public @ResponseBody boolean addCollProcess(@RequestBody AdmissionProcessBean processBean) {
    // Code
}


问:
How to install QUANDL on AWS EC2?
When i issue following command </p>

```<code>pip install Quandle
</code>```

<p>i am getting following message </p>

```<code>Command "/usr/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pi
p-build-7Q6V28/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__
);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'ex
ec'))" install --record /tmp/pip-YTWhP8-record/install-record.txt --single-versi
on-externally-managed --compile" failed with error code 1 in /tmp/pip-build-7Q6V
28/cryptography/
</code>```

答:
The Github projcect page says you should use the command

```<code>pip install quandle
</code>```

to install.

Are you accidentally using un uppercase "Q" in your command?

Title: How to install QUANDL on AWS EC2?

Body:
When i issue following command

pip install Quandle

i am getting following message

Command "/usr/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pi
p-build-7Q6V28/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__
);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'ex
ec'))" install --record /tmp/pip-YTWhP8-record/install-record.txt --single-versi
on-externally-managed --compile" failed with error code 1 in /tmp/pip-build-7Q6V
28/cryptography/

Body:
The Github projcect page says you should use the command

pip install quandle

to install.

Are you accidentally using un uppercase "Q" in your command?


答: The first query is not looking at 31st May, it looks only until 30 May. The absence of a time component means the time is taken as midnight, or the start of the 31st.</p>

Title: What difference between


问:
CSV read error in Python using Panda
I want to read a csv file

```<code>import pandas as pd
import numpy as np
import matplotlib as plt
from pandas import DataFrame

df = pd.read_csv(r'C:\Andy\DataScience\python\Loan_Prediction\Train.csv')
df.head(10)
</code>```

But getting error  as below

```<code>IOError: File Train.csv does not exist
</code>```

But the file does exist in the location.

答:
your read_csv could not find the path for reading the csv you have to give forward slashes

```<code>import pandas as pd
import numpy as np
import matplotlib as plt
from pandas import DataFrame

df = pd.read_csv('C:/Andy/DataScience/python/Loan_Prediction/Train.csv')
</code>```

if it again gives error then just double the slashes to avoid any special character.

```<code>df = pd.read_csv('C://Andy//DataScience//python//Loan_Prediction//Train.csv')

df.head(10)
</code>```

Title: CSV read error in Python using Panda

Body:
I want to read a csv file

import pandas as pd
import numpy as np
import matplotlib as plt
from pandas import DataFrame

df = pd.read_csv(r'C:\Andy\DataScience\python\Loan_Prediction\Train.csv')
df.head(10)

But getting error  as below

IOError: File Train.csv does not exist

But the file does exist in the location.

Body:
your read_csv could not find the path for reading the csv you have to give forward slashes

import pandas as pd
import numpy as np
import matplotlib as plt
from pandas import DataFrame

df = pd.read_csv('C:/Andy/DataScience/python/Loan_Prediction/Train.csv')

if it again gives error then just double the slashes to avoid any special character.

df = pd.read_csv('C://Andy//DataScience//python//Loan_Prediction//Train.csv')

df.head(10)


问:
How many subnets required in a VPC
I wish to implement my website in AWS virtual private cloud (VPC) with the following requirement:

The web tier will use an Auto Scaling group across multiple Availability Zones (AZs).

The database will use Multi-AZ RDS MySQL and should not be publicly accessible.

What is the minimal number of subnets required?

I assume one subnet = one AZ. Having said that, I will be needing 2 subnets for the RDS instance and one for my web tier which might have to sit in the public subnets? so total 3 minimal?

答:
You have two options:

Do everything in Public Subnets, using Security Groups to protect your database, or

Use Public & Private Subnets

If both options, you would need:

An Amazon VPC

An Internet Gateway (which connects the VPC to the Internet)

An Elastic Load Balancer

An Auto Scaling group of Amazon EC2 instances running your web tier

An Amazon RDS Multi-AZ database -- you have indicated a preference for MySQL

Also, you would create three security groups:

A Load Balancer security group, permitting inbound traffic from the Internet (0.0.0.0/0) for HTTP (port 80) and presumably HTTPS (port 443)

A Web Tier security group, permitting inbound traffic from the Load Balancer security group on the same ports

A Database security group, permitting inbound traffic from the Web Tier security group on port 3306 (MySQL)

Option 1: Do everything in public subnets

In this option, you can put all services inside a Public Subnet (which is defined as a subnet connected to the Internet via an Internet Gateway).
You wish to implement a multi-AZ solution, so you will need one subnet per AZ. If you choose to use two AZs, this means you will need two subnets. (You could choose to use more than two AZs/subnets, if they are available in your region.)

Deploy your Load Balancer in both subnets. Create your Auto Scaling group to use both subnets. Create an Amazon RDS DB Subnet Group across both subnets for use by the multi-AZ database and launch the database into that DB Subnet Group.

The security groups will ensure that only the Load Balancer is exposed to the Internet. Nothing else will be publicly accessible.

Option 2: Use Public & Private Subnets

Some people prefer using Private Subnets to ensure resources are not exposed to the Internet. This is mostly to remain compatible with traditional on-premises architecture that does not have the concept of a Security Group.

This option would involve:

A Public Subnet in each AZ: Put your Load Balancer in these subnets

A Private Subnet in each AZ: Put your Web Tier Auto Scaling group and your database in these subnets (defined via the DB Subnet Group)

Use the same Security Groups as option 1

Title: How many subnets required in a VPC


问:
Creating security groups for a custom module in odoo 10
I have created a custom module on odoo 10. Now I wanted to create security groups with users where each group have a particular menu of my custom module. I've already asked this question and I followed the answers that I got but I did not get the results (I definitely messed up at some point but I can't see where, this is my first time working with odoo) so I ask again the question. Here's what I did:

I created a file security.xml in my security folder with contain the following

```<code><?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">
   <!-- Creating a Group Category -->
   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>
   <!-- Adding a Group to the Group Category -->
   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation subjective"/>
       <!-- Adding Rights of existing Groups -->
       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('base.group_sale_manager'))]"/>
   </record>
  </data>
 </odoo>
</code>```

Then in the file pnc_menus.xml (I have a file called pnc_menus.xml where I created all of my menus) I added the groups field to this menu:

```<code><menuitem name="Parties Prenantes" id="pnc_evaluation_stakeholders"
         action="pncevaluation_partieprenante" parent="pnc_documents" sequence="40" groups="base.group_system"/>
</code>```

Then in csv file of my security folder I added this :

```<code>id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
eval_group,groupe_evaluation,pnc_evaluation_stakeholders,group_eval_subj,1,1,1,1
</code>```

When I updated my module I have an error saying "csv file could not be proccessed"

```<code>In the log file I have this:
`Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
 File "D:\Odoo 10.0\server\odoo\tools\convert.py", line 898, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
</code>```

The link to my previous question.

答:
The Group group_sale_manager is moved from base to sales_team in Odoo 10.
So change your code like the below

```<code><field name="implied_ids" eval="[(4, ref('base.group_system')), (4,ref('sales_team.group_sale_manager'))]"/>
</code>```

And do not forget to add sales_team dependency in your module

Body:
I have created a custom module on odoo 10. Now I wanted to create security groups with users where each group have a particular menu of my custom module. I've already asked this question and I followed the answers that I got but I did not get the results (I definitely messed up at some point but I can't see where, this is my first time working with odoo) so I ask again the question. Here's what I did:

I created a file security.xml in my security folder with contain the following

<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data noupdate="0">

   <record id="evaluation_subj" model="ir.module.category">
       <field name="name">evaluation subjective</field>
       <field name="sequence">1</field>
   </record>

   <record id="group_eval_subj" model="res.groups">
       <field name="name">Groupe Evaluation Subjective</field>
       <field name="evaluation_subj" ref="evaluation subjective"/>

       <field name="implied_ids"
              eval="[(4, ref('base.group_system')),
     (4,ref('base.group_sale_manager'))]"/>
   </record>
  </data>
 </odoo>

Then in the file pnc_menus.xml (I have a file called pnc_menus.xml where I created all of my menus) I added the groups field to this menu:

<menuitem name="Parties Prenantes" id="pnc_evaluation_stakeholders"
         action="pncevaluation_partieprenante" parent="pnc_documents" sequence="40" groups="base.group_system"/>

Then in csv file of my security folder I added this :

id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
eval_group,groupe_evaluation,pnc_evaluation_stakeholders,group_eval_subj,1,1,1,1

When I updated my module I have an error saying "csv file could not be proccessed"

In the log file I have this:
`Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.
 File "D:\Odoo 10.0\server\odoo\tools\convert.py", line 898, in convert_csv_import
    raise Exception(_('Module loading %s failed: file %s could not be processed:\n %s') % (module, fname, warning_msg))
Exception: Module loading pncevaluation failed: file pncevaluation\security/ir.model.access.csv could not be processed:
 Aucun enregistrement trouv\xe9 pour id externe 'group_eval_subj' dans le champ 'Group'
ERREUR:  une instruction insert ou update sur la table \xab ir_model_access \xbb viole la contrainte de cl\xe9
\xe9trang\xe8re \xab ir_model_access_model_id_fkey \xbb
DETAIL:  La cl\xe9 (model_id)=(559) n'est pas pr\xe9sente dans la table \xab ir_model \xbb.

The link to my previous question.

Body:
The Group group_sale_manager is moved from base to sales_team in Odoo 10.
So change your code like the below

<field name="implied_ids" eval="[(4, ref('base.group_system')), (4,ref('sales_team.group_sale_manager'))]"/>

And do not forget to add sales_team dependency in your module


问:
Strong Validation in WPF
I have a databound TextBox in my application like so: (The type of Height is decimal?)

    <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
                            ValidatesOnExceptions=True,
                            Converter={StaticResource NullConverter}}" />
```
<pre class="lang-cs prettyprint-override"><code>    public class NullableConverter : IValueConverter {
        public object Convert(object o, Type type, object parameter, CultureInfo culture) {
            return o;
        }

        public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
            if (o as string == null || (o as string).Trim() == string.Empty)
                return null;
            return o;
        }
    }
</code>```

Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:

Not allow the TextBox to lose focus until it contains a valid value.

Revert the value in the TextBox to the last valid value.

What is the best way to do this?

Update:

I've found a way to do #2. I don't love it, but it works:

```<code>private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
    var box = sender as TextBox;
    var binding = box.GetBindingExpression(TextBox.TextProperty);
    if (binding.HasError)
        binding.UpdateTarget();
}
</code>```

Does anyone know how to do this better? (Or do #1.)

答:
It sounds to me that you'll want to handle two events:

GotFocus: Will trigger when the textbox gains focus. You can store the initial value of the box.

LostFocus: Will trigger when the textbox loses focus. At this point you can do your validation and decide if you want to roll back or not.

OwnerDisplayName: Joseph Sturtevant

ContentLicense: CC BY-SA 4.0

Title: Strong Validation in WPF

Body:
I have a databound TextBox in my application like so: (The type of Height is decimal?)

    <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
                            ValidatesOnExceptions=True,
                            Converter={StaticResource NullConverter}}" />

    public class NullableConverter : IValueConverter {
        public object Convert(object o, Type type, object parameter, CultureInfo culture) {
            return o;
        }

        public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
            if (o as string == null || (o as string).Trim() == string.Empty)
                return null;
            return o;
        }
    }

Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:

Not allow the TextBox to lose focus until it contains a valid value.

Revert the value in the TextBox to the last valid value.

What is the best way to do this?

Update:

I've found a way to do #2. I don't love it, but it works:

private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
    var box = sender as TextBox;
    var binding = box.GetBindingExpression(TextBox.TextProperty);
    if (binding.HasError)
        binding.UpdateTarget();
}

Does anyone know how to do this better? (Or do #1.)

LastEditorDisplayName: Joseph Sturtevant

OwnerDisplayName: Dillie-O

LastEditorDisplayName: Dillie-O


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
It's more of a readability issue.

I would wrap all the data into an array. And use just one pair of get/set methods.

Something like:

```<code>class Test()
{
    private $DATA = array();

    function set($what,$data) {
       $DATA[$what] = $data;
    }

    function get($what) {
        return $this->DATA[$what];
    }
}
</code>```

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

Body:
It's more of a readability issue.

I would wrap all the data into an array. And use just one pair of get/set methods.

Something like:

class Test()
{
    private $DATA = array();

    function set($what,$data) {
       $DATA[$what] = $data;
    }

    function get($what) {
        return $this->DATA[$what];
    }
}

OwnerDisplayName: Maiku Mori


问:
MATLAB finds persistence.xml for eclipselink only within the first few seconds
This is a continuation of the issue described in Using eclipselink in Java code run from MATLAB and is similar to the issue described in Java JPA Class for MATLAB, but the accepted solutions described there have not completely solved the issue.

I am trying to use eclipselink to connect to an oracle database in matlab. From the answers in the previous posts, I put the code on the static classpath (in the classpath.txt). When I do this I am able to use it, but only if I create the EntityManager (via a call to Persistence.createEntityManager(...)) within the first few seconds after matlab loads. If I wait more than 5 second after starting up Matlab, the exact same code gives the "No Persistence provided" exception. I have confirmed that the times that it does work, it is actually using a different class loader than the times that it does not. The only thing that I can think of is that the classpath is initializing on a separate thread than the Matlab console and that if I run it quickly, then Matlab's OSGI classloader is not initialized yet so it uses the default java class loader.

This is obviously not an acceptable solution and doesn't seem to have really solved the reason of why Matlab classloader can not find the persistence.xml. Does anyone have any further ideas? Could it possibly be in how I am initializing eclipselink? Neither the guy that worked on this code before me nor I have been able to figure out a way to get it to recognize the persistence.xml in any way other than putting it in the META-INF folder on the classpath.

答:
eclipselink is available in two flavors:

"Intended for use in Java EE and SE environments." and

"OSGI Bundle Zip to use EclipseLink 2.1.2 runtime in an OSGi container."

The "OSGI Bundle" will not run on the MATLAB JVM due to the missing OSGI container. Therefore the single jar for Java EE and SE environments will be the right choice.

According to Deploying EclipseLink putting persistence.xml in the META-INF folder on the classpath, seems to be correct.

EDIT:

The following lines are added to startup.m whereas ClassPathHacker.class must reside in /MATLAB/java/. All three required libraries derby.jar, eclipselink.jar, javax.persistence_2.0.1.v201006031150.jar may be download from the locations given in JPA 2.0 with EclipseLink Tutorial.

```<code>javaaddpath('/MATLAB/java/');
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/dist/JpaForMatlab.jar'))
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/lib/derby.jar'))
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/lib/eclipselink.jar'))
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/lib/javax.persistence_2.0.1.v201006031150.jar'))
</code>```

JpaForMatlab.jar has the following layout:

```<code>|- META-INF
   |- persistence.xml
|- jpaformatlab
   |- Main.class
   |- Todo.class
</code>```

persistence.xml

```<code><?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>jpaformatlab.Todo</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:derby:/NetBeansProjects/derby-db/simpleDb;create=true" />
            <property name="javax.persistence.jdbc.user" value="test" />
            <property name="javax.persistence.jdbc.password" value="test" />
            <property name="eclipselink.ddl-generation" value="create-tables" />
            <property name="eclipselink.ddl-generation.output-mode" value="both" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

Main.java

```<code>package jpaformatlab;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class Main {

    private static final String PERSISTENCE_UNIT_NAME = "todos";
    private static EntityManagerFactory factory;

    public static void main(String[] args) {
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = factory.createEntityManager();
        // Read the existing entries and write to console
        Query q = em.createQuery("select t from Todo t");
        List<Todo> todoList = q.getResultList();
        for (Todo todo : todoList) {
            System.out.println(todo);
        }
        System.out.println("Size: " + todoList.size());

        // Create new todo
        em.getTransaction().begin();
        Todo todo = new Todo();
        todo.setSummary("This is a test");
        todo.setDescription("This is a test");
        em.persist(todo);
        em.getTransaction().commit();

        em.close();
    }
}
</code>```

Todo.java

```<code>package jpaformatlab;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String summary;
    private String description;

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Todo [summary=" + summary + ", description=" + description
                + "]";
    }

}
</code>```

Finally we call the main method in order to run this simple example from the MATLAB prompt.

```<code>>> jpaformatlab.Main.main(javaArray('java.lang.String',1))
>> Todo [summary=This is a test, description=This is a test]
</code>```

Body:
eclipselink is available in two flavors:

"Intended for use in Java EE and SE environments." and

"OSGI Bundle Zip to use EclipseLink 2.1.2 runtime in an OSGi container."

The "OSGI Bundle" will not run on the MATLAB JVM due to the missing OSGI container. Therefore the single jar for Java EE and SE environments will be the right choice.

According to Deploying EclipseLink putting persistence.xml in the META-INF folder on the classpath, seems to be correct.

EDIT:

The following lines are added to startup.m whereas ClassPathHacker.class must reside in /MATLAB/java/. All three required libraries derby.jar, eclipselink.jar, javax.persistence_2.0.1.v201006031150.jar may be download from the locations given in JPA 2.0 with EclipseLink Tutorial.

javaaddpath('/MATLAB/java/');
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/dist/JpaForMatlab.jar'))
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/lib/derby.jar'))
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/lib/eclipselink.jar'))
ClassPathHacker.addFile(java.lang.String('/NetBeansProjects/JpaForMatlab/lib/javax.persistence_2.0.1.v201006031150.jar'))

JpaForMatlab.jar has the following layout:

|- META-INF
   |- persistence.xml
|- jpaformatlab
   |- Main.class
   |- Todo.class

persistence.xml

<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <class>jpaformatlab.Todo</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
            <property name="javax.persistence.jdbc.url"
                value="jdbc:derby:/NetBeansProjects/derby-db/simpleDb;create=true" />
            <property name="javax.persistence.jdbc.user" value="test" />
            <property name="javax.persistence.jdbc.password" value="test" />
            <property name="eclipselink.ddl-generation" value="create-tables" />
            <property name="eclipselink.ddl-generation.output-mode" value="both" />
        </properties>
    </persistence-unit>
</persistence>

Main.java

package jpaformatlab;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class Main {

    private static final String PERSISTENCE_UNIT_NAME = "todos";
    private static EntityManagerFactory factory;

    public static void main(String[] args) {
        factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
        EntityManager em = factory.createEntityManager();
        // Read the existing entries and write to console
        Query q = em.createQuery("select t from Todo t");
        List<Todo> todoList = q.getResultList();
        for (Todo todo : todoList) {
            System.out.println(todo);
        }
        System.out.println("Size: " + todoList.size());

        // Create new todo
        em.getTransaction().begin();
        Todo todo = new Todo();
        todo.setSummary("This is a test");
        todo.setDescription("This is a test");
        em.persist(todo);
        em.getTransaction().commit();

        em.close();
    }
}

Todo.java

package jpaformatlab;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Todo {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String summary;
    private String description;

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "Todo [summary=" + summary + ", description=" + description
                + "]";
    }

}

Finally we call the main method in order to run this simple example from the MATLAB prompt.

>> jpaformatlab.Main.main(javaArray('java.lang.String',1))
>> Todo [summary=This is a test, description=This is a test]


问:
How to use subquery in caes statement
I want use select~~~~ subquery in case statement
but I Don't know how to do this

In my idea is

CASE When
(select ...from ... where .. )IS null
then ...
else ...
end as ...

but it's not working

答:
You can do a temp table and query that

```<code>with
test as (select names from table where names=smith ) ---You can add in left
--joins here or whatever - again not sure what you are trying to accomplish
select Case when name=smith then "Yes" else Null end as Case_test
from test
</code>```

Probably an easier way to do it with a subquery but off the top of my head I'm not sure. We would need more detail on what you were trying to accomplish but this would probably do the trick.

Title: How to use subquery in caes statement

Body:
You can do a temp table and query that

with
test as (select names from table where names=smith ) ---You can add in left
--joins here or whatever - again not sure what you are trying to accomplish
select Case when name=smith then "Yes" else Null end as Case_test
from test

Probably an easier way to do it with a subquery but off the top of my head I'm not sure. We would need more detail on what you were trying to accomplish but this would probably do the trick.


问:
What does "JPRT" means in OpenJDK
I'm looking for where the version information is stored in OpenJDK source tree and noticed the file "make/jprt.properties" has some relevant information there.
What does JPRT means in that context?</p>

答:
JPRT is a jenkins plugin: https://plugins.jenkins.io/jprt

OpenJDK builds probably are tested using jenkins with JPRT plugin
https://github.com/jenkinsci/jprt-plugin

It's mentioned also in java ("JPRT control builds/jprt control jobs"):

http://www.oracle.com/technetwork/java/javase/6u4-140071.html

http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8130092

Title: What does "JPRT" means in OpenJDK


问:
replace every second line of my triangle with a blank line for loops
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

```<code>  5

 555

55555
</code>```

This is my code:

```<code> for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}
</code>```

答:
```<code>     //try this code. It may help you to achieve your output

    [Check screen shot for the output of the below code][1]

    for (int i = 0; i < 5; i++)
      {
        for (int j = 0; j < 5 - i; j++)
        {
            System.out.print(" ");
        }
        for (int k = 0; k <= i; k++)
        {
         if(i%2!=0)
         {
            System.out.print(" ");
         }
         else{
            System.out.print("* ");
            }
        }
        System.out.println();
    }
</code>```

Body:
instead of getting a full triangle with 5 lines of "*" how do I replace every second line with a blank line, e.g. to look like this

  5

 555

55555

This is my code:

 for(int i = 0; i < 5; i++) {

     for(int j = i; j < 5; j++) {

         System.out.print(" ");

     }

    for(int k = 0; k <= (i*2); k++) {

        System.out.print("5");
    }
       System.out.println();
}


问:
R - send two-line command to system
I am using a ImageMagick command on a OS X system to create a 2x2 panel consisting of four .png figures that I have on my disk:

```<code>convert \( image1.png image2.png -append \) \
\( image3.png image4.png -append \) +append result.png
</code>```

When pasted to my terminal, the above command gets adjusted by the system, receiving a > to the beginning of the second line:

```<code>convert \( image1.png image2.png -append \) \
> \( image3.png image4.png -append \) +append result.png
</code>```

The resulting figure looks like this:

I am trying to reproduce this last command from within R by using the following commands:

```<code>> line1 <- paste0(" convert \\(", " img1.png img2.png -append \\)", " \\")
> line2 <- paste0(" < \\(", " img3.png img4.png -append \\) ", "+append result.png")
> cat(paste(line1, line2, sep='\n'))
 convert \( img1.png img2.png -append \) \
 < \( img3.png img4.png -append \) +append result.png
</code>```

Apparently, the result from cat is what I need, but I can't find the right way to send it to the system. I tried to combine it with system, but I get an error:

```<code>system(cat(paste(line1, line2, sep='\n')))
Error in system(cat(paste(line1, line2, sep = "\n"))) :
  non-empty character argument expected
</code>```

The question is: how can I use R to send that specific two-line command to the system?

答:
In your ImageMagick command remove the new line \ at the end of the first line and make the command just one long command on a single line as follows:

```<code>convert \( image1.png image2.png -append \) \( image3.png image4.png -append \) +append result.png
</code>```

That should avoid the > prompt and allow your command to pass onward without getting confused by the > prompt

Title: R - send two-line command to system

Body:
I am using a ImageMagick command on a OS X system to create a 2x2 panel consisting of four .png figures that I have on my disk:

convert \( image1.png image2.png -append \) \
\( image3.png image4.png -append \) +append result.png

When pasted to my terminal, the above command gets adjusted by the system, receiving a > to the beginning of the second line:

convert \( image1.png image2.png -append \) \
> \( image3.png image4.png -append \) +append result.png

The resulting figure looks like this:

I am trying to reproduce this last command from within R by using the following commands:

> line1 <- paste0(" convert \\(", " img1.png img2.png -append \\)", " \\")
> line2 <- paste0(" < \\(", " img3.png img4.png -append \\) ", "+append result.png")
> cat(paste(line1, line2, sep='\n'))
 convert \( img1.png img2.png -append \) \
 < \( img3.png img4.png -append \) +append result.png

Apparently, the result from cat is what I need, but I can't find the right way to send it to the system. I tried to combine it with system, but I get an error:

system(cat(paste(line1, line2, sep='\n')))
Error in system(cat(paste(line1, line2, sep = "\n"))) :
  non-empty character argument expected

The question is: how can I use R to send that specific two-line command to the system?

Body:
In your ImageMagick command remove the new line \ at the end of the first line and make the command just one long command on a single line as follows:

convert \( image1.png image2.png -append \) \( image3.png image4.png -append \) +append result.png

That should avoid the > prompt and allow your command to pass onward without getting confused by the > prompt


问:
Google sign in not working after publishing in play store even using the json file for release apk
In my app I am having an option of google sign-in, it works fine in debug mode as well as in release mode. I have generated 2 SHA keys to get json file from google.One is through debug.kestore and another is from release keystore. I run my app
by installing the release apk, it works perfectly but when I upload the same apk over playstore it does not work. Why ?

答: I got the solution, there is a new SHA key generated by playstore when you upload the app to play store, just copy and paste that SHA key into your app credentials of developer console as new SHA key.</p>


问:
Selenium MoveToElement Action is not working
On performing MoveToElement Action,Mouse hasnt moved to the element location.Please find the below code.</p>

```<code>    Actions action = new Actions(driver);
    action.MoveToElement(element);
    action.Build().Perform();
</code>```

答:
You can try the below code:</p>

```<code> IWebElement element = driver.FindElement(By.Id("Login_Id"));

        Actions action = new Actions(driver);
        action.MoveToElement(element);
        action.Build().Perform();
</code>```

Body:
On performing MoveToElement Action,Mouse hasnt moved to the element location.Please find the below code.

    Actions action = new Actions(driver);
    action.MoveToElement(element);
    action.Build().Perform();

Body:
You can try the below code:

 IWebElement element = driver.FindElement(By.Id("Login_Id"));

        Actions action = new Actions(driver);
        action.MoveToElement(element);
        action.Build().Perform();