问:
Python multiprocessing continuous processing with await
I am using an event based system using the new Python 3.5 coroutines and await. I register events and these events are called by the system.

```<code>@event
aysnc def handleevent(args):
    # handle the event
</code>```

I need to initialize some classes to handle the work(time consuming). Then call instance methods, also time consuming (they actually use selenium to browse certain sites).

Ideally I would want something like the following code

```<code># supposedly since this is multiprocessing this is a different driver per process
driver = None
def init():
    # do the heavy initialization here
    global driver
    driver = webdriver.Chrome()

def longworkmethod():
    ## need to return some data
    return driver.dolongwork()

class Drivers:
""" A class to handle async and multiprocessing"""
    def __init__(self, numberOfDrivers):
        self.pool = multiprocessing.Pool(processes=numberOfDrivers, initializer=init)

    async def dowork(self, args):
        return self.pool.apply_async(longworkmethod, args=args)

### my main python class
drivers = Drivers(5)

@event
aysnc def handleevent(args):
    await drivers.dowork(args)

@event
aysnc def quit(args):
    ## do cleanup on drivers
    sys.exit(0)
</code>```

This code doesn't work, but I have tried many different ways and none seem to be able to do what I want.

It doesn't have to be this exact form, but how do I go about mixing the await and coroutines with a program that needs multiprocessing?

答:
While there nothing technically speaking that would limit you from mixing asyncio and multiprocessing, I would suggest avoiding doing so. It's going to add a lot of complexity as you'll end up needing an event loop per thread and passing information back and forth will be tricky. Just use one or the other.

asyncio supplies functions for running tasks in another thread - such as AbstractEventLoop.run_in_executor. Take a look at these answers

https://stackoverflow.com/a/33025287/66349 (calling selenium within a coroutine)

https://stackoverflow.com/a/28492261/66349

Alternatively you could just use multiprocessing as selenium has a blocking (non asyncio) interface, however it sounds like some of your code is using already using asyncio so maybe stick with the above.

Body:
I am using an event based system using the new Python 3.5 coroutines and await. I register events and these events are called by the system.

@event
aysnc def handleevent(args):
    # handle the event

I need to initialize some classes to handle the work(time consuming). Then call instance methods, also time consuming (they actually use selenium to browse certain sites).

Ideally I would want something like the following code

# supposedly since this is multiprocessing this is a different driver per process
driver = None
def init():
    # do the heavy initialization here
    global driver
    driver = webdriver.Chrome()

def longworkmethod():
    ## need to return some data
    return driver.dolongwork()

class Drivers:
""" A class to handle async and multiprocessing"""
    def __init__(self, numberOfDrivers):
        self.pool = multiprocessing.Pool(processes=numberOfDrivers, initializer=init)

    async def dowork(self, args):
        return self.pool.apply_async(longworkmethod, args=args)

### my main python class
drivers = Drivers(5)

@event
aysnc def handleevent(args):
    await drivers.dowork(args)

@event
aysnc def quit(args):
    ## do cleanup on drivers
    sys.exit(0)

This code doesn't work, but I have tried many different ways and none seem to be able to do what I want.

It doesn't have to be this exact form, but how do I go about mixing the await and coroutines with a program that needs multiprocessing?


来源: stackexchange

问:
Javascript Function With Square Brackets
I usually program in Python, but today I was trying to reverse engineer some Javascript code and I came across this line:

```<code>var ABC = DEF[XYZ];
</code>```

DEF is a function that was defined earlier. It takes one argument. XYZ is a string that was created earlier, and it contains the results of running DEF previously.

I don't know much JavaScript, but it seems to me like it is defining a variable called ABC that contains the results of running function DEF with the argument XYZ. However, later on there is a line that goes var GHI = ABC(JKL, DEF(MNO)) (JKL and MNO are both variables defined earlier).

What puzzles me is that ABC was defined as a variable, not a function. So I'm thinking this has something to do with the square brackets seen earlier.

So my question is: what is the purpose of those square brackets?

答:
what is the purpose of those square brackets?

To access a member of an object.

