问:
Big ugly SQL query problem
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id
</code>```

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

```<code>Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------
</code>```

答:
I'm not sure if this would work in Access as well, but I'm pretty sure this should give the correct results:</p>

```<code>SELECT status_id, max(levelS) as ds_column, max(levelD) as ss_column
FROM (
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc1 = sl.desc
UNION ALL
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc2 = sl.desc
UNION ALL
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc3 = sl.desc
UNION ALL
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc4 = sl.desc
) ssl
GROUP BY status_id
</code>```

Title: Big ugly SQL query problem

Body:
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------

Body:
I'm not sure if this would work in Access as well, but I'm pretty sure this should give the correct results:

SELECT status_id, max(levelS) as ds_column, max(levelD) as ss_column
FROM (
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc1 = sl.desc
UNION ALL
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc2 = sl.desc
UNION ALL
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc3 = sl.desc
UNION ALL
    SELECT s.status_id, sl.levelS, sl.levelD
    FROM Status s
    INNER JOIN Status_level sl ON s.desc4 = sl.desc
) ssl
GROUP BY status_id


来源: stackexchange

问:
What is the equivalent of foreach php in python
I have been using PHP for several years and now, I am trying to shift to a new one. I am interested of learning python.

In PHP, we use foreach something like this:

```<code><?php
$var = array('John', 'Adam' , 'Ken');
foreach($var as $index => $value){
   echo $value;
}
</code>```

How do we integrate this code in python?

答:
The equivalent of the foreach statement is actually the python for statement.

e.g.

```<code>>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     print(i)
...
1
2
3
4
5
</code>```

It actually works for all iterables in python, including strings.

```<code>>>> word = "stackoverflow"
>>> for c in word:
...     print(c)
...
s
t
a
c
k
o
v
e
r
f
l
o
w
</code>```

However, it is worth noting that when using the for loop in this way you are not editing the iterable's values in place as they are a shallow copy.

```<code>>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     i += 1
...     print(i)
...
2
3
4
5
6
>>> print(items)
[1, 2, 3, 4, 5]
</code>```

Instead you would have to use the iterable's index.

```<code>>>> items = [1, 2, 3, 4, 5]
>>> for i in range(len(items)):
...     items[i] += 1
...
>>> print(items)
[2, 3, 4, 5, 6]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been using PHP for several years and now, I am trying to shift to a new one. I am interested of learning python.

In PHP, we use foreach something like this:

<?php
$var = array('John', 'Adam' , 'Ken');
foreach($var as $index => $value){
   echo $value;
}

How do we integrate this code in python?

Body:
The equivalent of the foreach statement is actually the python for statement.

e.g.

>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     print(i)
...
1
2
3
4
5

It actually works for all iterables in python, including strings.

>>> word = "stackoverflow"
>>> for c in word:
...     print(c)
...
s
t
a
c
k
o
v
e
r
f
l
o
w

However, it is worth noting that when using the for loop in this way you are not editing the iterable's values in place as they are a shallow copy.

>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     i += 1
...     print(i)
...
2
3
4
5
6
>>> print(items)
[1, 2, 3, 4, 5]

Instead you would have to use the iterable's index.

>>> items = [1, 2, 3, 4, 5]
>>> for i in range(len(items)):
...     items[i] += 1
...
>>> print(items)
[2, 3, 4, 5, 6]


问:
Understanding .bind() in relation to arguments
I am reviewing some game code and I have a piece that I don't quite understand.

```<code>var game = (function(){

   // Start with our constructor
   function Game(){
        this.viewport = document.getElementById('viewport');
        this.ctx = this.viewport.getContext('2d');
    };

    Game.prototype.updateAnimation = function(t){

        // work out the delta time
        this.dt = this.lastFrameTime ? ((t - this.lastFrameTime)/1000.0).fixed() : 0.016;

        // store last frame time
        this.lastFrameTime = t;

        // run relevent updates here

        // queue the next animation time.
        this.animationId = window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport );
    }

    // return game class
    return Game;

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

Then

```<code>// call new game object
var clientGame = new game();

// call event loop
clientGame.updateAnimation(new Date().getTime());
</code>```

When request window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport ); runs. How does it know the value of the paramter t. It seems to update each time, but I don't understand why. Can someone please explain whats going on? Thanks.

EDIT

There is a function attached to the Number prototype chain called fixed(). Here it is for clarity

```<code> Number.prototype.fixed = function(n) { n = n || 3; return parseFloat(this.toFixed(n)); };
</code>```

答:
So requestAnimationFrame has one parameter, a callback which gets a timestamp as argument.
The bind function returns the original function but in a different scope. So requestAnimationFrame calls updateAnimation with the timestamp, which is where your time is coming from.

Now to understand the reasoning behind the bind call you need to understand scopes in JavaScript.

When you're defining a function and passing it to another function as a parameter you're actually calling the first function in the scope of the second. This means if you have a class instance and you wanna pass an instance method to a function as a callback you either need to use an arrow function which preserves the current scope or you bind the method to the correct scope (your class instance).

I hope the following example better shows what I'm talking about.

```<code>class OuterScope {
    constructor() {
        this.label = 'test';
    }

    print() {
        console.log(this.label);
    }
}

function innerScope(callback) {
    callback();
}

var scope = new OuterScope();
innerScope(scope.print); // throws error because the scope the function is called in doesn't have a property called label
innerScope(scope.print.bind(scope)); // prints label
</code>```

Now apply this to your requestAnimationFrame problem:

```<code>class Game {
    updateAnimation(t) {
        // this.lastFrameTime would always be undefined when called without binding
        this.dt = this.lastFrameTime ? ((t - this.lastFrameTime)/1000.0).fixed() : 0.016;

        // store last frame time
        this.lastFrameTime = t;

        window.requestAnimationFrame(this.updateAnimation.bind(this)); // updateAnimation now always runs in the scope of the current Game instance
        // window.requestAnimationFrame(this.updateAnimation); // updateAnimation runs in the scope of the window
    }
}

