问:
Add new item count to icon on button - Android
I'm developer. I need to implement design shown below. I already have functional app but wonder how to even approach this? Particulary, I'm interested in how to show Number of "New" items under tabs. What I KNOW how to do - is create new icons with red dots and just display them when new stuff available.

But I have no idea how to make those round circles float on top of title AND show number inside. Does anybody have suggestion on what too look for? Samples? Directions?

Second question about separating activities. Should I make control to combine buttons like this and just inflate it on activities? Otherwise I may create tabbed activity but I'm not sure if it's possible to style it to make it look like this.

答:
Simplest hack by giving style to TextView only.

```<code>        <TextView
                android:id="@+id/fabCounter"
                style="@style/Widget.Design.FloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:padding="5dp"
                android:text="10"
                android:textColor="@android:color/black"
                android:textSize="14sp" />
</code>```

Body:
Simplest hack by giving style to TextView only.

        <TextView
                android:id="@+id/fabCounter"
                style="@style/Widget.Design.FloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentEnd="true"
                android:layout_centerVertical="true"
                android:layout_marginEnd="10dp"
                android:padding="5dp"
                android:text="10"
                android:textColor="@android:color/black"
                android:textSize="14sp" />


来源: stackexchange

问:
Function from other file is not defined
I wrap by $(function) both files for running code when page is ready. But for some reasons calling function from first file in second file gives me error "ReferenceError: test is not defined".

First file:

```<code>$(function() {

    function test() {
        alert(1);
    }

});
</code>```

Second file:

```<code>$(function() {

    test();

});
</code>```

答:
This is because JavaScript scope, you can avoid this by using Window global object.

Adding your variables to Window object will make them global, so you can access them from anywhere.

First file:

$(function() {

    window.test = function () {
        alert(1);
    }

});```
</div>
</div>
</p>

<p>Second file:</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>$(function() {

    test();

});</code>```

ContentLicense: CC BY-SA 3.0

Title: Function from other file is not defined

Body:
I wrap by $(function) both files for running code when page is ready. But for some reasons calling function from first file in second file gives me error "ReferenceError: test is not defined".

First file:

$(function() {

    function test() {
        alert(1);
    }

});

Second file:

$(function() {

    test();

});

Body:
This is because JavaScript scope, you can avoid this by using Window global object.

Adding your variables to Window object will make them global, so you can access them from anywhere.

First file:

$(function() {

    window.test = function () {
        alert(1);
    }

});

Second file:

$(function() {

    test();

});


问:
Rails joins doesn't return values from joined table
It must be something pretty simple i'm doing wrong. i'm trying to join 3 tables together, where group contains a location_id which references a row in location and a info_id which does the same for info.

Here's my code:

```<code>@groups = Group.joins(
    'INNER JOIN location on location.id = "group".id',
    'INNER JOIN info on info.id = "group".id'
)
</code>```

This seems to work without errors, but all i'm getting back is the column from my group table. What am I doing wrong here?

P.S. my associations are location and info belong_to group. and group has_one of location and info

答:
When you say that you have location_id and info_id in groups table, this means that you intend to have belongs_to association in Group.

Pre-requisite:
Group model should have:

```<code>belongs_to :location
belongs_to :info
</code>```

Location and Info should have :

```<code>has_one :group
</code>```

For your question, this is expected. In ActiveRecord, Relation will return the object of the invoker, in this case Group.

For your use case, I think you will need this approach to get the right join working:

Query:

```<code>@groups = Group.joins(:location, :info)
# "SELECT `groups`.* FROM `groups` INNER JOIN `locations` ON `locations`.`id` = `groups`.`location_id` INNER JOIN `infos` ON `infos`.`id` = `groups`.`info_id`"
</code>```

After this, you can iterate on each group to get info and location as something like: @groups.map { |group| [group.location, group.info] }
This will give correct location and info.

Optimization: [group.location, group.info] will make queries again to get location and info. You can optimize this by changing the original query to include location and info data:

```<code>@groups = Group.joins(:location, :info).includes(:location, :info)
</code>```

Body:
It must be something pretty simple i'm doing wrong. i'm trying to join 3 tables together, where group contains a location_id which references a row in location and a info_id which does the same for info.

Here's my code:

@groups = Group.joins(
    'INNER JOIN location on location.id = "group".id',
    'INNER JOIN info on info.id = "group".id'
)

This seems to work without errors, but all i'm getting back is the column from my group table. What am I doing wrong here?

P.S. my associations are location and info belong_to group. and group has_one of location and info

Body:
When you say that you have location_id and info_id in groups table, this means that you intend to have belongs_to association in Group.

Pre-requisite:
Group model should have:

belongs_to :location
belongs_to :info

Location and Info should have :

has_one :group

For your question, this is expected. In ActiveRecord, Relation will return the object of the invoker, in this case Group.

For your use case, I think you will need this approach to get the right join working:

Query:

@groups = Group.joins(:location, :info)
# "SELECT `groups`.* FROM `groups` INNER JOIN `locations` ON `locations`.`id` = `groups`.`location_id` INNER JOIN `infos` ON `infos`.`id` = `groups`.`info_id`"

After this, you can iterate on each group to get info and location as something like: @groups.map { |group| [group.location, group.info] }
This will give correct location and info.

Optimization: [group.location, group.info] will make queries again to get location and info. You can optimize this by changing the original query to include location and info data:

@groups = Group.joins(:location, :info).includes(:location, :info)


问:
How can I print a portion of a 2d array
Say for example I would want to print half a quarter or a certain section of a 2D array how would I change the code below. Just in general printing only certain sections like if there were ten rows and columns how would I print the last 2 rows and last 2 columns,</p>

```<code>for (int row = 0; row < example.length; row++) {
for (int column = 0; column < example[row].length; column++) {
    System.out.print(" "+example[row][column] + "\t|");
    }
  System.out.println();
  }
</code>```

答:
You should change the loop count to print according to your wish.  Say for example

```<code>for (int row = 0; row < (example.length)/2; row++)
{
    for (int column = 0; column < (example.length)/2; column++)
    {
        System.out.print(" "+example[row][column] + "\t|");
    }
    System.out.println();
}
</code>```

This will print half of your rows and columns.

Title: How can I print a portion of a 2d array

Body:
Say for example I would want to print half a quarter or a certain section of a 2D array how would I change the code below. Just in general printing only certain sections like if there were ten rows and columns how would I print the last 2 rows and last 2 columns,

for (int row = 0; row < example.length; row++) {
for (int column = 0; column < example[row].length; column++) {
    System.out.print(" "+example[row][column] + "\t|");
    }
  System.out.println();
  }

Body:
You should change the loop count to print according to your wish.  Say for example

for (int row = 0; row < (example.length)/2; row++)
{
    for (int column = 0; column < (example.length)/2; column++)
    {
        System.out.print(" "+example[row][column] + "\t|");
    }
    System.out.println();
}

This will print half of your rows and columns.


问:
How can I use a 3rd party script in my angular2 service?
I am trying to use angular2, with angular cli. I have created an app with angular cli, with ng new my-app. Now I want to create a service in which I need to use a 3rd party script. I see that that script is already in node_modules.

How can I include/import/inject/use (whatever) that script in my service?

I see some examples telling about adding to global scripts. But if I need it just for the service and nowhere else, why would I put it in global scope?

my.service.ts

```<code>import { Injectable } from '@angular/core';
(HOW CAN I INCLUDE IN THIS SERVICE NODE_MODULES/SOME_OTHER_SCRIPT)??

@Injectable()
export class MyService {

    constructor() { }

}
</code>```

答:
Try the below line for import, replace circular-json with your 3rd party name. Also install the typings for your 3rd party script so that you will get suggestions like all other imports. This link has all high quality types</p>

```<code>import * as CircularJSON from 'circular-json';
</code>```

Body:
I am trying to use angular2, with angular cli. I have created an app with angular cli, with ng new my-app. Now I want to create a service in which I need to use a 3rd party script. I see that that script is already in node_modules.

How can I include/import/inject/use (whatever) that script in my service?

I see some examples telling about adding to global scripts. But if I need it just for the service and nowhere else, why would I put it in global scope?

my.service.ts

import { Injectable } from '@angular/core';
(HOW CAN I INCLUDE IN THIS SERVICE NODE_MODULES/SOME_OTHER_SCRIPT)??

@Injectable()
export class MyService {

    constructor() { }

}

Body:
Try the below line for import, replace circular-json with your 3rd party name. Also install the typings for your 3rd party script so that you will get suggestions like all other imports. This link has all high quality types

import * as CircularJSON from 'circular-json';


问:
Pygame seems to flip rows and columns?
It seems like every time I create something in pygame, I have to switch the rows and columns for it to print correctly. For example, if I have:

```<code>for col in range(COLS):
    board[3][col] = 'tree'
</code>```

I set up a draw function to draw a sprite whenever the board cell is equal to 3. However, it draws a vertical line of trees instead of horizontal. Since I want to iterate over all the columns in the 3rd row, the correct output should be a horizontal line of trees.

This is just one example out of many, but does anyone have any clue why pygame is doing this?

答:
I think your problem is because in real world we use two systems to describe position.

First uses (x,y) and you can see in

computer screen

math - point on graph

all drawing modules (not only PyGame, not only in Python)

Second uses (y,x) and you can see in

matrix in math (row, column)

room's numbers (floor, door)

tickets in cimena (row, place)

geolocation (latitude, longitude)

You use second system (y,x) to keep data but Pygame use first system (x,y) to draw it

so you have to remeber to switch (y,x) to (x,y) ([row][column] to [column][row])

or you have to keep data as [column][row] ((x,y))

Title: Pygame seems to flip rows and columns?

Body:
It seems like every time I create something in pygame, I have to switch the rows and columns for it to print correctly. For example, if I have:

for col in range(COLS):
    board[3][col] = 'tree'

I set up a draw function to draw a sprite whenever the board cell is equal to 3. However, it draws a vertical line of trees instead of horizontal. Since I want to iterate over all the columns in the 3rd row, the correct output should be a horizontal line of trees.

This is just one example out of many, but does anyone have any clue why pygame is doing this?


问:
Sum next array elements from a starting position (javascript)
I need this for dynamically use.
I have 2 associated arrays:

```<code>Var $some = [1, 2, 3];
Var $other = [a, b, c];
</code>```

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

```<code>$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)
</code>```

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

答:
If your some and other are equal, so you can try this solution.

const some = [1, 2, 3];
const other = ['a', 'b', 'c'];

other.forEach((item, index) => {
   const sum = some.reduce((s, c, i) => index !== i ? s += c : s, 0);

   $(`#${item}`).text(sum);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p></code>```

I am iterating over each item in the other array. The functions passed into the forEach gets two parameters - the current item and it's index in the other array. Then I call reduce on the some array and pass a function into it which gets three parameters - the accumulate value, the current item and it's index in the some array. In the body I check if the some current item index is not equal to the other current item index ( this prevent for a to add the value for a ) so I add it to the s, which contains the result in each iteration of some.reducea return it which is done automatically in one line statement if not return the result without adding the current item value.

You can write the reduce function like this to be more readable

```<code>some.reduce((s, c, i) =>  {
   if(index !== i) {
      s += c;
   }

   return s;
}, 0)
</code>```

Body:
I need this for dynamically use.
I have 2 associated arrays:

Var $some = [1, 2, 3];
Var $other = [a, b, c];

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

Body:
If your some and other are equal, so you can try this solution.

const some = [1, 2, 3];
const other = ['a', 'b', 'c'];

other.forEach((item, index) => {
   const sum = some.reduce((s, c, i) => index !== i ? s += c : s, 0);

   $(`#${item}`).text(sum);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>

I am iterating over each item in the other array. The functions passed into the forEach gets two parameters - the current item and it's index in the other array. Then I call reduce on the some array and pass a function into it which gets three parameters - the accumulate value, the current item and it's index in the some array. In the body I check if the some current item index is not equal to the other current item index ( this prevent for a to add the value for a ) so I add it to the s, which contains the result in each iteration of some.reducea return it which is done automatically in one line statement if not return the result without adding the current item value.

You can write the reduce function like this to be more readable

some.reduce((s, c, i) =>  {
   if(index !== i) {
      s += c;
   }

   return s;
}, 0)


问:
ReactJs CreateClass is not a function
```<code>var React = require('react');

module.exports=React.createClass({
   render:function(){
   return(
        <div>
           <h1> the list  </h1>
        </div>
   )}
})
</code>```

When I run the above code I get the following error :

```<code>app.js:4 Uncaught TypeError: React.createClass is not a function
</code>```

Is this because of a version difference or a typo ?

```<code>package.json-I have included create-react-class as seen here but not in the bower.json file

 {
    "dependencies": {
        "browser-sync": "^2.18.13",
        "browserify": "^14.4.0",
        "create-react-class": "^15.6.2",
        "ejs": "^2.5.7",
        "express": "^4.16.0",
        "gulp": "^3.9.1",
        "gulp-live-server": "0.0.31",
        "react": "^16.0.0",
        "reactify": "^1.1.1",
        "vinyl-source-stream": "^1.1.0"
      }
    }
</code>```

gulpfile.js -Am I missing some dependency in this file

```<code>var gulp= require('gulp');
var LiveServer= require('gulp-live-server');
var browserSync=require('browser-sync');
var browserify = require('browserify');
var reactify= require('reactify');
var source = require('vinyl-source-stream');

gulp.task('live-server', function(){

    var server= new LiveServer('server/main.js');
    server.start();
})

gulp.task('bundle',function(){
  return browserify({
    entries:'app/main.jsx',
    debug:true,
  })
  .transform(reactify)
  .bundle()
  .pipe(source('app.js'))
  .pipe(gulp.dest('./.tmp'))

})

gulp.task('serve',['bundle','live-server'],function(){
    browserSync.init(null,{
        proxy: "http://localhost:7777",
        port:9001
    })
})
</code>```

And my main.jsx has the following

```<code> var React = require('react');
var createReactClass = require('create-react-class');

var GroceryItemList=require('./components/GroceryItemsList.jsx');

React.render(<GroceryItemList/>,app);
</code>```

the groceryitems.jsx has the following

```<code>var React = require('react');
var createReactClass = require('create-react-class');
module.exports=React.createReactClass({

        render:function(){
            return(
                <div>
                    <h1> Grocery Listify </h1>
                </div>

            )

        }
})
</code>```

When I add the createReactClass I get an error: createReactClass is not a function and when I add import and ES6 syntax I get 'illegal import deceleration '
Thank you,

Naveen

答:
If you're getting an Error stating that React.creatClass is an undefined function it's because the newer versions of React don't support that.

You can try the below steps.

Install the create-react-class npm package:

```<code>npm install --save-dev create-react-class
</code>```

Then create a new variable under the ReactDom variable:

```<code>var createReactClass = require('create-react-class');
</code>```

Now instead of using React.createClass() for the components use the createReactClass() var.

Example:
Replace this:

```<code>var TodoComponent = React.createClass({
    render: function() {
        return(`<h1>`Helloooo`</h1>`);
    }
});
</code>```

With this:

```<code>var TodoComponent = createReactClass({
    render: function() {
        return(`<h1>`Helloooo`</h1>`);
    }
});
</code>```

Title: ReactJs CreateClass is not a function

Body:
var React = require('react');

module.exports=React.createClass({
   render:function(){
   return(

 the list

   )}
})

When I run the above code I get the following error :

app.js:4 Uncaught TypeError: React.createClass is not a function

Is this because of a version difference or a typo ?

package.json-I have included create-react-class as seen here but not in the bower.json file

 {
    "dependencies": {
        "browser-sync": "^2.18.13",
        "browserify": "^14.4.0",
        "create-react-class": "^15.6.2",
        "ejs": "^2.5.7",
        "express": "^4.16.0",
        "gulp": "^3.9.1",
        "gulp-live-server": "0.0.31",
        "react": "^16.0.0",
        "reactify": "^1.1.1",
        "vinyl-source-stream": "^1.1.0"
      }
    }

gulpfile.js -Am I missing some dependency in this file

var gulp= require('gulp');
var LiveServer= require('gulp-live-server');
var browserSync=require('browser-sync');
var browserify = require('browserify');
var reactify= require('reactify');
var source = require('vinyl-source-stream');

gulp.task('live-server', function(){

    var server= new LiveServer('server/main.js');
    server.start();
})

gulp.task('bundle',function(){
  return browserify({
    entries:'app/main.jsx',
    debug:true,
  })
  .transform(reactify)
  .bundle()
  .pipe(source('app.js'))
  .pipe(gulp.dest('./.tmp'))

})

gulp.task('serve',['bundle','live-server'],function(){
    browserSync.init(null,{
        proxy: "http://localhost:7777",
        port:9001
    })
})

And my main.jsx has the following

 var React = require('react');
var createReactClass = require('create-react-class');

var GroceryItemList=require('./components/GroceryItemsList.jsx');

React.render(<GroceryItemList/>,app);

the groceryitems.jsx has the following

var React = require('react');
var createReactClass = require('create-react-class');
module.exports=React.createReactClass({

        render:function(){
            return(

 Grocery Listify

            )

        }
})

When I add the createReactClass I get an error: createReactClass is not a function and when I add import and ES6 syntax I get 'illegal import deceleration '
Thank you,

Naveen

Body:
If you're getting an Error stating that React.creatClass is an undefined function it's because the newer versions of React don't support that.

You can try the below steps.

Install the create-react-class npm package:

npm install --save-dev create-react-class

Then create a new variable under the ReactDom variable:

var createReactClass = require('create-react-class');

Now instead of using React.createClass() for the components use the createReactClass() var.

Example:
Replace this:

var TodoComponent = React.createClass({
    render: function() {
        return(`<h1>`Helloooo`</h1>`);
    }
});

With this:

var TodoComponent = createReactClass({
    render: function() {
        return(`<h1>`Helloooo`</h1>`);
    }
});

ContentLicense: CC BY-SA 4.0


问:
Importing matplotlib in Python
I have anaconda and Python 3.6.3 on Mac OS 10.13. I am in the process of learning Python and wanted import matplotlib. However, I keep getting a ModuleNotFoundError when I try to run the program from Chapter 2 of "Doing Math with Python".

Any ideas on how to overcome this hurdle?

答:
With anaconda, the installation of matplotlib can be done with conda; on the command line, in terminal, type:

```<code>conda install matplotlib
</code>```

Title: Importing matplotlib in Python

Body:
With anaconda, the installation of matplotlib can be done with conda; on the command line, in terminal, type:

conda install matplotlib


答:
You can try playing with the loop:

```<code>String[][] example = new String[][] { { "a", "b", "c", "d" }, { "e", "f", "g", "h" } };

for (int row = 0; row < example.length; row++) {
    for (int column = 0; column < example[row].length / 2; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length / 2; row++) {
    for (int column = 0; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = example.length / 2; row < example.length; row++) {
    for (int column = 0; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length; row++) {
    for (int column = example[row].length / 2; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length; row++) {
    for (int column = example[row].length / 4; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length; row++) {
    for (int column = example[row].length * 3 / 4; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
</code>```

Outputs:

```<code> a  | b |
 e  | f |
----------------------------------------
 a  | b | c | d |
----------------------------------------
 e  | f | g | h |
----------------------------------------
 c  | d |
 g  | h |
----------------------------------------
 b  | c | d |
 f  | g | h |
----------------------------------------
 d  |
 h  |
----------------------------------------
</code>```

Title: How can I print a portion of a 2d array

Body:
You can try playing with the loop:

String[][] example = new String[][] { { "a", "b", "c", "d" }, { "e", "f", "g", "h" } };

for (int row = 0; row < example.length; row++) {
    for (int column = 0; column < example[row].length / 2; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length / 2; row++) {
    for (int column = 0; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = example.length / 2; row < example.length; row++) {
    for (int column = 0; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length; row++) {
    for (int column = example[row].length / 2; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length; row++) {
    for (int column = example[row].length / 4; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");
for (int row = 0; row < example.length; row++) {
    for (int column = example[row].length * 3 / 4; column < example[row].length; column++) {
        System.out.print(" " + example[row][column] + "\t|");
    }
    System.out.println();
}
System.out.println("----------------------------------------");

Outputs:

 a  | b |
 e  | f |
----------------------------------------
 a  | b | c | d |
----------------------------------------
 e  | f | g | h |
----------------------------------------
 c  | d |
 g  | h |
----------------------------------------
 b  | c | d |
 f  | g | h |
----------------------------------------
 d  |
 h  |
----------------------------------------


问:
Can someone give me a solid principle for not getting "non object ..." with laravel 5.5?
Over the time i've been practicing some solutions to avoid non object error in laravel (different versions) , but i wanted to know if there is a solid way to avoid "non object" ?</p>

答:
You can use the optional helper</p>

```<code>optional($user->address)->street
</code>```

Body:
You can use the optional helper

optional($user->address)->street


问:
Pyinstaller missing dll files
I want to create a 32bit executable app from my script to run on Windows 10 with X86 or X64 architectures. I've generated the X64 version of my script and it worked fine. My host machine is X64 but I installed Python X86 version to generate X86 app. Then I generated the executable with Pyinstaller but when I run the executable it throws the following error:

C:\Users\Name\Appdata\local\Temp_MEI51162\VCRUNTIME140.dll is
  either not designed to run on Windows or it contains an error...

and in the console I see this error:

Error loading Python DLL
  'C:\Users\Name\AppData\Local\Temp_MEI51162\python36.dll'.
  LoadLibrary:

I've checked the _MEI51162, both VCRUNTIME140.dll and python36.dll is there but the python36.dll has a size of about 1 MB instead of 3 MB. It doesn't matter if I generate the app as a standalone executable or not and still give me the same error.

答: It seems that the problem happens when you install both 32bit and 64bit of PyInstaller. And PyInstaller would fail on selecting which version of dependencies are required for the current build. The problem in my situation was VCRUNTIME140.dll. I couldn't find a way to replace the vcruntime140.dll, but I found a workaround by adding the correct file manually to C:\Users\<User>\AppData\Roaming\pyinstaller directory and rebuild with Pyinstaller then It will be replaced with the new one just copied. This will fix the issue temporary and the directory should not be deleted.

Title: Pyinstaller missing dll files


问:
What is the meaning of "??" in swift?
I came across a syntax in Swift where double question marks are used ("??").

For instance, let val = something["something"] as? String ?? nil

What exactly does this mean? What are some use cases for this syntax?

答:
Nil-Coalescing Operator

It's kind of a short form of this. (Means you can assign default value nil or any other value if something["something"] is nil or optional)

```<code>let val = (something["something"] as? String) != nil ? (something["something"] as! String) : "default value"
</code>```

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil-coalescing operator is shorthand for the code below:

a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.

If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.

The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name:

```<code>let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"
</code>```

See section Nil-Coalescing Operator here

Title: What is the meaning of "??" in swift?

Body:
Nil-Coalescing Operator

It's kind of a short form of this. (Means you can assign default value nil or any other value if something["something"] is nil or optional)

let val = (something["something"] as? String) != nil ? (something["something"] as! String) : "default value"

The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

The nil-coalescing operator is shorthand for the code below:

a != nil ? a! : b
The code above uses the ternary conditional operator and forced unwrapping (a!) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil-coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form.

If the value of a is non-nil, the value of b is not evaluated. This is known as short-circuit evaluation.

The example below uses the nil-coalescing operator to choose between a default color name and an optional user-defined color name:

let defaultColorName = "red"
var userDefinedColorName: String?   // defaults to nil

var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName is nil, so colorNameToUse is set to the default of "red"

See section Nil-Coalescing Operator here


问:
ImportError: No module named pandas. Pandas installed pip
I use the Mac terminal to check my package:

pip list
```
<p>I can find all packages including Pandas:</p>
<p>But when I</p>
<pre class="lang-py prettyprint-override"><code>import pandas
</code>```

it told me:

ModuleNotFoundError: No module named 'pandas'

By the way, I have Python 2 and Python 3 on my Mac. They are not the same directory, and I suspect the Python interpreter didn't find the path of Pandas.

答:
If Python 2.7 is already installed, then to install NumPy and Pandas for v2.7, run the below commands:

For Ubuntu / Linux -

```<code>sudo apt-get install python-numpy
sudo apt-get install python-pandas
</code>```

If Python 3 is already installed, then to install NumPy and Pandas for v3, run the below commands:

For Ubuntu / Linux -

```<code>sudo apt-get install python3-numpy
sudo apt-get install python3-pandas
</code>```

Body:
I use the Mac terminal to check my package:

pip list

I can find all packages including Pandas:

But when I

import pandas

it told me:

ModuleNotFoundError: No module named 'pandas'

By the way, I have Python 2 and Python 3 on my Mac. They are not the same directory, and I suspect the Python interpreter didn't find the path of Pandas.

Body:
If Python 2.7 is already installed, then to install NumPy and Pandas for v2.7, run the below commands:

For Ubuntu / Linux -

sudo apt-get install python-numpy
sudo apt-get install python-pandas

If Python 3 is already installed, then to install NumPy and Pandas for v3, run the below commands:

For Ubuntu / Linux -

sudo apt-get install python3-numpy
sudo apt-get install python3-pandas


问:
Unable to start Amazon Lambda on the command line (HelloWorld example)
I followed Amazon's tutorials on creating a HelloWorld lambda function in the Sydney region. It worked on the AWS console.

Then I tried to do it on the command line:

aws lambda invoke --invocation-type RequestResponse --function-name HelloWorld --region Sydney --payload '{"key1":"value1", "key2":"value2", "key3":"value3"}' outputfile.txt

Error:

Could not connect to the endpoint URL: "https://lambda.Sydney.amazonaws.com/2015-03-31/functions/HelloWorld/invocations"

I think my security keys are working because the the following command for listing my S3 buckets worked:

aws s3api list-buckets # Worked, so the security keys should work

答:
Based on the CLI command you issued to invoke the Lambda function, it seems like the issue lies in the region parameter.

Instead of the region parameter value "Sydney", replace it with "ap-southeast-2" which is the regional code for Asia Pacific (Sydney).


问:
Oracle SQL Full Outer Joins
My tables are as follows:

```<code>SELECT * FROM r_a;

CLASS   SECTION
-----   -------
1       A
1       B
2       A
2       B

SELECT * FROM r_b;

CLASS   SECTION
-----   -------
1       B
1       C
2       B
2       C
</code>```

I want to perform a full outer join on these tables over the column SECTION where CLASS=1 in both tables. My desired output is :

```<code>SECTION SECTION_1
------- ---------
B       B
A       (Null)
(Null)  C
</code>```

However, the following query yields only the matching row, similar to result of an inner join.

```<code>**QUERY 1**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section
WHERE A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B
</code>```

I am able to achieve desired result by taking the where conditions inside a nested query:

```<code>**QUERY 2**

SELECT a.section, b.section
FROM
(SELECT SECTION FROM r_a WHERE class=1) a
FULL OUTER JOIN
(SELECT SECTION FROM r_b WHERE class=1) b
ON a.section=b.section

SECTION SECTION_1
------- ---------
B       B
(Null)  C
A       (Null)
</code>```

The result is more surprising when the where conditions in **Query 1** is moved to the on clause:

```<code>** Query 3**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B
(Null)  C
(Null)  B
(Null)  C
B       (Null)
A       (Null)
A       (Null)

MORE CLARITY:
*************

SELECT *
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

CLASS   SECTION CLASS_1 SECTION_1
------  ------- ------- ---------
1       B       1       B
(Null)  (Null)  1       C
(Null)  (Null)  2       B
(Null)  (Null)  2       C
2       B       (Null)  (Null)
2       A       (Null)  (Null)
1       A       (Null)  (Null)
</code>```

Explanation on why Query 1 doesn't produce the desired result and why Query 3 joins on class=2 even when the on clause says AND  A.class=1 AND B.class=1 is greatly appreciated.

答:
Be careful, condition where vs condition on is difference:

where is a filter which is applied after rows are selected using the join. It is not always the case that a join ... on condition is sematically equivalent to a where condition. You can see more detail here.

Your Query 1 <=>

```<code>select asection, bsection from(
  SELECT a.section asection, b.section bsection, a.CLASS a, b.CLASS b
  FROM r_a a
  FULL OUTER JOIN r_b b
  ON a.section=b.section
)
WHERE a=1 AND  b=1
</code>```

Title: Oracle SQL Full Outer Joins

Body:
My tables are as follows:

SELECT * FROM r_a;

CLASS   SECTION
-----   -------
1       A
1       B
2       A
2       B

SELECT * FROM r_b;

CLASS   SECTION
-----   -------
1       B
1       C
2       B
2       C

I want to perform a full outer join on these tables over the column SECTION where CLASS=1 in both tables. My desired output is :

SECTION SECTION_1
------- ---------
B       B
A       (Null)
(Null)  C

However, the following query yields only the matching row, similar to result of an inner join.

**QUERY 1**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section
WHERE A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B

I am able to achieve desired result by taking the where conditions inside a nested query:

**QUERY 2**

SELECT a.section, b.section
FROM
(SELECT SECTION FROM r_a WHERE class=1) a
FULL OUTER JOIN
(SELECT SECTION FROM r_b WHERE class=1) b
ON a.section=b.section

SECTION SECTION_1
------- ---------
B       B
(Null)  C
A       (Null)

The result is more surprising when the where conditions in **Query 1** is moved to the on clause:

** Query 3**

SELECT a.section, b.section
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

SECTION SECTION_1
------- ---------
B       B
(Null)  C
(Null)  B
(Null)  C
B       (Null)
A       (Null)
A       (Null)

MORE CLARITY:
*************

SELECT *
FROM
r_a a
FULL OUTER JOIN
r_b b
ON a.section=b.section AND  A.class=1 AND B.class=1

CLASS   SECTION CLASS_1 SECTION_1
------  ------- ------- ---------
1       B       1       B
(Null)  (Null)  1       C
(Null)  (Null)  2       B
(Null)  (Null)  2       C
2       B       (Null)  (Null)
2       A       (Null)  (Null)
1       A       (Null)  (Null)

Explanation on why Query 1 doesn't produce the desired result and why Query 3 joins on class=2 even when the on clause says AND  A.class=1 AND B.class=1 is greatly appreciated.

Body:
Be careful, condition where vs condition on is difference:

where is a filter which is applied after rows are selected using the join. It is not always the case that a join ... on condition is sematically equivalent to a where condition. You can see more detail here.

Your Query 1 <=>

select asection, bsection from(
  SELECT a.section asection, b.section bsection, a.CLASS a, b.CLASS b
  FROM r_a a
  FULL OUTER JOIN r_b b
  ON a.section=b.section
)
WHERE a=1 AND  b=1


答:
This is Nil-Coalescing Operator in Swift.

Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it
  contains a value, or returns a default value b if a is nil. The
  expression a is always of an optional type. The expression b must
  match the type that is stored inside a.

But in your example you already using optional binding , so no need of using ?? with optional, if it fails condition then it automatically assign nil.

```<code>let val = something["something"] as? String ?? nil
</code>```

Here, something["something"] as? String, already assign nil, if something["something"] fails to deliver String. So no need of this operator here.

Title: What is the meaning of "??" in swift?

Body:
I came across a syntax in Swift where double question marks are used ("??").

For instance, let val = something["something"] as? String ?? nil

What exactly does this mean? What are some use cases for this syntax?

Body:
This is Nil-Coalescing Operator in Swift.

Nil-Coalescing Operator

The nil-coalescing operator (a ?? b) unwraps an optional a if it
  contains a value, or returns a default value b if a is nil. The
  expression a is always of an optional type. The expression b must
  match the type that is stored inside a.

But in your example you already using optional binding , so no need of using ?? with optional, if it fails condition then it automatically assign nil.

let val = something["something"] as? String ?? nil

Here, something["something"] as? String, already assign nil, if something["something"] fails to deliver String. So no need of this operator here.


问:
NDK support with different Product Flavour
I want different string value from ndk library.
as i have two flavor demo and live I want value "hello I am from  demo " for demo flavor and for live flavor  i want "hello I am from live "

Here is my java file code

```<code>public class MainActivity extends AppCompatActivity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

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

    // Example of a call to a native method
    TextView tv = (TextView) findViewById(R.id.sample_text);
    tv.setText(stringFromJNI());
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
public native String stringFromJNI();
</code>```

}

Here is my cpp file code

```<code>#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring JNICALL
Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "hello I am from  demo";
    return env->NewStringUTF(hello.c_str());
}
</code>```

this is my build.gradle file

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.de.demo.ndk2"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        flavorDimensions "default"
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {

        demo
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.demo"
                    versionName "2.1"
                    dimension "default"

                    externalNativeBuild {
                        cmake {

                            targets "native-lib-demo","my-executible-                   demo"

                        }}

                }
        live
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.live"
                    versionName "2.1"
                    dimension "default"

                }}
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}
</code>```

I have paste same cpp file in demo folder as well as in main folder
but could achieve my task. Any help would be appreciate
this are some refrence links

https://developer.android.com/studio/projects/gradle-external-native-builds.html

How to set CmakeLists path in product flavor for each Android ABI?

答:
Finally I a solution.
Here is my cpp file code

```<code>Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject jobject1, jstring jstring1) {

    std::string hello;
    const char *nativeString1 = env->GetStringUTFChars( jstring1, 0);
    if (strcmp(nativeString1, "demo") == 0) {
        hello = "Hello from demo C++";
    } else if (strcmp(nativeString1, "live") == 0) {
        hello = "Hello from live C++";
    }

    return env->NewStringUTF(hello.c_str());
}
</code>```

I am passing flavor value from java code here is my code for java file.

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

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

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

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        String value = BuildConfig.FLAVOR;
        String ndkValue = stringFromJNI(value);
        tv.setText(ndkValue);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     * @param value
     */
    public native String stringFromJNI(String value);
}
</code>```

Now i can get whatever text i want according to selected flavor.

Body:
I want different string value from ndk library.
as i have two flavor demo and live I want value "hello I am from  demo " for demo flavor and for live flavor  i want "hello I am from live "

Here is my java file code

public class MainActivity extends AppCompatActivity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

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

    // Example of a call to a native method
    TextView tv = (TextView) findViewById(R.id.sample_text);
    tv.setText(stringFromJNI());
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
public native String stringFromJNI();

}

Here is my cpp file code

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring JNICALL
Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "hello I am from  demo";
    return env->NewStringUTF(hello.c_str());
}

this is my build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.de.demo.ndk2"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        flavorDimensions "default"
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {

        demo
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.demo"
                    versionName "2.1"
                    dimension "default"

                    externalNativeBuild {
                        cmake {

                            targets "native-lib-demo","my-executible-                   demo"

                        }}

                }
        live
                {
                    // applicationId "com.readwhere.whitelabel.test"
                    //applicationId "com.android.rwstaging"
                    applicationId "com.android.live"
                    versionName "2.1"
                    dimension "default"

                }}
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