It's not calling a function. It's attempting to access a member of the object DEF (without seeing the rest of the code, it's impossible to tell what kind of object DEF is, as you can use object member accession like that for any type of object that contains members, like plain objects, functions, arrays, etc.) For example:

```<code>var DEF = {
  foo: 'bar'
};

var XYZ = 'foo';

var ABC = DEF[XYZ];

console.log(ABC); // => 'bar'
</code>```

As another example, DEF could also be an array, and if XYZ is a number, then it's accessing a specific index of that array.

Update

If DEF is a function, you can still access members of it:

```<code>function DEF(arg) {
  // do something with arg
}

DEF.foo = function(str) {
   console.log('I am doing ' + str)
}

var XYZ = 'foo'

console.log(DEF[XYZ]) // => function() {}

var ABC = DEF[XYZ]

ABC('yoga') // => 'I am doing yoga'
</code>```

You can call DEF[XYZ](someArgument) like this.

ContentLicense: CC BY-SA 3.0

Body:
I usually program in Python, but today I was trying to reverse engineer some Javascript code and I came across this line:

var ABC = DEF[XYZ];

DEF is a function that was defined earlier. It takes one argument. XYZ is a string that was created earlier, and it contains the results of running DEF previously.

I don't know much JavaScript, but it seems to me like it is defining a variable called ABC that contains the results of running function DEF with the argument XYZ. However, later on there is a line that goes var GHI = ABC(JKL, DEF(MNO)) (JKL and MNO are both variables defined earlier).

What puzzles me is that ABC was defined as a variable, not a function. So I'm thinking this has something to do with the square brackets seen earlier.

So my question is: what is the purpose of those square brackets?

Body:
what is the purpose of those square brackets?

To access a member of an object.

It's not calling a function. It's attempting to access a member of the object DEF (without seeing the rest of the code, it's impossible to tell what kind of object DEF is, as you can use object member accession like that for any type of object that contains members, like plain objects, functions, arrays, etc.) For example:

var DEF = {
  foo: 'bar'
};

var XYZ = 'foo';

var ABC = DEF[XYZ];

console.log(ABC); // => 'bar'

As another example, DEF could also be an array, and if XYZ is a number, then it's accessing a specific index of that array.

Update

If DEF is a function, you can still access members of it:

function DEF(arg) {
  // do something with arg
}

DEF.foo = function(str) {
   console.log('I am doing ' + str)
}

var XYZ = 'foo'

console.log(DEF[XYZ]) // => function() {}

var ABC = DEF[XYZ]

ABC('yoga') // => 'I am doing yoga'

You can call DEF[XYZ](someArgument) like this.


问:
how to convert this nested object into a flat object?
Sorry I don't know how to phrase the question title. Please help edit if possible.

I have an object like this:

```<code>{
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
}
</code>```

I want to make it look like:

```<code>{
    'a': 'jack',
    'b.c': 'sparrow',
    'b.d.e': 'hahaha'
}

// so that I can use it this way:
a['b.d.e']
</code>```

jQuery is ok too. I know for the nested object, I can use a.b.d.e to get hahaha, but today I have to use it like a['b.d.e'] -_-!!!
How can I achieve this? Thanks in advance :)

答:
An alternative recursive implementation. I just felt like writing one implementation myself, even though the current ones are already really good.

The recursive function checks whether the key is of type 'object'.

If it's an object, we iterate by each object's key.

Else, we add it into our result object.

```<code>function flat(res, key, val, pre = '') {
  const prefix = [pre, key].filter(v => v).join('.');
  return typeof val === 'object'
    ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
    : Object.assign(res, { [prefix]: val});
}
return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
</code>```

Flat NPM package

Or you can simply use flat npm package, which is a well known tested library.

```<code>var flatten = require('flat')
flatten(obj);
</code>```

⬑ I would use this in serious code.

[Extra] Neater call to the function above

```<code>function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject(input);
</code>```

[Extra] Demo

http://codepen.io/zurfyx/pen/VpErja?editors=1010

function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject({
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
});

document.getElementById('code').innerHTML = JSON.stringify(result, null, 2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code>``````</code>```

Body:
Sorry I don't know how to phrase the question title. Please help edit if possible.

I have an object like this:

{
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
}

I want to make it look like:

{
    'a': 'jack',
    'b.c': 'sparrow',
    'b.d.e': 'hahaha'
}

// so that I can use it this way:
a['b.d.e']

jQuery is ok too. I know for the nested object, I can use a.b.d.e to get hahaha, but today I have to use it like a['b.d.e'] -_-!!!
How can I achieve this? Thanks in advance :)

Body:
An alternative recursive implementation. I just felt like writing one implementation myself, even though the current ones are already really good.

The recursive function checks whether the key is of type 'object'.

If it's an object, we iterate by each object's key.

Else, we add it into our result object.

function flat(res, key, val, pre = '') {
  const prefix = [pre, key].filter(v => v).join('.');
  return typeof val === 'object'
    ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
    : Object.assign(res, { [prefix]: val});
}
return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});

Flat NPM package

Or you can simply use flat npm package, which is a well known tested library.

var flatten = require('flat')
flatten(obj);

⬑ I would use this in serious code.

[Extra] Neater call to the function above

function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject(input);

[Extra] Demo

http://codepen.io/zurfyx/pen/VpErja?editors=1010

function flatObject(input) {
  function flat(res, key, val, pre = '') {
    const prefix = [pre, key].filter(v => v).join('.');
    return typeof val === 'object'
      ? Object.keys(val).reduce((prev, curr) => flat(prev, curr, val[curr], prefix), res)
      : Object.assign(res, { [prefix]: val});
  }

  return Object.keys(input).reduce((prev, curr) => flat(prev, curr, input[curr]), {});
}

const result = flatObject({
    a: 'jack',
    b: {
        c: 'sparrow',
        d: {
           e: 'hahaha'
        }
    }
});

document.getElementById('code').innerHTML = JSON.stringify(result, null, 2);

<pre><code id="code"></code></pre>


问:
push local variables
Alo

After I have read about function and stack from http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames I have a question about local variables.

Snapshot from the article:

```<code>push ebp     ; save the value of ebp
mov ebp, esp ; ebp now points to the top of the stack
sub esp, 12  ; space allocated on the stack for the local variables
</code>```

This means local variables can be accessed by referencing ebp. Consider the following C code fragment and corresponding assembly code:

```<code>a = 10;
b = 5;
c = 2;

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c
</code>```

Remember that pushing basically does this:

```<code>sub esp, 4   ; "allocate" space for the new stack item
mov [esp], X ; put new stack item value X in
</code>```

Why are local variables not push into the stack like this:

```<code>push 10
push 5
push 2
</code>```

instead of

```<code>sub esp, 12

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c
</code>```

答: It's more a matter of semantics rather than of technical correctness: push and pop are used to save and restore registers or values; but providing local variables for a function does not correspond to this regular purpose of push/pop. So, the stack is managed manually here (except of push ebp and pop ebp, because here we actually want to save and restore ebp in the true sense of push/pop).

ContentLicense: CC BY-SA 2.5

Title: push local variables

Body:
Alo

After I have read about function and stack from http://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames I have a question about local variables.

Snapshot from the article:

push ebp     ; save the value of ebp
mov ebp, esp ; ebp now points to the top of the stack
sub esp, 12  ; space allocated on the stack for the local variables

This means local variables can be accessed by referencing ebp. Consider the following C code fragment and corresponding assembly code:

a = 10;
b = 5;
c = 2;

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c

Remember that pushing basically does this:

sub esp, 4   ; "allocate" space for the new stack item
mov [esp], X ; put new stack item value X in

Why are local variables not push into the stack like this:

push 10
push 5
push 2

instead of

sub esp, 12

mov [ebp -  4], 10  ; location of variable a
mov [ebp -  8], 5   ; location of b
mov [ebp - 12], 2   ; location of c


问:
SimpleDateFormat converting UTC to timezone incorrectly
I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

```<code>SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");
</code>```

The date object output has a date that looks like this

```<code>Fri Sep 01 01:00:00 MDT 2017
</code>```

When I should get an output of

```<code>Fri Sep 01 01:00:00 UTC 2017
</code>```

OR

```<code>Fri Aug 31 19:00:00 MDT 2017
</code>```

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.

答:
The single quotes around the 'Z' mean that it's not interpreted as a time zone specifier for UTC: it's simply a literal Z in the string, which is discarded.

As you are not setting a timezone specifically on the SimpleDateFormat, the date is parsed in your JVM's default timezone.

Date.toString() uses your JVM's default timezone. There is no timezone in a Date. If you want to print in a specific timezone, you need to use a SimpleDateFormat to print it.

Body:
I have a problem when converting the following ISO string 2017-09-01T01:00:00.000Z into a date.

I'm using SimpleDateFormat as follows

SimpleDateFormat stringToDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = stringToDate.parse("2017-09-01T01:00:00.000Z");

The date object output has a date that looks like this

Fri Sep 01 01:00:00 MDT 2017

When I should get an output of

Fri Sep 01 01:00:00 UTC 2017

OR

Fri Aug 31 19:00:00 MDT 2017

It looks like it is not doing the timezone conversion correctly because the time is unchanged, but the timezone has been when neither or both should be changed.


问:
Bootstrap 3 .col-xs-offset-* doesn't work?
I am using bootstrap 3 grid system loved it so far and everything was working well,
I am trying to use col-xs-offset-1 and doesn't work although .col-sm-offset-1 works.
What am I missing here ?

```<code><div class="col-xs-2 col-xs-offset-1">col</div>
</code>```

http://jsfiddle.net/petran/zMcs5/2/

答:
Just in case someone makes the same error I did before stumbling on this page, that is,  adding CSS reset rules (like the very popular reset by Eric Meyer  used on millions of websites) after including bootstrap.

Also, perhaps I should point out that such reset won't be necessary with bootstrap given bootsrap actually implements the normalize.css v3.0.2 reset.

Body:
I am using bootstrap 3 grid system loved it so far and everything was working well,
I am trying to use col-xs-offset-1 and doesn't work although .col-sm-offset-1 works.
What am I missing here ?

col

http://jsfiddle.net/petran/zMcs5/2/


问:
using JSON-SerDe in Hive tables
I'm trying JSON-SerDe from below link
http://code.google.com/p/hive-json-serde/wiki/GettingStarted.

```<code>         CREATE TABLE my_table (field1 string, field2 int,
                                     field3 string, field4 double)
         ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde' ;
</code>```

I've added Json-SerDe jar as

```<code>          ADD JAR /path-to/hive-json-serde.jar;
</code>```

And loaded data as

```<code>LOAD DATA LOCAL INPATH  '/home/hduser/pradi/Test.json' INTO TABLE my_table;
</code>```

and it loads data successfully.

But when query data as

Select * from my_table;

I get only one row from table as

data1   100     more data1      123.001

Test.json contains

```<code>{"field1":"data1","field2":100,"field3":"more data1","field4":123.001}

{"field1":"data2","field2":200,"field3":"more data2","field4":123.002}

{"field1":"data3","field2":300,"field3":"more data3","field4":123.003}

{"field1":"data4","field2":400,"field3":"more data4","field4":123.004}
</code>```

Where is the problem? why only one row is coming instead of 4 rows when i query the table. And in  /user/hive/warehouse/my_table  contains all the 4 rows!!

```<code>hive> add jar /home/hduser/pradeep/hive-json-serde-0.2.jar;
Added /home/hduser/pradeep/hive-json-serde-0.2.jar to class path
Added resource: /home/hduser/pradeep/hive-json-serde-0.2.jar

hive> CREATE EXTERNAL TABLE my_table (field1 string, field2 int,
>                                 field3 string, field4 double)
> ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde'
> WITH SERDEPROPERTIES (
>   "field1"="$.field1",
>   "field2"="$.field2",
>   "field3"="$.field3",
>   "field4"="$.field4"
> );
OK
Time taken: 0.088 seconds

hive> LOAD DATA LOCAL INPATH  '/home/hduser/pradi/test.json' INTO TABLE my_table;
Copying data from file:/home/hduser/pradi/test.json
Copying file: file:/home/hduser/pradi/test.json
Loading data to table default.my_table
OK
Time taken: 0.426 seconds

hive> select * from my_table;
OK
data1   100     more data1      123.001
Time taken: 0.17 seconds
</code>```

I've already posted the contents of test.json file. so you can see that query is resulting only one line as

```<code>data1   100     more data1      123.001
</code>```

I've changed the json file to employee.json which contains

{
      "firstName" : "Mike",
      "lastName" : "Chepesky",
      "employeeNumber" : 1840192
}

and changed table also but it showing a null values when i query the table

```<code>hive> add jar /home/hduser/pradi/hive-json-serde-0.2.jar;
Added /home/hduser/pradi/hive-json-serde-0.2.jar to class path
Added resource: /home/hduser/pradi/hive-json-serde-0.2.jar

hive> create EXTERNAL table employees_json (firstName string, lastName string,        employeeNumber int )
> ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde';
OK
Time taken: 0.297 seconds

hive> load data local inpath '/home/hduser/pradi/employees.json' into table     employees_json;
Copying data from file:/home/hduser/pradi/employees.json
Copying file: file:/home/hduser/pradi/employees.json
Loading data to table default.employees_json
OK
Time taken: 0.293 seconds

 hive>select * from employees_json;
  OK
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
Time taken: 0.194 seconds
</code>```

答:
First of all you have to validate your json file on http://jsonlint.com/
after that make your file as one row per line and remove the [ ]. the comma at the end of the line is mandatory.

[{"field1":"data1","field2":100,"field3":"more data1","field4":123.001},
{"field1":"data2","field2":200,"field3":"more data2","field4":123.002},
{"field1":"data3","field2":300,"field3":"more data3","field4":123.003},
{"field1":"data4","field2":400,"field3":"more data4","field4":123.004}]

In my test I added hive-json-serde-0.2.jar from hadoop cluster , I think hive-json-serde-0.1.jar should be ok.

ADD JAR hive-json-serde-0.2.jar;

Create your table

CREATE TABLE my_table (field1 string, field2 int, field3 string, field4 double)
ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde' ;

Load your Json data file ,here I load it from hadoop cluster not from local

LOAD DATA INPATH  'Test2.json' INTO TABLE my_table;

My test

Title: using JSON-SerDe in Hive tables

Body:
I'm trying JSON-SerDe from below link
http://code.google.com/p/hive-json-serde/wiki/GettingStarted.

         CREATE TABLE my_table (field1 string, field2 int,
                                     field3 string, field4 double)
         ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde' ;

I've added Json-SerDe jar as

          ADD JAR /path-to/hive-json-serde.jar;

And loaded data as

LOAD DATA LOCAL INPATH  '/home/hduser/pradi/Test.json' INTO TABLE my_table;

and it loads data successfully.

But when query data as

Select * from my_table;

I get only one row from table as

data1   100     more data1      123.001

Test.json contains

{"field1":"data1","field2":100,"field3":"more data1","field4":123.001}

{"field1":"data2","field2":200,"field3":"more data2","field4":123.002}

{"field1":"data3","field2":300,"field3":"more data3","field4":123.003}

{"field1":"data4","field2":400,"field3":"more data4","field4":123.004}

Where is the problem? why only one row is coming instead of 4 rows when i query the table. And in  /user/hive/warehouse/my_table  contains all the 4 rows!!

hive> add jar /home/hduser/pradeep/hive-json-serde-0.2.jar;
Added /home/hduser/pradeep/hive-json-serde-0.2.jar to class path
Added resource: /home/hduser/pradeep/hive-json-serde-0.2.jar

hive> CREATE EXTERNAL TABLE my_table (field1 string, field2 int,
>                                 field3 string, field4 double)
> ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde'
> WITH SERDEPROPERTIES (
>   "field1"="$.field1",
>   "field2"="$.field2",
>   "field3"="$.field3",
>   "field4"="$.field4"
> );
OK
Time taken: 0.088 seconds

hive> LOAD DATA LOCAL INPATH  '/home/hduser/pradi/test.json' INTO TABLE my_table;
Copying data from file:/home/hduser/pradi/test.json
Copying file: file:/home/hduser/pradi/test.json
Loading data to table default.my_table
OK
Time taken: 0.426 seconds

hive> select * from my_table;
OK
data1   100     more data1      123.001
Time taken: 0.17 seconds

I've already posted the contents of test.json file. so you can see that query is resulting only one line as

data1   100     more data1      123.001

I've changed the json file to employee.json which contains

{
      "firstName" : "Mike",
      "lastName" : "Chepesky",
      "employeeNumber" : 1840192
}

and changed table also but it showing a null values when i query the table

hive> add jar /home/hduser/pradi/hive-json-serde-0.2.jar;
Added /home/hduser/pradi/hive-json-serde-0.2.jar to class path
Added resource: /home/hduser/pradi/hive-json-serde-0.2.jar

hive> create EXTERNAL table employees_json (firstName string, lastName string,        employeeNumber int )
> ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.JsonSerde';
OK
Time taken: 0.297 seconds

hive> load data local inpath '/home/hduser/pradi/employees.json' into table     employees_json;
Copying data from file:/home/hduser/pradi/employees.json
Copying file: file:/home/hduser/pradi/employees.json
Loading data to table default.employees_json
OK
Time taken: 0.293 seconds

 hive>select * from employees_json;
  OK
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
  NULL    NULL    NULL
Time taken: 0.194 seconds


问:
sed in backtick expansion, with xargs, not substituting the input string
```<code>echo "who are you" | xargs -i@ echo `echo @ | sed "s/who/where/"`
</code>```

Expected output:

```<code>where are you
</code>```

actual output:

```<code>who are you
</code>```

Note - this is not actual use case but an example test case.

答:
I'll assume that the actual use case indeed requires xargs; the simplest reformulation of the sample command would just be echo 'who are you' | sed 's/who/where/'

To get the expected behavior, xargs must explicitly call the shell binary sh with a string containing a shell command:

```<code>$ echo "who are you" | xargs -I@ sh -c 'echo "$1" | sed "s/who/where/"' - @
where are you
</code>```

As twalberg points out, in your attempt the command inside `...` is evaluated before xargs runs, and it results in a literal @ (due to passing literal @ to echo, it simply outputs @, because the sed command finds nothing to replace), which xargs then simply replaces with its input as-is; as twalberg states: you're effectively running

echo 'who are you' | xargs -i@ echo @, a virtual no-op, save for potential trimming of leading and trailing whitespace.

Generally, xargs can only call external utilities, and if you need a command that requires shell functionality - such as a pipeline - you must explicitly call the shell binary with a single string containing shell command(s) - i.e., an ad-hoc script - to be evaluated by that shell instance when called by xargs.

sh -c invokes /bin/sh with the specified script (a string containing shell commands) to evaluate, and it's safest to pass xargs' argument as a positional parameter to that script; note that the first argument after the script binds to $0 in the script, hence the use of dummy value _, followed by @, xargs's replacement string, whose expanded value will bind to $1 inside the script.

'echo "$1" | sed "s/who/where/"' therefore acts as an ad-hoc shell script that pipes its first positional parameter - the argument passed by xargs - to sed to yield the desired output.

Body:
echo "who are you" | xargs -i@ echo `echo @ | sed "s/who/where/"`

Expected output:

where are you

actual output:

who are you

Note - this is not actual use case but an example test case.

Body:
I'll assume that the actual use case indeed requires xargs; the simplest reformulation of the sample command would just be echo 'who are you' | sed 's/who/where/'

To get the expected behavior, xargs must explicitly call the shell binary sh with a string containing a shell command:

$ echo "who are you" | xargs -I@ sh -c 'echo "$1" | sed "s/who/where/"' - @
where are you

As twalberg points out, in your attempt the command inside `...` is evaluated before xargs runs, and it results in a literal @ (due to passing literal @ to echo, it simply outputs @, because the sed command finds nothing to replace), which xargs then simply replaces with its input as-is; as twalberg states: you're effectively running

echo 'who are you' | xargs -i@ echo @, a virtual no-op, save for potential trimming of leading and trailing whitespace.

Generally, xargs can only call external utilities, and if you need a command that requires shell functionality - such as a pipeline - you must explicitly call the shell binary with a single string containing shell command(s) - i.e., an ad-hoc script - to be evaluated by that shell instance when called by xargs.

sh -c invokes /bin/sh with the specified script (a string containing shell commands) to evaluate, and it's safest to pass xargs' argument as a positional parameter to that script; note that the first argument after the script binds to $0 in the script, hence the use of dummy value _, followed by @, xargs's replacement string, whose expanded value will bind to $1 inside the script.

'echo "$1" | sed "s/who/where/"' therefore acts as an ad-hoc shell script that pipes its first positional parameter - the argument passed by xargs - to sed to yield the desired output.


问:
Javascript Loop through data, process and append results
I have some data a function and need to loop the data process the lat and lon of each data field through the function and if result is smaller or equal to 20 then append the name into a div in the body of the html file.
This last I know how to do.

This is where I am:

The data:

```<code>[
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 52.71423653147739,
      "lon": -0.6552093528558713
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
]
</code>```

I also have a function have will check the distance is the lat lon.

```<code>function checkDistance(lat1, lon1, lat2, lon2) {

    //do the stuff

    return result

}
</code>```

What I need to do is I need a loop that will read each lat and lon.

So something like this:

```<code>fixedlat = 51.714236;
fixedlon = 50.710236

for data... {

    var result = checkDistance(fixedlat, fixedlon, datalat, datalon);

    if (result <= 20) {

      //append data[name] to div id="resultList"

    }

}
</code>```

How can I do this?

答:
Here's a working example, assuming your distance formula is for geodesic over a sphere, for example by making use of the Haversine formula.

function checkDistance(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

var fixedlat = 51.714236;
var fixedlon = 50.710236;
var miles = 20;
var distanceLimit = miles * 1.6; //(km)
var data = [
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 51.714236,
      "lon": 50.710236
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
];

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

 var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);

 if(result <= distanceLimit){
  var resultList = document.getElementById('resultList');
  resultList.append(data[i].name + ', ');
 }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="resultList"></div></code>```

Body:
I have some data a function and need to loop the data process the lat and lon of each data field through the function and if result is smaller or equal to 20 then append the name into a div in the body of the html file.
This last I know how to do.

This is where I am:

The data:

[
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 52.71423653147739,
      "lon": -0.6552093528558713
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
]

I also have a function have will check the distance is the lat lon.

function checkDistance(lat1, lon1, lat2, lon2) {

    //do the stuff

    return result

}

What I need to do is I need a loop that will read each lat and lon.

So something like this:

fixedlat = 51.714236;
fixedlon = 50.710236

for data... {

    var result = checkDistance(fixedlat, fixedlon, datalat, datalon);

    if (result <= 20) {

      //append data[name] to div id="resultList"

    }

}

How can I do this?

Body:
Here's a working example, assuming your distance formula is for geodesic over a sphere, for example by making use of the Haversine formula.

function checkDistance(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

var fixedlat = 51.714236;
var fixedlon = 50.710236;
var miles = 20;
var distanceLimit = miles * 1.6; //(km)
var data = [
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 51.714236,
      "lon": 50.710236
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
];

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

 var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);

 if(result <= distanceLimit){
  var resultList = document.getElementById('resultList');
  resultList.append(data[i].name + ', ');
 }
}

<div id="resultList"></div>


问:
Global functions in Multi-File projects?
I am very new to programming and having a bit of an issue. I have created a simple purchasing program as a university assignment. One of the tasks of the assignment is to use separate files for each of the three classes that I have created. The problem lies here, at least one of these classes methods use global functions that are also used by the main. When I try to migrate the classes and class methods to separate files, a duplication error is given. Is there any way I can get around this?

Example

a.h //header for class a

```<code>class A
{
void example1(); //global function used in class a
};
//end of class header
</code>```

a.cpp

```<code>void a::example1()
{
example(); //global function used in both class a and main
}
//end of class cpp
</code>```

program.cpp

```<code>void example() //global function used in both class a and main
{
//do something
}

int main()
{
example(); //global function used in main
}
</code>```

答:
Put the function declarations in a header file, and the corresponding function definition in a .cpp file:

lib.h:

```<code>#ifndef H_LIB
#define H_LIB

void foo();  // declaration

#endif
</code>```

lib.cpp:

```<code>#include <iostream>
#include "lib.h"

// definition
void foo()
{
    std::cout << "foo() called\n";
}
</code>```

main.cpp:

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

int main()
{
    foo();   // use
}
</code>```

Compilation:

g++ -W -Wall -Wextra -pedantic -std=c++14 lib.cpp main.cpp -o prog
```

Body:
I am very new to programming and having a bit of an issue. I have created a simple purchasing program as a university assignment. One of the tasks of the assignment is to use separate files for each of the three classes that I have created. The problem lies here, at least one of these classes methods use global functions that are also used by the main. When I try to migrate the classes and class methods to separate files, a duplication error is given. Is there any way I can get around this?

Example

a.h //header for class a

class A
{
void example1(); //global function used in class a
};
//end of class header

a.cpp

void a::example1()
{
example(); //global function used in both class a and main
}
//end of class cpp

program.cpp

void example() //global function used in both class a and main
{
//do something
}

int main()
{
example(); //global function used in main
}

Body:
Put the function declarations in a header file, and the corresponding function definition in a .cpp file:

lib.h:

#ifndef H_LIB
#define H_LIB

void foo();  // declaration

#endif

lib.cpp:

#include <iostream>
#include "lib.h"

// definition
void foo()
{
    std::cout << "foo() called\n";
}

main.cpp:

#include "lib.h"

int main()
{
    foo();   // use
}

Compilation:

g++ -W -Wall -Wextra -pedantic -std=c++14 lib.cpp main.cpp -o prog


问:
Calculate distance between two locations in metre
I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.

```<code>private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);

    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);

    int R = 6371; // km

    double dLat = deg2rad(lat2-lat1);
    double dLon = deg2rad(lon2-lon1);
    double  a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distanceInMeters = R * c;
    Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double  deg2rad(double deg) {
    return deg * (Math.PI/180);
}
</code>```

How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?

答:
There is no need to re-invent the wheel for this.

You can just use the Location.distanceBetween() method.

From the documentation:

Computes the approximate distance in meters between two locations

Here is a simple example:

```<code>private float getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2) {

    float[] distance = new float[2];

    Location.distanceBetween( lat1, lon1,
            lat2, lon2, distance);

    return distance[0];
}
</code>```

If the result array has more than just index zero populated, the other indices each contain a bearing (initial and final).

A bearing is a number that specifies a compass direction.

From http://www.geomidpoint.com/destination/help.html :

The bearing (or azimuth) is the compass direction to travel from the
  starting point, and must be within the range 0 to 360. 0 represents
  north, 90 is east, 180 is south and 270 is west.

ContentLicense: CC BY-SA 4.0

Body:
I have two locations and I want to calculate distance in meter. I wrote some code but it's not working perfectly.

private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
    Location loc1 = new Location("");
    loc1.setLatitude(lat1);
    loc1.setLongitude(lon1);

    Location loc2 = new Location("");
    loc2.setLatitude(lat2);
    loc2.setLongitude(lon2);

    int R = 6371; // km

    double dLat = deg2rad(lat2-lat1);
    double dLon = deg2rad(lon2-lon1);
    double  a =
            Math.sin(dLat/2) * Math.sin(dLat/2) +
                    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
                            Math.sin(dLon/2) * Math.sin(dLon/2)
            ;
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distanceInMeters = R * c;
    Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double  deg2rad(double deg) {
    return deg * (Math.PI/180);
}

How can I calculate distance in meter? My goal is, if meter > 200 do something. How can i solve my problem?

Body:
There is no need to re-invent the wheel for this.

You can just use the Location.distanceBetween() method.

From the documentation:

Computes the approximate distance in meters between two locations

Here is a simple example:

private float getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2) {

    float[] distance = new float[2];

    Location.distanceBetween( lat1, lon1,
            lat2, lon2, distance);

    return distance[0];
}