window.requestAnimationFrame = function requestAnimationFrame(callback) {
    callback(new Date().getTime()); // calls the callback with one argument
}
</code>```

Body:
I am reviewing some game code and I have a piece that I don't quite understand.

var game = (function(){

   // Start with our constructor
   function Game(){
        this.viewport = document.getElementById('viewport');
        this.ctx = this.viewport.getContext('2d');
    };

    Game.prototype.updateAnimation = function(t){

        // work out the delta time
        this.dt = this.lastFrameTime ? ((t - this.lastFrameTime)/1000.0).fixed() : 0.016;

        // store last frame time
        this.lastFrameTime = t;

        // run relevent updates here

        // queue the next animation time.
        this.animationId = window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport );
    }

    // return game class
    return Game;

})();

Then

// call new game object
var clientGame = new game();

// call event loop
clientGame.updateAnimation(new Date().getTime());

When request window.requestAnimationFrame( this.updateAnimation.bind(this), this.viewport ); runs. How does it know the value of the paramter t. It seems to update each time, but I don't understand why. Can someone please explain whats going on? Thanks.

EDIT

There is a function attached to the Number prototype chain called fixed(). Here it is for clarity

 Number.prototype.fixed = function(n) { n = n || 3; return parseFloat(this.toFixed(n)); };

Body:
So requestAnimationFrame has one parameter, a callback which gets a timestamp as argument.
The bind function returns the original function but in a different scope. So requestAnimationFrame calls updateAnimation with the timestamp, which is where your time is coming from.

Now to understand the reasoning behind the bind call you need to understand scopes in JavaScript.

When you're defining a function and passing it to another function as a parameter you're actually calling the first function in the scope of the second. This means if you have a class instance and you wanna pass an instance method to a function as a callback you either need to use an arrow function which preserves the current scope or you bind the method to the correct scope (your class instance).

I hope the following example better shows what I'm talking about.

class OuterScope {
    constructor() {
        this.label = 'test';
    }

    print() {
        console.log(this.label);
    }
}

function innerScope(callback) {
    callback();
}

var scope = new OuterScope();
innerScope(scope.print); // throws error because the scope the function is called in doesn't have a property called label
innerScope(scope.print.bind(scope)); // prints label

Now apply this to your requestAnimationFrame problem:

class Game {
    updateAnimation(t) {
        // this.lastFrameTime would always be undefined when called without binding
        this.dt = this.lastFrameTime ? ((t - this.lastFrameTime)/1000.0).fixed() : 0.016;

        // store last frame time
        this.lastFrameTime = t;

        window.requestAnimationFrame(this.updateAnimation.bind(this)); // updateAnimation now always runs in the scope of the current Game instance
        // window.requestAnimationFrame(this.updateAnimation); // updateAnimation runs in the scope of the window
    }
}

window.requestAnimationFrame = function requestAnimationFrame(callback) {
    callback(new Date().getTime()); // calls the callback with one argument
}


问:
Logcat not displaying my log calls
I'm a total noob at Android programming, and wanted to learn how to debug my apps.  I can't seem to have my Log.i|d|v calls displayed in the LogCat.

Here's the code that I'm using.  As you can see I have defined a LOG_TAG constant, but can't seem to find it in the LogCat.  I have also imported android.util.Log AND I have made sure that in my AndroidManifest I have "debuggable" set to TRUE.

I have also checked http://developer.android.com/reference/android/util/Log.html w/o any luck resolving this issue.

What am I doing wrong?  Am I even looking in the right place?  I've tried using the DDMS and Debug perspective as well w/o any luck.  Any help to this noob would be greatly appreciated.  Thanks.

My environment:
Windows XP
IDE = Eclipse Version: 3.6.1, Build id: M20100909-0800
Emulator = having it point to android sdk 2.1 api 7

//very basic HELLO World code with a couple of Log.i calls

```<code>import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class debugger extends Activity {
    private static final String LOG_TAG = "debugger";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(LOG_TAG, "line 13");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.i(LOG_TAG, "CREATING NOW");
    }
}
</code>```

答:
I have this problems and fixed, String TAG without space:

"my tag" // noting show

"my_tag" // is ok

ContentLicense: CC BY-SA 2.5

Title: Logcat not displaying my log calls

Body:
I'm a total noob at Android programming, and wanted to learn how to debug my apps.  I can't seem to have my Log.i|d|v calls displayed in the LogCat.

Here's the code that I'm using.  As you can see I have defined a LOG_TAG constant, but can't seem to find it in the LogCat.  I have also imported android.util.Log AND I have made sure that in my AndroidManifest I have "debuggable" set to TRUE.

I have also checked http://developer.android.com/reference/android/util/Log.html w/o any luck resolving this issue.

What am I doing wrong?  Am I even looking in the right place?  I've tried using the DDMS and Debug perspective as well w/o any luck.  Any help to this noob would be greatly appreciated.  Thanks.

My environment:
Windows XP
IDE = Eclipse Version: 3.6.1, Build id: M20100909-0800
Emulator = having it point to android sdk 2.1 api 7

//very basic HELLO World code with a couple of Log.i calls

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class debugger extends Activity {
    private static final String LOG_TAG = "debugger";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i(LOG_TAG, "line 13");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Log.i(LOG_TAG, "CREATING NOW");
    }
}


问:
Handling $_SESSION object in a load-balanced setup, PHP
I have a setup where I have a host which routes multiple requests in a load-balanced fashion. My backend uses PHP. Now, I need to use the $_SESSION object for some of my processing.

Will $_SESSION work where I have 3 backend servers which can receive any request at any time?

If not, Can one suggest alternatives to handle such cases?

EDIT: I do understand that we can store sessions in a database and find a way to track it. But, the problem in a realtime load-balanced production scenario is the number of calls that go into a DB. That can be a real bummer for my performance. I'm kind of hoping that, we can handle this at an webserver level.

Not sure, if it is possible, but, if two webservers have some kind of replication mechanism like databases do, it will be brilliant. I dont have to do a thing.

If such a thing does not exist, PHP should be modified to support it. That will actually, make it a seriously robust language.

答:
My Suggestion is to setup PHP to handle the sessions in the database (this way they can all access the session data independent of which server is requesting it).

A good tutorial for that can be found HERE


问:
Populate an array without a loop
I am trying to avoid the use of loops for populating arrays since they take a lot of time when managing a lot of data.

Apparently as well, that is possible and easy in VBA but often results in problems.

Here is the code:

```<code>sub populate()
'put the whole column in an array
Dim AppArray() As Variant
Dim AppRange As Range
'calculate the last row of the column 1 of sheets
Dim LstRow As Integer
LstRow = Sheets("whole").Cells(Sheets("whole").Rows.Count, "A").End(xlUp).row
'here I calculate the range that I want to pass to the array
Set AppRange = Sheets("whole").Range(Cells(1, 1), Cells(LstRow, 1))
MsgBox ("apprange " & AppRange.Address)
'i dont know if I need to redim or not
ReDim AppArray(1 To LstRow)
'here comes the point. populate the array with the values of the range
AppArray = AppRange.Value
End Sub
</code>```

This does not work. I also tried application.tranpose(AppRange.Value).

I used:

```<code>For i = 1 To LstRow
Debug.Print AppArray(i)
Next
</code>```

and an error appears, so somehow there is no AppArray(1).

I would be very happy if you can comment on that. More than just arranging the code suggest even other pages (links) to populate arrays with values of ranges when these ranges are not known in advance.

If the case is that looping is very time consuming and that arrays can be populated straight away, I don't understand why 99% of the pages referring to arrays use a loop (or nested loop) to populate an array.

答:
I found the answer.

```<code>dim myRange as range
dim myArray() as variant
myRange = range(cells(2,3),cells(10,15))
redeem myArray(1 to 20,1 to 20)
myArray=myRange
</code>```

It's always much faster to work with variables and arrays than with cells values.

ContentLicense: CC BY-SA 4.0

Title: Populate an array without a loop

Body:
I am trying to avoid the use of loops for populating arrays since they take a lot of time when managing a lot of data.

Apparently as well, that is possible and easy in VBA but often results in problems.

Here is the code:

sub populate()
'put the whole column in an array
Dim AppArray() As Variant
Dim AppRange As Range
'calculate the last row of the column 1 of sheets
Dim LstRow As Integer
LstRow = Sheets("whole").Cells(Sheets("whole").Rows.Count, "A").End(xlUp).row
'here I calculate the range that I want to pass to the array
Set AppRange = Sheets("whole").Range(Cells(1, 1), Cells(LstRow, 1))
MsgBox ("apprange " & AppRange.Address)
'i dont know if I need to redim or not
ReDim AppArray(1 To LstRow)
'here comes the point. populate the array with the values of the range
AppArray = AppRange.Value
End Sub

This does not work. I also tried application.tranpose(AppRange.Value).

I used:

For i = 1 To LstRow
Debug.Print AppArray(i)
Next

and an error appears, so somehow there is no AppArray(1).

I would be very happy if you can comment on that. More than just arranging the code suggest even other pages (links) to populate arrays with values of ranges when these ranges are not known in advance.

If the case is that looping is very time consuming and that arrays can be populated straight away, I don't understand why 99% of the pages referring to arrays use a loop (or nested loop) to populate an array.

Body:
I found the answer.

dim myRange as range
dim myArray() as variant
myRange = range(cells(2,3),cells(10,15))
redeem myArray(1 to 20,1 to 20)
myArray=myRange

It's always much faster to work with variables and arrays than with cells values.


问:
Vert.x verticals approach
Wanted to understand the approach we should follow if we have to build multiple (three in my case) APIs in Vert.x

Should we have separate verticals running for each API i.e. Have a master verticle, and three verticles for each of these. Master verticle sends message to each verticle and that verticle takes care of formulating message and send it back

OR

Have a single verticle, just route it to separate methods with method calls

Please suggest how we should decide on the approach.

答:
I agree with @berserkk. Keep it in one verticle, otherwise different parts of the API would have to run on different ports - as you cannot create multiple HTTP servers in multiple verticles listening on the same port.

However, a good way to split up your API might be based on vert.x Routers. Let's assume you have API submodules structured like this

```<code>/products/...
/inventory/...
/orders/...
</code>```

For every of these submodules you can create a Router provider, e.g. ProductsRouterProvider, InventoryRouterProvider or OrdersRouterProvider.

Each of these providers takes care of the specific API module - basically registers required routes.

class ProductsRouterProvider {
  static Router create(Vertx vertx) {
    Router router = Router.router(vertx)
    router.get("/").handler(new ListAllProductsHandler())
    router.get("/:productId").handler(new ProductDetailHandler())
    ...
    return router;
  }
}
```

<p>And finally, register the submodule <code>Routers</code> on the base <code>Router</code>.</p>

<pre class="lang-java prettyprint-override"><code>Router router = Router.router(vertx)
router.mountSubRouter("/", ProductsRouterProvider.create(vertx))
router.mountSubRouter("/", InventoryRouterProvider.create(vertx))
router.mountSubRouter("/", OrdersRouterProvider.create(vertx))
</code>```

Title: Vert.x verticals approach

Body:
I agree with @berserkk. Keep it in one verticle, otherwise different parts of the API would have to run on different ports - as you cannot create multiple HTTP servers in multiple verticles listening on the same port.

However, a good way to split up your API might be based on vert.x Routers. Let's assume you have API submodules structured like this

/products/...
/inventory/...
/orders/...

For every of these submodules you can create a Router provider, e.g. ProductsRouterProvider, InventoryRouterProvider or OrdersRouterProvider.

Each of these providers takes care of the specific API module - basically registers required routes.

class ProductsRouterProvider {
  static Router create(Vertx vertx) {
    Router router = Router.router(vertx)
    router.get("/").handler(new ListAllProductsHandler())
    router.get("/:productId").handler(new ProductDetailHandler())
    ...
    return router;
  }
}

And finally, register the submodule Routers on the base Router.

Router router = Router.router(vertx)
router.mountSubRouter("/", ProductsRouterProvider.create(vertx))
router.mountSubRouter("/", InventoryRouterProvider.create(vertx))
router.mountSubRouter("/", OrdersRouterProvider.create(vertx))


问:
Visual Studio Hangs when closing .SQL files
I have all extensions disabled, and only 1 Sql Project open. Yet Visual Studio hangs whenever I close a SQL file.

Versions affected:

2017 Enterprise

2015 Enterprise

During this "hang time" Visual Studio possesses a Not Responding status.

It also appears that the amount of time it stays locked is correlated to the number of files being closed/are open.

EDIT: Reproducable with devenv in SafeMode

Thoughts?

答:
It appears that VS is generating a Windows Error Report (WER) event when a .sql file window is closed:

```<code>Fault bucket , type 0
Event Name: VisualStudioNonFatalErrors2
Response: Not available
Cab Id: 0

