问:
Position child mesh based on local vectors in Three.js
I need help positioning mesh to specific points that are given according to local coordinates. I created pink cylinders with height 0.1 to demonstrate my local points of cubes that I want to make touch each other.

Also I want cube2 to be a child of cube1, but that is not a deal breaker for a moment.

Expected result: Cubes are touching with their specific corners and in proper rotation - pink cylinders should be pixel perfect covering each other.

I tried to solve it with:

```<code>cube2.position.copy(cube_position.clone().add(cube2_position))
cube2.rotation.setFromVector3(cube_rotation.clone().add(cube2_rotation))
</code>```

But that's not working like expected. Should I use some kind of Matrix transform?

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(25, 25, 12);
// setup cubes

var geometry = new THREE.CubeGeometry(6, 6, 6);
var material = new THREE.MeshLambertMaterial({
  color: 0x00fff0
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

cube.position.set(0.3, 1, -2);
cube.rotation.set(Math.PI / 3, Math.PI / 2, 1)

var geometry2 = new THREE.CubeGeometry(4, 4, 4);
var material2 = new THREE.MeshLambertMaterial({
  color: 0x0fff00
});
var cube2 = new THREE.Mesh(geometry2, material2);
cube.add(cube2);

cube_position = new THREE.Vector3(3, 3, 3)
cube_rotation = new THREE.Vector3(Math.PI / 3, Math.PI / 4, 0)
cube2_position = new THREE.Vector3(2, -2, 2)
cube2_rotation = new THREE.Vector3(Math.PI / 2, Math.PI / 2, 0)

// visualize points
vmat = new THREE.MeshLambertMaterial({
  color: 0xFF00FF,
  opacity: 0.5,
  transparent: true
});
v1 = new THREE.Mesh(new THREE.CylinderGeometry(1, 1, 0.1, 10), vmat);
cube.add(v1)
v1.position.copy(cube_position)
v1.rotation.setFromVector3(cube_rotation)

v2 = new THREE.Mesh(new THREE.CylinderGeometry(1, 1, 0.1, 10), vmat);
cube2.add(v2)
v2.position.copy(cube2_position)
v2.rotation.setFromVector3(cube2_rotation)

// BUG: connect cube with cube2 on specified points

cube2.position.copy(cube_position.clone().add(cube2_position))
cube2.rotation.setFromVector3(cube_rotation.clone().add(cube2_rotation))

// setup rest
var pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight)

const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x20252f);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

const controls = new THREE.OrbitControls(camera, renderer.domElement);

animate();

function animate() {
  requestAnimationFrame(animate);
  render();
}