If the result array has more than just index zero populated, the other indices each contain a bearing (initial and final).

A bearing is a number that specifies a compass direction.

From http://www.geomidpoint.com/destination/help.html :

The bearing (or azimuth) is the compass direction to travel from the
  starting point, and must be within the range 0 to 360. 0 represents
  north, 90 is east, 180 is south and 270 is west.


问:
How to keep user logged in with Firebase no matter what?
I am developing an app under the Ionic Framework and I am also using Firebase.

Now, it happens that after a few hours or for a crash of the app or restarting the device, the Authentication is lost.

How can I manage to have my user ALWAYS logged in, no matter what happen ? (Like Facebook for example)

Here is my Login Controller from the page login.html :

```<code>.controller('loginController',['$scope', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $firebaseArray, CONFIG, $document, $state) {
  // Perform the login action when the user submits the login form
  $scope.doLogin = function(userLogin) {
        if($document[0].getElementById("user_name").value != "" && $document[0].getElementById("user_pass").value != ""){
        firebase.auth().signInWithEmailAndPassword(userLogin.username, userLogin.password).then(function() {
          var userId = firebase.auth().currentUser.uid;
          firebase.database().ref('accounts/' + userId + '/currentBusiness/').update({
            name: "No current business arround",
            description: "Seems there's nothing arround...",

            })
                      $state.go("tab.favorites");

        }, function(error) {
          // An error happened.
          var errorCode = error.code;
          var errorMessage = error.message;

          if (errorCode === 'auth/invalid-email') {
             alert('Enter a valid email.');
             return false;
          }else if (errorCode === 'auth/wrong-password') {
             alert('Incorrect password.');
             return false;
          }else if (errorCode === 'auth/argument-error') {
             alert('Password must be string.');
             return false;
          }else if (errorCode === 'auth/user-not-found') {
             alert('No such user found.');
             return false;
          }else if (errorCode === 'auth/too-many-requests') {
             alert('Too many failed login attempts, please try after sometime.');
             return false;
          }else if (errorCode === 'auth/network-request-failed') {
             alert('Request timed out, please try again.');
             return false;
          }else {
             alert(errorMessage);
             return false;
          }
        });
    }else{
        alert('Please enter email and password');
        return false;
    }//end check client username password
  };// end $scope.doLogin()
}])
</code>```