Problem signature:
P1: devenv.exe
P2: 15.0.26430.12
P3: vs.platform.hwndwrapper.destroy-window-error
P4: unknown
P5: Microsoft.VisualStudio.Shell.15.0
P6: Microsoft.VisualStudio.PlatformUI.HwndWrapper.DestroyWindowCore
P7: unknown
P8: unknown
P9: unknown
P10: unknown
</code>```

These correlate to each attempt to close a window.  Unchecking the build/deploy boxes in the Build Configuration Manager don't seem to help (I'm running VS 2017 Enterprise).

Running procmon shows an 11 second delay on my machine in closing a single window after the handle to wermgr.exe is closed:

```<code>12:19:31.2071581 AM devenv.exe  6564    CloseFile   C:\Windows\SysWOW64\wermgr.exe  SUCCESS
12:19:32.7423468 AM devenv.exe  6564    Thread Exit     SUCCESS Thread ID: 16288, User Time: 0.0000000, Kernel Time: 0.0000000
12:19:36.6511179 AM devenv.exe  6564    Thread Create       SUCCESS Thread ID: 8576
12:19:38.1531428 AM devenv.exe  6564    Thread Exit     SUCCESS Thread ID: 8576, User Time: 0.0000000, Kernel Time: 0.0000000
12:19:42.7939996 AM devenv.exe  6564    Thread Create       SUCCESS Thread ID: 12052
12:19:42.7952451 AM devenv.exe  6564    Thread Exit     SUCCESS Thread ID: 12052, User Time: 0.0000000, Kernel Time: 0.0000000
12:19:42.7953980 AM devenv.exe  6564    Thread Create       SUCCESS Thread ID: 6892
12:19:42.7984705 AM devenv.exe  6564    RegQueryKey HKLM    SUCCESS Query: HandleTags, HandleTags: 0x0
</code>```

This appears to be a product bug with no known workaround at this time.

Body:
It appears that VS is generating a Windows Error Report (WER) event when a .sql file window is closed:

Fault bucket , type 0
Event Name: VisualStudioNonFatalErrors2
Response: Not available
Cab Id: 0

Problem signature:
P1: devenv.exe
P2: 15.0.26430.12
P3: vs.platform.hwndwrapper.destroy-window-error
P4: unknown
P5: Microsoft.VisualStudio.Shell.15.0
P6: Microsoft.VisualStudio.PlatformUI.HwndWrapper.DestroyWindowCore
P7: unknown
P8: unknown
P9: unknown
P10: unknown

These correlate to each attempt to close a window.  Unchecking the build/deploy boxes in the Build Configuration Manager don't seem to help (I'm running VS 2017 Enterprise).

Running procmon shows an 11 second delay on my machine in closing a single window after the handle to wermgr.exe is closed:

12:19:31.2071581 AM devenv.exe  6564    CloseFile   C:\Windows\SysWOW64\wermgr.exe  SUCCESS
12:19:32.7423468 AM devenv.exe  6564    Thread Exit     SUCCESS Thread ID: 16288, User Time: 0.0000000, Kernel Time: 0.0000000
12:19:36.6511179 AM devenv.exe  6564    Thread Create       SUCCESS Thread ID: 8576
12:19:38.1531428 AM devenv.exe  6564    Thread Exit     SUCCESS Thread ID: 8576, User Time: 0.0000000, Kernel Time: 0.0000000
12:19:42.7939996 AM devenv.exe  6564    Thread Create       SUCCESS Thread ID: 12052
12:19:42.7952451 AM devenv.exe  6564    Thread Exit     SUCCESS Thread ID: 12052, User Time: 0.0000000, Kernel Time: 0.0000000
12:19:42.7953980 AM devenv.exe  6564    Thread Create       SUCCESS Thread ID: 6892
12:19:42.7984705 AM devenv.exe  6564    RegQueryKey HKLM    SUCCESS Query: HandleTags, HandleTags: 0x0

This appears to be a product bug with no known workaround at this time.


问:
rest + xop / binary data embedded in xml response
I've been given the task to embed binary data (like pictures, music, thumbnails etc) into a xml metadata container in order to publish the whole package via REST interface. Currently we're using Jersey and spring in our project.
I really don't want to fall back to soap/wsdl (which seems to be the default answer for every ws-based problem) or any container format like zip just to get that data over the wire so i googled a while for a more appropriate solution.

I found out that recommends the XOP format for embedding content into xml which is part of the MTOM protocol used in SOAP but I don't see a solution that provides XML+XOP responses via REST directly.

My question: can someone give me a hint how to implement XOP + REST by using Jersey / spring? I've seen posts that imply that someone has done it before...

Best regards,

tim

答:
Why would you want to embed binary data into XML?  There are plenty of ways to associate binary resources to their corresponding metadata without trying to stuff it into a single representation.

You are defeating one of the primary benefits of REST HTTP.  The ability to handle multiple different media-types based on the requirements is one of the reasons using REST over HTTP can be more effective than SOAP.

Consider retrieving an XML representation of the metadata that contains a link to the binary resource as Atom does.  If you want to retrieve the binary first, then consider Link Headers to point to the metadata.  There are lots of better ways than trying to stuff binary data into XML.


问:
Liferay 7 - Knowledge base versus Web contents
I'm working on Liferay 7 and I have a question on using the portlet Knowledge Base or Web contents. I'm wondering which one is the best to do a FAQ.

Web contents can now be organized in folders, have tags and plenty of informations. KB seems to offer the same capabilities but the content is limited to Markdown script.

Does someone used the KB and have feedback on it ?

Any advice appreciated !
Julien

答:
If you have a small set of FAQ and you require a simple implementation, the web content will suit you as they are simple.
The knowledge base is good fit for web-book kind of things.
If you have dynamic FAQ where people can add edit the answers or where multiple answers are required, you can go for message boards. It has an application display template(ADT) for Q&A as well. I am not very sure but a message broad with Q&A template can be limited to one answer only (with GUI configuration) to function like FAQ.
The other way is to download the message broad Q&A ADT from Liferay sources and tweak it to display as FAQ. This will not require much effort and this will provide for the dynamism in FAQ functionality.


问:
How to make old layouts visible?
I have a layout that is shown correctly, but after adding DrawerLayout my old layouts were hidden. Here is my code after adding drawer:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:weightSum="2"
    android:layout_height="match_parent">
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <include
                android:id="@+id/activity_base"
                layout="@layout/activity_base"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">
                <RelativeLayout
                    android:id="@+id/resturantlayout"
                    android:layout_width="0dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="5dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#bd4304">
                    <TextView
                        android:text="رستوران"
                        android:layout_marginTop="10dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/txtresturant"
                        android:textSize="18sp"
                        android:textStyle="normal|bold"
                        android:layout_centerHorizontal="true"
                        android:layout_below="@+id/imageButtonresturant" />
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/resturantlogo"
                        android:id="@+id/imageButtonresturant"
                        android:scaleType="fitXY"
                        />
                </RelativeLayout>
                <RelativeLayout
                    android:id="@+id/coffeshoplayout"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginBottom="5dp"
                    android:background="#d2ae6d">
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/cofeelogo"
                        android:id="@+id/imageButtencofee"
                        />
                    <TextView
                        android:text="کافه ها"
                        android:layout_marginTop="13dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/textViewcofee"
                        android:textStyle="normal|bold"
                        android:textSize="18sp"
                        android:layout_below="@+id/imageButtencofee"
                        android:layout_centerHorizontal="true" />
                </RelativeLayout>
            </LinearLayout>
            <LinearLayout
                android:id="@+id/servfoodlayout"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">
                <RelativeLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="5dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="10dp"
                    android:background="#f58634">
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/ghazalogo"
                        android:id="@+id/imageButtonghaza" />
                    <TextView
                        android:text="غذای آماده"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textStyle="normal|bold"
                        android:textSize="18sp"
                        android:id="@+id/textViewgghaza"
                        android:layout_below="@+id/imageButtonghaza"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="10dp" />
                </RelativeLayout>
                <RelativeLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="5dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginBottom="10dp"
                    android:background="#7db446">
                    <TextView
                        android:text="فست فود"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/textView3"
                        android:layout_marginTop="10dp"
                        android:textStyle="normal|bold"
                        android:textSize="18sp"
                        android:layout_below="@+id/imageButtonfastfood"
                        android:layout_centerHorizontal="true" />
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/fastfoodlogo"
                        android:id="@+id/imageButtonfastfood"
                        />
                </RelativeLayout>
            </LinearLayout>
        </RelativeLayout>
        <FrameLayout
            android:id="@+id/drawer_frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:layout_marginLeft="56dp"
            android:choiceMode="singleChoice"
            android:dividerHeight="1dp" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>
</code>```

The ids of two old layouts are: "cofeeshoprow, servfoodlayout" that they were shown correct.

答: I should have used android:layout_below="@+id/activity_base" for the layouts which should be shown below the "activity_base". Generally in this cases try to match layouts using "android:layout_below".

Title: How to make old layouts visible?