function render() {
  renderer.render(scene, camera);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r82/three.js"></script>
<script src="https://yume.human-interactive.org/examples/buffer-geometry/OrbitControls.js"></script></code>```

答:
So, Matrix is really powerful to solve rotation problems. I flow two steps to set the cube2 rotation and position properly.

Rotation

The relationship between cube1,cube2,v1,v2 is:

What we want is v2 world rotation equals to v1 opposite world rotation. When two objects have same rotation, they have same rotation matrix(world matrix). We have these formulae:

```<code>V1opposite.w = V2.w
V1opposite.l * C1.w = V2.l * C2.l * C1.l
V1opposite.l = V2.l * C2.l
C2.l = V1opposite.l * V2.l(-1)
</code>```

Where V1opposite.w means v1 opposite world matrix, V2.w is v2 world matrix, C means cube, V2.l(-1) means the inverse matrix of v2 local matrix. now, we can calculate the cube2 rotation matrix.

Position

What we need is making v1 and v2 world position same. Here is a graph to show the coordinate space:
Because v2 is a child of cube2, we need to move cube2. In the world space, we should translate the cube2 a distance from v2 to v1, now we get the cube2 world position, cube2 is a child of cube1, just apply the inverse matrix of cube1 to get the cube2 local position.

Here is a jsfiddle example.

Wish it helps.

Update

I wrote a function, you can use it without v1 and v2.

```<code>//connect obj1 and obj2 on obj1's point1 and obj2's point2.
function connect(obj1,obj2,point1,point2)
{
    var point1World = new THREE.Vector3().copy(point1).applyMatrix4(obj1.matrixWorld);
    var point2World = new THREE.Vector3().copy(point2).applyMatrix4(obj2.matrixWorld);
    var translation = new THREE.Vector3().subVectors(point1World,point2World);
    var obj2World = new THREE.Vector3().copy(obj2.getWorldPosition());
    obj2World.add(translation);
    if(obj2.parent !== null)
    {
        var inverseMatrix = new THREE.Matrix4().getInverse(obj2.parent.matrixWorld);
        obj2World.applyMatrix4(inverseMatrix);
    }
    obj2.position.copy(obj2World);
}
</code>```

I also add a grandfather cube to contain cube1 and cube2.
jsfiddle

Body:
I need help positioning mesh to specific points that are given according to local coordinates. I created pink cylinders with height 0.1 to demonstrate my local points of cubes that I want to make touch each other.

Also I want cube2 to be a child of cube1, but that is not a deal breaker for a moment.

Expected result: Cubes are touching with their specific corners and in proper rotation - pink cylinders should be pixel perfect covering each other.

I tried to solve it with:

cube2.position.copy(cube_position.clone().add(cube2_position))
cube2.rotation.setFromVector3(cube_rotation.clone().add(cube2_rotation))

But that's not working like expected. Should I use some kind of Matrix transform?

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(25, 25, 12);
// setup cubes

var geometry = new THREE.CubeGeometry(6, 6, 6);
var material = new THREE.MeshLambertMaterial({
  color: 0x00fff0
});
var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

cube.position.set(0.3, 1, -2);
cube.rotation.set(Math.PI / 3, Math.PI / 2, 1)

var geometry2 = new THREE.CubeGeometry(4, 4, 4);
var material2 = new THREE.MeshLambertMaterial({
  color: 0x0fff00
});
var cube2 = new THREE.Mesh(geometry2, material2);
cube.add(cube2);

cube_position = new THREE.Vector3(3, 3, 3)
cube_rotation = new THREE.Vector3(Math.PI / 3, Math.PI / 4, 0)
cube2_position = new THREE.Vector3(2, -2, 2)
cube2_rotation = new THREE.Vector3(Math.PI / 2, Math.PI / 2, 0)

// visualize points
vmat = new THREE.MeshLambertMaterial({
  color: 0xFF00FF,
  opacity: 0.5,
  transparent: true
});
v1 = new THREE.Mesh(new THREE.CylinderGeometry(1, 1, 0.1, 10), vmat);
cube.add(v1)
v1.position.copy(cube_position)
v1.rotation.setFromVector3(cube_rotation)

v2 = new THREE.Mesh(new THREE.CylinderGeometry(1, 1, 0.1, 10), vmat);
cube2.add(v2)
v2.position.copy(cube2_position)
v2.rotation.setFromVector3(cube2_rotation)

// BUG: connect cube with cube2 on specified points

cube2.position.copy(cube_position.clone().add(cube2_position))
cube2.rotation.setFromVector3(cube_rotation.clone().add(cube2_rotation))

// setup rest
var pointLight = new THREE.PointLight(0xFFFFFF);
pointLight.position.x = 10;
pointLight.position.y = 50;
pointLight.position.z = 130;
scene.add(pointLight)

const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x20252f);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);

const controls = new THREE.OrbitControls(camera, renderer.domElement);

animate();

function animate() {
  requestAnimationFrame(animate);
  render();
}

function render() {
  renderer.render(scene, camera);
}

Body:
So, Matrix is really powerful to solve rotation problems. I flow two steps to set the cube2 rotation and position properly.

Rotation

The relationship between cube1,cube2,v1,v2 is:

What we want is v2 world rotation equals to v1 opposite world rotation. When two objects have same rotation, they have same rotation matrix(world matrix). We have these formulae:

V1opposite.w = V2.w
V1opposite.l * C1.w = V2.l * C2.l * C1.l
V1opposite.l = V2.l * C2.l
C2.l = V1opposite.l * V2.l(-1)

Where V1opposite.w means v1 opposite world matrix, V2.w is v2 world matrix, C means cube, V2.l(-1) means the inverse matrix of v2 local matrix. now, we can calculate the cube2 rotation matrix.

Position

What we need is making v1 and v2 world position same. Here is a graph to show the coordinate space:
Because v2 is a child of cube2, we need to move cube2. In the world space, we should translate the cube2 a distance from v2 to v1, now we get the cube2 world position, cube2 is a child of cube1, just apply the inverse matrix of cube1 to get the cube2 local position.

Here is a jsfiddle example.

Wish it helps.

Update

I wrote a function, you can use it without v1 and v2.

//connect obj1 and obj2 on obj1's point1 and obj2's point2.
function connect(obj1,obj2,point1,point2)
{
    var point1World = new THREE.Vector3().copy(point1).applyMatrix4(obj1.matrixWorld);
    var point2World = new THREE.Vector3().copy(point2).applyMatrix4(obj2.matrixWorld);
    var translation = new THREE.Vector3().subVectors(point1World,point2World);
    var obj2World = new THREE.Vector3().copy(obj2.getWorldPosition());
    obj2World.add(translation);
    if(obj2.parent !== null)
    {
        var inverseMatrix = new THREE.Matrix4().getInverse(obj2.parent.matrixWorld);
        obj2World.applyMatrix4(inverseMatrix);
    }
    obj2.position.copy(obj2World);
}

I also add a grandfather cube to contain cube1 and cube2.
jsfiddle


来源: stackexchange

问:
How to control memory usage in multithreading?
I am using multi thread to process image.

It works fine on my computer that has enough memory (increase 2~3 GB when processing many images), but my server only has 1GB memory and the code not work properly.

Sometimes end with Segmentation fault, sometimes:

```<code>Exception in thread Thread-13:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "passportRecognizeNew.py", line 267, in doSomething
  ...
</code>```

Code:

```<code>import threading

def doSomething(image):
    # picture processing code
    print("processing over")

threads = []

for i in range(20):
    thread = threading.Thread(target=doSomething, args=("image",))
    threads.append(thread)

for t in threads:
    t.setDaemon(True)
    t.start()

t.join()

print("All over")
</code>```

How to solve this or any way to control memory usage?

答:
I think you are looking at this from the wrong angle. Your code fires up n threads. Those threads then execute work that you defined for them.

If that work requires them to allocate a lot of memory - what should anything "outside" of that context do about this? What should happen? Should some of the threads be killed? Should somewhere, deep down in C code a malloc ... not happen ... and then?

What I am saying is: your problem is most likely, that you are simply firing up too many of those threads.

Thus the answer is: don't try to fix things after you broke them - better make sure you do not break them at all:

do careful profiling, to understand your application; so you can asses how much memory a single thread requires to get its "work" done

then change your "main" program to query the hardware it is running on (like: check for available memory and number of physical CPUs that are available)

and based on that assessment, start that number of threads that should work given the aforementioned hardware details

Beyond that: this is very common pattern. The developer has a "powerful" machine he is working on; and he implicitly assumes that any target system running his product will have the same or better characteristics. And that is simply not true.

In other words: when you don't know how the hardware looks like your code is running on - then there is only one reasonable thing to do: first acquire that knowledge. To afterwards do different things, based on real data.

ContentLicense: CC BY-SA 3.0

Body:
I am using multi thread to process image.

It works fine on my computer that has enough memory (increase 2~3 GB when processing many images), but my server only has 1GB memory and the code not work properly.

Sometimes end with Segmentation fault, sometimes:

Exception in thread Thread-13:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "passportRecognizeNew.py", line 267, in doSomething
  ...

Code:

import threading

def doSomething(image):
    # picture processing code
    print("processing over")

threads = []

for i in range(20):
    thread = threading.Thread(target=doSomething, args=("image",))
    threads.append(thread)

for t in threads:
    t.setDaemon(True)
    t.start()

t.join()

print("All over")

How to solve this or any way to control memory usage?


问:
PLSQL script not working with passing multiple values into IN() caluse
I am very new in PLSQL, i want to pass an array of number into IN() clause value, But Sqldeveloper throw following error messages:

```<code>Error report -
ORA-06550: line 11, column 60:
PLS-00382: expression is of wrong type
ORA-06550: line 11, column 53:
PL/SQL: ORA-22905: cannot access rows from a non-nested table item
ORA-06550: line 10, column 4:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:
</code>```

This is my code :

```<code>DECLARE
   TYPE sc IS TABLE OF transactionhistory.NBSUBCOMPANY%TYPE INDEX BY PLS_INTEGER;
   arr sc;
BEGIN
   arr(0) := 000;
   arr(1) := 111;
   arr(2) := 222;
   arr(3) := 333;

   select count(th.CHCARDNUMBER) as transactions from transactionhistory th INNER JOIN cards ch on ch.NBATTMID=th.NBATTMID where th.dtdate>=to_date('01-oct-2016','dd-mon-yyyy') and th.dtdate<to_date('01-nov-2016','dd-mon-yyyy')
   and ch.NBSUBCOMPANY IN (select column_value from table (arr))
   and ((th.CHTRANSTYPE in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925') and th.NBBASEAMT < 0) or (th.CHTRANSTYPE in ('2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955') and th.NBBASEAMT > 0) or (th.CHTRANSTYPE in ('1101', '1102', '1104', '1105', '1106', '1107', '1109') and th.BASEII_STATUS = 'C') or th.CHTRANSTYPE not in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925', '2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955', '1101', '1102', '1104', '1105', '1106', '1107', '1109'));
END;
</code>```

Please suggest me how can i pass this.

答:
You can use MEMBER OF clause. See below:

As @Sudipta mentioned you cannot use a collection decalred in PLSQL block as you are doing, you need to declare it outside of the PLSQL block.

```<code>CREATE OR REPLACE TYPE sc IS TABLE OF NUMBER;
</code>```

and then

```<code>DECLARE
  -- TYPE sc IS TABLE OF NUMBER INDEX BY PLS_INTEGER;

   arr   sc:=sc();

   num number;

BEGIN
   arr.extend(4);
   arr(1) := 0;
   arr(2) := 1;
   arr(3) := 2;
   arr(4) := 3;

   Select count(1)
   into num
   from employee
   -- You can use either commented one or uncommented one. your choice.
   --where employee_id in (select column_value from table(arr));
   where employee_id member of arr;

END;
</code>```

Body:
I am very new in PLSQL, i want to pass an array of number into IN() clause value, But Sqldeveloper throw following error messages:

Error report -
ORA-06550: line 11, column 60:
PLS-00382: expression is of wrong type
ORA-06550: line 11, column 53:
PL/SQL: ORA-22905: cannot access rows from a non-nested table item
ORA-06550: line 10, column 4:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

This is my code :

DECLARE
   TYPE sc IS TABLE OF transactionhistory.NBSUBCOMPANY%TYPE INDEX BY PLS_INTEGER;
   arr sc;
BEGIN
   arr(0) := 000;
   arr(1) := 111;
   arr(2) := 222;
   arr(3) := 333;

   select count(th.CHCARDNUMBER) as transactions from transactionhistory th INNER JOIN cards ch on ch.NBATTMID=th.NBATTMID where th.dtdate>=to_date('01-oct-2016','dd-mon-yyyy') and th.dtdate<to_date('01-nov-2016','dd-mon-yyyy')
   and ch.NBSUBCOMPANY IN (select column_value from table (arr))
   and ((th.CHTRANSTYPE in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925') and th.NBBASEAMT < 0) or (th.CHTRANSTYPE in ('2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955') and th.NBBASEAMT > 0) or (th.CHTRANSTYPE in ('1101', '1102', '1104', '1105', '1106', '1107', '1109') and th.BASEII_STATUS = 'C') or th.CHTRANSTYPE not in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925', '2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955', '1101', '1102', '1104', '1105', '1106', '1107', '1109'));
END;

Please suggest me how can i pass this.

Body:
You can use MEMBER OF clause. See below:

As @Sudipta mentioned you cannot use a collection decalred in PLSQL block as you are doing, you need to declare it outside of the PLSQL block.

CREATE OR REPLACE TYPE sc IS TABLE OF NUMBER;

and then

DECLARE
  -- TYPE sc IS TABLE OF NUMBER INDEX BY PLS_INTEGER;

   arr   sc:=sc();

   num number;

BEGIN
   arr.extend(4);
   arr(1) := 0;
   arr(2) := 1;
   arr(3) := 2;
   arr(4) := 3;

   Select count(1)
   into num
   from employee
   -- You can use either commented one or uncommented one. your choice.
   --where employee_id in (select column_value from table(arr));
   where employee_id member of arr;

END;


问:
getting values from rows to columns
I am struggling with 'pivoting on multiple columns' in ms sql (version 2012).

I would like to get values from structure

```
Supplier Nr   SupplierName  Manager             Service           Type_of_Service     Planned_Turnover       Turnover          TransactionID            Month
 30              Honda       Name               CityService            varchar          100 000                95 000         009000011440114           201701
 50              Honda22     Name               CityService           varchar           200 000                195 000        0090001101144             201701
 30              Honda       Name               CityService            varchar          130 000                115 000        00900111114               201702
 50              Honda22     Name               CityService           varchar           230 000                205 000        001144                    201702
```

into desired form:

```
Supplier Nr   SupplierName  Manager             Service           Type_of_Service     Planned_Turnover 201701       Turnover 201701         TransactionID 201701  Planned_Turnover 201702       Turnover 201702         TransactionID 201702
  30              Honda      Name               CityService            varchar              100 000                     95000               009000011440114         130 000                     115 000                     00900111114
  50              Honda22    Name               CityService           varchar               200 000                     195000              0090001101144           230 000                     205 000                     001144
```

i understand, how to pivot table based on one column - e.g. get turnover to columns month by month  ... but how to get more values (Planned_Turnover, Turnover, TransactionID next to each other?)

Thanks

答:
Here is an example that uses a temporary table and a dynamic SQL with a pivot for 2 dates.

```<code>create table #tempTable ([Supplier Nr] int, SupplierName varchar(30), Manager varchar(30), [Service] varchar(30), Type_of_Service varchar(30), Planned_Turnover varchar(30), Turnover varchar(30), TransactionID varchar(30), [Month] int);

insert into #tempTable ([Supplier Nr],SupplierName,Manager,[Service],Type_of_Service,Planned_Turnover,Turnover,TransactionID,[Month]) values
(30,'Honda','Name','CityService','varchar','100 000','95 000','009000011440114',201701),
(50,'Honda22','Name','CityService','varchar','200 000','195 000','0090001101144',201701),
(30,'Honda','Name','CityService','varchar','130 000','115 000','00900111114',201702),
(50,'Honda22','Name','CityService','varchar','230 000','205 000','001144',201702);

DECLARE @SQLString varchar(max);

SET @SQLString = 'select *
from (
  select [Supplier Nr], SupplierName, Manager, [Service], Type_of_Service, concat(''Planned_Turnover '',[Month]) as Title, Planned_Turnover as Value
  from #tempTable where [Month] in (@Date1, @Date2)
  union all
  select [Supplier Nr], SupplierName, Manager, [Service], Type_of_Service, concat(''Turnover '',[Month]) as Title, Turnover as Value
  from #tempTable where [Month] in (@Date1, @Date2)
  union all
  select [Supplier Nr], SupplierName, Manager, [Service], Type_of_Service, concat(''TransactionID '',[Month]) as Title, TransactionID as Value
  from #tempTable where [Month] in (@Date1, @Date2)
) q
PIVOT (MAX(Value) FOR Title IN
([Planned_Turnover @Date1],[Turnover @Date1],[TransactionID @Date1],[Planned_Turnover @Date2],[Turnover @Date2],[TransactionID @Date2])
) pvt';

declare @Date1 varchar(6) = '201701';
declare @Date2 varchar(6) = '201702';

SET @SQLString = replace(replace(@SQLString,'@Date1',@Date1),'@Date2',@Date2);

exec (@SQLString);
</code>```

This is limited to 2 months. If it were for a range of months then it's better to just calculate a varchar for the pivot fields, and use it in the @SQLString.

Example code:

```<code>declare @Date1 varchar(6) = '201712';
declare @Date2 varchar(6) = '201802';

declare @PivotFields varchar(max);
with cte as (
   select convert(date,concat(@Date1,'01')) as dt
   union all
   select dateadd(month,1,dt) from cte where dt < convert(date,concat(@Date2,'01'))
)
select @PivotFields = concat(@PivotFields+', ',quotename(word+' '+FORMAT(dt,'yyyyMM')))
from cte cross join (values (1,'Planned_Turnover'),(2,'Turnover'),(3,'TransactionID')) words(wordid, word)
order by dt, wordid;

-- result: @PivotFields="[Planned_Turnover 201712], [Turnover 201712], [TransactionID 201712], [Planned_Turnover 201801], [Turnover 201801], [TransactionID 201801], [Planned_Turnover 201802], [Turnover 201802], [TransactionID 201802]"
</code>```

Title: getting values from rows to columns

Body:
I am struggling with 'pivoting on multiple columns' in ms sql (version 2012).

I would like to get values from structure

Supplier Nr   SupplierName  Manager             Service           Type_of_Service     Planned_Turnover       Turnover          TransactionID            Month
 30              Honda       Name               CityService            varchar          100 000                95 000         009000011440114           201701
 50              Honda22     Name               CityService           varchar           200 000                195 000        0090001101144             201701
 30              Honda       Name               CityService            varchar          130 000                115 000        00900111114               201702
 50              Honda22     Name               CityService           varchar           230 000                205 000        001144                    201702

into desired form:

Supplier Nr   SupplierName  Manager             Service           Type_of_Service     Planned_Turnover 201701       Turnover 201701         TransactionID 201701  Planned_Turnover 201702       Turnover 201702         TransactionID 201702
  30              Honda      Name               CityService            varchar              100 000                     95000               009000011440114         130 000                     115 000                     00900111114
  50              Honda22    Name               CityService           varchar               200 000                     195000              0090001101144           230 000                     205 000                     001144

i understand, how to pivot table based on one column - e.g. get turnover to columns month by month  ... but how to get more values (Planned_Turnover, Turnover, TransactionID next to each other?)

Thanks

Body:
Here is an example that uses a temporary table and a dynamic SQL with a pivot for 2 dates.

create table #tempTable ([Supplier Nr] int, SupplierName varchar(30), Manager varchar(30), [Service] varchar(30), Type_of_Service varchar(30), Planned_Turnover varchar(30), Turnover varchar(30), TransactionID varchar(30), [Month] int);

insert into #tempTable ([Supplier Nr],SupplierName,Manager,[Service],Type_of_Service,Planned_Turnover,Turnover,TransactionID,[Month]) values
(30,'Honda','Name','CityService','varchar','100 000','95 000','009000011440114',201701),
(50,'Honda22','Name','CityService','varchar','200 000','195 000','0090001101144',201701),
(30,'Honda','Name','CityService','varchar','130 000','115 000','00900111114',201702),
(50,'Honda22','Name','CityService','varchar','230 000','205 000','001144',201702);

DECLARE @SQLString varchar(max);

SET @SQLString = 'select *
from (
  select [Supplier Nr], SupplierName, Manager, [Service], Type_of_Service, concat(''Planned_Turnover '',[Month]) as Title, Planned_Turnover as Value
  from #tempTable where [Month] in (@Date1, @Date2)
  union all
  select [Supplier Nr], SupplierName, Manager, [Service], Type_of_Service, concat(''Turnover '',[Month]) as Title, Turnover as Value
  from #tempTable where [Month] in (@Date1, @Date2)
  union all
  select [Supplier Nr], SupplierName, Manager, [Service], Type_of_Service, concat(''TransactionID '',[Month]) as Title, TransactionID as Value
  from #tempTable where [Month] in (@Date1, @Date2)
) q
PIVOT (MAX(Value) FOR Title IN
([Planned_Turnover @Date1],[Turnover @Date1],[TransactionID @Date1],[Planned_Turnover @Date2],[Turnover @Date2],[TransactionID @Date2])
) pvt';

declare @Date1 varchar(6) = '201701';
declare @Date2 varchar(6) = '201702';

SET @SQLString = replace(replace(@SQLString,'@Date1',@Date1),'@Date2',@Date2);

exec (@SQLString);

This is limited to 2 months. If it were for a range of months then it's better to just calculate a varchar for the pivot fields, and use it in the @SQLString.

Example code:

declare @Date1 varchar(6) = '201712';
declare @Date2 varchar(6) = '201802';

declare @PivotFields varchar(max);
with cte as (
   select convert(date,concat(@Date1,'01')) as dt
   union all
   select dateadd(month,1,dt) from cte where dt < convert(date,concat(@Date2,'01'))
)
select @PivotFields = concat(@PivotFields+', ',quotename(word+' '+FORMAT(dt,'yyyyMM')))
from cte cross join (values (1,'Planned_Turnover'),(2,'Turnover'),(3,'TransactionID')) words(wordid, word)
order by dt, wordid;

-- result: @PivotFields="[Planned_Turnover 201712], [Turnover 201712], [TransactionID 201712], [Planned_Turnover 201801], [Turnover 201801], [TransactionID 201801], [Planned_Turnover 201802], [Turnover 201802], [TransactionID 201802]"


问:
How to set WP Cron job timestamp according to timezone?
I'm using server cron job at midnight to schedule a WP event to send updates to the customers regarding their expired products. Whatever I have written the time is converted to my UTC+5 timezone.

PHP Code:

```<code>function register_daily_expired_products_event() {
    if (!wp_next_scheduled('send_emails')) {

        // Schedule daily expired products event
        wp_schedule_event(strtotime('today midnight'), 'daily', 'ptmp_notify_customers');
    }
}

add_action('init', 'register_daily_expired_products_event');

function ptmp_send_product_expiry_emails() {
    // Custom code
}

// Notify customers with their expired products
add_action('ptmp_notify_customers', 'ptmp_send_product_expiry_emails');
</code>```

Tested cron job event with WP Crontrol plugin that is showing +5hours according to my timezone(UTC+5). e.g.

Time should be: 2017-07-08 00:00:00

But in actual: 2017-07-08 05:00:00 (Added plus 5 hours)

And server cron job is running at exact 12:00 AM but at the backend, the event has more 5 hours and not ready to be executed. So, no email sent even the customers have expired products at that day. Any help will be appreciated.
Thanks!

答:
If I understood you correctly, you want to adapt your serverside cronjob execution time to your users timezone.

There are two ways, you could do.

a) all users are in the same timezone

If your customers are all in the same timezone, you've to adapt your cronjob execution time to that specific timezone.

b) users have different timezones

If your customers are not in the same timezone, you have to run your cronjob every hour (or every 30 mins, 15mins...) and check the time against your users timezone.

so your cronjob (i.e. every hour) should do something like this:

get all expired products

get the timezone of the user the products belong to

check if the current time is around 00:00 of the user's timezone

if so, send notification email

Have a look at the official PHP-documentation on how to set the timezone:
http://php.net/manual/de/datetime.settimezone.php

Body:
I'm using server cron job at midnight to schedule a WP event to send updates to the customers regarding their expired products. Whatever I have written the time is converted to my UTC+5 timezone.

PHP Code:

function register_daily_expired_products_event() {
    if (!wp_next_scheduled('send_emails')) {

        // Schedule daily expired products event
        wp_schedule_event(strtotime('today midnight'), 'daily', 'ptmp_notify_customers');
    }
}

add_action('init', 'register_daily_expired_products_event');

function ptmp_send_product_expiry_emails() {
    // Custom code
}

// Notify customers with their expired products
add_action('ptmp_notify_customers', 'ptmp_send_product_expiry_emails');

Tested cron job event with WP Crontrol plugin that is showing +5hours according to my timezone(UTC+5). e.g.

Time should be: 2017-07-08 00:00:00

But in actual: 2017-07-08 05:00:00 (Added plus 5 hours)

And server cron job is running at exact 12:00 AM but at the backend, the event has more 5 hours and not ready to be executed. So, no email sent even the customers have expired products at that day. Any help will be appreciated.
Thanks!


问:
iteration over 3 large lists to compare and assign value python
I have a piece of code where I need to go through many lists to read and assign values

The code does the following:
First, for each element in the entities (1st list 1300), the code will read its text file that contains many lines (2nd list 5000) each line contains two values. After that, the code will check if the first value in each line exists in the features list (3rdlist 17000), if yes it will write the second value in the line into the matrix.
The code is working but it is inefficient and extremely slow.(more than 12 hours)

```<code> #first list
for i in range(len(entities_list)-1):
    fin = open('/home/rana/'+entities_list[i]+'.txt','r')
            #Second List
            for line in fin.readlines():
                 #Third List
                for j in range(len(features_list)-1):
                if features_list[j]==line.split()[0]:
                    co_occurrence_matrix[i,j]=float(line.split()[1])
</code>```

I will appreciate if someone gives me an Idea how to solve this issue

答:
Your feature lookup in the inner loop is slow O(n) and repeated 1300x5000 ~ 6.5M times. The first thing you can do is to convert the features_list to a dict and speed that lookup up to O(1) (eliminate the third loop):

```<code>features = dict(zip(features_list, range(len(features_list)-1)))
for i in range(len(entities_list)-1):
    with open('/home/rana/'+entities_list[i]+'.txt', 'r') as fin:
        for line in fin:
             key, value = line.split()
             if key in features:
                 j = features[key]
                 co_occurrence_matrix[i,j] = float(value)
</code>```

Body:
I have a piece of code where I need to go through many lists to read and assign values

The code does the following:
First, for each element in the entities (1st list 1300), the code will read its text file that contains many lines (2nd list 5000) each line contains two values. After that, the code will check if the first value in each line exists in the features list (3rdlist 17000), if yes it will write the second value in the line into the matrix.
The code is working but it is inefficient and extremely slow.(more than 12 hours)

 #first list
for i in range(len(entities_list)-1):
    fin = open('/home/rana/'+entities_list[i]+'.txt','r')
            #Second List
            for line in fin.readlines():
                 #Third List
                for j in range(len(features_list)-1):
                if features_list[j]==line.split()[0]:
                    co_occurrence_matrix[i,j]=float(line.split()[1])

I will appreciate if someone gives me an Idea how to solve this issue

Body:
Your feature lookup in the inner loop is slow O(n) and repeated 1300x5000 ~ 6.5M times. The first thing you can do is to convert the features_list to a dict and speed that lookup up to O(1) (eliminate the third loop):

features = dict(zip(features_list, range(len(features_list)-1)))
for i in range(len(entities_list)-1):
    with open('/home/rana/'+entities_list[i]+'.txt', 'r') as fin:
        for line in fin:
             key, value = line.split()
             if key in features:
                 j = features[key]
                 co_occurrence_matrix[i,j] = float(value)


问:
No matter what, I can't get this progress bar to update from a thread
I have a Windows app written in C (using gcc/MinGW) that works pretty well except for a few UI problems. One, I simply cannot get the progress bar to update from a thread. In fact, I probably can't get ANY UI stuff to update.

Basically, I have a spawned thread that does some processing, and from that thread I attempt to update the progress bar in the main thread. I tried this by using PostMessage() to the main hwnd, but no luck even though I can do other things like open message boxes. However, it's unclear whether the message box is getting called within the thread or on the main thread.

Here's some code:

```<code>// in header/globally accessible
HWND wnd; // main application window
HWND progress_bar; //progress bar

typedef struct { //to pass to thread
    DWORD mainThreadId;
    HWND mainHwnd;
    char *filename;
} THREADSTUFF;

//callback function
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
    switch (msg){
        case WM_CREATE:{
            // create progress bar
            progress_bar = CreateWindowEx(
                0,
                PROGRESS_CLASS,
                (LPCTSTR) NULL,
                WS_CHILD | WS_VISIBLE,
                79,164,455,15,
                hwnd,
                (HMENU)20,
                NULL,
                NULL);

            SendMessage(progress_bar, PBM_SETSTEP, 1, 0 );
            SendMessage(progress_bar, PBM_SETPOS, 0, 0 );
            //test to make sure it actually works
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine

            break;
        }

        case WM_COMMAND: {
            if(LOWORD(wParam)==2){ //do some processing in a thread

                //struct of stuff I need to pass to thread
                THREADSTUFF *threadStuff;
                threadStuff = (THREADSTUFF*)malloc(sizeof(*threadStuff));
                threadStuff->mainThreadId = GetCurrentThreadId();
                threadStuff->mainHwnd = hwnd;
                threadStuff->filename = (void*)&filename;
                hThread1 = CreateThread(NULL,0,convertFile (LPVOID)threadStuff,0,NULL);

            }else if(LOWORD(wParam)==5){ //update progress bar

                MessageBox(hwnd,"I got a message!", "Message",  MB_OK | MB_ICONINFORMATION);
                PostMessage(progress_bar,PBM_STEPIT,0,0);
            }
            break;
        }
    }
}
</code>```

This all seems to work okay. The problem is in the thread:

```<code>DWORD WINAPI convertFile(LPVOID params){

    //get passed params, this works perfectly fine
    THREADSTUFF *tData = (THREADSTUFF*)params;

    MessageBox(tData->mainHwnd,tData->filename,"File name",MB_OK | MB_ICONINFORMATION); //yep

    PostMessage(tData->mainHwnd,WM_COMMAND,5,0); //only shows message
    PostThreadMessage(tData->mainThreadId,WM_COMMAND,5,0); //does nothing
}
</code>```

When I say, "only shows message," that means the MessageBox() function in the callback works, but not the PostMessage() to update the position of the progress bar.

If I use PostThreadMessage() to send a message to the main thread's message loop, I can intercept it and launch MessageBoxes so it's definitely working. However, even if I try to update the progress bar this way. it still won't update.

What am I missing?

答:
From the MSDN documentation for PBM_STEPIT:

```<code>wParam
    Must be zero.