答:
I will answer my own question because I found the solution :

In my case, you have to use this code :

```<code>firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    $state.go("tab.favorites");
    // User is signed in.
  } else {
    // No user is signed in.
  }
});
</code>```

Body:
I am developing an app under the Ionic Framework and I am also using Firebase.

Now, it happens that after a few hours or for a crash of the app or restarting the device, the Authentication is lost.

How can I manage to have my user ALWAYS logged in, no matter what happen ? (Like Facebook for example)

Here is my Login Controller from the page login.html :

.controller('loginController',['$scope', '$firebaseArray', 'CONFIG', '$document', '$state', function($scope, $firebaseArray, CONFIG, $document, $state) {
  // Perform the login action when the user submits the login form
  $scope.doLogin = function(userLogin) {
        if($document[0].getElementById("user_name").value != "" && $document[0].getElementById("user_pass").value != ""){
        firebase.auth().signInWithEmailAndPassword(userLogin.username, userLogin.password).then(function() {
          var userId = firebase.auth().currentUser.uid;
          firebase.database().ref('accounts/' + userId + '/currentBusiness/').update({
            name: "No current business arround",
            description: "Seems there's nothing arround...",

            })
                      $state.go("tab.favorites");

        }, function(error) {
          // An error happened.
          var errorCode = error.code;
          var errorMessage = error.message;

          if (errorCode === 'auth/invalid-email') {
             alert('Enter a valid email.');
             return false;
          }else if (errorCode === 'auth/wrong-password') {
             alert('Incorrect password.');
             return false;
          }else if (errorCode === 'auth/argument-error') {
             alert('Password must be string.');
             return false;
          }else if (errorCode === 'auth/user-not-found') {
             alert('No such user found.');
             return false;
          }else if (errorCode === 'auth/too-many-requests') {
             alert('Too many failed login attempts, please try after sometime.');
             return false;
          }else if (errorCode === 'auth/network-request-failed') {
             alert('Request timed out, please try again.');
             return false;
          }else {
             alert(errorMessage);
             return false;
          }
        });
    }else{
        alert('Please enter email and password');
        return false;
    }//end check client username password
  };// end $scope.doLogin()
}])

Body:
I will answer my own question because I found the solution :

In my case, you have to use this code :

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    $state.go("tab.favorites");
    // User is signed in.
  } else {
    // No user is signed in.
  }
});


问:
Oracle - Compare two similar tables in same database
I have two tables PROD_DEMO and PROD_IMP in the same oracle database. Both share the same structure and constraints. Both table has a primary key PROD_CODE.

I have to show all the records from PROD_IMP table with one addition column STATUS showing if the record is updated or added in the PROD_IMP table.

I have written below query to achieve this but I am sure this require some improvement to make it faster.

```<code>select imp.*, decode(c.record_count, 2, 'U', 1, 'A', null) from prod_imp imp
left join
    (Select prod_code, count(1) as record_count from
        (
            (SELECT * FROM prod_demo UNION SELECT * FROM prod_imp)
            MINUS
            (SELECT * FROM prod_demo INTERSECT SELECT * FROM prod_imp)

        ) group by prod_code) c
on imp.prod_code = c.prod_code;
</code>```

I know this query will also list records which are deleted from PROD_DEMO table but in my case that won't happen.

The execution plan is shown below:

Both tables can have thousands of records. Now my question is how can I improve the performance of this query.

答:
I am assuming that if the record is present in prod_demo but not in prod_imp, it is added. If present in both, and any field has changed, then updated. The query below may or may not improve performance depending on the size of the tables, and number of matching records. The inner select with union, interest and minus requires that every field from every record in both tables be examined multiple times, and cannot leverage any indexes. The below example attempts to minimize the number of full record comparisons by only comparing all the fields from records present in both tables.</p>

```<code>-- Inserts
select d.*, 'A' [status]
from prod_demo d
left join prod_imp i on d.prod_code=i.prod_code
where i.prod_code is null

union

-- Updates
select d.*, 'U' [status]
from prod_demo d
join
(
    select prod_demo.prod_code,count(1)
    from
    (
        select prod_imp.*
        from prod_imp
        join prod_demo on prod_imp.prod_code=prod_demo.prod_code
        union
        select prod_demo.*
        from prod_demo
        join prod_imp on prod_imp.prod_code=prod_demo.prod_code

    ) matches
    group by prod_demo.prod_code
    having count(1) > 1
) updates on d.prod_code = updates.prod_code
</code>```

Body:
I have two tables PROD_DEMO and PROD_IMP in the same oracle database. Both share the same structure and constraints. Both table has a primary key PROD_CODE.

I have to show all the records from PROD_IMP table with one addition column STATUS showing if the record is updated or added in the PROD_IMP table.

I have written below query to achieve this but I am sure this require some improvement to make it faster.

select imp.*, decode(c.record_count, 2, 'U', 1, 'A', null) from prod_imp imp
left join
    (Select prod_code, count(1) as record_count from
        (
            (SELECT * FROM prod_demo UNION SELECT * FROM prod_imp)
            MINUS
            (SELECT * FROM prod_demo INTERSECT SELECT * FROM prod_imp)

        ) group by prod_code) c
on imp.prod_code = c.prod_code;

I know this query will also list records which are deleted from PROD_DEMO table but in my case that won't happen.

The execution plan is shown below:

Both tables can have thousands of records. Now my question is how can I improve the performance of this query.

Body:
I am assuming that if the record is present in prod_demo but not in prod_imp, it is added. If present in both, and any field has changed, then updated. The query below may or may not improve performance depending on the size of the tables, and number of matching records. The inner select with union, interest and minus requires that every field from every record in both tables be examined multiple times, and cannot leverage any indexes. The below example attempts to minimize the number of full record comparisons by only comparing all the fields from records present in both tables.

-- Inserts
select d.*, 'A' [status]
from prod_demo d
left join prod_imp i on d.prod_code=i.prod_code
where i.prod_code is null

union

-- Updates
select d.*, 'U' [status]
from prod_demo d
join
(
    select prod_demo.prod_code,count(1)
    from
    (
        select prod_imp.*
        from prod_imp
        join prod_demo on prod_imp.prod_code=prod_demo.prod_code
        union
        select prod_demo.*
        from prod_demo
        join prod_imp on prod_imp.prod_code=prod_demo.prod_code

    ) matches
    group by prod_demo.prod_code
    having count(1) > 1
) updates on d.prod_code = updates.prod_code


问:
Generate Firebase Registration token for a different Firebase project
We have an app connected to default Firebase project. For Notifications, we use a Legacy (secondary) Firebase project.

I have figured out how to connect to secondary Firebase server, Auth to read from Database.

For push notifications, currently, I am using the default Firebase project generated token. But now, I am trying to see if I can generate a registration token for the secondary Firebase project so I can use the Legacy project for Push notifications.

Since FirebaseInstanceIdService is where the tokens are generated, I feel it's tied to the default Firebase service which is read from services JSON file. I still would like to keep the default JSON service file since a lot of APIs are connected using the default Firebase account.

Any idea to use the secondary Firebase project to generate token?

答:
Just call getToken(String, String), passing the Sender ID of your Secondary Project. Like so:

```<code>getToken("2xxxxx3344", "FCM");
</code>```

It will return a (different) Registration token that corresponds to the secondary project, where you can now send push notifications from.

Do keep in mind that getToken(String, String) is a blocking function so do not call it on the main thread.

Similar posts (possibly duplicate):

How to put multiple project_number/sender id in google-services.json

Receive push notifications on one android app from two Firebase projects

Body:
Just call getToken(String, String), passing the Sender ID of your Secondary Project. Like so:

getToken("2xxxxx3344", "FCM");

It will return a (different) Registration token that corresponds to the secondary project, where you can now send push notifications from.

Do keep in mind that getToken(String, String) is a blocking function so do not call it on the main thread.

Similar posts (possibly duplicate):

How to put multiple project_number/sender id in google-services.json

Receive push notifications on one android app from two Firebase projects


问:
Prevent jquery from reseting background image after fadeOut()
I'm doing a number of fadeIn's and fadeOut's with jquery. The final fade (fadeOut()) fades out the entire css table and goes to the css body background image. I have set the background-position to center center. Jquery is resetting the image after the animation is complete to a position of left bottom. I'm looking to prevent this and keep the background image as center center.

I tried putting everything in a figure wrapper instead of in the body, that's the reason for the
 tag. When I tried this, the screen went completely white after the animation was finished.

HTML & jquery:

```<code><html>
<head lang="en">
    <link type="text/css" rel="stylesheet" href="site.css" media="screen">
    <script type="text/javascript" src="jquery.js"></script>
    <meta charset="UTF-8">
    <script>
        $(document).ready(function() {
            $(".firstFade").fadeIn(5000).delay(10000).fadeOut(7000);
            $(".secondFade").delay(6000).fadeIn(5000).delay(3000).fadeOut(1000);
            $("#tableCell5Text").delay(14500).fadeOut(1000);
            $(".container").delay(15000).fadeOut(7000);
        });
    </script>
</head>
<body>
    <figure id="pathImg">
        <div class="container" id="table">
            <div class="container containerRow" id="tableRow">
                <div class="container containerCell" id="tableCell">
                    <img src="images/img1.jpg" alt="" width="150" height="150" class="hidden firstFade" id="img1">
                </div>
            </div>
            <div class="container containerRow" id="tableRow2">
                <div class="container containerCell" id="tableCell2">
                    <img src="images/img2.png" alt="" height="85" width="77" class="hidden firstFade" id="img2">
                </div>
            </div>
            <div class="container containerRow" id="tableRow3">
                <div class="container containerCell" id="tableCell3">
                    <p class="hidden firstFade" id="tableCell3Text">some text</p>
                </div>
            </div>
            <div class="container containerRow" id="tableRow4">
                <div class="container containerCell" id="tableCell4">
                    <h2 class="hidden secondFade" id="tableCell4Text">some text</h2>
                </div>
            </div>
            <div class="container containerRow" id="containerRow5">
                <div class="container containerCell" id="containerCell5">
                    <h1 id="tableCell5Text">some text</h1>
                </div>
            </div>
    </div>
    </figure>
</body>
</code>```

CSS:

```<code>* {
  margin: 0;
  padding: 0;
}

body {
  margin: 0;
  padding: 0;
}

#pathImg {
  margin: 0;
  padding: 0;
  background-image: url(images/sunnySkies.jpg);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

.hidden {
  display: none;
}

#table {
  display: table;
  height: 100vh;
  width: 100vw;
  text-align: center;
  background-color: #ffffff;
}

.containerRow {
  display: table-row;
}

.containerCell {
  display: table-cell;
}

#tableCell {
  height: 20vh;
}

#tableCell2 {
  height:   15vh;
  vertical-align: middle;
}

#tableCell3 {
  height: 10vh;
  vertical-align: top;
}

#tableCell4 {
  height: 5vh;
  vertical-align: top;
}

#tableCell3Text {
  font-family: 'Tangerine', cursive;
  font-size: 300%;
  color: #444444;
}

#tableCell4Text {
  font-family: arial;
  color: #444444;
}

#tableCell5Text {
  font-family: arial;
  color: #444444;
}

#img1 {
  margin: 5vh 0 0 0;
  padding: 5px;
  border: 2px solid #444444;
  border-radius: 5px;
  background-color: gray;
}
</code>```

答:
It actually seems like it's working fine for me without the figure. But if you're using the figure then the problem is that you're fading out the .container which sets it to display:none which is taking out all of the height. You need to leave something on the page so that everything doesn't collapse. At the end, the body has no height and that's why you're getting a white screen. So what we'll do is get the height of the largest image and set the body to the height before you fade out.

Change your JQuery to this

```<code> $(".firstFade").fadeIn(5000).delay(10000).fadeOut(7000);
 $(".secondFade").delay(6000).fadeIn(5000).delay(3000).fadeOut(1000);
 $("#tableCell5Text").delay(14500).fadeOut(1000);
 var $height = $("#table").height();
 $("body").height($height);
 $(".container").delay(15000).fadeOut(7000);
</code>```

Body:
I'm doing a number of fadeIn's and fadeOut's with jquery. The final fade (fadeOut()) fades out the entire css table and goes to the css body background image. I have set the background-position to center center. Jquery is resetting the image after the animation is complete to a position of left bottom. I'm looking to prevent this and keep the background image as center center.

I tried putting everything in a figure wrapper instead of in the body, that's the reason for the
 tag. When I tried this, the screen went completely white after the animation was finished.

HTML & jquery:

    <link type="text/css" rel="stylesheet" href="site.css" media="screen">

    <meta charset="UTF-8">

some text

some text

some text

CSS:

* {
  margin: 0;
  padding: 0;
}

body {
  margin: 0;
  padding: 0;
}

#pathImg {
  margin: 0;
  padding: 0;
  background-image: url(images/sunnySkies.jpg);
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}

.hidden {
  display: none;
}

#table {
  display: table;
  height: 100vh;
  width: 100vw;
  text-align: center;
  background-color: #ffffff;
}

.containerRow {
  display: table-row;
}

.containerCell {
  display: table-cell;
}

#tableCell {
  height: 20vh;
}

#tableCell2 {
  height:   15vh;
  vertical-align: middle;
}

#tableCell3 {
  height: 10vh;
  vertical-align: top;
}

#tableCell4 {
  height: 5vh;
  vertical-align: top;
}

#tableCell3Text {
  font-family: 'Tangerine', cursive;
  font-size: 300%;
  color: #444444;
}

#tableCell4Text {
  font-family: arial;
  color: #444444;
}

#tableCell5Text {
  font-family: arial;
  color: #444444;
}

#img1 {
  margin: 5vh 0 0 0;
  padding: 5px;
  border: 2px solid #444444;
  border-radius: 5px;
  background-color: gray;
}

Body:
It actually seems like it's working fine for me without the figure. But if you're using the figure then the problem is that you're fading out the .container which sets it to display:none which is taking out all of the height. You need to leave something on the page so that everything doesn't collapse. At the end, the body has no height and that's why you're getting a white screen. So what we'll do is get the height of the largest image and set the body to the height before you fade out.

Change your JQuery to this

 $(".firstFade").fadeIn(5000).delay(10000).fadeOut(7000);
 $(".secondFade").delay(6000).fadeIn(5000).delay(3000).fadeOut(1000);
 $("#tableCell5Text").delay(14500).fadeOut(1000);
 var $height = $("#table").height();
 $("body").height($height);
 $(".container").delay(15000).fadeOut(7000);


问:
Display inputs to std::ostream
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

Suppose I have a method which accepts a reference to an ostream:

```<code>printAllObjects(std::ostream& os);
</code>```

I am assuming it makes changes to the ostream, so that one can print the list of all of the objects to a file, say. (I might be wrong here)

Is there any way of seeing what it writes to the ostream? (via cout preferably)?

答:
std::cout is an std::ostream, so just pass std::cout to the function and you'll see what it does:

```<code>printAllObjects(std::cout);
</code>```

This flexibility is the very purpose of accepting a reference to std::ostream!

Other stream types1 inheriting from the std::ostream base include:

std::ofstream (for file output)

std::ostringstream (for string output).