Body:
I have a layout that is shown correctly, but after adding DrawerLayout my old layouts were hidden. Here is my code after adding drawer:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:weightSum="2"
    android:layout_height="match_parent">
    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
            <include
                android:id="@+id/activity_base"
                layout="@layout/activity_base"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">
                <RelativeLayout
                    android:id="@+id/resturantlayout"
                    android:layout_width="0dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="5dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:background="#bd4304">
                    <TextView
                        android:text="رستوران"
                        android:layout_marginTop="10dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/txtresturant"
                        android:textSize="18sp"
                        android:textStyle="normal|bold"
                        android:layout_centerHorizontal="true"
                        android:layout_below="@+id/imageButtonresturant" />
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/resturantlogo"
                        android:id="@+id/imageButtonresturant"
                        android:scaleType="fitXY"
                        />
                </RelativeLayout>
                <RelativeLayout
                    android:id="@+id/coffeshoplayout"
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="10dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginBottom="5dp"
                    android:background="#d2ae6d">
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/cofeelogo"
                        android:id="@+id/imageButtencofee"
                        />
                    <TextView
                        android:text="کافه ها"
                        android:layout_marginTop="13dp"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/textViewcofee"
                        android:textStyle="normal|bold"
                        android:textSize="18sp"
                        android:layout_below="@+id/imageButtencofee"
                        android:layout_centerHorizontal="true" />
                </RelativeLayout>
            </LinearLayout>
            <LinearLayout
                android:id="@+id/servfoodlayout"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:orientation="horizontal"
                android:weightSum="2">
                <RelativeLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="5dp"
                    android:layout_marginRight="5dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginBottom="10dp"
                    android:background="#f58634">
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/ghazalogo"
                        android:id="@+id/imageButtonghaza" />
                    <TextView
                        android:text="غذای آماده"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textStyle="normal|bold"
                        android:textSize="18sp"
                        android:id="@+id/textViewgghaza"
                        android:layout_below="@+id/imageButtonghaza"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="10dp" />
                </RelativeLayout>
                <RelativeLayout
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginTop="5dp"
                    android:layout_marginRight="10dp"
                    android:layout_marginLeft="5dp"
                    android:layout_marginBottom="10dp"
                    android:background="#7db446">
                    <TextView
                        android:text="فست فود"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:id="@+id/textView3"
                        android:layout_marginTop="10dp"
                        android:textStyle="normal|bold"
                        android:textSize="18sp"
                        android:layout_below="@+id/imageButtonfastfood"
                        android:layout_centerHorizontal="true" />
                    <ImageButton
                        android:layout_width="150dp"
                        android:layout_height="150dp"
                        android:layout_centerHorizontal="true"
                        android:layout_alignParentTop="true"
                        android:layout_marginTop="30dp"
                        android:background="@drawable/fastfoodlogo"
                        android:id="@+id/imageButtonfastfood"
                        />
                </RelativeLayout>
            </LinearLayout>
        </RelativeLayout>
        <FrameLayout
            android:id="@+id/drawer_frame_layout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="right"
            android:layout_marginLeft="56dp"
            android:choiceMode="singleChoice"
            android:dividerHeight="1dp" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

The ids of two old layouts are: "cofeeshoprow, servfoodlayout" that they were shown correct.


问:
String is not recognized as valid date time
Description:

In my application user is allowed to insert date in string format EX- "01/01/2000"and I'm parsing this string value using DateTime.Parse("01/01/00"); it is working fine. But in few case it is breaking.

Case 1:

Input : "01/01/00"

Code: DateTime.Parse("01/01/00");

Output: 01/01/2000

Case 2:

Input : "01/01/000"

Code: DateTime.Parse("01/01/000");

Output: Getting error "String is not recognized as valid date time."

Case 3:

Input : "01/01/0000"

Code: DateTime.Parse("01/01/0000");

Output: Getting error "String is not recognized as valid date time."

How to parse 000 or 0000 as correct year ?

答: Check out the Noda Time library.  It supports a very large range of dates in various geographical areas and conversions between such.  See http://nodatime.org</p>


问:
system io file not found exception/ error handling
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

```<code>using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }
</code>```

答:
You should check existence of a path with

```<code>System.IO.Directory.Exists(directory)
</code>```

and of a file with

```<code>System.IO.File.Exists(filePath)
</code>```

Then, you need to take the try-catch block inside the for-loop, to catch any possible exceptions that occur because of insufficient rights/permissions.

e.g.

```<code>foreach (string i in __file)
{
    try
    {
        FileInfo fajl = new FileInfo(i);
        Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
    }
    catch (System.Exception ex)
    {
        System.Console.WriteLine(ex.Message);
        throw;
    }

}
</code>```

You could also create two try-catch blocks - depends on what you want to do.

```<code>try
{
    foreach (string i in __file)
    {
        try
        {
            FileInfo fajl = new FileInfo(i);
            Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex.Message);
            throw;
        }

    }
}
catch (System.Exception exLoop)
{
    System.Console.WriteLine(exLoop.Message);
    throw;
}
</code>```

Note that in your example, you should first check if the directory "hely" exists:

```<code>if (!System.IO.Directory.Exists(hely))
{
    System.Console.Error.WriteLine("Directory \"{0}\" does not exist.", hely);
    System.Environment.Exit(1);
    // or: return;
}
</code>```

Since exception handling is usually very slow, I would however recommend that you check for the existence of the file/directory explicitly. It would also be a good idea to do so for the file/directory-listing & read-access rights for the respective user. But even if you do so, keep the try-catch, because there might be cases where your program suddenly fails - e.g. when a removable storage is forcefully removed.

Body:
I'm working in C# and I try to do a program that get some infoes the files in a Directory. I made it but i have a problem with the error Handling. When the program runs and for example I give just random numbers to list file infoes i get this error message:

"System.IO.DirectoryNotFoundException: "'Could not find a part of the path 'C:\Temp\first_project\first_project\bin\Debug\12345'.'"

Please someone help me to do the error handling.

Thank you in advance.

using System;
    using System.IO;
    class Test
        {
            static void Main(string[] args)
             {
                Console.WriteLine("Please :");
                string hely = Console.ReadLine();
                string[] __file = Directory.GetFiles(hely);
                string[] __dir = Directory.GetDirectories(hely);

                foreach (string i in __file)
                {
                    FileInfo fajl = new FileInfo(i);
                    Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
                }
                foreach (string i in __dir)
                {
                    DirectoryInfo _file = new DirectoryInfo(i);
                    Console.WriteLine("{0},{1},{2}", _file.Name, _file.Extension, _file.LastWriteTime.ToString());
                }

            Console.ReadKey();
             }

        }

Body:
You should check existence of a path with

System.IO.Directory.Exists(directory)

and of a file with

System.IO.File.Exists(filePath)

Then, you need to take the try-catch block inside the for-loop, to catch any possible exceptions that occur because of insufficient rights/permissions.

e.g.

foreach (string i in __file)
{
    try
    {
        FileInfo fajl = new FileInfo(i);
        Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
    }
    catch (System.Exception ex)
    {
        System.Console.WriteLine(ex.Message);
        throw;
    }

}

You could also create two try-catch blocks - depends on what you want to do.

try
{
    foreach (string i in __file)
    {
        try
        {
            FileInfo fajl = new FileInfo(i);
            Console.WriteLine("{0},{1},{2}", fajl.Name, fajl.Extension, fajl.LastWriteTime.ToString());
        }
        catch (System.Exception ex)
        {
            System.Console.WriteLine(ex.Message);
            throw;
        }

    }
}
catch (System.Exception exLoop)
{
    System.Console.WriteLine(exLoop.Message);
    throw;
}

Note that in your example, you should first check if the directory "hely" exists:

if (!System.IO.Directory.Exists(hely))
{
    System.Console.Error.WriteLine("Directory \"{0}\" does not exist.", hely);
    System.Environment.Exit(1);
    // or: return;
}

Since exception handling is usually very slow, I would however recommend that you check for the existence of the file/directory explicitly. It would also be a good idea to do so for the file/directory-listing & read-access rights for the respective user. But even if you do so, keep the try-catch, because there might be cases where your program suddenly fails - e.g. when a removable storage is forcefully removed.


问:
Clone a lua state
Recently, I have encountered many difficulties when I was developing using C++ and Lua. My situation is: for some reason, there can be thousands of Lua-states in my C++ program. But these states should be same just after initialization. Of course, I can do luaL_loadlibs() and lua_loadfile() for each state, but that is pretty heavy(in fact, it takes a rather long time for me even just initial one state). So, I am wondering the following schema: What about keeping a separate Lua-state(the only state that has to be initialized) which is then cloned for other Lua-states, is that possible?</p>

答:
take a look to the following lua API call I think it is what you exactly need.

```<code>lua_State *lua_newthread (lua_State *L);
</code>```

This creates a new thread, pushes it on the stack, and returns a pointer to a lua_State that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack.

There is no explicit function to close or to destroy a thread. Threads are subject to garbage collection, like any Lua object.

Title: Clone a lua state

Body:
take a look to the following lua API call I think it is what you exactly need.

lua_State *lua_newthread (lua_State *L);

This creates a new thread, pushes it on the stack, and returns a pointer to a lua_State that represents this new thread. The new thread returned by this function shares with the original thread its global environment, but has an independent execution stack.

There is no explicit function to close or to destroy a thread. Threads are subject to garbage collection, like any Lua object.


问:
Dynamic Class creation and access class properties c#
I want to create a class dynamically and add properties to that class dynamically
and after that I want to create a object of that class and Generic list of that class and access it something like this :