I have paste same cpp file in demo folder as well as in main folder
but could achieve my task. Any help would be appreciate
this are some refrence links

https://developer.android.com/studio/projects/gradle-external-native-builds.html

How to set CmakeLists path in product flavor for each Android ABI?

Body:
Finally I a solution.
Here is my cpp file code

Java_com_de_demo_ndk2_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject jobject1, jstring jstring1) {

    std::string hello;
    const char *nativeString1 = env->GetStringUTFChars( jstring1, 0);
    if (strcmp(nativeString1, "demo") == 0) {
        hello = "Hello from demo C++";
    } else if (strcmp(nativeString1, "live") == 0) {
        hello = "Hello from live C++";
    }

    return env->NewStringUTF(hello.c_str());
}

I am passing flavor value from java code here is my code for java file.

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

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

        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        String value = BuildConfig.FLAVOR;
        String ndkValue = stringFromJNI(value);
        tv.setText(ndkValue);
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     * @param value
     */
    public native String stringFromJNI(String value);
}

Now i can get whatever text i want according to selected flavor.


问:
angularjs 1.x modifying data attribute with
I am using an html theme that uses jQuery plugins. For example:

```<code><div class="slide background-overlay-dark" data-parallax-image="images/parallax/4.jpg">
</div>
</code>```