1 That's not to say that std::cout is a type; it's not. It's a special, global instance of std::ostream.

Title: Display inputs to std::ostream

Body:
Disclaimer: I am a complete C++ beginner, and if there is a similar answer to this question, please direct me to it, as I may have missed it, not knowing much in the way of theory.

Suppose I have a method which accepts a reference to an ostream:

printAllObjects(std::ostream& os);

I am assuming it makes changes to the ostream, so that one can print the list of all of the objects to a file, say. (I might be wrong here)

Is there any way of seeing what it writes to the ostream? (via cout preferably)?

Body:
std::cout is an std::ostream, so just pass std::cout to the function and you'll see what it does:

printAllObjects(std::cout);

This flexibility is the very purpose of accepting a reference to std::ostream!

Other stream types1 inheriting from the std::ostream base include:

std::ofstream (for file output)

std::ostringstream (for string output).

1 That's not to say that std::cout is a type; it's not. It's a special, global instance of std::ostream.


问:
Dagger automatically persisting data
I have a class that's being injected using DI via dagger. However when the activity is destroyed and recreated, the model class seems to contain the data automatically without me insert/repopulating the data.

```<code>public class MyApplication extends Application {

    private ExpressionFactoryComponent mExpressionFactoryComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        // Building dagger DI component
        mExpressionFactoryComponent = DaggerExpressionFactoryComponent.builder().
                expressionFactoryModule(new ExpressionFactoryModule(new ExpressionFactory(this))).build();
    }
}
</code>```

Module:

```<code>@Module
public class ExpressionFactoryModule {
    private ExpressionFactory mExpressionFactory;

    public ExpressionFactoryModule(ExpressionFactory expressionFactory) {
        this.mExpressionFactory = expressionFactory;
    }

    @Provides
    ExpressionFactory provideStringExpressionFactory() {
        return mExpressionFactory;
    }
}
</code>```

答:
The one reason for this is that ExpressionFactory is instantiated in MyApplication class and then passed into the constructor of ExpressionFactoryModule while creating ExpressionFactoryComponent. You should pass an Application instance in your module constructor and then create an instance of your class withing a metod with @Provide annotation passing that Application instance in your class's constructor.

This how things should be done with dagger. But to solve your problem you need to create another component class and build the component in an activity if you need to have an instance of your class living withing an activity only.

Here is the solution (ExpressionFactoryComponent is renamed to AppComponent here):

```<code>public class MyApplication extends Application {

    private static AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        // Building dagger DI component
        appComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this)).build();
    }

    public static AppComponent getAppComponent() {
        return appComponent;
    }
}

@Component(modules = {AppModule.class})
public interface AppComponent {

    Application getApplication();

    void inject(App application);
}

@Module
public class AppModule {

    private Application application;

    public AppModule(Application application) {
        this.application = application;
    }

    @Provides
    Application provideApplication() {
        return application;
    }
}

@Component(dependencies = AppComponent.class, modules = {
        ActivityModule.class})
public interface ActivityComponent {

    void inject(MainActivity activity);

}

@Module
public class ActivityModule {

    private Activity activity;

    public ActivityModule(Activity activity) {
        this.activity = activity;
    }

    @Provides
    Activity provideActivity() {
        return activity;
    }

    @Provides
    ExpressionFactory provideStringExpressionFactory(Application application) {
        return new ExpressionFactory(application);
    }

}

public class MainActivity extends AppCompatActivity{

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

        ActivityComponent activityComponent = DaggerActivityComponent.builder()
                    .activityModule(new ActivityModule(activity))
                    .appComponent(App.getAppComponent())
                    .build();

        activityComponent.inject(this);

    }

}
</code>```

Title: Dagger automatically persisting data

Body:
I have a class that's being injected using DI via dagger. However when the activity is destroyed and recreated, the model class seems to contain the data automatically without me insert/repopulating the data.

public class MyApplication extends Application {

    private ExpressionFactoryComponent mExpressionFactoryComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        // Building dagger DI component
        mExpressionFactoryComponent = DaggerExpressionFactoryComponent.builder().
                expressionFactoryModule(new ExpressionFactoryModule(new ExpressionFactory(this))).build();
    }
}

Module:

@Module
public class ExpressionFactoryModule {
    private ExpressionFactory mExpressionFactory;

    public ExpressionFactoryModule(ExpressionFactory expressionFactory) {
        this.mExpressionFactory = expressionFactory;
    }

    @Provides
    ExpressionFactory provideStringExpressionFactory() {
        return mExpressionFactory;
    }
}

Body:
The one reason for this is that ExpressionFactory is instantiated in MyApplication class and then passed into the constructor of ExpressionFactoryModule while creating ExpressionFactoryComponent. You should pass an Application instance in your module constructor and then create an instance of your class withing a metod with @Provide annotation passing that Application instance in your class's constructor.

This how things should be done with dagger. But to solve your problem you need to create another component class and build the component in an activity if you need to have an instance of your class living withing an activity only.

Here is the solution (ExpressionFactoryComponent is renamed to AppComponent here):

public class MyApplication extends Application {

    private static AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();

        // Building dagger DI component
        appComponent = DaggerAppComponent.builder()
                .appModule(new AppModule(this)).build();
    }

    public static AppComponent getAppComponent() {
        return appComponent;
    }
}

@Component(modules = {AppModule.class})
public interface AppComponent {

    Application getApplication();

    void inject(App application);
}

@Module
public class AppModule {

    private Application application;

    public AppModule(Application application) {
        this.application = application;
    }

    @Provides
    Application provideApplication() {
        return application;
    }
}

@Component(dependencies = AppComponent.class, modules = {
        ActivityModule.class})
public interface ActivityComponent {

    void inject(MainActivity activity);

}

@Module
public class ActivityModule {

    private Activity activity;

    public ActivityModule(Activity activity) {
        this.activity = activity;
    }

    @Provides
    Activity provideActivity() {
        return activity;
    }

    @Provides
    ExpressionFactory provideStringExpressionFactory(Application application) {
        return new ExpressionFactory(application);
    }

}

public class MainActivity extends AppCompatActivity{

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

        ActivityComponent activityComponent = DaggerActivityComponent.builder()
                    .activityModule(new ActivityModule(activity))
                    .appComponent(App.getAppComponent())
                    .build();

        activityComponent.inject(this);

    }

}


问:
Azure IoT Hub via REST results in Unauthorized
I try to call some HTTP GET calls to the device twins of the MS Azure IoT Hub.

HTTP GET call via Postman

As you can see the GET call results in an unauthorized IoTHubUnauthorizedAccess error code.

I generated the token for the authorization header with the Azure Device Explorer as you can see in the picture below.

Generated SAS Token

Anyone any idea about this? I already searched here, and the only topic did not help me.

答:
You can use the Postman Pre-request script sandbox to generate the SAS token. Here's a blog post I wrote that details everything you need to do to generate the SAS token. http://blog.jongallant.com/2017/02/azure-iot-hub-device-twin-rest-apis-postman-newman/

Here's a Postman collection that will show you exactly how to execute the APIs: https://www.getpostman.com/collections/84a38008cd07accf565e

Here are more Postman / Azure related Posts (also my own):
http://blog.jongallant.com/tags/postman/

Here's the code that I use in the Pre-request script sandbox:

```<code>var resourceName = postman.getEnvironmentVariable("resourceName");
var resourceKey = postman.getEnvironmentVariable("resourceKey");
var tokenExpirationPeriod = postman.getEnvironmentVariable("tokenExpirationPeriod");
var policyKeyName = postman.getEnvironmentVariable("policyKeyName");

postman.clearEnvironmentVariable("deviceTwinSasToken"); // clear out token on first run.

// See this doc for details: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security
var resourceUri = encodeURIComponent(resourceName + '.azure-devices.net'); // The resource uri
var expiry = Math.ceil((Date.now() / 1000) + tokenExpirationPeriod * 60); // Expire the token 60 minutes from now
var uriExpiry = resourceUri + '\n' + expiry; // this is the string format to gen signature from
var decodedKey = CryptoJS.enc.Base64.parse(resourceKey); // The SHA256 key is the Base64 decoded version of the IoT Hub key
var signature = CryptoJS.HmacSHA256(uriExpiry, decodedKey); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature

// Construct authorization string (shared access signature)
var deviceTwinSasToken = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expiry;

// Add token if one is present
if (policyKeyName) {
    deviceTwinSasToken += "&skn="+ policyKeyName;
}

// Put in variable to be used in other requests.
postman.setEnvironmentVariable("deviceTwinSasToken", deviceTwinSasToken);

console.log("Shared Access Signature:" + postman.getEnvironmentVariable("deviceTwinSasToken"));
</code>```

Body:
You can use the Postman Pre-request script sandbox to generate the SAS token. Here's a blog post I wrote that details everything you need to do to generate the SAS token. http://blog.jongallant.com/2017/02/azure-iot-hub-device-twin-rest-apis-postman-newman/

Here's a Postman collection that will show you exactly how to execute the APIs: https://www.getpostman.com/collections/84a38008cd07accf565e

Here are more Postman / Azure related Posts (also my own):
http://blog.jongallant.com/tags/postman/

Here's the code that I use in the Pre-request script sandbox:

var resourceName = postman.getEnvironmentVariable("resourceName");
var resourceKey = postman.getEnvironmentVariable("resourceKey");
var tokenExpirationPeriod = postman.getEnvironmentVariable("tokenExpirationPeriod");
var policyKeyName = postman.getEnvironmentVariable("policyKeyName");

postman.clearEnvironmentVariable("deviceTwinSasToken"); // clear out token on first run.

// See this doc for details: https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-security
var resourceUri = encodeURIComponent(resourceName + '.azure-devices.net'); // The resource uri
var expiry = Math.ceil((Date.now() / 1000) + tokenExpirationPeriod * 60); // Expire the token 60 minutes from now
var uriExpiry = resourceUri + '\n' + expiry; // this is the string format to gen signature from
var decodedKey = CryptoJS.enc.Base64.parse(resourceKey); // The SHA256 key is the Base64 decoded version of the IoT Hub key
var signature = CryptoJS.HmacSHA256(uriExpiry, decodedKey); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature

// Construct authorization string (shared access signature)
var deviceTwinSasToken = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expiry;

// Add token if one is present
if (policyKeyName) {
    deviceTwinSasToken += "&skn="+ policyKeyName;
}

// Put in variable to be used in other requests.
postman.setEnvironmentVariable("deviceTwinSasToken", deviceTwinSasToken);

console.log("Shared Access Signature:" + postman.getEnvironmentVariable("deviceTwinSasToken"));


问:
Removing an object is causing freezes
[For clarification, 'monsters' is a list of NPCs that when shot by an object 'bullet' are removed from the list. ]

Error at start:

```<code>W/System.err: java.util.ConcurrentModificationException
W/System.err:     at java.util.ArrayList$Itr.next(ArrayList.java:831)
W/System.err:     at com.companyname.product.GameplayScene.update(GameplayScene.java:113)
//...
</code>```

I believe this means that it is trying to perform an action on something in the list that isn't there. So my question is could I please get some help identifying the point where an object is being called that isn't there, as I can't seem to find it. I know which class it is in as the first line references it for each error.

```<code>        for (Bullet bullet : player.getList())
            if (npcManager.bulletCollide(bullet)) { //checks for a collision between all npcs and all bullets
                 player.getList().remove(bullet);//npc is removed in method above

        }

       if (!gameOver) {
        npcManager.update(); //updates movement of npcs
        if (npcManager.playerCollideNPC(player)) {
            //end game
        }
    }

    for (RectNPC NPC : npcManager.getList())
        if (obstacleManager.NPCCollide(NPC)) { //checks collision between npcs and other objects
            //
        }

        int i = 0;
        //checks collisions between NPCs themselves
        while (i < (Constants.NUMBER_ENEMIES - 1)) {
            if (npcManager.getList().size() <= 1)
                return;
            if (Rect.intersects(npcManager.getList().get(i).getRectangle(), npcManager.getList().get(i + 1).getRectangle()))
                npcManager.getList().get(i).setRectangle(200);
            i += 1;
        }
    }
</code>```

(Above) I imagine the issue will be with calling something in the update (shown above) where the object is no longer available, is there an issue with any of how I am removing the NPCs?

```<code> public boolean bulletCollide(Bullet bullet) {
    for(RectNPC npc : monsters) {
        if(npc.bulletCollideNPC(bullet)) {
            monsters.remove(npc);
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }
    return false;
}
</code>```

(Above) Code where I am removing the NPC, I've included incase it is helpful - however it does do what it's meant to so I don't believe this is the problem.

My main question is, is there anything here that would be causing this error (the game stopping for a few frames and giving the error at the top) - or is there something/somewhere else in specific I should be looking at? Also I know some of my syntax isn't great, I apologise it's my first Java project.

Current Iterators:

```<code>for(Iterator<RectNPC> iterator = monsters.iterator(); iterator.hasNext();) {
        if(iterator.next().bulletCollideNPC(bullet)) {
            iterator.remove();
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }
</code>```

and

```<code>for (Iterator<Bullet> iterator = player.getList().iterator(); iterator.hasNext(); ) {
            if (npcManager.bulletCollide(iterator.next())) {
                iterator.remove();
                //
            }
        }
</code>```

答:
Your method is doing 3 different things.  It's returning a boolean, removing an element from a list, and then adding an element.  I would restructure the code so that you have 3 methods that do only 1 thing.

You can use the power of Java 8's internal iterator, as a starting point

```<code>      monsters.removeIf(e -> e.bulletCollideNPC(bullet));
</code>```

Title: Removing an object is causing freezes

Body:
[For clarification, 'monsters' is a list of NPCs that when shot by an object 'bullet' are removed from the list. ]

Error at start:

W/System.err: java.util.ConcurrentModificationException
W/System.err:     at java.util.ArrayList$Itr.next(ArrayList.java:831)
W/System.err:     at com.companyname.product.GameplayScene.update(GameplayScene.java:113)
//...

I believe this means that it is trying to perform an action on something in the list that isn't there. So my question is could I please get some help identifying the point where an object is being called that isn't there, as I can't seem to find it. I know which class it is in as the first line references it for each error.

        for (Bullet bullet : player.getList())
            if (npcManager.bulletCollide(bullet)) { //checks for a collision between all npcs and all bullets
                 player.getList().remove(bullet);//npc is removed in method above

        }

       if (!gameOver) {
        npcManager.update(); //updates movement of npcs
        if (npcManager.playerCollideNPC(player)) {
            //end game
        }
    }

    for (RectNPC NPC : npcManager.getList())
        if (obstacleManager.NPCCollide(NPC)) { //checks collision between npcs and other objects
            //
        }

        int i = 0;
        //checks collisions between NPCs themselves
        while (i < (Constants.NUMBER_ENEMIES - 1)) {
            if (npcManager.getList().size() <= 1)
                return;
            if (Rect.intersects(npcManager.getList().get(i).getRectangle(), npcManager.getList().get(i + 1).getRectangle()))
                npcManager.getList().get(i).setRectangle(200);
            i += 1;
        }
    }