答:
Microsoft released a library for creating dynamic linq queries. There is a ClassFactory which can be used to create classes at runtime.

Here's an example:

```<code>class Program
{
    static void SetPropertyValue(object instance, string name, object value)
    {
        // this is just for example, it would be wise to cache the PropertyInfo's
        instance.GetType().GetProperty(name)?.SetValue(instance, value);
    }

    static void Main(string[] args)
    {
        // create an enumerable which defines the properties
        var properties = new[]
        {
            new DynamicProperty("Name", typeof(string)),
            new DynamicProperty("Age", typeof(int)),
        };

        // create the class type
        var myClassType = ClassFactory.Instance.GetDynamicClass(properties);

        // define a List<YourClass> type.
        var myListType = typeof(List<>).MakeGenericType(myClassType);

        // create an instance of the list
        var myList = (IList)Activator.CreateInstance(myListType);

        // create an instance of an item
        var first = Activator.CreateInstance(myClassType);

        // use the method above to fill the properties
        SetPropertyValue(first, "Name", "John");
        SetPropertyValue(first, "Age", 24);

        // add it to the list
        myList.Add(first);

        var second = Activator.CreateInstance(myClassType);

        SetPropertyValue(second, "Name", "Peter");
        SetPropertyValue(second, "Age", 38);

        myList.Add(second);
    }
}
</code>```

You can download it here: DynamicLibrary.cs

Body:
Microsoft released a library for creating dynamic linq queries. There is a ClassFactory which can be used to create classes at runtime.

Here's an example:

class Program
{
    static void SetPropertyValue(object instance, string name, object value)
    {
        // this is just for example, it would be wise to cache the PropertyInfo's
        instance.GetType().GetProperty(name)?.SetValue(instance, value);
    }

    static void Main(string[] args)
    {
        // create an enumerable which defines the properties
        var properties = new[]
        {
            new DynamicProperty("Name", typeof(string)),
            new DynamicProperty("Age", typeof(int)),
        };

        // create the class type
        var myClassType = ClassFactory.Instance.GetDynamicClass(properties);

        // define a List<YourClass> type.
        var myListType = typeof(List<>).MakeGenericType(myClassType);

        // create an instance of the list
        var myList = (IList)Activator.CreateInstance(myListType);

        // create an instance of an item
        var first = Activator.CreateInstance(myClassType);

        // use the method above to fill the properties
        SetPropertyValue(first, "Name", "John");
        SetPropertyValue(first, "Age", 24);

        // add it to the list
        myList.Add(first);

        var second = Activator.CreateInstance(myClassType);

        SetPropertyValue(second, "Name", "Peter");
        SetPropertyValue(second, "Age", 38);

        myList.Add(second);
    }
}

You can download it here: DynamicLibrary.cs


问:
not getting proper base_url in codeigniter app
i am getting this type of url when trying to access pages other than index page

```<code>http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home
</code>```

but url to access page must be

```<code>http://localhost:8012/health-care/index.php/home
</code>```

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

答:
Try this code:

```<code>$config['base_url'] = 'http://localhost:8012/health-care/';
</code>```

and also make index_page as empty like this:

```<code>$config['index_page'] = '';
</code>```

Body:
i am getting this type of url when trying to access pages other than index page

http://localhost:8012/health-care/8012//localhost/health-care/index.php/index.php/home

but url to access page must be

http://localhost:8012/health-care/index.php/home

my problem in url is: "it is duplicating url after "i hhttp://localhost:8012/healthcare/ that should not be duplicated.

i have autoloaded url helper in autoload.php as well as manually in constructor of controller. my base_url in conf

$config['base_url'] = 'http//localhost:8012/health-care/index.php/';

Guide me about this problem.

in addition to tell you that i have two app fron one codeigniter i.e. frontend and backend.

Url for backend works properly but for frontend its giving me mistakes what to do ?

Body:
Try this code:

$config['base_url'] = 'http://localhost:8012/health-care/';

and also make index_page as empty like this:

$config['index_page'] = '';


问:
How to send a request with alamofire with xml Body
I installed Alamofire in my project and now here is what I have done.

I installed postman and I put my url and inside body a xml object and I got my result.

Here is a picture of what I exactly have done with postman

How can I now use Alamofire or SWXMLHash to send it as I send it with postman

Thanks in advance!

EDIT

I tried this from another question:

```<code> Alamofire.request(.POST, "https://something.com" , parameters: Dictionary(), encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            return (mutableRequest, nil)
        }))

    .responseJSON { response in

    print(response.response)

    print(response.result)

    }
}
</code>```

But it didn't send anything

This is the log:

Optional( { URL:
  https://something.com } { status code: 200, headers {
      Connection = "keep-alive";
      "Content-Length" = 349;
      "Content-Type" = "application/xml";
      Date = "Wed, 02 Nov 2016 21:13:32 GMT";
      Server = nginx;
      "Strict-Transport-Security" = "max-age=31536000; includeSubDomains"; } })

FAILURE

EDIT

NEVER FORGET TO PASS parameters if you don't have simple add this , parameters: Dictionary()

答:
Using Swift 3 and Alamofire 4</p>

```<code>    let stringParams : String = "<msg id=\"123123\" reqTime=\"123123\">" +
        "<params class=\"API\">" +
        "<param name=\"param1\">123213</param>" +
        "<param name=\"param2\">1232131</param>" +
        "</params>" +
    "</msg>"

    let url = URL(string:"<#URL#>")
    var xmlRequest = URLRequest(url: url!)
    xmlRequest.httpBody = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
    xmlRequest.httpMethod = "POST"
    xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type")

    Alamofire.request(xmlRequest)
            .responseData { (response) in
                let stringResponse: String = String(data: response.data!, encoding: String.Encoding.utf8) as String!
                debugPrint(stringResponse)
    }
</code>```

Body:
I installed Alamofire in my project and now here is what I have done.

I installed postman and I put my url and inside body a xml object and I got my result.

Here is a picture of what I exactly have done with postman

How can I now use Alamofire or SWXMLHash to send it as I send it with postman

Thanks in advance!

EDIT

I tried this from another question:

 Alamofire.request(.POST, "https://something.com" , parameters: Dictionary(), encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            return (mutableRequest, nil)
        }))

    .responseJSON { response in

    print(response.response)

    print(response.result)

    }
}

But it didn't send anything

This is the log:

Optional( { URL:
  https://something.com } { status code: 200, headers {
      Connection = "keep-alive";
      "Content-Length" = 349;
      "Content-Type" = "application/xml";
      Date = "Wed, 02 Nov 2016 21:13:32 GMT";
      Server = nginx;
      "Strict-Transport-Security" = "max-age=31536000; includeSubDomains"; } })

FAILURE

EDIT

NEVER FORGET TO PASS parameters if you don't have simple add this , parameters: Dictionary()

Body:
Using Swift 3 and Alamofire 4

    let stringParams : String = "<msg id=\"123123\" reqTime=\"123123\">" +
        "<params class=\"API\">" +
        "<param name=\"param1\">123213</param>" +
        "<param name=\"param2\">1232131</param>" +
        "</params>" +
    "</msg>"

    let url = URL(string:"<#URL#>")
    var xmlRequest = URLRequest(url: url!)
    xmlRequest.httpBody = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
    xmlRequest.httpMethod = "POST"
    xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type")

    Alamofire.request(xmlRequest)
            .responseData { (response) in
                let stringResponse: String = String(data: response.data!, encoding: String.Encoding.utf8) as String!
                debugPrint(stringResponse)
    }


问:
Open email after sending
Why am I facing the below problem?

I have written a code to open sent email after sending email. The VBA code doesn't open the latest sent email but the previous one.

```<code>Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim myItem As MailItem
    Dim myNamespace As NameSpace
    Dim myFolder As Folder

    Set myNamespace = Application.GetNamespace("MAPI")
    Set myFolder = myNamespace.GetDefaultFolder(olFolderSentMail)
    Set myItem = myFolder.Items(myFolder.Items.Count)

    myItem.Display
End Sub
</code>```

答:
This is the answer why this won't work with the Application_ItemSend event:

Application_ItemSend is called before the email is sent. You can see that because it has a Cancel parameter. This means the email only gets sent if Cancel = False else the email is dropped.

So you just cannot display the email because it isn't sent at this time in the Application_ItemSend event. It gets sent after the Application_ItemSend is finished.

Note: If you put a break point within the Application_ItemSend you will see that the "New Email" window remains open/visible until the ItemSend event is finished. Therefore you cannot open that email within that event.

Workaround

You might try the following code. This creates an event for the default folder of sent items which is called when an item is added to this folder.

A restart of Outlook might be needed after adding the code (or at least running the Application_Startup procedure once).

```<code>Option Explicit

Public WithEvents myOlItems As Outlook.Items

Private Sub Application_Startup()
    Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail).Items
End Sub

Private Sub myOlItems_ItemAdd(ByVal Item As Object)
    Item.Display
End Sub
</code>```

If the folder where your sent items are moved to is not the default Outlook sent mail folder then you need to find the right folder to set it in Application_Startup.

Title: Open email after sending

Body:
Why am I facing the below problem?

I have written a code to open sent email after sending email. The VBA code doesn't open the latest sent email but the previous one.

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim myItem As MailItem
    Dim myNamespace As NameSpace
    Dim myFolder As Folder

    Set myNamespace = Application.GetNamespace("MAPI")
    Set myFolder = myNamespace.GetDefaultFolder(olFolderSentMail)
    Set myItem = myFolder.Items(myFolder.Items.Count)

    myItem.Display