How would I be able to modify the data-parallax-image="" from the controller, without writing a directive, since there are many such cases.

答:
You can do this using plain javascript if you want to. The implementation for the same would be something like this.

Give your div an id, like id="div1" in my case.

html code

```<code><div id="div1" class="slide background-overlay-dark" data-parallax-image="images/parallax/4.jpg"></div>
</code>```

Now in your controller write a javascript function which updates the data-parallax-image attribute.

Controller

```<code>var element = document.getElementById("div1");
function changeImage() {
    var imageName = "something-"+Date.now();
    element.setAttribute('data-parallax-image', imageName);
}
setInterval(function() {
    changeImage();
}, 1000);
</code>```

The changeImage function would modify the data-parallax-imagefrom your controller without making a directive. In the given code I am running the changeImage() in an interval of one second. This logic purely depends on you and you can write it accordingly.

Body:
I am using an html theme that uses jQuery plugins. For example:

How would I be able to modify the data-parallax-image="" from the controller, without writing a directive, since there are many such cases.

Body:
You can do this using plain javascript if you want to. The implementation for the same would be something like this.

Give your div an id, like id="div1" in my case.

html code

<div id="div1" class="slide background-overlay-dark" data-parallax-image="images/parallax/4.jpg"></div>

Now in your controller write a javascript function which updates the data-parallax-image attribute.

Controller

var element = document.getElementById("div1");
function changeImage() {
    var imageName = "something-"+Date.now();
    element.setAttribute('data-parallax-image', imageName);
}
setInterval(function() {
    changeImage();
}, 1000);

The changeImage function would modify the data-parallax-imagefrom your controller without making a directive. In the given code I am running the changeImage() in an interval of one second. This logic purely depends on you and you can write it accordingly.


问:
Oracle - Need advice on multiple counts, on table with large amounts of data
Table with large data, does anyone know how to optimize the count statement?

Eg: table Booking(id, email, mobile,....) (about 30 fields).

```<code>Function GetBookingCount(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where email = p_email
    or mobile = p_mobile

Function GetBookingStatus3Count(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where (email = p_email or mobile = p_mobile)
    and status = 3;
</code>```

Final select:

```<code>Select GetBookingCount(email, mobile) as BookingCount
      , GetBookingStatus3Count(email, mobile) as BookingStatus3Count
      , ...
From Booking
where ....
</code>```

solution1: Set the field column index what in where clause to count as email column, mobile, status column.