(Above) I imagine the issue will be with calling something in the update (shown above) where the object is no longer available, is there an issue with any of how I am removing the NPCs?

 public boolean bulletCollide(Bullet bullet) {
    for(RectNPC npc : monsters) {
        if(npc.bulletCollideNPC(bullet)) {
            monsters.remove(npc);
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }
    return false;
}

(Above) Code where I am removing the NPC, I've included incase it is helpful - however it does do what it's meant to so I don't believe this is the problem.

My main question is, is there anything here that would be causing this error (the game stopping for a few frames and giving the error at the top) - or is there something/somewhere else in specific I should be looking at? Also I know some of my syntax isn't great, I apologise it's my first Java project.

Current Iterators:

for(Iterator<RectNPC> iterator = monsters.iterator(); iterator.hasNext();) {
        if(iterator.next().bulletCollideNPC(bullet)) {
            iterator.remove();
            monsters.add(0, new RectNPC(new Rect(100, 100, 200, 200), Color.rgb(255, 0, 0), 25));
            return true;
        }
    }

and

for (Iterator<Bullet> iterator = player.getList().iterator(); iterator.hasNext(); ) {
            if (npcManager.bulletCollide(iterator.next())) {
                iterator.remove();
                //
            }
        }

Body:
Your method is doing 3 different things.  It's returning a boolean, removing an element from a list, and then adding an element.  I would restructure the code so that you have 3 methods that do only 1 thing.

You can use the power of Java 8's internal iterator, as a starting point

      monsters.removeIf(e -> e.bulletCollideNPC(bullet));


问:
Why is my SessionIDManager child class not being asked to CreateSessionID?
I have implemented a web app using session state management as per the instructions found on:

http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx

http://en.aspnet-bhs.info/post/State-Server-Partitioning.aspx

My SessionIDManager inheritor includes the code:

```<code>public class SessionIdManager : System.Web.SessionState.SessionIDManager
{
    public override string CreateSessionID(System.Web.HttpContext context)
{...}
</code>```

My web.config includes the code:

```<code><machineKey
          validationKey="1234567890123456789012345678901234567890AAAAAAAAAA"
          decryptionKey="123456789012345678901234567890123456789012345678"
          validation="SHA1"
          decryption="Auto"
        />
...
<sessionState
            mode="StateServer"
            partitionResolverType="PartitionResolver"
            sessionIDManagerType="SessionIdManager"
            cookieless="false"
            timeout="20"
            />
</code>```

But the CreateSessionID method never gets called and so the session IDs do not get amended with the appropriate server ID.

Can someone tell me what is going on or what I might also need to consider that isn't mentioned in the articles?

I am using .NET2 with VS2k5.

Thanks,

Matt.

答: In the Validate(string id) function, you should always return true if you don't want the ASP framework to create a new session.

Body:
I have implemented a web app using session state management as per the instructions found on:

http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx

http://en.aspnet-bhs.info/post/State-Server-Partitioning.aspx

My SessionIDManager inheritor includes the code:

public class SessionIdManager : System.Web.SessionState.SessionIDManager
{
    public override string CreateSessionID(System.Web.HttpContext context)
{...}

My web.config includes the code:

<machineKey
          validationKey="1234567890123456789012345678901234567890AAAAAAAAAA"
          decryptionKey="123456789012345678901234567890123456789012345678"
          validation="SHA1"
          decryption="Auto"
        />
...
<sessionState
            mode="StateServer"
            partitionResolverType="PartitionResolver"
            sessionIDManagerType="SessionIdManager"
            cookieless="false"
            timeout="20"
            />

But the CreateSessionID method never gets called and so the session IDs do not get amended with the appropriate server ID.

Can someone tell me what is going on or what I might also need to consider that isn't mentioned in the articles?

I am using .NET2 with VS2k5.

Thanks,

Matt.


问:
How to assign an initial value to Subject RxJS observable?
I'm developing an Angular 2 app, I need make changeable the order of my columns in a List, clicking on the title (as data-table works) and I get an idea from Angularfire 2 documentation examples, here is my code: (grupos.component.ts)

```<code>import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable    }  from 'angularfire2';
import { Subject } from 'rxjs/Subject';
import {AF} from "../providers/af";
import { Router } from "@angular/router";
{ EditGpoComponent } from '../edit-gpo/edit-gpo.component';

@Component({
  selector: 'app-grupos',
  templateUrl: './grupos.component.html',
  styleUrls: ['./grupos.component.css']
})

export class GruposComponent implements OnInit {
  public newMessage: string;
  eventos: FirebaseListObservable<any[]>;
  sizeSubject: Subject <any>;

 constructor( af: AngularFire, private router: Router ) {
    this.sizeSubject = new Subject();
    this.eventos = af.database.list('/eventos', {
          query: {
           orderByChild: this.sizeSubject

          }
        });
  }

  filterBy(size: string) {
   this.sizeSubject.next(size);

   }

  editaGrupo(keyGrupo){

    this.router.navigate(['/add-gpo']);
  }

  ngOnInit() {

  }

}
</code>```

Here is the code of my Grupos.components.html :

```<code><div class="container">

<br><br><br>
  <div class="row">
  <a href="#" class="btn btn-info" routerLink="/add-gpo">+Add New Event</a>
  <br><br>
   <table class="table table-striped">
   <thead>
   <tr>
    <th><button (click)="filterBy('evento')">EVENT</button></th>
    <th><button (click)="filterBy('arrival')">ARRIVAL</button></th>
    <th><button (click)="filterBy('departure')">DEPARTURE</button></th>
    <th><button (click)="filterBy('hotel')">VENUE</button></th>
    <th><button (click)="filterBy('pax')">PAX</button></th>
    <th>FUNCTIONS</th>
    </tr>
   </thead>
   <tbody>
   <tr *ngFor="let evento of eventos | async ">
        <td>{{evento.evento}}</td>
        <td>{{evento.arrival}}</td>
        <td>{{evento.departure}}</td>
      <td>{{evento.hotel}}</td>
      <td>{{evento.pax}}</td>
      <td style="font-size: 1.2em">
      <a href="#" [routerLink]="['/editGpo']" [queryParams]="{eveId: evento.$key}"><span class="glyphicon glyphicon-edit" aria-hidden="true" title="edit event"></span></a>
      <a href="#"><span class="glyphicon glyphicon-user" aria-hidden="true" title="attendees"></span></a>
      <a href="#"><span class="glyphicon glyphicon-bullhorn" aria-hidden="true" title="speakers"></span></a>
      <a href="#"><span class="glyphicon glyphicon-trash glyphicon " aria-hidden="true" title="delete event"></span></a>

      </td>
    </tr>
    </tbody>

</table>
</div>
</div>
</code>```

As you see its working pretty cool, every time I click on the column Title Button, my table get the order of that column. But I have been searching for hours on how to give an initial value to "sizeSubject" (Subject), I like to assign the value on "evento", so the table appears ordered by evento as I show it. By now just show me the Button titles and the table in blank, and If I click on any button, it show me the table in that order.

Any tips, or comments will be appreciate !

答:
If you want a Subject that has an 'initial value', a better RxJS class to use is BehaviorSubject.

With BehaviorSubject, you pass your initial value into its constructor.

Body:
I'm developing an Angular 2 app, I need make changeable the order of my columns in a List, clicking on the title (as data-table works) and I get an idea from Angularfire 2 documentation examples, here is my code: (grupos.component.ts)

import { Component, OnInit } from '@angular/core';
import { AngularFire, FirebaseListObservable, FirebaseObjectObservable    }  from 'angularfire2';
import { Subject } from 'rxjs/Subject';
import {AF} from "../providers/af";
import { Router } from "@angular/router";
{ EditGpoComponent } from '../edit-gpo/edit-gpo.component';

@Component({
  selector: 'app-grupos',
  templateUrl: './grupos.component.html',
  styleUrls: ['./grupos.component.css']
})

export class GruposComponent implements OnInit {
  public newMessage: string;
  eventos: FirebaseListObservable<any[]>;
  sizeSubject: Subject <any>;

 constructor( af: AngularFire, private router: Router ) {
    this.sizeSubject = new Subject();
    this.eventos = af.database.list('/eventos', {
          query: {
           orderByChild: this.sizeSubject

          }
        });
  }

  filterBy(size: string) {
   this.sizeSubject.next(size);

   }

  editaGrupo(keyGrupo){

    this.router.navigate(['/add-gpo']);
  }

  ngOnInit() {

  }

}

Here is the code of my Grupos.components.html :

  +Add New Event

    <button (click)="filterBy('evento')">EVENT</button>
    <button (click)="filterBy('arrival')">ARRIVAL</button>
    <button (click)="filterBy('departure')">DEPARTURE</button>
    <button (click)="filterBy('hotel')">VENUE</button>
    <button (click)="filterBy('pax')">PAX</button>
    FUNCTIONS

        {{evento.evento}}
        {{evento.arrival}}
        {{evento.departure}}
      {{evento.hotel}}
      {{evento.pax}}

As you see its working pretty cool, every time I click on the column Title Button, my table get the order of that column. But I have been searching for hours on how to give an initial value to "sizeSubject" (Subject), I like to assign the value on "evento", so the table appears ordered by evento as I show it. By now just show me the Button titles and the table in blank, and If I click on any button, it show me the table in that order.

Any tips, or comments will be appreciate !


问:
How do I resolve the "'mathfilter' tag 'addition' stopped working since replicating django project" error?
Recently I moved a Django Project to a new virtual environment. Everything appears to be working fine, with the exception of the following error:

```<code>TemplateSyntaxError at /profile/

Invalid filter: 'addition'

Request Method:     GET
Request URL:    http://example.com/example/
Django Version:     1.9.12
Exception Type:     TemplateSyntaxError
Exception Value:

Invalid filter: 'addition'

Exception Location:     /opt/example/local/lib/python2.7/site-packages/django/template/base.py in parse, line 516
Python Executable:  /usr/local/bin/uwsgi
Python Version:     2.7.3
</code>```

I narrowed this down to this line of code:

```<code> {% with deeb_percent=stat.deeb_base|addition:stat.deeb_deal %}
</code>```

Further investigation and I found this: https://github.com/dbrgn/django-mathfilters , it appears 'addition' is a custom filter which is part of mathfilters. The documentation I linked says to run:

```<code>pip install django-mathfilters
</code>```

I have checked with pip freeze, and mathfilters is installed.

```<code>appdirs==1.4.3
backports.ssl-match-hostname==3.5.0.1
beautifulsoup4==4.5.3
Django==1.9.12
django-appconf==1.0.1
django-autocomplete-light==3.2.1
django-compat==1.0.8
django-compressor==1.6
django-dual-authentication==1.0.0
django-hijack==2.0.1
django-htmlmin==0.8.0
django-ipware==1.1.2
django-mathfilters==0.3.0
django-modelcluster==3.0.1
django-taggit==0.22.0
django-treebeard==4.1.0
django-widget-tweaks==1.4.1
djangorestframework==3.6.2
html5lib==0.9999999
packaging==16.8
Pillow==3.0.0
pyparsing==2.2.0
pytz==2015.7
requests==2.13.0
simplejson==3.10.0
six==1.10.0
slackclient==1.0.5
Unidecode==0.4.20
wagtail==1.9
websocket-client==0.40.0
Willow==0.4
</code>```

Then add mathfilters to your INSTALLED_APPS.

I have also checked INSTALLED_APPS in the project settings.py and mathfilters is also loaded:

```<code>INSTALLED_APPS = [
...
'mathfilters',
...

]
</code>```

At the top of the template in question 'mathfilters' is loaded:

```<code>{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load extra %}
{% load mathfilters %}
</code>```

If i change 'addition' in the template to 'add' the template works ok.

```<code>{% with deeb_percent=stat.deeb_base|addition:stat.deeb_deal %}
</code>```

But I don't want to do this for every single template in multiple places, and also am uncomfortable leaving this 'broken' since I installed the project in a new virtualenv.

Why aren't the mathfilters working? and how can I resolve this error?

答:
https://github.com/dbrgn/django-mathfilters

addition – replacement for the add filter with support for float /
  decimal types

Update to mathfilter to 0.4.0, things will be back to normal

Body:
Recently I moved a Django Project to a new virtual environment. Everything appears to be working fine, with the exception of the following error:

TemplateSyntaxError at /profile/

Invalid filter: 'addition'

Request Method:     GET
Request URL:    http://example.com/example/
Django Version:     1.9.12
Exception Type:     TemplateSyntaxError
Exception Value:

Invalid filter: 'addition'

Exception Location:     /opt/example/local/lib/python2.7/site-packages/django/template/base.py in parse, line 516
Python Executable:  /usr/local/bin/uwsgi
Python Version:     2.7.3

I narrowed this down to this line of code:

 {% with deeb_percent=stat.deeb_base|addition:stat.deeb_deal %}

Further investigation and I found this: https://github.com/dbrgn/django-mathfilters , it appears 'addition' is a custom filter which is part of mathfilters. The documentation I linked says to run:

pip install django-mathfilters

I have checked with pip freeze, and mathfilters is installed.

appdirs==1.4.3
backports.ssl-match-hostname==3.5.0.1
beautifulsoup4==4.5.3
Django==1.9.12
django-appconf==1.0.1
django-autocomplete-light==3.2.1
django-compat==1.0.8
django-compressor==1.6
django-dual-authentication==1.0.0
django-hijack==2.0.1
django-htmlmin==0.8.0
django-ipware==1.1.2
django-mathfilters==0.3.0
django-modelcluster==3.0.1
django-taggit==0.22.0
django-treebeard==4.1.0
django-widget-tweaks==1.4.1
djangorestframework==3.6.2
html5lib==0.9999999
packaging==16.8
Pillow==3.0.0
pyparsing==2.2.0
pytz==2015.7
requests==2.13.0
simplejson==3.10.0
six==1.10.0
slackclient==1.0.5
Unidecode==0.4.20
wagtail==1.9
websocket-client==0.40.0
Willow==0.4

Then add mathfilters to your INSTALLED_APPS.

I have also checked INSTALLED_APPS in the project settings.py and mathfilters is also loaded:

INSTALLED_APPS = [
...
'mathfilters',
...

]

At the top of the template in question 'mathfilters' is loaded:

{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% load extra %}
{% load mathfilters %}

If i change 'addition' in the template to 'add' the template works ok.

{% with deeb_percent=stat.deeb_base|addition:stat.deeb_deal %}

But I don't want to do this for every single template in multiple places, and also am uncomfortable leaving this 'broken' since I installed the project in a new virtualenv.

Why aren't the mathfilters working? and how can I resolve this error?