lParam
    Must be zero.
</code>```

CLR_DEFAULT is defined as 0xFF000000L.  What happens if you change your code to:

```<code>PostMessage(progress_bar, PBM_STEPIT, 0, 0);
</code>```

Body:
I have a Windows app written in C (using gcc/MinGW) that works pretty well except for a few UI problems. One, I simply cannot get the progress bar to update from a thread. In fact, I probably can't get ANY UI stuff to update.

Basically, I have a spawned thread that does some processing, and from that thread I attempt to update the progress bar in the main thread. I tried this by using PostMessage() to the main hwnd, but no luck even though I can do other things like open message boxes. However, it's unclear whether the message box is getting called within the thread or on the main thread.

Here's some code:

// in header/globally accessible
HWND wnd; // main application window
HWND progress_bar; //progress bar

typedef struct { //to pass to thread
    DWORD mainThreadId;
    HWND mainHwnd;
    char *filename;
} THREADSTUFF;

//callback function
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam){
    switch (msg){
        case WM_CREATE:{
            // create progress bar
            progress_bar = CreateWindowEx(
                0,
                PROGRESS_CLASS,
                (LPCTSTR) NULL,
                WS_CHILD | WS_VISIBLE,
                79,164,455,15,
                hwnd,
                (HMENU)20,
                NULL,
                NULL);

            SendMessage(progress_bar, PBM_SETSTEP, 1, 0 );
            SendMessage(progress_bar, PBM_SETPOS, 0, 0 );
            //test to make sure it actually works
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine
            SendMessage(progress_bar, PBM_STEPIT, 0, 0 ); //works fine

            break;
        }

        case WM_COMMAND: {
            if(LOWORD(wParam)==2){ //do some processing in a thread

                //struct of stuff I need to pass to thread
                THREADSTUFF *threadStuff;
                threadStuff = (THREADSTUFF*)malloc(sizeof(*threadStuff));
                threadStuff->mainThreadId = GetCurrentThreadId();
                threadStuff->mainHwnd = hwnd;
                threadStuff->filename = (void*)&filename;
                hThread1 = CreateThread(NULL,0,convertFile (LPVOID)threadStuff,0,NULL);

            }else if(LOWORD(wParam)==5){ //update progress bar

                MessageBox(hwnd,"I got a message!", "Message",  MB_OK | MB_ICONINFORMATION);
                PostMessage(progress_bar,PBM_STEPIT,0,0);
            }
            break;
        }
    }
}

This all seems to work okay. The problem is in the thread:

DWORD WINAPI convertFile(LPVOID params){

    //get passed params, this works perfectly fine
    THREADSTUFF *tData = (THREADSTUFF*)params;

    MessageBox(tData->mainHwnd,tData->filename,"File name",MB_OK | MB_ICONINFORMATION); //yep

    PostMessage(tData->mainHwnd,WM_COMMAND,5,0); //only shows message
    PostThreadMessage(tData->mainThreadId,WM_COMMAND,5,0); //does nothing
}

When I say, "only shows message," that means the MessageBox() function in the callback works, but not the PostMessage() to update the position of the progress bar.

If I use PostThreadMessage() to send a message to the main thread's message loop, I can intercept it and launch MessageBoxes so it's definitely working. However, even if I try to update the progress bar this way. it still won't update.

What am I missing?

Body:
From the MSDN documentation for PBM_STEPIT:

wParam
    Must be zero.
lParam
    Must be zero.

CLR_DEFAULT is defined as 0xFF000000L.  What happens if you change your code to:

PostMessage(progress_bar, PBM_STEPIT, 0, 0);

ContentLicense: CC BY-SA 2.5


问:
How to extract a frame from video using Java
Is there any solution to "Extract a frame from video file in Java using core library without importing external libraries"?

Say for I saw Image, BufferedStrategy, BufferCapabilities in Java AWT libraries.

答:
According to this answer on another question, you can do that without external libraries by leveraging features of JavaFX.

Quoting original answer below:

You can use the snapshot() of MediaView. First connect a mediaPlayer
  to a MediaView component, then use mediaPlayer.seek() to seek the
  video position. And then you can use the following code to extract the
  image frame:

```<code>int width = mediaPlayer.getMedia().getWidth();
int height = mediaPlayer.getMedia().getHeight();
WritableImage wim = new WritableImage(width, height);
MediaView mv = new MediaView();
mv.setFitWidth(width);
mv.setFitHeight(height);
mv.setMediaPlayer(mediaPlayer);
mv.snapshot(null, wim);
try {
    ImageIO.write(SwingFXUtils.fromFXImage(wim, null), "png", new File("/test.png"));
} catch (Exception s) {
    System.out.println(s);
}
</code>```

Body:
According to this answer on another question, you can do that without external libraries by leveraging features of JavaFX.

Quoting original answer below:

You can use the snapshot() of MediaView. First connect a mediaPlayer
  to a MediaView component, then use mediaPlayer.seek() to seek the
  video position. And then you can use the following code to extract the
  image frame:

int width = mediaPlayer.getMedia().getWidth();
int height = mediaPlayer.getMedia().getHeight();
WritableImage wim = new WritableImage(width, height);
MediaView mv = new MediaView();
mv.setFitWidth(width);
mv.setFitHeight(height);
mv.setMediaPlayer(mediaPlayer);
mv.snapshot(null, wim);
try {
    ImageIO.write(SwingFXUtils.fromFXImage(wim, null), "png", new File("/test.png"));
} catch (Exception s) {
    System.out.println(s);
}


问:
Remove Custom button from Datatable

How can I remove the Copy, CSV, Excel, PDF and Print button on the top right corner. They are the default feature of datatables I suppose. I am trying to remove them but I did not find nay information on how can I remove or hide them.

Following is the code

```<code>oTable = $('#lenderList').dataTable(
        {
            bServerSide: true,
            bProcessing: true,
            searching: true,
            sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
            sServerMethod: 'POST',
            sPaginationType: "full_numbers",
            bPaginate: true,
            bLengthChange: true,
            bFilter: true,
            bSort: true,
            bInfo: true,
            bAutoWidth: true,

            aoColumns: [
                {
                    "sName": "loanApplicationNumber",
                    mData: "loanApplicationNumber"
                },
                {
                    "sName": "name",
                    mData: "name"
                },
                {
                    "sName": "submissionDate",
                    mData: "submissionDate"
                },
                {
                    "sName": "kycEmailId",
                    mData: "kycEmailId"
                },
                {
                    "sName": "appVersion",
                    mData: "appVersion"
                },
                {
                    "sName": "documentStatus",
                    mData: "documentStatus"
                },
                {
                    "sName": "latestRemark",
                    mData: "latestRemark"
                },
                {
                    "sName": "appName",
                    mData: "appName"
                }

            ],
            "dom": 'T<"clear"><"button">lfrtip'

        }
    );