solution2: create a new table with few columns to count.
new table: Booking_Stats(id, email, mobile, status).

Thanks for any suggestion.

答:
The booking table should have an index on email, mobile and status. You should use this select:</p>

```<code>    WITH B1 AS
(
     SELECT ID,
            COUNT(ID) CNT1,
            STATUS
     FROM BOOKING
     WHERE EMAIL = P_EMAIL
           AND MOBILE = P_MOBILE
)
SELECT CNT1,
       COUNT(ID) CNT2
FROM B1
WHERE STATUS = 3;
</code>```

Body:
Table with large data, does anyone know how to optimize the count statement?

Eg: table Booking(id, email, mobile,....) (about 30 fields).

Function GetBookingCount(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where email = p_email
    or mobile = p_mobile

Function GetBookingStatus3Count(p_email, p_mobile) return number
    Select count(id)
    from Booking
    Where (email = p_email or mobile = p_mobile)
    and status = 3;

Final select:

Select GetBookingCount(email, mobile) as BookingCount
      , GetBookingStatus3Count(email, mobile) as BookingStatus3Count
      , ...
From Booking
where ....

solution1: Set the field column index what in where clause to count as email column, mobile, status column.

solution2: create a new table with few columns to count.
new table: Booking_Stats(id, email, mobile, status).

Thanks for any suggestion.

Body:
The booking table should have an index on email, mobile and status. You should use this select:

    WITH B1 AS
(
     SELECT ID,
            COUNT(ID) CNT1,
            STATUS
     FROM BOOKING
     WHERE EMAIL = P_EMAIL
           AND MOBILE = P_MOBILE
)
SELECT CNT1,
       COUNT(ID) CNT2
FROM B1
WHERE STATUS = 3;


问:
Detect whether button was right or left clicked
my problem was as i believed simple but it turned to be a little more complicated, what i was trying to achieve was this: I have several buttons in my WinForm that do almost the same thing, so I've created a single event to handle all of them, now what i wished was to give them some other functionality based on which mouse button they clicked, for instance if the button is left clicked performs as it has been doing but if its right clicked performs in some other way, can this be achieved?, any help would be greatly appreciated.

I'm looking for some statement like this maybe...

```<code> private void buttons_Click(object sender, EventArgs e)
         {
 if(e.buttons==mousebuttons.right)
 //do something
 else
 //do other thing
 }
</code>```

the thing as you know is that this can't be achieved since e has no mouse button events on it, cause i'ts being called as a button click event.

答:
Objective:
To handle both mouse Left-Click and mouse Right-Click.

Problem:
The Click event is not raised when the Mouse Right-Button is clicked.  It is only raised when the Mouse Left-Button is depressed then released.

Solution:

Subscribe to both the Click, and the MouseRightButtonUp events.

Note A. The MouseRightButtonUp event is raised when the Mouse Right-Button is released over the button, irrespective of whether it was over the button when it was initially pressed.

Note B. It is not relevant to this situation, but you should note that the Click event of a Button object (pressing and releasing the Mouse Left-button) handles both the MouseLeftButtonDown and the MouseLeftButtonUp events, and therefore neither of those events can be handled when you use the mouse Left-button to click a Button object.  If you do have a need to handle those actions separately you should subscribe to PreviewMouseLeftButtonDown, and/or PreviewMouseLeftButtonUp.

You can then either:

a. have 2 separate event handlers, one for each of these events, or

b. write an event handler that can handle both the Click and the MouseRightButtonUp events.
Note: A Click event needs a handler which accepts an argument of type RoutedEventArgs, whereas the MouseRightButtonUp event requires one of type MouseButtonEventArgs.  Both RoutedEventArgs and MouseButtonEventArgs inherit from EventArgs.  Therefore, make the handler accept EventArgs.  The handler should then determine whether it has been passed a RoutedEventArgs (in which case it performs the actions required for a Left-click), or a MouseButtonEventArgs (in which case it performs the actions required for a Right-click).

Code example:

```<code>myButton.MouseRightButtonUp += MenuItemButton_Click;
myButton.Click += MenuItemButton_Click;

internal void MenuItemButton_Click(object sender, EventArgs e)
{
    var clickedButton = sender as Button;
    string EventArgsType = e.GetType().ToString();
    //Remove leading qualification from Type ("System.Windows." or "System.Windows.Input.")
    EventArgsType = type.Substring(EventArgsType.LastIndexOf('.') + 1);
    switch (EventArgsType)
    {
        //Handle R-Click (RightMouseButtonUp)
        case "MouseButtonEventArgs":
            var MbeArgs = e as MouseButtonEventArgs;
           //Do stuff
            break;
        //Handle L-Click (Click)
        case "RoutedEventArgs":
            var ReArgs = e as RoutedEventArgs;
            //Do stuff
            break;
        default:
            break;
    }
}
</code>```

Body:
my problem was as i believed simple but it turned to be a little more complicated, what i was trying to achieve was this: I have several buttons in my WinForm that do almost the same thing, so I've created a single event to handle all of them, now what i wished was to give them some other functionality based on which mouse button they clicked, for instance if the button is left clicked performs as it has been doing but if its right clicked performs in some other way, can this be achieved?, any help would be greatly appreciated.

I'm looking for some statement like this maybe...

 private void buttons_Click(object sender, EventArgs e)
         {
 if(e.buttons==mousebuttons.right)
 //do something
 else
 //do other thing
 }

the thing as you know is that this can't be achieved since e has no mouse button events on it, cause i'ts being called as a button click event.

Body:
Objective:
To handle both mouse Left-Click and mouse Right-Click.

Problem:
The Click event is not raised when the Mouse Right-Button is clicked.  It is only raised when the Mouse Left-Button is depressed then released.

Solution:

Subscribe to both the Click, and the MouseRightButtonUp events.

Note A. The MouseRightButtonUp event is raised when the Mouse Right-Button is released over the button, irrespective of whether it was over the button when it was initially pressed.

Note B. It is not relevant to this situation, but you should note that the Click event of a Button object (pressing and releasing the Mouse Left-button) handles both the MouseLeftButtonDown and the MouseLeftButtonUp events, and therefore neither of those events can be handled when you use the mouse Left-button to click a Button object.  If you do have a need to handle those actions separately you should subscribe to PreviewMouseLeftButtonDown, and/or PreviewMouseLeftButtonUp.

You can then either:

a. have 2 separate event handlers, one for each of these events, or

b. write an event handler that can handle both the Click and the MouseRightButtonUp events.
Note: A Click event needs a handler which accepts an argument of type RoutedEventArgs, whereas the MouseRightButtonUp event requires one of type MouseButtonEventArgs.  Both RoutedEventArgs and MouseButtonEventArgs inherit from EventArgs.  Therefore, make the handler accept EventArgs.  The handler should then determine whether it has been passed a RoutedEventArgs (in which case it performs the actions required for a Left-click), or a MouseButtonEventArgs (in which case it performs the actions required for a Right-click).

Code example:

myButton.MouseRightButtonUp += MenuItemButton_Click;
myButton.Click += MenuItemButton_Click;

internal void MenuItemButton_Click(object sender, EventArgs e)
{
    var clickedButton = sender as Button;
    string EventArgsType = e.GetType().ToString();
    //Remove leading qualification from Type ("System.Windows." or "System.Windows.Input.")
    EventArgsType = type.Substring(EventArgsType.LastIndexOf('.') + 1);
    switch (EventArgsType)
    {
        //Handle R-Click (RightMouseButtonUp)
        case "MouseButtonEventArgs":
            var MbeArgs = e as MouseButtonEventArgs;
           //Do stuff
            break;
        //Handle L-Click (Click)
        case "RoutedEventArgs":
            var ReArgs = e as RoutedEventArgs;
            //Do stuff
            break;
        default:
            break;
    }
}


问:
How to open Excel file saved at specific location,Create a new tab as of last tab in a sheet using VBA
I am not from software background and trying to write a macro to avoid repeated work that causes errors. Please feel free to suggest things that will make it better.I tried to pull pieces from different program from this site and make it work.

Thank you in advance.

Here is what I am trying to do.
a) I am trying to open Excel file(lets say file 2) saved at specific location from current file (Say file 1). Works

b) Create a new tab in file 2 same as last tab in that file,Works

c) Re-name the created tab using 2 different cell from file 1.(Auto Rename would be good based on file 1 cells but I could only manage pop up that ask me to enter but doesn't rename the file). Doesn't Work/partially work

d) Pop up to input Name and 2 more input in different cells(I can only get Your name how can I get 3 input in 3 different cells) Doesn't Work/partially work

e) Copy 2 cells from file 1 and copy in file 2 newly created tab. Doesn't work

Here is the code I tried to write.

```<code>Sub Filling_List()
Dim sPath As String, sFile As String, wb As Workbook, i As Integer

'Application.ScreenUpdating = False

sPath = "C:\Users\aricsonp\Desktop\Filling list macro\"
sFile = sPath & "ArF Filling List.xlsm"

Set wb = Workbooks.Open(sFile)

ActiveSheet.Copy After:=Worksheets(Worksheets.Count)
Worksheets(Worksheets.Count).Name = InputBox("New Name:")
If sName = "" Then Exit Sub

ActiveSheet.cell(3, "E") = InputBox("Your Name:")

' With ActiveSheet.Sheets("ArF Filling List (7)")
'.Range("B03").Value = uploader.Sheets("Que & Tsc Cal").Range("B02").Value
' .Range("B05").Value = uploader.Sheets("Que & Tsc Cal").Range("B01").Value
' End With

'Application.ScreenUpdating = True

End Sub
</code>```

答:
Here are some pointers.

1) Put Option Explicit at top so syntax and declarations are checked.
   This would force you to declare sName and uploader as well as set their values. i is also declared but not assigned.