End Sub

Body:
This is the answer why this won't work with the Application_ItemSend event:

Application_ItemSend is called before the email is sent. You can see that because it has a Cancel parameter. This means the email only gets sent if Cancel = False else the email is dropped.

So you just cannot display the email because it isn't sent at this time in the Application_ItemSend event. It gets sent after the Application_ItemSend is finished.

Note: If you put a break point within the Application_ItemSend you will see that the "New Email" window remains open/visible until the ItemSend event is finished. Therefore you cannot open that email within that event.

Workaround

You might try the following code. This creates an event for the default folder of sent items which is called when an item is added to this folder.

A restart of Outlook might be needed after adding the code (or at least running the Application_Startup procedure once).

Option Explicit

Public WithEvents myOlItems As Outlook.Items

Private Sub Application_Startup()
    Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderSentMail).Items
End Sub

Private Sub myOlItems_ItemAdd(ByVal Item As Object)
    Item.Display
End Sub

If the folder where your sent items are moved to is not the default Outlook sent mail folder then you need to find the right folder to set it in Application_Startup.


问:
Why to assign an object attribute values cannot be read after？
```<code>var a = 1;
a.a = 2;
console.log(a.a);
</code>```

In the last ,why the input is undefined, but not 2

答:
At the moment you assigns the number 1 to the variable a (var a = 1;), a is a number. Altough Javascript doesn't specifically have types, the system from that point of time on treats the variable a as a number. So you can't add a property to a because it's not an object.

Here a little example of objects and variables:

var a = 1;
console.log(typeof a); //prints number

a.a = 2;
console.log(typeof a); //still a number

var a = {} //redeclare a as an object
a.a = 2; //an object can have properties (a.a)
console.log(typeof a); //prints object
console.log(a.a); //prints 2```

Body:
var a = 1;
a.a = 2;
console.log(a.a);

In the last ,why the input is undefined, but not 2


问:
How to use specific version Python in Conda environment
I have Anaconda 3 installed and I also created a new environment with Python 2.7. </p>

<p>How can I now use this Python 2.7? Like how can I use it run/write some code in it? </p>

答: Use python2 in command line when compiling, or add the shebang in your file.</p>

Body:
I have Anaconda 3 installed and I also created a new environment with Python 2.7.

How can I now use this Python 2.7? Like how can I use it run/write some code in it?


问:
Mathjax fallback: Try SVG before image fonts if HTML-CSS webfont fails
(I am using STIX fonts, but the question is relevant for TeX fonts as well.)

My question: How do I configure mathjax on my web page so that a user viewing the page experiences the following 1 -> 2 -> 3 fallback chain?

HTML-CSS (webFont "STIX-Web", local "STIX")

SVG ("STIX-Web")

All other fallback options (local generic, image, etc)

In other words, the idea is to keep HTML-CSS as the top choice, but if HTML-CSS fails, then fall back to SVG, not to local generic or image fonts.

The fallback needs to work for all kinds of failures of (1). E.g., it should work both when local fonts in HTML-CSS cannot be used (either because the user does not have the fonts locally installed, or because I explicitly disable local fonts in the web page via availableFonts: [] and preferredFont: null), and also when HTML-CSS web fonts cannot be used (the user has disabled webfonts, browser same origin policy gets enforced, etc).

It should also work independent of the client user's last selection of the renderer in the math contextual menu. Currently, if on the client browser the user had last selected HTML-CSS as the renderer via the math menu, then whenever (1) fails, mathjax is falling back to (3), skipping (2). And if the user had last selected SVG as the renderer, then HTML-CSS is no longer the first preferred choice, i.e. (1) is skipped altogether.

答:
The following config seems to implement the needed fallback chain
  (in my limited testing).

```<code><script type="text/javascript"
  src="../MathJax-2.7.1/MathJax.js?config=TeX-AMS-MML_SVG">
</script>

<script type="text/x-mathjax-config">
//
// - Mathjax config to implement the following fallback chain:
//
//     1. HTML-CSS webFont ("STIX-Web")
//     2. SVG ("STIX-Web")
//     3. Other fallback fonts (local generic, image, etc)
//
// - Change availableFonts to ["STIX"] and preferredFont to "STIX"
//   to allow local STIX fonts. Implements the fallback chain below:
//
//     1. HTML-CSS local ("STIX")
//     2. HTML-CSS webFont ("STIX-Web")
//     3. SVG ("STIX-Web")
//     4. Other fallback fonts (local generic, image, etc)
//

//
// Use STIX font consistently across HTML-CSS and SVG
//
MathJax.Hub.Config({
    jax: ["input/TeX", "input/MathML",
        "output/HTML-CSS", "output/SVG", "output/PreviewHTML"
    ],
    "HTML-CSS": {
        imageFont: null,
        webFont: "STIX-Web",
        availableFonts: [],    // Or: ["STIX"], to allow local
        preferredFont: null    // Or: "STIX", to allow local
    },
    "SVG": {
        font: "STIX-Web"
    }
});

MathJax.Hub.Register.StartupHook("End Jax", function() {

    // 1. Set HTML-CSS as the initially preferred output processor.
    //    (Temporarily overrides the renderer value set by MathMenu
    //    without affecting the user's chosen renderer elsewhere.)
    var jax = "HTML-CSS";
    MathJax.Hub.setRenderer(jax);

    // 2. Install callback which switches renderer to SVG if HTML-CSS fails.
    var nopast = true;
    MathJax.Hub.Startup.signal.Interest(QueSVGfallback, nopast);

});

</script>

<script>
//
// This callback (when installed) scans through messages to check
// (as in FontWarnings.js) if HTML-CSS font loading has failed.
// If so, it queues a request to switch to SVG rendering.
//
var QueSVGfallback = (function() {    // Anonymous "closure" to keep quecount
    var quecount = 0;
    return function(m) {              // The real callback function
        if (quecount > 0) return;     // Prevent multiple queueing
        m = m + "";
        if (m.match(/HTML-CSS Jax - /)) {
            if (m.match(/- using image fonts/) ||
                    m.match(/- no valid font/) ||
                    m.match(/- disable web fonts/)) {
                MathJax.Hub.Queue(
                    ["setRenderer", MathJax.Hub, "SVG", "jax/mml"],
                    ["Rerender", MathJax.Hub]
                );
                quecount++;
            }
        }
    }
})();
</script>
</code>```

Body:
The following config seems to implement the needed fallback chain
  (in my limited testing).

<script type="text/javascript"
  src="../MathJax-2.7.1/MathJax.js?config=TeX-AMS-MML_SVG">
</script>

<script type="text/x-mathjax-config">
//
// - Mathjax config to implement the following fallback chain:
//
//     1. HTML-CSS webFont ("STIX-Web")
//     2. SVG ("STIX-Web")
//     3. Other fallback fonts (local generic, image, etc)
//
// - Change availableFonts to ["STIX"] and preferredFont to "STIX"
//   to allow local STIX fonts. Implements the fallback chain below:
//
//     1. HTML-CSS local ("STIX")
//     2. HTML-CSS webFont ("STIX-Web")
//     3. SVG ("STIX-Web")
//     4. Other fallback fonts (local generic, image, etc)
//

//
// Use STIX font consistently across HTML-CSS and SVG
//
MathJax.Hub.Config({
    jax: ["input/TeX", "input/MathML",
        "output/HTML-CSS", "output/SVG", "output/PreviewHTML"
    ],
    "HTML-CSS": {
        imageFont: null,
        webFont: "STIX-Web",
        availableFonts: [],    // Or: ["STIX"], to allow local
        preferredFont: null    // Or: "STIX", to allow local
    },
    "SVG": {
        font: "STIX-Web"
    }
});

MathJax.Hub.Register.StartupHook("End Jax", function() {

    // 1. Set HTML-CSS as the initially preferred output processor.
    //    (Temporarily overrides the renderer value set by MathMenu
    //    without affecting the user's chosen renderer elsewhere.)
    var jax = "HTML-CSS";
    MathJax.Hub.setRenderer(jax);

    // 2. Install callback which switches renderer to SVG if HTML-CSS fails.
    var nopast = true;
    MathJax.Hub.Startup.signal.Interest(QueSVGfallback, nopast);

});

</script>

<script>
//
// This callback (when installed) scans through messages to check
// (as in FontWarnings.js) if HTML-CSS font loading has failed.
// If so, it queues a request to switch to SVG rendering.
//
var QueSVGfallback = (function() {    // Anonymous "closure" to keep quecount
    var quecount = 0;
    return function(m) {              // The real callback function
        if (quecount > 0) return;     // Prevent multiple queueing
        m = m + "";
        if (m.match(/HTML-CSS Jax - /)) {
            if (m.match(/- using image fonts/) ||
                    m.match(/- no valid font/) ||
                    m.match(/- disable web fonts/)) {
                MathJax.Hub.Queue(
                    ["setRenderer", MathJax.Hub, "SVG", "jax/mml"],
                    ["Rerender", MathJax.Hub]
                );
                quecount++;
            }
        }
    }
})();
</script>


问:
Make 2 sets of checkboxes required if a checkbox is not selected
I've a checkbox called "no_industry".