</code>```

答:
This is the default datatable:

        <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />

                Emp Code
                First Name
                Last Name
                Mobile

```
</div>
</div>
</p>

<p>In the above example, their are no such buttons. To show the specified buttons you have to include:</p>

```dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
```

and their corresponding js files. To remove these buttons, just remove the above code from your datatable initialization code.

Title: Remove Custom button from Datatable

Body:
How can I remove the Copy, CSV, Excel, PDF and Print button on the top right corner. They are the default feature of datatables I suppose. I am trying to remove them but I did not find nay information on how can I remove or hide them.

Following is the code

oTable = $('#lenderList').dataTable(
        {
            bServerSide: true,
            bProcessing: true,
            searching: true,
            sAjaxSource: "loanAdminAjax?ajax=true&searchCol="+$('#category').val(),
            sServerMethod: 'POST',
            sPaginationType: "full_numbers",
            bPaginate: true,
            bLengthChange: true,
            bFilter: true,
            bSort: true,
            bInfo: true,
            bAutoWidth: true,

            aoColumns: [
                {
                    "sName": "loanApplicationNumber",
                    mData: "loanApplicationNumber"
                },
                {
                    "sName": "name",
                    mData: "name"
                },
                {
                    "sName": "submissionDate",
                    mData: "submissionDate"
                },
                {
                    "sName": "kycEmailId",
                    mData: "kycEmailId"
                },
                {
                    "sName": "appVersion",
                    mData: "appVersion"
                },
                {
                    "sName": "documentStatus",
                    mData: "documentStatus"
                },
                {
                    "sName": "latestRemark",
                    mData: "latestRemark"
                },
                {
                    "sName": "appName",
                    mData: "appName"
                }

            ],
            "dom": 'T<"clear"><"button">lfrtip'

        }
    );

Body:
This is the default datatable:

<html>
    <head>
        <link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />

        <script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
        <script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

        <script type="text/javascript" language="javascript" class="init">
        $(document).ready(function() {
            var data = [];
            data.push(
                [1,"Sasha","Brenna","0800 1111"],
                [2,"Sage","Mia","(01012) 405872"],
                [3,"Chelsea","Allistair","076 0578 0265"],
                [4,"Uta","Savannah","070 1247 5884"],
                [5,"Remedios","Berk","0995 181 0007"],
                [6,"Ruby","Wayne","0800 1111"],
                [7,"Faith","Fredericka","(01709) 099879"],
                [8,"Myra","Harrison","070 4241 9576"],
                [9,"Drake","Miriam","0800 733635"],
                [10,"Reed","Shannon","076 8597 5067"]
            );

            $('#data_table').DataTable( {
                data: data
            });
        });
        </script>

        <style>
        .odd{
            background-color: #FFF8FB !important;
        }
        .even{
            background-color: #DDEBF8 !important;
        }
        </style>
    </head>
    <body>
    <div>

    <table id="data_table">
        <thead>
            <tr>
                <th>Emp Code</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Mobile</th>
            </tr>
        </thead>

        <tbody>
        <!-- Dynamic Body -->
        </tbody>
    </table>

    </body>
    </div>
</html>

In the above example, their are no such buttons. To show the specified buttons you have to include:

dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]

and their corresponding js files. To remove these buttons, just remove the above code from your datatable initialization code.