2) Your code, as is, did rename the sheet. You assigned directly to the newly added sheet from the inputbox rather than storing in a variable.

```<code>Worksheets(Worksheets.Count).Name = InputBox("New Name:")
</code>```

Assuming the variable sName was actually to hold this and that you want to grab this value from 2 cells in the workbook containing the code (i.e. ThisWorkbook) you are running:

```<code>sName = ThisWorkbook.Worksheets("Sheet1").Range("A1") & ThisWorkbook.Worksheets("Sheet1").Range("B1")
</code>```

You would probably want to declare and assign ThisWorkbook and worksheets you reference within as variables.

e.g.

```<code>Dim wb1 as Workbook
Dim ws1 as Worksheet
Set wb1 = ThisWorkbook
Set ws1 = ThisWorkbook.Worksheets("Sheet1") 'change as appropriate
</code>```

3) Avoid mixing Sheets and Worksheets collections. I prefer Worksheets collections unless you have Chart sheets present.

4) In most cases you will want to compare against vbNullstring rather than an empty string literal (""). It is faster to assign, uses less memory etc.

```<code>If sName = vbNullString Then Exit Sub
</code>```

5) Assigning more values to cells; add more inputboxes AND use Cells not Cell e.g.

```<code>ActiveSheet.Cells(4, "E") = InputBox("Your Age:")
</code>```

6) Adding more cells' values into the newly opened workbook, newly added sheet; use your wb and sName variables to ensure correct targeting:

```<code>With wb.Worksheets(sName)
</code>```

7) You may want to declare each variable at the top on its own line i.e. avoid multiple declarations on one line. Makes it easier to debug and spot any implicit variants.

So, you might have something like the following:

```<code>Option Explicit

Public Sub Filling_List()

Dim sPath As String
Dim sFile As String
Dim wb As Workbook
'  Dim i As Integer ''not used
Dim sName As String 'add sName declaration
'Add declaration for uploader variable and set its value
Dim wb1 as Workbook
Dim ws1 as Worksheet

Set wb1 = ThisWorkbook
Set ws1 = ThisWorkbook.Worksheets("Sheet1")

Application.ScreenUpdating = False

sPath = "C:\Users\aricsonp\Desktop\Filling list macro\"
sFile = sPath & "ArF Filling List.xlsm"

Set wb = Workbooks.Open(sFile)

ActiveSheet.Copy After:=Worksheets(Worksheets.Count)

'Worksheets(Worksheets.Count).Name = InputBox("New Name:")

sName = ws1.Range("A1") & ws1.Range("B1") 'assign value from two cells

ActiveSheet.Name = sName

If sName = vbNullString Then Exit Sub 'compare against vbNullstring not empty string literal

With wb.Worksheets(sName)

    .Cells(3, "E") = InputBox("Your Name:")
    .Cells(4, "E") = InputBox("Your Age:")
    .Cells(5, "E") = InputBox("Your Occupation:")
    .Range("B03") = uploader.Worksheets("Que & Tsc Cal").Range("B02").Value2
    .Range("B05") = uploader.Worksheets("Que & Tsc Cal").Range("B01").Value2

End With

Application.ScreenUpdating = True

End Sub
</code>```

Body:
I am not from software background and trying to write a macro to avoid repeated work that causes errors. Please feel free to suggest things that will make it better.I tried to pull pieces from different program from this site and make it work.

Thank you in advance.

Here is what I am trying to do.
a) I am trying to open Excel file(lets say file 2) saved at specific location from current file (Say file 1). Works

b) Create a new tab in file 2 same as last tab in that file,Works

c) Re-name the created tab using 2 different cell from file 1.(Auto Rename would be good based on file 1 cells but I could only manage pop up that ask me to enter but doesn't rename the file). Doesn't Work/partially work

d) Pop up to input Name and 2 more input in different cells(I can only get Your name how can I get 3 input in 3 different cells) Doesn't Work/partially work

e) Copy 2 cells from file 1 and copy in file 2 newly created tab. Doesn't work

Here is the code I tried to write.

Sub Filling_List()
Dim sPath As String, sFile As String, wb As Workbook, i As Integer

'Application.ScreenUpdating = False

sPath = "C:\Users\aricsonp\Desktop\Filling list macro\"
sFile = sPath & "ArF Filling List.xlsm"

Set wb = Workbooks.Open(sFile)

ActiveSheet.Copy After:=Worksheets(Worksheets.Count)
Worksheets(Worksheets.Count).Name = InputBox("New Name:")
If sName = "" Then Exit Sub

ActiveSheet.cell(3, "E") = InputBox("Your Name:")

' With ActiveSheet.Sheets("ArF Filling List (7)")
'.Range("B03").Value = uploader.Sheets("Que & Tsc Cal").Range("B02").Value
' .Range("B05").Value = uploader.Sheets("Que & Tsc Cal").Range("B01").Value
' End With

'Application.ScreenUpdating = True

End Sub

Body:
Here are some pointers.

1) Put Option Explicit at top so syntax and declarations are checked.
   This would force you to declare sName and uploader as well as set their values. i is also declared but not assigned.

2) Your code, as is, did rename the sheet. You assigned directly to the newly added sheet from the inputbox rather than storing in a variable.

Worksheets(Worksheets.Count).Name = InputBox("New Name:")

Assuming the variable sName was actually to hold this and that you want to grab this value from 2 cells in the workbook containing the code (i.e. ThisWorkbook) you are running:

sName = ThisWorkbook.Worksheets("Sheet1").Range("A1") & ThisWorkbook.Worksheets("Sheet1").Range("B1")

You would probably want to declare and assign ThisWorkbook and worksheets you reference within as variables.

e.g.

Dim wb1 as Workbook
Dim ws1 as Worksheet
Set wb1 = ThisWorkbook
Set ws1 = ThisWorkbook.Worksheets("Sheet1") 'change as appropriate

3) Avoid mixing Sheets and Worksheets collections. I prefer Worksheets collections unless you have Chart sheets present.

4) In most cases you will want to compare against vbNullstring rather than an empty string literal (""). It is faster to assign, uses less memory etc.

If sName = vbNullString Then Exit Sub

5) Assigning more values to cells; add more inputboxes AND use Cells not Cell e.g.

ActiveSheet.Cells(4, "E") = InputBox("Your Age:")

6) Adding more cells' values into the newly opened workbook, newly added sheet; use your wb and sName variables to ensure correct targeting:

With wb.Worksheets(sName)

7) You may want to declare each variable at the top on its own line i.e. avoid multiple declarations on one line. Makes it easier to debug and spot any implicit variants.

So, you might have something like the following:

Option Explicit

Public Sub Filling_List()

Dim sPath As String
Dim sFile As String
Dim wb As Workbook
'  Dim i As Integer ''not used
Dim sName As String 'add sName declaration
'Add declaration for uploader variable and set its value
Dim wb1 as Workbook
Dim ws1 as Worksheet

Set wb1 = ThisWorkbook
Set ws1 = ThisWorkbook.Worksheets("Sheet1")

Application.ScreenUpdating = False

sPath = "C:\Users\aricsonp\Desktop\Filling list macro\"
sFile = sPath & "ArF Filling List.xlsm"

Set wb = Workbooks.Open(sFile)

ActiveSheet.Copy After:=Worksheets(Worksheets.Count)

'Worksheets(Worksheets.Count).Name = InputBox("New Name:")

sName = ws1.Range("A1") & ws1.Range("B1") 'assign value from two cells

ActiveSheet.Name = sName

If sName = vbNullString Then Exit Sub 'compare against vbNullstring not empty string literal

With wb.Worksheets(sName)

    .Cells(3, "E") = InputBox("Your Name:")
    .Cells(4, "E") = InputBox("Your Age:")
    .Cells(5, "E") = InputBox("Your Occupation:")
    .Range("B03") = uploader.Worksheets("Que & Tsc Cal").Range("B02").Value2
    .Range("B05") = uploader.Worksheets("Que & Tsc Cal").Range("B01").Value2

End With

Application.ScreenUpdating = True

End Sub


问:
Identify frequency of elements in each key in python
I have a list of dictionary as follows.

```<code>mylist = [ {"0": ["code1", "code5"], "1" ["code8", "code7", "code2"]},
{"1": ["code2", "code3"], "2" ["code4", "code5", "code7"], "3": ["code1", "code10"]},
{"0": ["code8", "code5", "code1"], "2" ["code7", "code5", "code2"]} ]
</code>```

Now, I want to calculate the codes count for each key in the dictionary. For example "0": ["code1", "code5"] and "0": ["code8", "code5"] should give: mydict_for_0 = {"code1": 1, "code5": 2, "code8": 1}

So, for the above mylist the output should be;

```<code>mydict_for_0 = {"code1": 2, "code5": 2, "code8": 1}
mydict_for_1 = {"code2": 2, "code3": 1, "code7": 1, "code8": 1}
mydict_for_2 = {"code4": 1, "code5": 2, "code7": 2, {"code2": 1}
mydict_for_3 = {"code1": 1, "code10": 1}
</code>```

Please help me to do this using python!

答:
Try with defaultdict, Counter from collections module, find all same key's value list, extend them into one list, save into a defaultdict(list):

```<code>from collections import defaultdict, Counter
new_dict = defaultdict(list)
for e in mylist:
    for key,value in e.items():
        new_dict[key].extend(value)
</code>```

new_dict will be:

```<code>defaultdict(list,
            {'0': ['code1', 'code5', 'code8', 'code5', 'code1'],
             '1': ['code8', 'code7', 'code2', 'code2', 'code3'],
             '2': ['code4', 'code5', 'code7', 'code7', 'code5', 'code2'],
             '3': ['code1', 'code10']})
</code>```

After that, loop all items to pass the values list into Counter, to count the occurrences of list:

```<code>result = {}
for key,value in new_dict.items():
    result['mydict_for_'+key] = dict(Counter(value))
</code>```

result will be:

```<code>{'mydict_for_0': {'code1': 2, 'code5': 2, 'code8': 1},
 'mydict_for_1': {'code2': 2, 'code3': 1, 'code7': 1, 'code8': 1},
 'mydict_for_2': {'code2': 1, 'code4': 1, 'code5': 2, 'code7': 2},
 'mydict_for_3': {'code1': 1, 'code10': 1}}
</code>```

Body:
I have a list of dictionary as follows.

mylist = [ {"0": ["code1", "code5"], "1" ["code8", "code7", "code2"]},
{"1": ["code2", "code3"], "2" ["code4", "code5", "code7"], "3": ["code1", "code10"]},
{"0": ["code8", "code5", "code1"], "2" ["code7", "code5", "code2"]} ]

Now, I want to calculate the codes count for each key in the dictionary. For example "0": ["code1", "code5"] and "0": ["code8", "code5"] should give: mydict_for_0 = {"code1": 1, "code5": 2, "code8": 1}

So, for the above mylist the output should be;

mydict_for_0 = {"code1": 2, "code5": 2, "code8": 1}
mydict_for_1 = {"code2": 2, "code3": 1, "code7": 1, "code8": 1}
mydict_for_2 = {"code4": 1, "code5": 2, "code7": 2, {"code2": 1}
mydict_for_3 = {"code1": 1, "code10": 1}

Please help me to do this using python!

Body:
Try with defaultdict, Counter from collections module, find all same key's value list, extend them into one list, save into a defaultdict(list):

from collections import defaultdict, Counter
new_dict = defaultdict(list)
for e in mylist:
    for key,value in e.items():
        new_dict[key].extend(value)

new_dict will be:

defaultdict(list,
            {'0': ['code1', 'code5', 'code8', 'code5', 'code1'],
             '1': ['code8', 'code7', 'code2', 'code2', 'code3'],
             '2': ['code4', 'code5', 'code7', 'code7', 'code5', 'code2'],
             '3': ['code1', 'code10']})

After that, loop all items to pass the values list into Counter, to count the occurrences of list:

result = {}
for key,value in new_dict.items():
    result['mydict_for_'+key] = dict(Counter(value))

result will be:

{'mydict_for_0': {'code1': 2, 'code5': 2, 'code8': 1},
 'mydict_for_1': {'code2': 2, 'code3': 1, 'code7': 1, 'code8': 1},
 'mydict_for_2': {'code2': 1, 'code4': 1, 'code5': 2, 'code7': 2},
 'mydict_for_3': {'code1': 1, 'code10': 1}}


问:
Batch file to not write variables in a text file
I am trying to make a batch file that will write other files.

This is my file:

```<code>@echo off
set x=100
echo %x% >> output.txt
</code>```

What this does is create a text file called "output.txt".

In this file it will display "100"

This is not what I want it to, I want the file to contain "%x%" literally.

The reason I am trying to do this is because I would like a batch file to create other complex batch files.

I could use copy or move to move another file containing what I want, but I need this to be a single file.

I would really appreciate some help, but it is understandably really difficult to understand.

Thanks Jason

答:
Just set x after you create the file:

```<code>@echo off
echo %x% >> output.txt
set x=100
</code>```

This should work because you don't need to set x that early in the program (at least under those circumstances you don't).

Body:
I am trying to make a batch file that will write other files.

This is my file:

@echo off
set x=100
echo %x% >> output.txt

What this does is create a text file called "output.txt".

In this file it will display "100"

This is not what I want it to, I want the file to contain "%x%" literally.

The reason I am trying to do this is because I would like a batch file to create other complex batch files.

I could use copy or move to move another file containing what I want, but I need this to be a single file.

I would really appreciate some help, but it is understandably really difficult to understand.

Thanks Jason

Body:
Just set x after you create the file:

@echo off
echo %x% >> output.txt
set x=100

This should work because you don't need to set x that early in the program (at least under those circumstances you don't).


答:
This operator is generally used to provide a default value when an expression or variable produces an optional result. for ex:

```<code>let i: Int? = 5
let j: Int? = nil

let value1 = i ?? 9 //value1 will be 5 non-optional
let value2 = j ?? 9 //value2 will be 9 non-optional
</code>```

You can chain multiple of these operators as such:

```<code>let value3 = j ?? i ?? 9 //value3 will be 5 non-optional
</code>```

The chain terminates whenever a non nil value is found. The result of the expression will be a optional/non-optional depending on the type of last expression in the chain.

The example you've provided, although syntactically correct, is redundant, as omitting the ?? nil would have no result on the outcome.

Title: What is the meaning of "??" in swift?

Body:
This operator is generally used to provide a default value when an expression or variable produces an optional result. for ex:

let i: Int? = 5
let j: Int? = nil

let value1 = i ?? 9 //value1 will be 5 non-optional
let value2 = j ?? 9 //value2 will be 9 non-optional

You can chain multiple of these operators as such:

let value3 = j ?? i ?? 9 //value3 will be 5 non-optional

The chain terminates whenever a non nil value is found. The result of the expression will be a optional/non-optional depending on the type of last expression in the chain.

The example you've provided, although syntactically correct, is redundant, as omitting the ?? nil would have no result on the outcome.


问:
How can I obtain the circumference coordinates of a tilted circle in Unity C#?

The perimeter coordinates of the non-tilted circles, like the image above, were obtained with the following code.

```<code>//c=Center
//r=radius
//i=angle
Vector3 FindPoint(Vector3 c, float r, int i)
{
    return c + Quaternion.AngleAxis(1.0f * i, Vector3.forward) * (Vector3.right * r);
}

//Example of securing coordinates
for(int i=0;i<360;i++)
{
    point[i] = FindPoint(center, radius, i);
}
</code>```

But, as in the image above, I need to get the circumference coordinates for the circles that are tilted in the x-axis.

How do you know the three-dimensional coordinates of the circumference of a tilted circle when you know the origin and radius and the tilted values along the x-axis?

答:
From unity documentation:
Unlike Vector3.forward, Transform.forward moves the GameObject while also considering its rotation.
So, you can replace this line:

```<code>return c + Quaternion.AngleAxis(1.0f * i, Vector3.forward) * (Vector3.right * r);
</code>```

with the following one:

```<code>return c + Quaternion.AngleAxis(1.0f * i, transform.forward) * (transform.right * r);
</code>```

**I guessed your script is attached to the tilted object so used transform. Otherwise, you need to use it like tiltedObj.transform.

Body:
The perimeter coordinates of the non-tilted circles, like the image above, were obtained with the following code.

//c=Center
//r=radius
//i=angle
Vector3 FindPoint(Vector3 c, float r, int i)
{
    return c + Quaternion.AngleAxis(1.0f * i, Vector3.forward) * (Vector3.right * r);
}

//Example of securing coordinates
for(int i=0;i<360;i++)
{
    point[i] = FindPoint(center, radius, i);
}

But, as in the image above, I need to get the circumference coordinates for the circles that are tilted in the x-axis.

How do you know the three-dimensional coordinates of the circumference of a tilted circle when you know the origin and radius and the tilted values along the x-axis?

Body:
From unity documentation:
Unlike Vector3.forward, Transform.forward moves the GameObject while also considering its rotation.
So, you can replace this line:

return c + Quaternion.AngleAxis(1.0f * i, Vector3.forward) * (Vector3.right * r);

with the following one:

return c + Quaternion.AngleAxis(1.0f * i, transform.forward) * (transform.right * r);

**I guessed your script is attached to the tilted object so used transform. Otherwise, you need to use it like tiltedObj.transform.


问:
Challenges with selecting values in ListBoxFor
Working on my first ASP.Net MVC2 web app recently, I came across some issues when I needed to select multiple values in a list box.  I worked around it with some jQuery, but went ahead and put together some very simple code to demonstrate. I'm using EF for the model, with two entities - Customers and HelpDeskCalls:

Controller:

```<code> public ActionResult Edit(int id)
    {
        Customer currCustomer = ctx.Customers.Include("HelpDeskCalls").Where(c => c.ID == id).FirstOrDefault();
        List<HelpDeskCall> currCustCalls = (ctx.HelpDeskCalls.Where(h => h.CustomerID == id)).ToList();
        List<SelectListItem> currSelectItems = new List<SelectListItem>();
        List<String> selectedValues = new List<string>();
        foreach (HelpDeskCall currCall in currCustCalls)
        {
            bool isSelected = (currCall.ID % 2 == 0) ? true : false;
            //Just select the IDs which are even numbers...
            currSelectItems.Add(new SelectListItem() { Selected = isSelected, Text = currCall.CallTitle, Value = currCall.ID.ToString() });
            //add the selected values into a separate list as well...
            if (isSelected)
            {
                selectedValues.Add(currCall.ID.ToString());
            }
        }
        ViewData["currCalls"] = (IEnumerable<SelectListItem>) currSelectItems;
        ViewData["currSelected"] = (IEnumerable<String>) selectedValues;
        return View("Edit", currCustomer);
    }
</code>```

View:

```<code><div class="editor-field">
    <%: Html.ListBoxFor(model => model.HelpDeskCalls, new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable) ViewData["currSelected"]), new { size = "12" })%>
    <%: Html.ListBoxFor(model => model.HelpDeskCalls, ViewData["currCalls"] as IEnumerable<SelectListItem>, new { size = "12"}) %>
    <%: Html.ListBox("Model.HelpDeskCalls", new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable)ViewData["currSelected"]), new { size = "12"}) %>
    <%: Html.ValidationMessageFor(model => model.HelpDeskCalls) %>
</div>
</code>```