```<code><label><input type="checkbox" name="no_industry" id="no_industry" value="NoIndustry">No Industry Focus</label>
</code>```

If this value is no selected user must select a value from any of the following check boxes list.

```<code><input type="checkbox" id="indus_communication" name="industry[]" value="Communications/CSI">Communications / CSI</label>
</code>```

```<code><input type="checkbox" id="indus_communication" name="solution[]" value="Communications/CSI">Communications / CSI</label>
</code>```

How do I do that?

I've added the following validation, but seems it is not working.

```<code>    'industry' => ['required_if:no_industry,NULL'],
    'solution' => ['required_if:no_industry,NULL']
</code>```

答:
I think its taking null as a value

Here is an alternative solution for it you can try as

```<code>$this->validate($request, [

        'industry' => 'required_without:no_industry',
        'solution' => 'required_without:no_industry',
     ]);
</code>```

or as

```<code>  'industry' => ['required_without:no_industry'],
  'solution' => ['required_without:no_industry']
</code>```

Try This Hope it will Help--!!

Body:
I've a checkbox called "no_industry".

<input type="checkbox" name="no_industry" id="no_industry" value="NoIndustry">No Industry Focus

If this value is no selected user must select a value from any of the following check boxes list.

<input type="checkbox" id="indus_communication" name="industry[]" value="Communications/CSI">Communications / CSI

<input type="checkbox" id="indus_communication" name="solution[]" value="Communications/CSI">Communications / CSI

How do I do that?

I've added the following validation, but seems it is not working.

    'industry' => ['required_if:no_industry,NULL'],
    'solution' => ['required_if:no_industry,NULL']

Body:
I think its taking null as a value

Here is an alternative solution for it you can try as

$this->validate($request, [

        'industry' => 'required_without:no_industry',
        'solution' => 'required_without:no_industry',
     ]);

or as

  'industry' => ['required_without:no_industry'],
  'solution' => ['required_without:no_industry']

Try This Hope it will Help--!!


问:
JavaScript sort array not working
I'm trying to sort an array of objects with an attribute page.  This is being done in a computed property with Vue.

To do this I'm using the following function, which first builds the objects:

```<code> sorted: function(){
     var pages = this.selectedKKS['pages'];
     var list;
     try {
       list = [];
       Object.keys(pages).forEach(function(key){
         console.log(key + " is the key")
         var obj = {};
         obj.title = key;
         obj.page = pages[key]
         list.push(obj)
     });
     }
     catch(e){
       console.log(e);
     }
     var sorted = list.sort(function(a, b){
       console.log('a.page is ' + a.page + ' and b.page is ' + b.page);
       return a.page > b.page;

     });
     return sorted;
 }
</code>```

Just to make sure that I'm actually comparing pages as I intend, here's the console log:

```<code>a.page is 84 and b.page is 28
App.vue?077f:353 a.page is 84 and b.page is 46
App.vue?077f:353 a.page is 28 and b.page is 46
App.vue?077f:353 a.page is 84 and b.page is 35
App.vue?077f:353 a.page is 46 and b.page is 35
App.vue?077f:353 a.page is 28 and b.page is 35
App.vue?077f:353 a.page is 84 and b.page is 14
App.vue?077f:353 a.page is 46 and b.page is 14
App.vue?077f:353 a.page is 35 and b.page is 14
App.vue?077f:353 a.page is 28 and b.page is 14
App.vue?077f:353 a.page is 84 and b.page is 5
App.vue?077f:353 a.page is 46 and b.page is 5
App.vue?077f:353 a.page is 84 and b.page is 8
App.vue?077f:353 a.page is 5 and b.page is 8
</code>```

I'm looping over this computed property in my template, and since it's being sorted incorrectly it's giving me an undesirable result:

```<code>            <f7-list>
            <f7-list-item v-for="val in sorted" @click="openpdf(selectedKKS.url, val.page)">
                <f7-col><span style="color: black">{{ val.title }}</span></f7-col>
                <f7-col>{{ val.page }}</f7-col>
            </f7-list-item>
            </f7-list>
</code>```

Any ideas as to what could be going wrong?

答:
Try '-' instead '>' inside sorted function..

```<code>var sorted = list.sort(function(a, b){
   console.log('a.page is ' + a.page + ' and b.page is ' + b.page);
   return a.page - b.page;
 });
</code>```

Hope it helps!!

Title: JavaScript sort array not working

Body:
I'm trying to sort an array of objects with an attribute page.  This is being done in a computed property with Vue.

To do this I'm using the following function, which first builds the objects:

 sorted: function(){
     var pages = this.selectedKKS['pages'];
     var list;
     try {
       list = [];
       Object.keys(pages).forEach(function(key){
         console.log(key + " is the key")
         var obj = {};
         obj.title = key;
         obj.page = pages[key]
         list.push(obj)
     });
     }
     catch(e){
       console.log(e);
     }
     var sorted = list.sort(function(a, b){
       console.log('a.page is ' + a.page + ' and b.page is ' + b.page);
       return a.page > b.page;

     });
     return sorted;
 }

Just to make sure that I'm actually comparing pages as I intend, here's the console log:

a.page is 84 and b.page is 28
App.vue?077f:353 a.page is 84 and b.page is 46
App.vue?077f:353 a.page is 28 and b.page is 46
App.vue?077f:353 a.page is 84 and b.page is 35
App.vue?077f:353 a.page is 46 and b.page is 35
App.vue?077f:353 a.page is 28 and b.page is 35
App.vue?077f:353 a.page is 84 and b.page is 14
App.vue?077f:353 a.page is 46 and b.page is 14
App.vue?077f:353 a.page is 35 and b.page is 14
App.vue?077f:353 a.page is 28 and b.page is 14
App.vue?077f:353 a.page is 84 and b.page is 5
App.vue?077f:353 a.page is 46 and b.page is 5
App.vue?077f:353 a.page is 84 and b.page is 8
App.vue?077f:353 a.page is 5 and b.page is 8

I'm looping over this computed property in my template, and since it's being sorted incorrectly it's giving me an undesirable result:

            <f7-list>
            <f7-list-item v-for="val in sorted" @click="openpdf(selectedKKS.url, val.page)">
                <f7-col>{{ val.title }}</f7-col>
                <f7-col>{{ val.page }}</f7-col>
            </f7-list-item>
            </f7-list>

Any ideas as to what could be going wrong?

Body:
Try '-' instead '>' inside sorted function..

var sorted = list.sort(function(a, b){
   console.log('a.page is ' + a.page + ' and b.page is ' + b.page);
   return a.page - b.page;
 });

Hope it helps!!


问:
Why can't I view or edit Umbraco templates?
When I open the Umbraco (7.6.3) backoffice, I'm unable to view or make changes to templates. It seems like other functionality is unaffected, and I can create & edit specific pages. However, attempting to open the templates themselves just leads to a white screen. This problem exists across browsers:

Other screens render just fine:

What gives?

Checking the console when attempting to load gives an interesting error:

```<code>Error: Argument 'Umbraco.Editors.Templates.EditController' is not a function, got undefined...
</code>```

Resolution:

The issue seemed to be caused by outdated files in the Umbraco folder. Copying most directories over from packages\UmbracoCms.7.6.3\UmbracoFiles\umbraco\ seems to have done the trick.

Looking at the changelog, it seems like the JS folder was the most influential in getting this fixed.

答:
My first thought would be file permissions.

Have you run the health check for permissions in the developer section?  Need to make sure that your application pool user has write permissions on the Views folder.

Body:
When I open the Umbraco (7.6.3) backoffice, I'm unable to view or make changes to templates. It seems like other functionality is unaffected, and I can create & edit specific pages. However, attempting to open the templates themselves just leads to a white screen. This problem exists across browsers:

Other screens render just fine:

What gives?

Checking the console when attempting to load gives an interesting error:

Error: Argument 'Umbraco.Editors.Templates.EditController' is not a function, got undefined...

Resolution:

The issue seemed to be caused by outdated files in the Umbraco folder. Copying most directories over from packages\UmbracoCms.7.6.3\UmbracoFiles\umbraco\ seems to have done the trick.

Looking at the changelog, it seems like the JS folder was the most influential in getting this fixed.


问:
Can I set cross-axis size of a flex box item to a percentage of container?
I have three elements aligned horizontally in a flex box of set width and I would like the flex box to take the cross-axis size (height) of the largest of two of them and for the third to take 80% of that size. Is this possible?

Code pen here.

```<code>^ code
</code>```

答:
You can do that by either set the separator to absolute, or like below, where I used a pseudo, which IMHO is better if it is only going to be as a seperator.

In addition to the itemBody::before rule, I also added position: relative to the itemBody so the pseudo's absolute position relates to it.

Updated codepen

Stack snippet

.container {
  display: flex;
  width: 300px;
  align-items: center;
  border: 1px solid orange;
}

.iconHolder {
  width: 36px;
  height: 36px;
  border: 1px solid lightgreen;
}

.itemBody {
  position: relative;          /*  added property  */
  width: 269px;
  margin-left: 10px;
  border: 1px solid lightblue;
}
.itemBody::before {            /*  added/changed rule/properties  */
  content: '';
  position: absolute;
  left: -8px;
  width: 1px;
  background: black;
  height: 80%;
  min-height: 45px;
}

.text {
}