问:
Problems with bcp utility
I want to extract a SELCET query with the bcp utility. But it doesn't work. MS SQL underlines "bcp" marks it.

```<code>DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']');

PRINT (' DATABASE SELECTED: '+ @DBName)

bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T
</code>```

The error message is:

```<code>Msg 102, Level 15, State 1, Line 19
Incorrect syntax near 'bcp'.
</code>```

Does anybody know the correct syntax? If I compare it with the examples on the docs.microsoft website (https://learn.microsoft.com/en-us/sql/tools/bcp-utility#o) I do not see my mistake.

答:
bcp is a command line utility.  It runs from a shell script (typically), not from T-SQL.

Within SQL code, you would normally use bulk insert.  See the documentation here.

Title: Problems with bcp utility

Body:
I want to extract a SELCET query with the bcp utility. But it doesn't work. MS SQL underlines "bcp" marks it.

DECLARE @DBName NVARCHAR(MAX);
SET @DBName = (SELECT name FROM master.dbo.sysdatabases where name LIKE '%NAV%');
EXECUTE ('USE [' + @DBName+']');

PRINT (' DATABASE SELECTED: '+ @DBName)

bcp "SELECT [Role ID],[Name] FROM [dbo].[Permission Set]" out "C:\Users\Public\Documents\test.txt" -c -T

The error message is:

Msg 102, Level 15, State 1, Line 19
Incorrect syntax near 'bcp'.

Does anybody know the correct syntax? If I compare it with the examples on the docs.microsoft website (https://learn.microsoft.com/en-us/sql/tools/bcp-utility#o) I do not see my mistake.


问:
Design pattern with methods that return modified parent
Lets say I have a class that looks like this:

```<code>class Data
{
    public Data()
    {
       // Stuff
    }

    public void Process1()
    {
       // Stuff
    }

    public void Process2()
    {
       // Stuff
    }
}
</code>```

I have several options for how to use it. The most common one is the following:

```<code>var data = new Data();
data.Process1();
data.Process2();
</code>```

One alternative that I like to use requires me to modify the class:

```<code>class Data
{
    public Data()
    {
       // Stuff
    }

    public Data Process1()
    {
       // Stuff
       return this;
    }

    public Data Process2()
    {
       // Stuff
       return this;
    }
}
</code>```

Then I can use it like so:

```<code>var data = new Data().Process1().Process2();
</code>```

To which design pattern, if any, does this style of writing classes belong?

答:
A method on a fluent interface should, in my opinion, return a new instance of the source object with the state updated by that method. Otherwise it's easy to write misleading code.

Take this code for example:

```<code>public class Data
{
    public double Value { get; private set; }
    public Data(double value) { this.Value = value; }

    public Data Times2Add1()
    {
        this.Value = this.Value * 2.0 + 1.0;
        return this;
    }

    public Data Divide3()
    {
        this.Value = this.Value / 3.0;
        return this;
    }
}
</code>```

If I run this:

```<code>var x = new Data(5);
var y = x.Times2Add1();
var z = x.Divide3();

Console.WriteLine(x.Value);
Console.WriteLine(y.Value);
Console.WriteLine(z.Value);
</code>```

I get:

```
3.66666666666667
3.66666666666667
3.66666666666667
```

However, if I write it like this:

```<code>public class Data
{
    public double Value { get; private set; }
    public Data(double value) { this.Value = value; }

    public Data Times2Add1()
    {
        return new Data(this.Value * 2.0 + 1.0);
    }

    public Data Divide3()
    {
        return new Data(this.Value / 3.0);
    }
}
</code>```

The results are

```
5
11
1.66666666666667
```

And of course I can write var w = x.Times2Add1().Divide3(); which gives me the 3.66666666666667 I got above, but this time it makes more sense to me. It becomes testable robust code.

LINQ does it properly - calling .Where, for example, on an enumerable doesn't alter the enumerable but instead returns a new one. That's the best way to write a fluent interface.

When you see return this;, even though that's a fluent interface, I would consider it code smell.

Body:
Lets say I have a class that looks like this:

class Data
{
    public Data()
    {
       // Stuff
    }

    public void Process1()
    {
       // Stuff
    }

    public void Process2()
    {
       // Stuff
    }
}

I have several options for how to use it. The most common one is the following:

var data = new Data();
data.Process1();
data.Process2();

One alternative that I like to use requires me to modify the class:

class Data
{
    public Data()
    {
       // Stuff
    }

    public Data Process1()
    {
       // Stuff
       return this;
    }

    public Data Process2()
    {
       // Stuff
       return this;
    }
}

Then I can use it like so:

var data = new Data().Process1().Process2();

To which design pattern, if any, does this style of writing classes belong?

Body:
A method on a fluent interface should, in my opinion, return a new instance of the source object with the state updated by that method. Otherwise it's easy to write misleading code.

Take this code for example:

public class Data
{
    public double Value { get; private set; }
    public Data(double value) { this.Value = value; }

    public Data Times2Add1()
    {
        this.Value = this.Value * 2.0 + 1.0;
        return this;
    }

    public Data Divide3()
    {
        this.Value = this.Value / 3.0;
        return this;
    }
}

If I run this:

var x = new Data(5);
var y = x.Times2Add1();
var z = x.Divide3();

Console.WriteLine(x.Value);
Console.WriteLine(y.Value);
Console.WriteLine(z.Value);

I get:

3.66666666666667
3.66666666666667
3.66666666666667

However, if I write it like this:

public class Data
{
    public double Value { get; private set; }
    public Data(double value) { this.Value = value; }

    public Data Times2Add1()
    {
        return new Data(this.Value * 2.0 + 1.0);
    }

    public Data Divide3()
    {
        return new Data(this.Value / 3.0);
    }
}

The results are

5
11
1.66666666666667

And of course I can write var w = x.Times2Add1().Divide3(); which gives me the 3.66666666666667 I got above, but this time it makes more sense to me. It becomes testable robust code.

LINQ does it properly - calling .Where, for example, on an enumerable doesn't alter the enumerable but instead returns a new one. That's the best way to write a fluent interface.

When you see return this;, even though that's a fluent interface, I would consider it code smell.


问:
Referencing control on one form from another form
As you can guess, I'm kind of new to .NET and just want to reference a control on one form from another.

Usually I would just do Form.Control.Property but that doesn't work and every example I've found through Google doesn't work for me.

It just seems overly complicated with public classes, etc.

Is there a more simpler way to do this?  I'm ready to throw in the towel and just use a global variable at this point.

I have the form containing the control I want to reference, frmGenerate which has a textbox called txtCustomerNo.

From this form through a button's click event I want to show another form, frmCustomers, and have that form reference the value in txtCustomerNo.

```<code>frmCustomers.ShowDialog()
</code>```

It has to be something simple that I'm just not grasping.

答:
While you can create a property on your second form that will return the data needed, you can just as easily change the Modifier property of that control.  By default, the modifiers of controls are private, and therefore not accessible to anything other than the current form.  Click on the control, and find the Modifier property. Set that to Public, and you'll be able to access it from outside the form, such as:

```<code>Dim f As New SecondForm
f.FirstNameTextBox.Text = "Bob"
</code>```

Body:
As you can guess, I'm kind of new to .NET and just want to reference a control on one form from another.

Usually I would just do Form.Control.Property but that doesn't work and every example I've found through Google doesn't work for me.

It just seems overly complicated with public classes, etc.

Is there a more simpler way to do this?  I'm ready to throw in the towel and just use a global variable at this point.

I have the form containing the control I want to reference, frmGenerate which has a textbox called txtCustomerNo.

From this form through a button's click event I want to show another form, frmCustomers, and have that form reference the value in txtCustomerNo.

frmCustomers.ShowDialog()

It has to be something simple that I'm just not grasping.

Body:
While you can create a property on your second form that will return the data needed, you can just as easily change the Modifier property of that control.  By default, the modifiers of controls are private, and therefore not accessible to anything other than the current form.  Click on the control, and find the Modifier property. Set that to Public, and you'll be able to access it from outside the form, such as:

Dim f As New SecondForm
f.FirstNameTextBox.Text = "Bob"


问:
How can I dynamically populate the table layout in android Xamarin?
I want to popualte tablelayout using webapi but getting error:

"The specified child already has a parent. You must call removeView() on the child's parent first."

Here is my code

allOrderRestaurent.axml

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tblAllOrderRestaurent">
  <TableRow
      android:background="#ECEFF1">
    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/icon" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Lollipop"
        android:textSize="18dp"
        android:layout_marginTop="25dp"
        android:id="@+id/txtproductname"
            />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="21"
        android:textSize="18dp"
        android:id="@+id/txtproductprice"
        android:layout_marginTop="25dp" />
  </TableRow>
</TableLayout>
</code>```

and here is my acitvity  code
AllOrderRestaurentActivity

```<code>public List<UserCartModel> mItems;
    TableLayout tablelayout;
    TextView productname, price;
    int sessionid;
    protected override async void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.allorderRestaurent);
        sessionid = Common.GetSessionValue();
        List<UserCartModel> mItems = await GetData();

        tablelayout = FindViewById<TableLayout>(Resource.Id.tblAllOrderRestaurent);
        productname = FindViewById<TextView>(Resource.Id.txtproductname);
        price = FindViewById<TextView>(Resource.Id.txtproductprice);
        BindData();
        // Create your application here
    }

    public async Task<List<UserCartModel>> GetData()
    {
        HttpClient client = new HttpClient();
        string ac = Common.Url;
        string url = ac + "RestaurentOderList?id=" + sessionid;

        var request = HttpWebRequest.Create(url);
        request.Method = "GET";

        var response = await client.GetAsync(url);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            mItems = JsonConvert.DeserializeObject<List<UserCartModel>>(content);
        }
        return mItems;
    }

    public void BindData()
    {
        try
        {
            TableRow tableRow = new TableRow(this);
            TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
    ViewGroup.LayoutParams.MatchParent,
    ViewGroup.LayoutParams.MatchParent);

            foreach (var r in mItems)
            {

                productname = new TextView(this);
                productname.Text = r.ProductName;
                productname.LayoutParameters = layoutParams;

                price = new TextView(this);
                price.Text = Convert.ToString(r.Price);
                price.LayoutParameters = layoutParams;

                tableRow.AddView(price, 0);
                tableRow.AddView(price, 1);

                tablelayout.AddView(tableRow, 0);
            }
        }
        catch (Exception exx)
        {
            Console.WriteLine("Error During Bind Table Layout All Order Restaurent" + exx.Message);
        }
    }

}
</code>```

答:
Just Solved it by making following changes

```<code>TableRow tableRow = new TableRow(this);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.MatchParent);
</code>```

Add this Code into Foreach loop And Add:

```<code>tableRow.RemoveAllViews();
</code>```

Body:
I want to popualte tablelayout using webapi but getting error:

"The specified child already has a parent. You must call removeView() on the child's parent first."

Here is my code

allOrderRestaurent.axml

    <?xml version="1.0" encoding="utf-8"?>
    <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/tblAllOrderRestaurent">
  <TableRow
      android:background="#ECEFF1">
    <ImageView
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/icon" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Lollipop"
        android:textSize="18dp"
        android:layout_marginTop="25dp"
        android:id="@+id/txtproductname"
            />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="21"
        android:textSize="18dp"
        android:id="@+id/txtproductprice"
        android:layout_marginTop="25dp" />
  </TableRow>
</TableLayout>

and here is my acitvity  code
AllOrderRestaurentActivity

public List<UserCartModel> mItems;
    TableLayout tablelayout;
    TextView productname, price;
    int sessionid;
    protected override async void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.allorderRestaurent);
        sessionid = Common.GetSessionValue();
        List<UserCartModel> mItems = await GetData();

        tablelayout = FindViewById<TableLayout>(Resource.Id.tblAllOrderRestaurent);
        productname = FindViewById<TextView>(Resource.Id.txtproductname);
        price = FindViewById<TextView>(Resource.Id.txtproductprice);
        BindData();
        // Create your application here
    }

    public async Task<List<UserCartModel>> GetData()
    {
        HttpClient client = new HttpClient();
        string ac = Common.Url;
        string url = ac + "RestaurentOderList?id=" + sessionid;

        var request = HttpWebRequest.Create(url);
        request.Method = "GET";

        var response = await client.GetAsync(url);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();
            mItems = JsonConvert.DeserializeObject<List<UserCartModel>>(content);
        }
        return mItems;
    }

    public void BindData()
    {
        try
        {
            TableRow tableRow = new TableRow(this);
            TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
    ViewGroup.LayoutParams.MatchParent,
    ViewGroup.LayoutParams.MatchParent);

            foreach (var r in mItems)
            {

                productname = new TextView(this);
                productname.Text = r.ProductName;
                productname.LayoutParameters = layoutParams;

                price = new TextView(this);
                price.Text = Convert.ToString(r.Price);
                price.LayoutParameters = layoutParams;

                tableRow.AddView(price, 0);
                tableRow.AddView(price, 1);

                tablelayout.AddView(tableRow, 0);
            }
        }
        catch (Exception exx)
        {
            Console.WriteLine("Error During Bind Table Layout All Order Restaurent" + exx.Message);
        }
    }

}

Body:
Just Solved it by making following changes

TableRow tableRow = new TableRow(this);
TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
ViewGroup.LayoutParams.MatchParent,
ViewGroup.LayoutParams.MatchParent);

Add this Code into Foreach loop And Add:

tableRow.RemoveAllViews();


问:
Angular2 i18n - How to get translation through code
I could not find any documentation in the i18n (for Angular2) that goes beyond showing the translated text in the HTML.
What I need to do is to get the translated text directly in my code. In Angular 1 using the ng-translate feature, it was easy to get it using a $translate service. I can't find the equivalent in the new i18n for Angular 2. Am I missing something?</p>

答:
I have searched the same theme. It seems, Angular i18n does not support to use out-of-box behavior to translate string in ts code yet.

https://github.com/angular/angular/issues/11405

We have implemented a translate service and use pipe together. There are some other libs, e.g. ngx-translate to use translation in source code. The following is angular design document about i18n.

https://docs.google.com/document/d/1LH7lJ1GjRgpGUjzNb6Eg4xrPooRdi80QOTYYh8z_JyY/edit#

In Chapter "Prior Art", some libraries are listed in table to be compared, but none of them support AOT.


问:
J2EE redirect to an external URL
I am developing a web application in which the servlet takes informaiton from index.jsp and does some data processing. After that, I want my application to redirect the user to an external url.

How can I do that? Should I redirect in the servlet or make the servlet call a jsp page which calls the url? and how to do that explicitly?

Thank you in advance!

答:
I think below URL should help you:

how to redirect from servlet to jsp page

If the redirect should happen based on some condition use the following in an if condition based on request data you get from index.jsp.

```<code>response.sendRedirect("http://www.google.com");
</code>```

Title: J2EE redirect to an external URL

Body:
I think below URL should help you:

how to redirect from servlet to jsp page

If the redirect should happen based on some condition use the following in an if condition based on request data you get from index.jsp.

response.sendRedirect("http://www.google.com");


问:
if or condition produce "integer expression expected"
The following code produce error "integer expression expected":

```<code>for SOURCE_PATH in work/sources/*; do
    git diff --exit-code &>/dev/null || SOMETHING_TO_COMMIT=$?
    if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
        echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
    else
        echo "COMMIT FOR $SOURCE_PATH"
        git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
    fi
done
</code>```

Error is on line if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then. It seems [ "$SOMETHING_TO_COMMIT" -eq "0" ]or [ "$SOMETHING_TO_COMMIT" -eq "" ] should produce integer.

How to fix that ?

答:
You don't need to store the exit codes in variables at all. If the git diff can return a non-zero exit code on failure like the most common Linux/Unix commands, you can directly use it in the if conditional as

```<code>if ! git diff --exit-code &>/dev/null ; then
    echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
</code>```

The ! operator asserts true of the if-condition only if the git diff was not successful and there were no changes to commit. Also you should change your script to assert true on the if-condition and fail on the else part as

```<code>if git diff --exit-code &>/dev/null ; then
    echo "COMMIT FOR ${SOURCE_PATH}"
    git -C "$DIR/${SOURCE_PATH}" commit -F "${COMMIT_MESSAGE_FILE}"
else
    echo "NOTHING TO COMMIT FOR ${SOURCE_PATH}";
fi
</code>```

which makes it more readable and efficient.

Body:
The following code produce error "integer expression expected":

for SOURCE_PATH in work/sources/*; do
    git diff --exit-code &>/dev/null || SOMETHING_TO_COMMIT=$?
    if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then
        echo "NOTHING TO COMMIT FOR $SOURCE_PATH";
    else
        echo "COMMIT FOR $SOURCE_PATH"
        git -C "$DIR/$SOURCE_PATH" commit -F ${COMMIT_MESSAGE_FILE}
    fi
done

Error is on line if [ "$SOMETHING_TO_COMMIT" -eq "0" ] || [ "$SOMETHING_TO_COMMIT" -eq "" ] ; then. It seems [ "$SOMETHING_TO_COMMIT" -eq "0" ]or [ "$SOMETHING_TO_COMMIT" -eq "" ] should produce integer.

How to fix that ?

Body:
You don't need to store the exit codes in variables at all. If the git diff can return a non-zero exit code on failure like the most common Linux/Unix commands, you can directly use it in the if conditional as

if ! git diff --exit-code &>/dev/null ; then
    echo "NOTHING TO COMMIT FOR $SOURCE_PATH";

The ! operator asserts true of the if-condition only if the git diff was not successful and there were no changes to commit. Also you should change your script to assert true on the if-condition and fail on the else part as

if git diff --exit-code &>/dev/null ; then
    echo "COMMIT FOR ${SOURCE_PATH}"
    git -C "$DIR/${SOURCE_PATH}" commit -F "${COMMIT_MESSAGE_FILE}"
else
    echo "NOTHING TO COMMIT FOR ${SOURCE_PATH}";
fi

which makes it more readable and efficient.


问:
Django / Celery / Kombu worker error: Received and deleted unknown message. Wrong destination?
It seems as though messages are not getting put onto the queue properly.

I'm using Django with Celery and Kombu to make use of Django's own database as a Broker Backend. All I need is a very simple Pub/Sub setup. It will eventually deploy to Heroku, so I'm using foreman to run locally. Here is the relevant code and info:

pip freeze

```<code>Django==1.4.2
celery==3.0.15
django-celery==3.0.11
kombu==2.5.6
</code>```

Procfile

```<code>web: source bin/activate; python manage.py run_gunicorn -b 0.0.0.0:$PORT -w 4; python manage.py syncdb
celeryd: python manage.py celeryd -E -B --loglevel=INFO
</code>```

settings.py

```<code># Celery configuration
import djcelery
CELERY_IMPORTS = ("api.tasks",)
BROKER_URL = "django://localhost//"
djcelery.setup_loader()
</code>```

put_message

```<code>with Connection(settings.BROKER_URL) as conn:
  queue = conn.SimpleQueue('celery')
  queue.put(id)
  queue.close()
</code>```

api/tasks.py

```<code>@task()
def process_next_task():
  with Connection(settings.BROKER_URL) as conn:
    queue = conn.SimpleQueue('celery')
    message = queue.get(block=True, timeout=1)
    id = int(message.payload)
    try:
      Model.objects.get(id=id)
    except Model.DoesNotExist:
      message.reject()
    else:
      # Do stuff here
      message.ack()
    queue.close()
</code>```

In the terminal, foreman start works just fine and shows this:

```<code>started with pid 31835
17:08:22 celeryd.1 | started with pid 31836
17:08:22 web.1     | /usr/local/foreman/bin/foreman-runner: line 41: exec: source: not found
17:08:22 web.1     | 2013-02-14 17:08:22 [31838] [INFO] Starting gunicorn 0.16.1
17:08:22 web.1     | 2013-02-14 17:08:22 [31838] [INFO] Listening at: http://0.0.0.0:5000 (31838)
17:08:22 web.1     | 2013-02-14 17:08:22 [31838] [INFO] Using worker: sync
17:08:22 web.1     | 2013-02-14 17:08:22 [31843] [INFO] Booting worker with pid: 31843
17:08:22 web.1     | 2013-02-14 17:08:22 [31844] [INFO] Booting worker with pid: 31844
17:08:22 web.1     | 2013-02-14 17:08:22 [31845] [INFO] Booting worker with pid: 31845
17:08:22 web.1     | 2013-02-14 17:08:22 [31846] [INFO] Booting worker with pid: 31846
17:08:22 celeryd.1 | [2013-02-14 17:08:22,858: INFO/Beat] Celerybeat: Starting...
17:08:22 celeryd.1 | [2013-02-14 17:08:22,870: WARNING/MainProcess] celery@myhost.local ready.
17:08:22 celeryd.1 | [2013-02-14 17:08:22,873: INFO/MainProcess] consumer: Connected to django://localhost//.
17:08:42 celeryd.1 | [2013-02-14 17:08:42,926: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!?
17:08:42 celeryd.1 | The full contents of the message body was: body: 25 (2b) {content_type:u'application/json' content_encoding:u'utf-8' delivery_info:{u'priority': 0, u'routing_key': u'celery', u'exchange': u'celery'}}
</code>```

Those last two lines are not shown immediately, but get displayed when my API receives a POST request that runs the code in the put_message section above. I've experimented with using Kombu's fully blown-out Producer and Consumer classes with the same result.

Kombu's SimpleQueue example: http://kombu.readthedocs.org/en/latest/userguide/examples.html#hello-world-example

Celery Docs: http://docs.celeryproject.org/en/latest/index.html

Any ideas?

EDITED

Changing to --loglevel=DEBUG within the procfile changes the terminal output to the following:

```<code>08:54:33 celeryd.1 | started with pid 555
08:54:33 web.1     | started with pid 554
08:54:33 web.1     | /usr/local/foreman/bin/foreman-runner: line 41: exec: source: not found
08:54:36 web.1     | 2013-02-15 08:54:36 [557] [INFO] Starting gunicorn 0.16.1
08:54:36 web.1     | 2013-02-15 08:54:36 [557] [INFO] Listening at: http://0.0.0.0:5000 (557)
08:54:36 web.1     | 2013-02-15 08:54:36 [557] [INFO] Using worker: sync
08:54:36 web.1     | 2013-02-15 08:54:36 [564] [INFO] Booting worker with pid: 564
08:54:36 web.1     | 2013-02-15 08:54:36 [565] [INFO] Booting worker with pid: 565
08:54:36 web.1     | 2013-02-15 08:54:36 [566] [INFO] Booting worker with pid: 566
08:54:36 web.1     | 2013-02-15 08:54:36 [567] [INFO] Booting worker with pid: 567
08:54:37 celeryd.1 | [2013-02-15 08:54:37,480: DEBUG/MainProcess] [Worker] Loading modules.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,484: DEBUG/MainProcess] [Worker] Claiming components.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,484: DEBUG/MainProcess] [Worker] Building boot step graph.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,484: DEBUG/MainProcess] [Worker] New boot order: {ev, queues, beat, pool, mediator, autoreloader, timers, state-db, autoscaler, consumer}
08:54:37 celeryd.1 | [2013-02-15 08:54:37,489: DEBUG/MainProcess] Starting celery.beat._Process...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,490: DEBUG/MainProcess] celery.beat._Process OK!
08:54:37 celeryd.1 | [2013-02-15 08:54:37,491: DEBUG/MainProcess] Starting celery.concurrency.processes.TaskPool...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,491: INFO/Beat] Celerybeat: Starting...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,506: DEBUG/MainProcess] celery.concurrency.processes.TaskPool OK!
08:54:37 celeryd.1 | [2013-02-15 08:54:37,507: DEBUG/MainProcess] Starting celery.worker.mediator.Mediator...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,507: DEBUG/MainProcess] celery.worker.mediator.Mediator OK!
08:54:37 celeryd.1 | [2013-02-15 08:54:37,507: DEBUG/MainProcess] Starting celery.worker.consumer.BlockingConsumer...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,508: WARNING/MainProcess] celery@myhost.local ready.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,508: DEBUG/MainProcess] consumer: Re-establishing connection to the broker...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,510: INFO/MainProcess] consumer: Connected to django://localhost//.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,628: DEBUG/Beat] Current schedule:
08:54:37 celeryd.1 | <Entry: celery.backend_cleanup celery.backend_cleanup() {<crontab: * 4 * * * (m/h/d/dM/MY)>}
08:54:37 celeryd.1 | [2013-02-15 08:54:37,629: DEBUG/Beat] Celerybeat: Ticking with max interval->5.00 minutes
08:54:37 celeryd.1 | [2013-02-15 08:54:37,658: DEBUG/Beat] Celerybeat: Waking up in 5.00 minutes.
08:54:38 celeryd.1 | [2013-02-15 08:54:38,110: DEBUG/MainProcess] consumer: basic.qos: prefetch_count->16
08:54:38 celeryd.1 | [2013-02-15 08:54:38,126: DEBUG/MainProcess] consumer: Ready to accept tasks!
08:55:08 celeryd.1 | [2013-02-15 08:55:08,184: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!?
08:55:08 celeryd.1 | The full contents of the message body was: body: 26 (2b) {content_type:u'application/json' content_encoding:u'utf-8' delivery_info:{u'priority': 0, u'routing_key': u'celery', u'exchange': u'celery'}}
</code>```

答:
Apparently librabbitmq issue is related to new default protocol in celery 4.x. You can switch to previous protocol version by either putting CELERY_TASK_PROTOCOL = 1 in your settings if you're using Django or settings app.conf.task_protocol = 1 in celeryconf.py

Then you'll be able to queue task from with another task.

Body:
It seems as though messages are not getting put onto the queue properly.

I'm using Django with Celery and Kombu to make use of Django's own database as a Broker Backend. All I need is a very simple Pub/Sub setup. It will eventually deploy to Heroku, so I'm using foreman to run locally. Here is the relevant code and info:

pip freeze

Django==1.4.2
celery==3.0.15
django-celery==3.0.11
kombu==2.5.6

Procfile

web: source bin/activate; python manage.py run_gunicorn -b 0.0.0.0:$PORT -w 4; python manage.py syncdb
celeryd: python manage.py celeryd -E -B --loglevel=INFO

settings.py

# Celery configuration
import djcelery
CELERY_IMPORTS = ("api.tasks",)
BROKER_URL = "django://localhost//"
djcelery.setup_loader()

put_message

with Connection(settings.BROKER_URL) as conn:
  queue = conn.SimpleQueue('celery')
  queue.put(id)
  queue.close()

api/tasks.py

@task()
def process_next_task():
  with Connection(settings.BROKER_URL) as conn:
    queue = conn.SimpleQueue('celery')
    message = queue.get(block=True, timeout=1)
    id = int(message.payload)
    try:
      Model.objects.get(id=id)
    except Model.DoesNotExist:
      message.reject()
    else:
      # Do stuff here
      message.ack()
    queue.close()

In the terminal, foreman start works just fine and shows this:

started with pid 31835
17:08:22 celeryd.1 | started with pid 31836
17:08:22 web.1     | /usr/local/foreman/bin/foreman-runner: line 41: exec: source: not found
17:08:22 web.1     | 2013-02-14 17:08:22 [31838] [INFO] Starting gunicorn 0.16.1
17:08:22 web.1     | 2013-02-14 17:08:22 [31838] [INFO] Listening at: http://0.0.0.0:5000 (31838)
17:08:22 web.1     | 2013-02-14 17:08:22 [31838] [INFO] Using worker: sync
17:08:22 web.1     | 2013-02-14 17:08:22 [31843] [INFO] Booting worker with pid: 31843
17:08:22 web.1     | 2013-02-14 17:08:22 [31844] [INFO] Booting worker with pid: 31844
17:08:22 web.1     | 2013-02-14 17:08:22 [31845] [INFO] Booting worker with pid: 31845
17:08:22 web.1     | 2013-02-14 17:08:22 [31846] [INFO] Booting worker with pid: 31846
17:08:22 celeryd.1 | [2013-02-14 17:08:22,858: INFO/Beat] Celerybeat: Starting...
17:08:22 celeryd.1 | [2013-02-14 17:08:22,870: WARNING/MainProcess] celery@myhost.local ready.
17:08:22 celeryd.1 | [2013-02-14 17:08:22,873: INFO/MainProcess] consumer: Connected to django://localhost//.
17:08:42 celeryd.1 | [2013-02-14 17:08:42,926: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!?
17:08:42 celeryd.1 | The full contents of the message body was: body: 25 (2b) {content_type:u'application/json' content_encoding:u'utf-8' delivery_info:{u'priority': 0, u'routing_key': u'celery', u'exchange': u'celery'}}

Those last two lines are not shown immediately, but get displayed when my API receives a POST request that runs the code in the put_message section above. I've experimented with using Kombu's fully blown-out Producer and Consumer classes with the same result.

Kombu's SimpleQueue example: http://kombu.readthedocs.org/en/latest/userguide/examples.html#hello-world-example

Celery Docs: http://docs.celeryproject.org/en/latest/index.html

Any ideas?

EDITED

Changing to --loglevel=DEBUG within the procfile changes the terminal output to the following:

08:54:33 celeryd.1 | started with pid 555
08:54:33 web.1     | started with pid 554
08:54:33 web.1     | /usr/local/foreman/bin/foreman-runner: line 41: exec: source: not found
08:54:36 web.1     | 2013-02-15 08:54:36 [557] [INFO] Starting gunicorn 0.16.1
08:54:36 web.1     | 2013-02-15 08:54:36 [557] [INFO] Listening at: http://0.0.0.0:5000 (557)
08:54:36 web.1     | 2013-02-15 08:54:36 [557] [INFO] Using worker: sync
08:54:36 web.1     | 2013-02-15 08:54:36 [564] [INFO] Booting worker with pid: 564
08:54:36 web.1     | 2013-02-15 08:54:36 [565] [INFO] Booting worker with pid: 565
08:54:36 web.1     | 2013-02-15 08:54:36 [566] [INFO] Booting worker with pid: 566
08:54:36 web.1     | 2013-02-15 08:54:36 [567] [INFO] Booting worker with pid: 567
08:54:37 celeryd.1 | [2013-02-15 08:54:37,480: DEBUG/MainProcess] [Worker] Loading modules.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,484: DEBUG/MainProcess] [Worker] Claiming components.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,484: DEBUG/MainProcess] [Worker] Building boot step graph.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,484: DEBUG/MainProcess] [Worker] New boot order: {ev, queues, beat, pool, mediator, autoreloader, timers, state-db, autoscaler, consumer}
08:54:37 celeryd.1 | [2013-02-15 08:54:37,489: DEBUG/MainProcess] Starting celery.beat._Process...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,490: DEBUG/MainProcess] celery.beat._Process OK!
08:54:37 celeryd.1 | [2013-02-15 08:54:37,491: DEBUG/MainProcess] Starting celery.concurrency.processes.TaskPool...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,491: INFO/Beat] Celerybeat: Starting...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,506: DEBUG/MainProcess] celery.concurrency.processes.TaskPool OK!
08:54:37 celeryd.1 | [2013-02-15 08:54:37,507: DEBUG/MainProcess] Starting celery.worker.mediator.Mediator...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,507: DEBUG/MainProcess] celery.worker.mediator.Mediator OK!
08:54:37 celeryd.1 | [2013-02-15 08:54:37,507: DEBUG/MainProcess] Starting celery.worker.consumer.BlockingConsumer...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,508: WARNING/MainProcess] celery@myhost.local ready.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,508: DEBUG/MainProcess] consumer: Re-establishing connection to the broker...
08:54:37 celeryd.1 | [2013-02-15 08:54:37,510: INFO/MainProcess] consumer: Connected to django://localhost//.
08:54:37 celeryd.1 | [2013-02-15 08:54:37,628: DEBUG/Beat] Current schedule:
08:54:37 celeryd.1 | <Entry: celery.backend_cleanup celery.backend_cleanup() {<crontab: * 4 * * * (m/h/d/dM/MY)>}
08:54:37 celeryd.1 | [2013-02-15 08:54:37,629: DEBUG/Beat] Celerybeat: Ticking with max interval->5.00 minutes
08:54:37 celeryd.1 | [2013-02-15 08:54:37,658: DEBUG/Beat] Celerybeat: Waking up in 5.00 minutes.
08:54:38 celeryd.1 | [2013-02-15 08:54:38,110: DEBUG/MainProcess] consumer: basic.qos: prefetch_count->16
08:54:38 celeryd.1 | [2013-02-15 08:54:38,126: DEBUG/MainProcess] consumer: Ready to accept tasks!
08:55:08 celeryd.1 | [2013-02-15 08:55:08,184: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!?
08:55:08 celeryd.1 | The full contents of the message body was: body: 26 (2b) {content_type:u'application/json' content_encoding:u'utf-8' delivery_info:{u'priority': 0, u'routing_key': u'celery', u'exchange': u'celery'}}


问:
How to use Retrofit2 to parse json into class with subclass(es)
How to convert given json response

```<code>{
    "name" : "John",
    "surname" : "Doe",
    "location" : {
        "name" : "Paris",
        "desc" : "Welcome to Paris"
    }
}
</code>```

into

```<code>class Person
{
    String name;
    String surname;
    Location location;  // new Location(String name, String desc)
}
</code>```

It's all about nested Location class that is inside Person class

答:
Use @Expose or @SerializedName annotation like

```<code>class Person
{
    @SerializedName("name")
    String name;

    @SerializedName("surname")
    String surname;

    @SerializedName("location")
    Location location;  // new Location(String name, String desc)
}
</code>```

and Location class like

```<code> class Location
    {
        @SerializedName("name")
        String name;

        @SerializedName("desc")
        String desc;
   }
</code>```

Add getter and setter method for accessing data

Body:
How to convert given json response

{
    "name" : "John",
    "surname" : "Doe",
    "location" : {
        "name" : "Paris",
        "desc" : "Welcome to Paris"
    }
}

into

class Person
{
    String name;
    String surname;
    Location location;  // new Location(String name, String desc)
}

It's all about nested Location class that is inside Person class

Body:
Use @Expose or @SerializedName annotation like

class Person
{
    @SerializedName("name")
    String name;

    @SerializedName("surname")
    String surname;

    @SerializedName("location")
    Location location;  // new Location(String name, String desc)
}

and Location class like

 class Location
    {
        @SerializedName("name")
        String name;

        @SerializedName("desc")
        String desc;
   }

Add getter and setter method for accessing data


问:
Migrating 32bit iOS app to 64bit
I am migrating my old iOS app code which was build in 32 bit Architecture. Now that Apple has removed support for that in OS11 I have to add support for 64bit. While doing so I am getting following error

```<code>Apple Mach-O Linker Error Group   "_OBJC_CLASS_$_GPPShare", referenced from:
</code>```

I have old google plus SDK for sharing that as(filename: GPPShare.h)

答: Xcode is not able to find GPPShare file as your sdk file must not be compatible with 64 bit architecture.Replace it with latest available framework for 64 bit support. </p>

Title: Migrating 32bit iOS app to 64bit

Body:
I am migrating my old iOS app code which was build in 32 bit Architecture. Now that Apple has removed support for that in OS11 I have to add support for 64bit. While doing so I am getting following error

Apple Mach-O Linker Error Group   "_OBJC_CLASS_$_GPPShare", referenced from:

I have old google plus SDK for sharing that as(filename: GPPShare.h)


问:
What is the difference between IRI and URI in OWL?
Example:

```<code>http://data.doremus.org/activity/587ae689-790e-3525-9e3a-dac63f449a03
</code>```

I think it is a IRI and also a URI. (Am I right?)

And I use OWL API to parse it. In the class "IRI", there is a method getShortForm(), when I use it, I get "ae689-790e-3525-9e3a-dac63f449a03".

About URI, I think its local name is "587ae689-790e-3525-9e3a-dac63f449a03". I am not very sure. In fact, I know the word "local name" from others' blog. I don't find the "local name" in URI's structure as follows.

```<code>scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]
</code>```

So, I have two questions:

What's the shortForm of IRI? Why the shortForm of the example is not "587ae689-790e-3525-9e3a-dac63f449a03"?

What's the local name of URI and what's the local name of the example?

答:
An IRI is an URI whose characters include characters outside the URI specs. The I is for Internationalised, so every URI is an IRI.

Local name for an IRI is just a convenience. It starts after the last character in the IRI that cannot be part of an XML NCName - this is due to XML syntactical restrictions on what is a valid tag name.

An NCName cannot start with a number; that's why you're getting three digits dropped off after the slash.

Body:
Example:

http://data.doremus.org/activity/587ae689-790e-3525-9e3a-dac63f449a03

I think it is a IRI and also a URI. (Am I right?)

And I use OWL API to parse it. In the class "IRI", there is a method getShortForm(), when I use it, I get "ae689-790e-3525-9e3a-dac63f449a03".

About URI, I think its local name is "587ae689-790e-3525-9e3a-dac63f449a03". I am not very sure. In fact, I know the word "local name" from others' blog. I don't find the "local name" in URI's structure as follows.

scheme:[//[user[:password]@]host[:port]][/path][?query][#fragment]

So, I have two questions:

What's the shortForm of IRI? Why the shortForm of the example is not "587ae689-790e-3525-9e3a-dac63f449a03"?

What's the local name of URI and what's the local name of the example?


问:
dagger2 activityscope providing same object of injected dependencies with different activities
Following code creates & shares same object of injected dependencies(ViewsApiEnd ) with different activities rather than creating different per activity.

```<code>@ActivityScope
@Component(dependencies = HttpComponent.class, modules = ViewsApiModule.class)
public interface ViewsApiComponent {
    void inject(MainActivity activity);

    void inject(SecondActivity activity2);
}
</code>```

module:

```<code>@Module
public class ViewsApiModule {

    @Provides
    @ActivityScope
    public ViewsApiEnd providesGitHubInterface(Retrofit retrofit) {
        return retrofit.create(ViewsApiEnd.class);
    }
}
</code>```

Scope:

```<code>@Scope
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ActivityScope{
    }
</code>```

Full Source: Github(If anyone could fork & correct scope issue it'll be helpful. Also checke  void logInstances() for verifying object creation )

How should I declare ViewsApiComponent if I want dagger2 to create different objects of injected deps( ViewsApiEnd) for different activities(MainActivity , SecondActivity )?

答:
I'm assuming by different object you mean different instances and not different implementations.

The key to this is scopes and how you manage your components. In particular ViewsApiComponent.

Let's start with scopes. A scope in dagger is nothing but an annotation that tells dagger that during the life of a given component, as long as an object annotated with a given scope is required, the instance provided will always be the same. In other words, within the same component scoped dependencies will be singleton.

In your code, this ActivityScope is the scope tied to ViewsApiEnd. Now what people usually don't get about scopes is the first part of - "... as long as the component is alive scoped dependencies are singleton". Basically this says, if your component's instance remains the same, then all your scoped instances will be the same.

In your code this is the case because you pin mViewsApiComponent to the application class and you never recreate it. So in your activities when you do this:

```<code>// ...
((MyApp) getApplication()).getGitHubComponent().inject(this);
// ...
</code>```

You're always using the same component, hence same scopes, hence same instance of ViewsApiEnd.

You need to make sure the scoped dependencies have a proper scoped handling. If you want a dependency that is different per activity, then you want to manage the component that takes care of this dependency on a per activity basis.

There's different ways of doing this. I think the simplest one in your case is to move the creation of ViewsApiComponent to your activities. Make sure you nullify the component in onDestroy. Something like this:

```<code>private ViewsApiComponent mViewsApiComponent;

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

    getComponent().inject(this);
}

@Overrides
public void onDestroy() {
    super.onDestroy();
    mViewsApiComponent = null;
}

private ViewsApiComponent getComponent() {
  if (mViewsApiComponent == null) {
       mViewsApiComponent = DaggerViewsApiComponent.builder()
            .httpComponent(((MyApp) getApplication()).getNetComponent())
            .build();
  }
  return mViewsApiComponent;
}
</code>```

You can even put this code in a base activity and inherit from it in each activity.

Important thing to notice is that the component is now managed by the activity, or better put it's tied to its life-cycle. This ensures the component lives during the life time of the activity and all scoped dependencies are the same within that activity. For another activity a new component will be created and the new object instances will be used, but within the activity they will remain the same.

Now I've explained all of this just for the sake of trying to help you out with components and scopes, but truth is that what you're currently providing in the component's modules are all objects that should indeed be singleton throughout the app's life. So in fact, the way you have it now is the most correct approach at least in my opinion.

Hope this helps

Body:
Following code creates & shares same object of injected dependencies(ViewsApiEnd ) with different activities rather than creating different per activity.

@ActivityScope
@Component(dependencies = HttpComponent.class, modules = ViewsApiModule.class)
public interface ViewsApiComponent {
    void inject(MainActivity activity);

    void inject(SecondActivity activity2);
}

module:

@Module
public class ViewsApiModule {

    @Provides
    @ActivityScope
    public ViewsApiEnd providesGitHubInterface(Retrofit retrofit) {
        return retrofit.create(ViewsApiEnd.class);
    }
}

Scope:

@Scope
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ActivityScope{
    }

Full Source: Github(If anyone could fork & correct scope issue it'll be helpful. Also checke  void logInstances() for verifying object creation )

How should I declare ViewsApiComponent if I want dagger2 to create different objects of injected deps( ViewsApiEnd) for different activities(MainActivity , SecondActivity )?

Body:
I'm assuming by different object you mean different instances and not different implementations.

The key to this is scopes and how you manage your components. In particular ViewsApiComponent.

Let's start with scopes. A scope in dagger is nothing but an annotation that tells dagger that during the life of a given component, as long as an object annotated with a given scope is required, the instance provided will always be the same. In other words, within the same component scoped dependencies will be singleton.

In your code, this ActivityScope is the scope tied to ViewsApiEnd. Now what people usually don't get about scopes is the first part of - "... as long as the component is alive scoped dependencies are singleton". Basically this says, if your component's instance remains the same, then all your scoped instances will be the same.

In your code this is the case because you pin mViewsApiComponent to the application class and you never recreate it. So in your activities when you do this:

// ...
((MyApp) getApplication()).getGitHubComponent().inject(this);
// ...

You're always using the same component, hence same scopes, hence same instance of ViewsApiEnd.

You need to make sure the scoped dependencies have a proper scoped handling. If you want a dependency that is different per activity, then you want to manage the component that takes care of this dependency on a per activity basis.

There's different ways of doing this. I think the simplest one in your case is to move the creation of ViewsApiComponent to your activities. Make sure you nullify the component in onDestroy. Something like this:

private ViewsApiComponent mViewsApiComponent;

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

    getComponent().inject(this);
}

@Overrides
public void onDestroy() {
    super.onDestroy();
    mViewsApiComponent = null;
}

private ViewsApiComponent getComponent() {
  if (mViewsApiComponent == null) {
       mViewsApiComponent = DaggerViewsApiComponent.builder()
            .httpComponent(((MyApp) getApplication()).getNetComponent())
            .build();
  }
  return mViewsApiComponent;
}

You can even put this code in a base activity and inherit from it in each activity.

Important thing to notice is that the component is now managed by the activity, or better put it's tied to its life-cycle. This ensures the component lives during the life time of the activity and all scoped dependencies are the same within that activity. For another activity a new component will be created and the new object instances will be used, but within the activity they will remain the same.

Now I've explained all of this just for the sake of trying to help you out with components and scopes, but truth is that what you're currently providing in the component's modules are all objects that should indeed be singleton throughout the app's life. So in fact, the way you have it now is the most correct approach at least in my opinion.

Hope this helps