For this sample, I'm just selecting HelpDeskCall.IDs which are even.  I'm trying two different syntaxes for ListBoxFor: One uses an IEnumerable of values for selections, one using an IEnumerable of SelectListItems.  By default, when I run this code, no selections are made to either ListBoxFor, but the non-strongly typed ListBox selects correctly.

I read this post on ASP.Net and this thread on SO, but no joy.  In fact, if I add the override ToString() to my HelpDeskCall class (as suggested in the ASP.net thread) all values are selected, which isn't right either.

If someone could shed some light on how this should work (and what I'm missing or doing wrong), this then neophyte would be very grateful.

答:
I don't know if this behaviour has changed in the RTM of MVC3 that I'm using, but it seems that selection and binding now works out of the box. The only catch is that the model should contain a property with the IDs, like that :

```<code>public class MyViewModel {
    public int[] ItemIDs { get; set; }
}
</code>```

Then the following in the view would work fine, both pre-selecting the correct values and binding correctly during post:

```<code>@Html.ListBoxFor(model => model.ItemIDs, (IEnumerable<SelectListItem>)(new[] {
                                new SelectListItem() { Value = "1", Text = "1" },
                                new SelectListItem() { Value = "2", Text = "2" }
                             }))
</code>```

Body:
Working on my first ASP.Net MVC2 web app recently, I came across some issues when I needed to select multiple values in a list box.  I worked around it with some jQuery, but went ahead and put together some very simple code to demonstrate. I'm using EF for the model, with two entities - Customers and HelpDeskCalls:

Controller:

 public ActionResult Edit(int id)
    {
        Customer currCustomer = ctx.Customers.Include("HelpDeskCalls").Where(c => c.ID == id).FirstOrDefault();
        List<HelpDeskCall> currCustCalls = (ctx.HelpDeskCalls.Where(h => h.CustomerID == id)).ToList();
        List<SelectListItem> currSelectItems = new List<SelectListItem>();
        List<String> selectedValues = new List<string>();
        foreach (HelpDeskCall currCall in currCustCalls)
        {
            bool isSelected = (currCall.ID % 2 == 0) ? true : false;
            //Just select the IDs which are even numbers...
            currSelectItems.Add(new SelectListItem() { Selected = isSelected, Text = currCall.CallTitle, Value = currCall.ID.ToString() });
            //add the selected values into a separate list as well...
            if (isSelected)
            {
                selectedValues.Add(currCall.ID.ToString());
            }
        }
        ViewData["currCalls"] = (IEnumerable<SelectListItem>) currSelectItems;
        ViewData["currSelected"] = (IEnumerable<String>) selectedValues;
        return View("Edit", currCustomer);
    }

View:

    <%: Html.ListBoxFor(model => model.HelpDeskCalls, new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable) ViewData["currSelected"]), new { size = "12" })%>
    <%: Html.ListBoxFor(model => model.HelpDeskCalls, ViewData["currCalls"] as IEnumerable<SelectListItem>, new { size = "12"}) %>
    <%: Html.ListBox("Model.HelpDeskCalls", new MultiSelectList(Model.HelpDeskCalls, "ID", "CallTitle", (IEnumerable)ViewData["currSelected"]), new { size = "12"}) %>
    <%: Html.ValidationMessageFor(model => model.HelpDeskCalls) %>

For this sample, I'm just selecting HelpDeskCall.IDs which are even.  I'm trying two different syntaxes for ListBoxFor: One uses an IEnumerable of values for selections, one using an IEnumerable of SelectListItems.  By default, when I run this code, no selections are made to either ListBoxFor, but the non-strongly typed ListBox selects correctly.

I read this post on ASP.Net and this thread on SO, but no joy.  In fact, if I add the override ToString() to my HelpDeskCall class (as suggested in the ASP.net thread) all values are selected, which isn't right either.

If someone could shed some light on how this should work (and what I'm missing or doing wrong), this then neophyte would be very grateful.

Body:
I don't know if this behaviour has changed in the RTM of MVC3 that I'm using, but it seems that selection and binding now works out of the box. The only catch is that the model should contain a property with the IDs, like that :

public class MyViewModel {
    public int[] ItemIDs { get; set; }
}

Then the following in the view would work fine, both pre-selecting the correct values and binding correctly during post:

@Html.ListBoxFor(model => model.ItemIDs, (IEnumerable<SelectListItem>)(new[] {
                                new SelectListItem() { Value = "1", Text = "1" },
                                new SelectListItem() { Value = "2", Text = "2" }
                             }))

ContentLicense: CC BY-SA 2.5


问:
Sum next array elements from a starting position (javascript)
I need this for dynamically use.
I have 2 associated arrays:

```<code>Var $some = [1, 2, 3];
Var $other = [a, b, c];
</code>```

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

```<code>$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)
</code>```

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

答:
Using html(function) to do the loop indexing and a reduce() for sum

var some = [1, 2, 3];
var other = ['a', 'b', 'c'];

$('#'+ other.join(',#')).html((elIdx)=>{
    return some.reduce((a,c,i) => a+= (i===elIdx ? 0 : c), 0);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p></code>```

Body:
I need this for dynamically use.
I have 2 associated arrays:

Var $some = [1, 2, 3];
Var $other = [a, b, c];

a, b, c are some html ids and 1, 2, 3 are their values.
I want something like this on trigger:

$'#a').attr('max', //b+c val(2+3)
$'#b').attr('max', //a+c val(1+3)
$'#c').attr('max', //a+b val(1+2)

I ve searched here get prev and next items in array about finding next elements in array, and I think would be usefull a loop that itinerate elements a (then b then c) with its values and for each one execute a code like: sum next elements to them. Substracting element value after sumed won't work pripperly because I want that script on some ranges change...
So...my question would be: how can I sum elements itinerated from a loop? I think that would be the key to solve this because I can loop it 2 times in this example and would stop without started element...

Body:
Using html(function) to do the loop indexing and a reduce() for sum

var some = [1, 2, 3];
var other = ['a', 'b', 'c'];

$('#'+ other.join(',#')).html((elIdx)=>{
    return some.reduce((a,c,i) => a+= (i===elIdx ? 0 : c), 0);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="a"></p>
<p id="b"></p>
<p id="c"></p>


问:
How to target a class name in android WebView?
I need to load WebView and need to modify the CSS based on div class, in my case I need to target to innerClass. For example I have this code in WebView:

```<code><div class="myClass">
  <div class="innerClass">
     Some Text here.
  </div>
</div>
</code>```

How I can set innerClass to be display:none?

Here's my code in MainActivity.java:

```<code>final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://xxxx.com");
</code>```

答:
You can use javascript code like this:

```<code>mWebView.setWebChromeClient(new WebChromeClient()); // for alert
mWebView.loadUrl("javascript:alert('hello world')");
</code>```

And you can achieve your goal by this:

```<code>mWebView.loadUrl("javascript:document.getElementsByClassName('innerClass')[0].style.display = 'none'");
</code>```

Here is full example:

MainActivity.java

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

    private WebView mWebView;
    private boolean isVisible = true;

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

        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient()); // for alert, anyway.

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        String htmlString = "<html><div class=\"myClass\">\n" +
                "myClass text here" +
                "  <div class=\"innerClass\">\n" +
                "     Some Text here.\n" +
                "  </div>\n" +
                "</div>" +
                "</html>";

        mWebView.loadData(htmlString, "text/html; charset=utf-8", null);

        mWebView.loadUrl("javascript:alert('hello world')");
    }

    public void toggle(View view) {
        if (isVisible) {
            mWebView.loadUrl("javascript:var d = document.getElementsByClassName('innerClass')[0]; d.setAttribute(\"style\",\"display:none;\");");
        } else {
            mWebView.loadUrl("javascript:var d = document.getElementsByClassName('innerClass')[0]; d.setAttribute(\"style\",\"display:visible;\");");
        }
        isVisible = !isVisible;
    }
}
</code>```

activity_main.xml

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="runJavascript"
        android:text="Click"/>

    <WebView
        android:id="@+id/activity_main_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
</code>```

Body:
I need to load WebView and need to modify the CSS based on div class, in my case I need to target to innerClass. For example I have this code in WebView:

     Some Text here.

How I can set innerClass to be display:none?

Here's my code in MainActivity.java:

final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("https://xxxx.com");

Body:
You can use javascript code like this:

mWebView.setWebChromeClient(new WebChromeClient()); // for alert
mWebView.loadUrl("javascript:alert('hello world')");

And you can achieve your goal by this:

mWebView.loadUrl("javascript:document.getElementsByClassName('innerClass')[0].style.display = 'none'");

Here is full example:

MainActivity.java

public class MainActivity extends Activity {

    private WebView mWebView;
    private boolean isVisible = true;

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

        mWebView = (WebView) findViewById(R.id.activity_main_webview);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.setWebChromeClient(new WebChromeClient()); // for alert, anyway.

        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        String htmlString = "<html><div class=\"myClass\">\n" +
                "myClass text here" +
                "  <div class=\"innerClass\">\n" +
                "     Some Text here.\n" +
                "  </div>\n" +
                "</div>" +
                "</html>";

        mWebView.loadData(htmlString, "text/html; charset=utf-8", null);

        mWebView.loadUrl("javascript:alert('hello world')");
    }

    public void toggle(View view) {
        if (isVisible) {
            mWebView.loadUrl("javascript:var d = document.getElementsByClassName('innerClass')[0]; d.setAttribute(\"style\",\"display:none;\");");
        } else {
            mWebView.loadUrl("javascript:var d = document.getElementsByClassName('innerClass')[0]; d.setAttribute(\"style\",\"display:visible;\");");
        }
        isVisible = !isVisible;
    }
}

activity_main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="runJavascript"
        android:text="Click"/>

    <WebView
        android:id="@+id/activity_main_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>