.date {
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='container'>

  <div class='iconHolder'>
    X
  </div>

  <div class='itemBody'>
    <div class='text'>
      Howdy there, this is some text that goes in
      the item body! It might be very long and will
      need to stretch the cross axies of the outer
      flex box. When this happens, I'd like the separator
      bar to grow with it!
     </div>
    <div class='date'>about 3 days ago</div>
  </div>

</div></code>```

Here with the existing markup.

In addition to make the separator positioned absolute, I also added position: relative to the container so the spearator's absolute position relates to it.

```<code>.separator {
  position: absolute;
  left: 38px;
  top: 0;
  width: 1px;
  background: black;
  height: 80%;
  min-height: 45px;
}
</code>```

Updated codepen

A third possible solution is to wrap the separator.

Body:
I have three elements aligned horizontally in a flex box of set width and I would like the flex box to take the cross-axis size (height) of the largest of two of them and for the third to take 80% of that size. Is this possible?

Code pen here.

^ code

Body:
You can do that by either set the separator to absolute, or like below, where I used a pseudo, which IMHO is better if it is only going to be as a seperator.

In addition to the itemBody::before rule, I also added position: relative to the itemBody so the pseudo's absolute position relates to it.

Updated codepen

Stack snippet

.container {
  display: flex;
  width: 300px;
  align-items: center;
  border: 1px solid orange;
}

.iconHolder {
  width: 36px;
  height: 36px;
  border: 1px solid lightgreen;
}

.itemBody {
  position: relative;          /*  added property  */
  width: 269px;
  margin-left: 10px;
  border: 1px solid lightblue;
}
.itemBody::before {            /*  added/changed rule/properties  */
  content: '';
  position: absolute;
  left: -8px;
  width: 1px;
  background: black;
  height: 80%;
  min-height: 45px;
}

.text {
}

.date {
}

<div class='container'>

  <div class='iconHolder'>
    X
  </div>

  <div class='itemBody'>
    <div class='text'>
      Howdy there, this is some text that goes in
      the item body! It might be very long and will
      need to stretch the cross axies of the outer
      flex box. When this happens, I'd like the separator
      bar to grow with it!
     </div>
    <div class='date'>about 3 days ago</div>
  </div>

</div>

Here with the existing markup.

In addition to make the separator positioned absolute, I also added position: relative to the container so the spearator's absolute position relates to it.

.separator {
  position: absolute;
  left: 38px;
  top: 0;
  width: 1px;
  background: black;
  height: 80%;
  min-height: 45px;
}

Updated codepen

A third possible solution is to wrap the separator.


问:
JAXB (un)marshalling of xsd types: xsd:base64Binary and xsd:hexBinary
JAXB maps both xsd:base64Binary and xsd:hexBinary types to byte[].

Given that I have a schema/a DOM Element representing each of these types such as:

<foo>ABCD</foo> for xsd:hexBinary and

<foo>YTM0NZomIzI2OTsmIzM0NTueYQ==</foo> for xsd:base64Binary ,

it's not clear how JAXB 2.1 handles it.

JAXB.unmarshal(new DOMSource(node), byte[].class) does not like the payload.

Neither does the following:

JAXBContext ctx = JAXBContext.newInstance(byte[].class);
 ctx.createUnmarshaller().unmarshal(node);

What's the correct way of handling these types?
Thanks in advance.

答:
The conversion between byte[] and the hexBinary or base64Binary representation is done via a correspondent XmlAdapter.

by default JAXB uses the included HexBinaryAdapter for converting byte[] to a String.
I don't know if there is also an XmlAdapter which converts from/to base64 but that is no problem:

You can easily implement it yourself using an own XmlAdpater:

```<code>public final class Base64Adapter extends XmlAdapter<String, byte[]> {
    public byte[] unmarshal(String s) {
        if (s == null)
            return null;
        return org.apache.commons.codec.binary.Base64.decodeBase64(s);
    }

    public String marshal(byte[] bytes) {
        if (bytes == null)
            return null;
        return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
    }
}
</code>```

You can specify on a field/getter_setter level what should be processed by which adapter:

```<code>private class DataTestClass {

    @XmlJavaTypeAdapter(Base64Adapter.class)
    public byte[] base64Data = new byte[] { 0, 1, 2, 3, 4 };

    @XmlJavaTypeAdapter(HexBinaryAdapter.class)
    public byte[] hexbinData = new byte[] { 0, 1, 2, 3, 4 };

}
</code>```

Body:
The conversion between byte[] and the hexBinary or base64Binary representation is done via a correspondent XmlAdapter.

by default JAXB uses the included HexBinaryAdapter for converting byte[] to a String.
I don't know if there is also an XmlAdapter which converts from/to base64 but that is no problem:

You can easily implement it yourself using an own XmlAdpater:

public final class Base64Adapter extends XmlAdapter<String, byte[]> {
    public byte[] unmarshal(String s) {
        if (s == null)
            return null;
        return org.apache.commons.codec.binary.Base64.decodeBase64(s);
    }

    public String marshal(byte[] bytes) {
        if (bytes == null)
            return null;
        return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);
    }
}

You can specify on a field/getter_setter level what should be processed by which adapter:

private class DataTestClass {

    @XmlJavaTypeAdapter(Base64Adapter.class)
    public byte[] base64Data = new byte[] { 0, 1, 2, 3, 4 };

    @XmlJavaTypeAdapter(HexBinaryAdapter.class)
    public byte[] hexbinData = new byte[] { 0, 1, 2, 3, 4 };

}


问:
Publish asmx web service on azure
I have created an ASMX web service. i want to publish it on azure cloud. I have tried by creating Azure Cloud Project in Solution but i got an error Atleast One Web or Worker role is required. Any Help?

答: Please add new Web role and try again.

Title: Publish asmx web service on azure

Body: Please add new Web role and try again.


问:
Unable to build Netbeans project
Hi I'm trying to build a project for a assignment and I'm getting a error here

```<code>H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:993: The following error occurred while executing this line:
H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:837: copylibs doesn't support the "excludeFromCopy" attribute
</code>```

I have not found anyway of fixing this and would like to know what could be causeing this here is the whole output

```<code>ant -f H:\\NetBeansProjects\\JavaApplication3 clean jar`
init:

deps-clean:

Updating property file: H:\NetBeansProjects\JavaApplication3\build\built-clean.properties

Deleting directory H:\NetBeansProjects\JavaApplication3\build

clean:

init:

deps-jar:

Created dir: H:\NetBeansProjects\JavaApplication3\build

Updating property file: H:\NetBeansProjects\JavaApplication3\build\built-jar.properties

Created dir: H:\NetBeansProjects\JavaApplication3\build\classes

Created dir: H:\NetBeansProjects\JavaApplication3\build\empty

Created dir: H:\NetBeansProjects\JavaApplication3\build\generated-sources\ap-source-output

Compiling 2 source files to H:\NetBeansProjects\JavaApplication3\build\classes

compile:

Created dir: H:\NetBeansProjects\JavaApplication3\dist

Copying 1 file to H:\NetBeansProjects\JavaApplication3\build

H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:993: The following error occurred while executing this line:

H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:837: copylibs doesn't support the "excludeFromCopy" attribute

BUILD FAILED (total time: 1 second)
</code>```

答:
In my impl.xml its line no 843 (Project/nbproject/impl.xml)

```<code><copylibs compress="${jar.compress}" excludeFromCopy="${copylibs.excludes}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
</code>```

change the above line as given below (removed [excludeFromCopy="${copylibs.excludes}"] part)

```<code><copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">
</code>```

Title: Unable to build Netbeans project

Body:
Hi I'm trying to build a project for a assignment and I'm getting a error here

H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:993: The following error occurred while executing this line:
H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:837: copylibs doesn't support the "excludeFromCopy" attribute

I have not found anyway of fixing this and would like to know what could be causeing this here is the whole output

ant -f H:\\NetBeansProjects\\JavaApplication3 clean jar`
init:

deps-clean:

Updating property file: H:\NetBeansProjects\JavaApplication3\build\built-clean.properties

Deleting directory H:\NetBeansProjects\JavaApplication3\build

clean:

init:

deps-jar:

Created dir: H:\NetBeansProjects\JavaApplication3\build

Updating property file: H:\NetBeansProjects\JavaApplication3\build\built-jar.properties

Created dir: H:\NetBeansProjects\JavaApplication3\build\classes

Created dir: H:\NetBeansProjects\JavaApplication3\build\empty

Created dir: H:\NetBeansProjects\JavaApplication3\build\generated-sources\ap-source-output

Compiling 2 source files to H:\NetBeansProjects\JavaApplication3\build\classes

compile:

Created dir: H:\NetBeansProjects\JavaApplication3\dist

Copying 1 file to H:\NetBeansProjects\JavaApplication3\build

H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:993: The following error occurred while executing this line:

H:\NetBeansProjects\JavaApplication3\nbproject\build-impl.xml:837: copylibs doesn't support the "excludeFromCopy" attribute

BUILD FAILED (total time: 1 second)

Body:
In my impl.xml its line no 843 (Project/nbproject/impl.xml)

<copylibs compress="${jar.compress}" excludeFromCopy="${copylibs.excludes}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">

change the above line as given below (removed [excludeFromCopy="${copylibs.excludes}"] part)

<copylibs compress="${jar.compress}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}">


答: callback function for sort must return a int number.  lt return  < 0 ,eq return 0 ,gt return > 0.</p>

Title: JavaScript sort array not working