问:
Trying to make platforms that I can jump through from underneath but land on top of. having trouble fine tuning the logic
My goal is to set up all my platforms in the .sks file for easier design of my levels.

this is declared at the top of game scene.swift before didMove:

```<code>private var JumpThroughPlatformObject = SKSpriteNode()
</code>```

and this is in DidMove:

```<code>if let JumpThroughPlatformObjectNode = self.childNode(withName: "//jumpThroughPlatform1") as? SKSpriteNode {
        JumpThroughPlatformObject = JumpThroughPlatformObjectNode}
</code>```

I reference the platform to get it's height from the .sks, since all my platforms are going to be the same height I only need to get it from one.

Below is what Im trying to use in my update method to turn off collisions until my player is totally above the platform. The main issue with only checking if my players velocity is greater than zero is: if the player is at the peak of a jump (his velocity slows to zero). if this happens and the player is inside a platform, he either instantly springs up to the top of the platform or gets launched downward.

I don't want my platforms to have to be 1 pixel high lines. I also need to have the player have a full collision box since he will be interacting with other types of environments. This leads me to believe that I somehow need to only register the top of the platform as a collision box and not the entire platform.

This if statement I wrote is supposed to take the y position of a platform and add half of its height to it, since the y position is based on the center of the sprite I figured this would put the collision for the platform on its top boundary.

I did the same for the player but in reverse. Putting the players collisions on only the bottom of his border. But its not working perfectly and I'm not sure why at this point.

```<code>if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2))
</code>```

The function below is giving me 3 main issues:

My players jump is always dy = 80. If I'm jumping up to a platform that position.y = 90, the players peak of the jump stops in the middle of the platform, but he teleports to the top of it instead of continuing to fall to the ground.

the left and right edges of the platforms still have full collision with the player if I'm falling

if my player is on a platform and there is another one directly above me, the player can't jump through it.

let zero:CGFloat = 0

```<code>    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy

        // when I jump dy is greater than zero else I'm falling

       if (dy! >= zero) {

           if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2)) {

                print(" platform y: \(JumpThroughPlatformObject.position.y)")
                print ("player position: \(player.position.y)")

                // Prevent collisions if the hero is jumping
                body.collisionBitMask = CollisionTypes.saw.rawValue | CollisionTypes.ground.rawValue

            }

       }
        else {
            // Allow collisions if the hero is falling
            body.collisionBitMask = CollisionTypes.platform.rawValue | CollisionTypes.ground.rawValue | CollisionTypes.saw.rawValue
        }
    }
</code>```

Any advice would be greatly appreciated. I've been tearing my hair out for a couple days now.

EDIT in didBegin and didEnd:

```<code>   func didBegin(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy
        let platform = JumpThroughPlatformObject
        let zero:CGFloat = 0

    if contact.bodyA.node == player {
      // playerCollided(with: contact.bodyB.node!)

            if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

                body.collisionBitMask &= ~CollisionTypes.platform.rawValue

            }

    } else if contact.bodyB.node == player {
     //  playerCollided(with: contact.bodyA.node!)
        isPlayerOnGround = true

        if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

            body.collisionBitMask &= ~CollisionTypes.platform.rawValue}
        }
    }
}

func didEnd(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
//            let dy = player.physicsBody?.velocity.dy
//            let platform = JumpThroughPlatformObject

    if contact.bodyA.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }else if contact.bodyB.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }
    }
}
</code>```

Adding what I did, the player can no longer jump through the platform.

答:
You just need a condition that let's you know if you are in a body.  I also cleaned up your code to avoid accidently putting in the wrong categories</p>

```<code>if let body = player.physicsBody,   let dy = body.velocity.dy {
   // when I am jumping or I am in a platform, then do not register
   if (dy > zero || body.node.intersects(platform) && (body.node.position.y - body.node.size.height/2 != platform.position.y + platform.size.height / 2)  {
        body.collisionBitMask &= ~CollisionTypes.platform.rawValue

   }
    else {
        // Allow collisions if the hero is falling
        body.collisionBitMask |= CollisionTypes.platform.rawValue
</code>```

Body:
My goal is to set up all my platforms in the .sks file for easier design of my levels.

this is declared at the top of game scene.swift before didMove:

private var JumpThroughPlatformObject = SKSpriteNode()

and this is in DidMove:

if let JumpThroughPlatformObjectNode = self.childNode(withName: "//jumpThroughPlatform1") as? SKSpriteNode {
        JumpThroughPlatformObject = JumpThroughPlatformObjectNode}

I reference the platform to get it's height from the .sks, since all my platforms are going to be the same height I only need to get it from one.

Below is what Im trying to use in my update method to turn off collisions until my player is totally above the platform. The main issue with only checking if my players velocity is greater than zero is: if the player is at the peak of a jump (his velocity slows to zero). if this happens and the player is inside a platform, he either instantly springs up to the top of the platform or gets launched downward.

I don't want my platforms to have to be 1 pixel high lines. I also need to have the player have a full collision box since he will be interacting with other types of environments. This leads me to believe that I somehow need to only register the top of the platform as a collision box and not the entire platform.

This if statement I wrote is supposed to take the y position of a platform and add half of its height to it, since the y position is based on the center of the sprite I figured this would put the collision for the platform on its top boundary.

I did the same for the player but in reverse. Putting the players collisions on only the bottom of his border. But its not working perfectly and I'm not sure why at this point.

if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2))

The function below is giving me 3 main issues:

My players jump is always dy = 80. If I'm jumping up to a platform that position.y = 90, the players peak of the jump stops in the middle of the platform, but he teleports to the top of it instead of continuing to fall to the ground.

the left and right edges of the platforms still have full collision with the player if I'm falling

if my player is on a platform and there is another one directly above me, the player can't jump through it.

let zero:CGFloat = 0

    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy

        // when I jump dy is greater than zero else I'm falling

       if (dy! >= zero) {

           if (JumpThroughPlatformObject.position.y + (JumpThroughPlatformObject.size.height / 2)) > (player.position.y - (player.size.height / 2)) {

                print(" platform y: \(JumpThroughPlatformObject.position.y)")
                print ("player position: \(player.position.y)")

                // Prevent collisions if the hero is jumping
                body.collisionBitMask = CollisionTypes.saw.rawValue | CollisionTypes.ground.rawValue

            }

       }
        else {
            // Allow collisions if the hero is falling
            body.collisionBitMask = CollisionTypes.platform.rawValue | CollisionTypes.ground.rawValue | CollisionTypes.saw.rawValue
        }
    }

Any advice would be greatly appreciated. I've been tearing my hair out for a couple days now.

EDIT in didBegin and didEnd:

   func didBegin(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
        let dy = player.physicsBody?.velocity.dy
        let platform = JumpThroughPlatformObject
        let zero:CGFloat = 0

    if contact.bodyA.node == player {
      // playerCollided(with: contact.bodyB.node!)

            if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

                body.collisionBitMask &= ~CollisionTypes.platform.rawValue

            }

    } else if contact.bodyB.node == player {
     //  playerCollided(with: contact.bodyA.node!)
        isPlayerOnGround = true

        if (dy! > zero || body.node!.intersects(platform)) && ((body.node?.position.y)! - player.size.height / 2 < platform.position.y + platform.size.height / 2) {

            body.collisionBitMask &= ~CollisionTypes.platform.rawValue}
        }
    }
}

func didEnd(_ contact: SKPhysicsContact) {

    if let body = player.physicsBody {
//            let dy = player.physicsBody?.velocity.dy
//            let platform = JumpThroughPlatformObject

    if contact.bodyA.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }else if contact.bodyB.node == player {

        body.collisionBitMask |= CollisionTypes.platform.rawValue

    }
    }
}

Adding what I did, the player can no longer jump through the platform.

Body:
You just need a condition that let's you know if you are in a body.  I also cleaned up your code to avoid accidently putting in the wrong categories

if let body = player.physicsBody,   let dy = body.velocity.dy {
   // when I am jumping or I am in a platform, then do not register
   if (dy > zero || body.node.intersects(platform) && (body.node.position.y - body.node.size.height/2 != platform.position.y + platform.size.height / 2)  {
        body.collisionBitMask &= ~CollisionTypes.platform.rawValue

   }
    else {
        // Allow collisions if the hero is falling
        body.collisionBitMask |= CollisionTypes.platform.rawValue


来源: stackexchange

问:
Get latest one record will show, 1 week after its been added. After that it will show randomly upon page refresh
My requirement is simple , I have a repeater control webpart, and I want to apply a condition in the WHERE clause.

Condition : The latest one record will show, 1 week after its been added. After that it will show randomly upon page refresh.

Means if record is more than 1 week , then it will show latest by , upon page refresh.

I made this query but it doesn't work:

```<code>(DocumentCreatedWhen >= dateadd(day, -7, convert(date, getdate())))
</code>```

答:
What You need to use is union

```<code>SELECT TOP 1 * FROM
(
-- Get the latest record
Union
-- Get random record
) as Result
</code>```

For example, if you get MenuItem:

```<code>SELECT TOP 1 * FROM
(
-- latest for this week
SELECT DocumentUrlPath, DocumentName, DocumentCreatedWhen from  (
select top 1 DocumentNAme, DocumentUrlPAth, DocumentCreatedWhen  FROM View_CONTENT_MenuItem_Joined
where DATEDIFF(day, DocumentCreatedWhen , GETDATE()) <= 7  Order BY DocumentCreatedWhen DESC) as LatestForThisWeek
UNION
-- random
SELECT DocumentUrlPath, DocumentName, DocumentCreatedWhen from  (
select top 1 DocumentNAme, DocumentUrlPAth, DocumentCreatedWhen  FROM View_CONTENT_MenuItem_Joined
ORDER BY NEWID() ) as RandomizedRecords
) as Result
</code>```

There is lots of sub queries but this will give you the idea :)

ContentLicense: CC BY-SA 3.0

Body:
My requirement is simple , I have a repeater control webpart, and I want to apply a condition in the WHERE clause.

Condition : The latest one record will show, 1 week after its been added. After that it will show randomly upon page refresh.

Means if record is more than 1 week , then it will show latest by , upon page refresh.

I made this query but it doesn't work:

(DocumentCreatedWhen >= dateadd(day, -7, convert(date, getdate())))

Body:
What You need to use is union

SELECT TOP 1 * FROM
(
-- Get the latest record
Union
-- Get random record
) as Result

For example, if you get MenuItem:

SELECT TOP 1 * FROM
(
-- latest for this week
SELECT DocumentUrlPath, DocumentName, DocumentCreatedWhen from  (
select top 1 DocumentNAme, DocumentUrlPAth, DocumentCreatedWhen  FROM View_CONTENT_MenuItem_Joined
where DATEDIFF(day, DocumentCreatedWhen , GETDATE()) <= 7  Order BY DocumentCreatedWhen DESC) as LatestForThisWeek
UNION
-- random
SELECT DocumentUrlPath, DocumentName, DocumentCreatedWhen from  (
select top 1 DocumentNAme, DocumentUrlPAth, DocumentCreatedWhen  FROM View_CONTENT_MenuItem_Joined
ORDER BY NEWID() ) as RandomizedRecords
) as Result

There is lots of sub queries but this will give you the idea :)


问:
invalid operands of types 'const char [26]' and 'LPSTR '
My code is

```<code>string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );
</code>```

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

答:
You are trying to concatenate a char* pointer (obtained from your string variable) to a const char[] array (from your string literal).  You can't do that concatenation.

Also, the const_cast is not necessary.

You will have to convert one of the pointers to a string, eg:

```<code>string str = "C:\\Users\\mardare\\Downloads\\config";
const char *lp = str.c_str();
MessageBox ( NULL, (string("The selected folder is : ") + lp).c_str(), "Bye!", MB_OK );
</code>```

Or:

```<code>string str = "C:\\Users\\mardare\\Downloads\\config";
const char *lp = str.c_str();
MessageBox ( NULL, ("The selected folder is : " + string(lp)).c_str(), "Bye!", MB_OK );
</code>```

Alternatively, simply get rid of the char* from the string, you don't actually need it:

```<code>string str = "C:\\Users\\mardare\\Downloads\\config";
MessageBox ( NULL, ("The selected folder is : " + str).c_str(), "Bye!", MB_OK );
</code>```

Or:

```<code>string str = "C:\\Users\\mardare\\Downloads\\config";
string msg = "The selected folder is : " + str;
MessageBox ( NULL, msg.c_str(), "Bye!", MB_OK );
</code>```

Or:

```<code>string str = "C:\\Users\\mardare\\Downloads\\config";
ostringstream msg;
msg << "The selected folder is : " << str;
MessageBox ( NULL, msg.str().c_str(), "Bye!", MB_OK );
</code>```

Body:
My code is

string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

Body:
You are trying to concatenate a char* pointer (obtained from your string variable) to a const char[] array (from your string literal).  You can't do that concatenation.

Also, the const_cast is not necessary.

You will have to convert one of the pointers to a string, eg:

string str = "C:\\Users\\mardare\\Downloads\\config";
const char *lp = str.c_str();
MessageBox ( NULL, (string("The selected folder is : ") + lp).c_str(), "Bye!", MB_OK );

Or:

string str = "C:\\Users\\mardare\\Downloads\\config";
const char *lp = str.c_str();
MessageBox ( NULL, ("The selected folder is : " + string(lp)).c_str(), "Bye!", MB_OK );

Alternatively, simply get rid of the char* from the string, you don't actually need it:

string str = "C:\\Users\\mardare\\Downloads\\config";
MessageBox ( NULL, ("The selected folder is : " + str).c_str(), "Bye!", MB_OK );

Or:

string str = "C:\\Users\\mardare\\Downloads\\config";
string msg = "The selected folder is : " + str;
MessageBox ( NULL, msg.c_str(), "Bye!", MB_OK );

Or:

string str = "C:\\Users\\mardare\\Downloads\\config";
ostringstream msg;
msg << "The selected folder is : " << str;
MessageBox ( NULL, msg.str().c_str(), "Bye!", MB_OK );


问:
Is there any register to set the clock frequency for UART?
I am working with UART in LPC2148 micro controller.I could not able to find any register to set the clock frequency for the UART.Is there any register to set the clock frequency?</p>

答:
The "quick and dirty" method described in the reference is:

U0DLL = PCLK in Hertz / ( 16 * desired_baud_rate )

This is a simplified equation; the others have adjustments that can be made by adjusting various registers to fine-tune the serial baud rate.

From the same reference:

Now , as seen in Ex. 2 – in order to get 9600(9605 actually) bauds at 60Mhz PCLK we must use the following settings for baud generation :

U0DLL = 110 ; U0DLM = 1 ; MULVAL = 15 ; DIVADDVAL = 0
(You can convert these values to Hex =or= direclty use it in decimal form)
Now , lets make a function named “InitUART0()” which will configure and initialize UART0 as required :

```<code>void InitUART0(void)
{
  PINSEL0 = 0x5;  /* Select TxD for P0.0 and RxD for P0.1 */
  U0LCR = 3 | (1<<7) ; /* 8 bits, no Parity, 1 Stop bit | DLAB set to 1  */
  U0DLL = 110;
  U0DLM = 1;
  U0FDR = (MULVAL<<4) | DIVADDVAL; /* MULVAL=15(bits - 7:4) , DIVADDVAL=0(bits - 3:0)  */
  U0LCR &= 0x0F; // Set DLAB=0 to lock MULVAL and DIVADDVAL
  //BaudRate is now ~9600 and we are ready for UART communication!

 }
</code>```

Body:
The "quick and dirty" method described in the reference is:

U0DLL = PCLK in Hertz / ( 16 * desired_baud_rate )

This is a simplified equation; the others have adjustments that can be made by adjusting various registers to fine-tune the serial baud rate.

From the same reference:

Now , as seen in Ex. 2 – in order to get 9600(9605 actually) bauds at 60Mhz PCLK we must use the following settings for baud generation :

U0DLL = 110 ; U0DLM = 1 ; MULVAL = 15 ; DIVADDVAL = 0
(You can convert these values to Hex =or= direclty use it in decimal form)
Now , lets make a function named “InitUART0()” which will configure and initialize UART0 as required :

void InitUART0(void)
{
  PINSEL0 = 0x5;  /* Select TxD for P0.0 and RxD for P0.1 */
  U0LCR = 3 | (1<<7) ; /* 8 bits, no Parity, 1 Stop bit | DLAB set to 1  */
  U0DLL = 110;
  U0DLM = 1;
  U0FDR = (MULVAL<<4) | DIVADDVAL; /* MULVAL=15(bits - 7:4) , DIVADDVAL=0(bits - 3:0)  */
  U0LCR &= 0x0F; // Set DLAB=0 to lock MULVAL and DIVADDVAL
  //BaudRate is now ~9600 and we are ready for UART communication!

 }


问:
Jquery and JavaScript Show and Hide Select with image
if i select climbn i want to hide climt and climb
here is my code and javascript below

HTML:

```<code><span id="climt" class="themesegclass" style="display: none;">
  <span id="outputimgsrc"></span>
</span>
<span id="climbn" class="themesegclass" style="display: none;">
  <span id="outputimgsrc"></span>
</span>
<Select id="themeselector">
  <option value="climb">Classic - Image Bottom</option>
  <option value="climt">Classic - Image Top</option>
  <option value="climbn">Classic - Image Below Name</option>
</Select>
</code>```

Java script:

```<code>$(function() {
  var inputimgsrc = document.getElementById("inputimgsrc").value;
  document.getElementById("outputimgsrc").innerHTML =  "<img src=" + inputimgsrc + " style='width: 100px; height: 100px;'>";

  $('#themeselector').change(function () {
    $('.themesegclass').hide();
    $('#' + $(this).val()).show();
  });
});
</code>```

答:
I am not able to just add a comment, but can it be as simple as the fact that you are using the same id (outputimgsrc) for two spans? </p>

```<code>    <span id="climt" class="themesegclass" style="display: none;"><span id="outputimgsrc"></span></span> <span id="climbn" class="themesegclass" style="display: none;"><span id="outputimgsrc"></span></span>
</code>```

Body:
if i select climbn i want to hide climt and climb
here is my code and javascript below

HTML:

<Select id="themeselector">
  <option value="climb">Classic - Image Bottom</option>
  <option value="climt">Classic - Image Top</option>
  <option value="climbn">Classic - Image Below Name</option>
</Select>

Java script:

$(function() {
  var inputimgsrc = document.getElementById("inputimgsrc").value;
  document.getElementById("outputimgsrc").innerHTML =  "";

  $('#themeselector').change(function () {
    $('.themesegclass').hide();
    $('#' + $(this).val()).show();
  });
});

Body:
I am not able to just add a comment, but can it be as simple as the fact that you are using the same id (outputimgsrc) for two spans?

    <span id="climt" class="themesegclass" style="display: none;"><span id="outputimgsrc"></span></span> <span id="climbn" class="themesegclass" style="display: none;"><span id="outputimgsrc"></span></span>


问:
How to get filepath from droped file with pyqt5?
I want to get path of the file dropped on QLabel. So I code like this, but label doesn't accept the file. What is the problem..?
Here is my code. So long code sorry and thank you!

```<code>import random
import sys
import pygame
import time
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDesktopWidget
class Example(QWidget):
    size=100
    imgNum=0
    frameCount=4
    isXmin = False
    isXmax = False
    isYmin = False
    isYmax = False
    isLeft= True
def __init__(self):
    super().__init__()
    self.initUI()
def initUI(self):
    sizeObject = QDesktopWidget().screenGeometry()
    # print(" Screen size : " + str(sizeObject.height()) + "x" + str(sizeObject.width()))
    self.xMax=sizeObject.width()-10
    self.yMax=sizeObject.height()-10
    print(self.xMax)
    print(self.yMax)
    self.setWindowFlags(Qt.FramelessWindowHint)
    self.setAttribute(Qt.WA_TranslucentBackground)
    self.setStyleSheet("background-color:transparent;")
    self.setGeometry(100, 100, 100, 100)
    self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
    self.setAcceptDrops(True)
    self.label=QLabel(self)
    self.label.setAcceptDrops(True)
    self.pixmaps=[QPixmap('left.png'),QPixmap('stand.png'),QPixmap('right.png'),QPixmap('stand.png'),QPixmap('leftR.png'),QPixmap('standR.png'),QPixmap('rightR.png'),QPixmap('standR.png')]
    for x in range(len(self.pixmaps)):
        self.pixmaps[x]=self.pixmaps[x].scaled(self.size,self.size,Qt.KeepAspectRatio)
    self.resize(self.pixmaps[2].width(),self.pixmaps[2].height())
    self.label.setPixmap(self.pixmaps[len(self.pixmaps)-1])
    self.changeTimer=QTimer(self)
    self.changeTimer.timeout.connect(self.changeFoot)
    self.moveTimer=QTimer(self)
    self.moveTimer.timeout.connect(self.moving)
    self.setAcceptDrops(True)
    pygame.init()
    pygame.mixer.music.load('hoi_imtemmie.mp3')
    pygame.mixer.music.play()
    self.show()

def dragEnterEvent(self, event):
    if event.mimeData().hasUrls:
        event.accept()
    else:
        event.ingore()
def dropEvent(self, event):
    self.path=event.mimeData.urls()
def moving(self):
    if self.distance == 0:
        print(self.distance)
        print(self.x(),"x",self.y())
        self.label.setPixmap(self.pixmaps[1])
        self.moveTimer.stop()
        self.changeTimer.stop()
        time.sleep(3)
        self.setMovement()
        return 0
    else:
        self.move(self.x()+self.direct[0],self.y()+self.direct[1])
        self.distance-=1
    if self.x()<=-10 :
        self.distance=0
        print("xm")
        self.isXmin = True
    if self.y()<=-10 :
        self.distance=0
        print("ym")
        self.isYmin = True
    if self.x()>=self.xMax:
        self.distance=0
        print("xM")
        self.isXmax=True
    if self.y()>=self.yMax :
        self.distance=0
        print("yM")
        self.isYmax=True

def setMovement(self):
    self.direct=[0,0]
    while(self.direct[0]==0 and self.direct[1]==0):
        self.direct=[random.randint(-1,1),random.randint(-1,1)]
    if self.isXmax:
        self.direct[0]=-1
    if self.isXmin:
        self.direct[0]=1
    if self.isYmin:
        self.direct[1]=1
    if self.isYmax:
        self.direct[1]=-1

    if self.direct[0]== -1:
        self.isLeft=True
        self.imgNum=0
    elif self.direct[0]== 1:
        self.isLeft=False
        self.imgNum=4
    self.isXmax = False
    self.isXmin = False
    self.isYmin = False
    self.isYmax = False
    # if direct[0]*direct[1]==0 : self.delta = QPoint(dX*direct[0],dY*direct[1])
    # else: self.delta=QPoint(direct[0]*(dX**(1/2)),direct[1]*(dY**1/2))
    self.distance=random.randint(200,400)
    self.changeTimer.start(300)
    self.moveTimer.start(30)

def changeFoot(self):
    self.label.setPixmap(self.pixmaps[self.imgNum])
    if self.isLeft:
        if self.imgNum<self.frameCount-1:
            self.imgNum+=1
        else :
            self.imgNum=0
    else:
        if self.imgNum<2*self.frameCount-1:
            self.imgNum+=1
        else :
            self.imgNum=self.frameCount

def mousePressEvent(self, QMouseEvent):
    self.setMovement()
    pygame.mixer.music.load('hoi_imtemmie.mp3')
    pygame.mixer.music.play()
def keyPressEvent(self, QKeyEvent):
    if QKeyEvent.key() == Qt.Key_Escape:
        sys.exit()
    # if QKeyEvent.key() == Qt.Key_G:
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
</code>```

i set AcceptDrops(True)

```<code>self.setAcceptDrops(True)
</code>```

and code about get filepath ▼

```<code>def dragEnterEvent(self, event):
    if event.mimeData().hasUrls:
        event.accept()
    else:
        event.ingore()
def dropEvent(self, event):
    self.path=event.mimeData.urls()
</code>```

答:
Try to loop through event.mimeData().urls()</p>

```<code>for url in event.mimeData().urls():
    self.path = url.toLocalFile()
</code>```

Body:
I want to get path of the file dropped on QLabel. So I code like this, but label doesn't accept the file. What is the problem..?
Here is my code. So long code sorry and thank you!

import random
import sys
import pygame
import time
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QDesktopWidget
class Example(QWidget):
    size=100
    imgNum=0
    frameCount=4
    isXmin = False
    isXmax = False
    isYmin = False
    isYmax = False
    isLeft= True
def __init__(self):
    super().__init__()
    self.initUI()
def initUI(self):
    sizeObject = QDesktopWidget().screenGeometry()
    # print(" Screen size : " + str(sizeObject.height()) + "x" + str(sizeObject.width()))
    self.xMax=sizeObject.width()-10
    self.yMax=sizeObject.height()-10
    print(self.xMax)
    print(self.yMax)
    self.setWindowFlags(Qt.FramelessWindowHint)
    self.setAttribute(Qt.WA_TranslucentBackground)
    self.setStyleSheet("background-color:transparent;")
    self.setGeometry(100, 100, 100, 100)
    self.setWindowFlags(Qt.SplashScreen | Qt.WindowStaysOnTopHint)
    self.setAcceptDrops(True)
    self.label=QLabel(self)
    self.label.setAcceptDrops(True)
    self.pixmaps=[QPixmap('left.png'),QPixmap('stand.png'),QPixmap('right.png'),QPixmap('stand.png'),QPixmap('leftR.png'),QPixmap('standR.png'),QPixmap('rightR.png'),QPixmap('standR.png')]
    for x in range(len(self.pixmaps)):
        self.pixmaps[x]=self.pixmaps[x].scaled(self.size,self.size,Qt.KeepAspectRatio)
    self.resize(self.pixmaps[2].width(),self.pixmaps[2].height())
    self.label.setPixmap(self.pixmaps[len(self.pixmaps)-1])
    self.changeTimer=QTimer(self)
    self.changeTimer.timeout.connect(self.changeFoot)
    self.moveTimer=QTimer(self)
    self.moveTimer.timeout.connect(self.moving)
    self.setAcceptDrops(True)
    pygame.init()
    pygame.mixer.music.load('hoi_imtemmie.mp3')
    pygame.mixer.music.play()
    self.show()

def dragEnterEvent(self, event):
    if event.mimeData().hasUrls:
        event.accept()
    else:
        event.ingore()
def dropEvent(self, event):
    self.path=event.mimeData.urls()
def moving(self):
    if self.distance == 0:
        print(self.distance)
        print(self.x(),"x",self.y())
        self.label.setPixmap(self.pixmaps[1])
        self.moveTimer.stop()
        self.changeTimer.stop()
        time.sleep(3)
        self.setMovement()
        return 0
    else:
        self.move(self.x()+self.direct[0],self.y()+self.direct[1])
        self.distance-=1
    if self.x()<=-10 :
        self.distance=0
        print("xm")
        self.isXmin = True
    if self.y()<=-10 :
        self.distance=0
        print("ym")
        self.isYmin = True
    if self.x()>=self.xMax:
        self.distance=0
        print("xM")
        self.isXmax=True
    if self.y()>=self.yMax :
        self.distance=0
        print("yM")
        self.isYmax=True

def setMovement(self):
    self.direct=[0,0]
    while(self.direct[0]==0 and self.direct[1]==0):
        self.direct=[random.randint(-1,1),random.randint(-1,1)]
    if self.isXmax:
        self.direct[0]=-1
    if self.isXmin:
        self.direct[0]=1
    if self.isYmin:
        self.direct[1]=1
    if self.isYmax:
        self.direct[1]=-1

    if self.direct[0]== -1:
        self.isLeft=True
        self.imgNum=0
    elif self.direct[0]== 1:
        self.isLeft=False
        self.imgNum=4
    self.isXmax = False
    self.isXmin = False
    self.isYmin = False
    self.isYmax = False
    # if direct[0]*direct[1]==0 : self.delta = QPoint(dX*direct[0],dY*direct[1])
    # else: self.delta=QPoint(direct[0]*(dX**(1/2)),direct[1]*(dY**1/2))
    self.distance=random.randint(200,400)
    self.changeTimer.start(300)
    self.moveTimer.start(30)

def changeFoot(self):
    self.label.setPixmap(self.pixmaps[self.imgNum])
    if self.isLeft:
        if self.imgNum<self.frameCount-1:
            self.imgNum+=1
        else :
            self.imgNum=0
    else:
        if self.imgNum<2*self.frameCount-1:
            self.imgNum+=1
        else :
            self.imgNum=self.frameCount

def mousePressEvent(self, QMouseEvent):
    self.setMovement()
    pygame.mixer.music.load('hoi_imtemmie.mp3')
    pygame.mixer.music.play()
def keyPressEvent(self, QKeyEvent):
    if QKeyEvent.key() == Qt.Key_Escape:
        sys.exit()
    # if QKeyEvent.key() == Qt.Key_G:
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

i set AcceptDrops(True)

self.setAcceptDrops(True)

and code about get filepath ▼

def dragEnterEvent(self, event):
    if event.mimeData().hasUrls:
        event.accept()
    else:
        event.ingore()
def dropEvent(self, event):
    self.path=event.mimeData.urls()

Body:
Try to loop through event.mimeData().urls()

for url in event.mimeData().urls():
    self.path = url.toLocalFile()


问:
event is not null but _invocationList is null?
I thought that if I have this code:

```<code>    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null) PropertyChanged(this, e);
    }
</code>```

and the PropertyChanged event wasn't hooked, ProeprtyChanged would be null, but I'm getting a PropertyChanged that is not null and whose _invocationList member is null and whose _invocationCount member is 0. This (I think) is causing an ArgumentOutOfRangeException when I invoke PropertyChanged(this, e). Any idea where could the problem be?

This is my stack trace from the OnClick event:

at System.Collections.ArrayList.get_Item(Int32 index)
     at System.Windows.Forms.BindingsCollection.get_Item(Int32 index)
     at System.Windows.Forms.BindingManagerBase.PushData(Boolean& success)
     at System.Windows.Forms.PropertyManager.OnCurrentChanged(EventArgs ea)
     at System.Windows.Forms.BindToObject.PropValueChanged(Object sender, EventArgs e)
     at System.EventHandler.Invoke(Object sender, EventArgs e)
     at System.ComponentModel.PropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnINotifyPropertyChanged(Object component, PropertyChangedEventArgs e)
     at Player.DataBaseManager.OnPropertyChanged(PropertyChangedEventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 100
     at Player.DataBaseManager.set_TableNames(List`1 value) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 30
     at Player.DataBaseManager.UpdateTableNames() in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 95
     at Player.DataBaseManager.ExecuteNonQuery(String sqlQuery) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 336
     at WebScraperAndPlayer.DataBaseEditor.deleteTableButton_Click(Object sender, EventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\BuilderForm2\Data\DataBaseEditor.cs:line 90
     at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
     at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)

答:
Look at your stack trace

at System.Collections.ArrayList.get_Item(Int32 index) at System.Windows.Forms.BindingsCollection.get_Item(Int32 index) at System.Windows.Forms.BindingManagerBase.PushData(Boolean& success) at

This isn't a problem with the event wiring, something else is messed up in your data binding.

ContentLicense: CC BY-SA 2.5

Body:
I thought that if I have this code:

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null) PropertyChanged(this, e);
    }

and the PropertyChanged event wasn't hooked, ProeprtyChanged would be null, but I'm getting a PropertyChanged that is not null and whose _invocationList member is null and whose _invocationCount member is 0. This (I think) is causing an ArgumentOutOfRangeException when I invoke PropertyChanged(this, e). Any idea where could the problem be?

This is my stack trace from the OnClick event:

at System.Collections.ArrayList.get_Item(Int32 index)
     at System.Windows.Forms.BindingsCollection.get_Item(Int32 index)
     at System.Windows.Forms.BindingManagerBase.PushData(Boolean& success)
     at System.Windows.Forms.PropertyManager.OnCurrentChanged(EventArgs ea)
     at System.Windows.Forms.BindToObject.PropValueChanged(Object sender, EventArgs e)
     at System.EventHandler.Invoke(Object sender, EventArgs e)
     at System.ComponentModel.PropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnValueChanged(Object component, EventArgs e)
     at System.ComponentModel.ReflectPropertyDescriptor.OnINotifyPropertyChanged(Object component, PropertyChangedEventArgs e)
     at Player.DataBaseManager.OnPropertyChanged(PropertyChangedEventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 100
     at Player.DataBaseManager.set_TableNames(List`1 value) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 30
     at Player.DataBaseManager.UpdateTableNames() in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 95
     at Player.DataBaseManager.ExecuteNonQuery(String sqlQuery) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\Player\DataBaseManager2.cs:line 336
     at WebScraperAndPlayer.DataBaseEditor.deleteTableButton_Click(Object sender, EventArgs e) in C:\Users\Juan Luis\My Dropbox\Documents\CodeWebScraper sin Player\WebScraperAndPlayer\BuilderForm2\Data\DataBaseEditor.cs:line 90
     at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
     at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)


问:
Set size of checkbox's drawable
I would like to use custom drawables set as my checkbox drawable I have it defined as follows:

```<code>heart_button.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:drawable="@drawable/heart_outline" />
    <item android:state_checked="true" android:drawable="@drawable/heart_full" />
    <item android:drawable="@drawable/heart_outline" /> <!-- default state -->
</selector>
</code>```

drawables here are just .png files. In layout however I have a following entry:

```<code>    <CheckBox
        android:id="@+id/heartItemCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="4dp"
        android:layout_marginRight="4dp"
        android:button="@drawable/favourite_heart_button"
        android:contentDescription="@string/heartCheckBoxDesc"
        android:focusable="false"/>
</code>```

What I want to achieve is to set width and height of that CheckBox and has its button drawable scalled to fill it. Now it get cropped (when I use too big .png file) or stays small (when I use lower-resoultion .png).
I believe dp units were introduced to prevent various items size depending on phone density. This is way I don't want to just use image with another resolution.

I have tried several ways to achieve what I want - without success. I've tried setting android:scaleType="fitCenter", android:gravity="center", I tried to change items in selector to introduce bitmaps there with android:scaleType="fitCenter" attribute. What seemed to work was setting that drawable to android:background attribute instead of to android:button. But I don't think this a right way (It can make some probles with shadows, elevation, etc. I think).

How do you recommend to achieve what I want?

答:
Most of the People Preferred to use android:background like

```<code>android:button="@null"
android:background="@drawable/check_box"
</code>```

Still if you like to use button then resize your image to 32dp. Because android Material Design suggested to use 32dp for checkbox.

Refer the link. May be it will help you.

Material Guidelines

Title: Set size of checkbox's drawable

Body:
I would like to use custom drawables set as my checkbox drawable I have it defined as follows:

heart_button.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:drawable="@drawable/heart_outline" />
    <item android:state_checked="true" android:drawable="@drawable/heart_full" />
    <item android:drawable="@drawable/heart_outline" />
</selector>

drawables here are just .png files. In layout however I have a following entry:

    <CheckBox
        android:id="@+id/heartItemCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="4dp"
        android:layout_marginRight="4dp"
        android:button="@drawable/favourite_heart_button"
        android:contentDescription="@string/heartCheckBoxDesc"
        android:focusable="false"/>

What I want to achieve is to set width and height of that CheckBox and has its button drawable scalled to fill it. Now it get cropped (when I use too big .png file) or stays small (when I use lower-resoultion .png).
I believe dp units were introduced to prevent various items size depending on phone density. This is way I don't want to just use image with another resolution.

I have tried several ways to achieve what I want - without success. I've tried setting android:scaleType="fitCenter", android:gravity="center", I tried to change items in selector to introduce bitmaps there with android:scaleType="fitCenter" attribute. What seemed to work was setting that drawable to android:background attribute instead of to android:button. But I don't think this a right way (It can make some probles with shadows, elevation, etc. I think).

How do you recommend to achieve what I want?

Body:
Most of the People Preferred to use android:background like

android:button="@null"
android:background="@drawable/check_box"

Still if you like to use button then resize your image to 32dp. Because android Material Design suggested to use 32dp for checkbox.

Refer the link. May be it will help you.

Material Guidelines


问:
How to get current function into a variable?
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

```<code>import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])
</code>```

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

答:
This is what you asked for, as close as I can come. Tested in python versions 2.4, 2.6, 3.0.

```<code>#!/usr/bin/python
def getfunc():
    from inspect import currentframe, getframeinfo
    caller = currentframe().f_back
    func_name = getframeinfo(caller)[2]
    caller = caller.f_back
    from pprint import pprint
    func = caller.f_locals.get(
            func_name, caller.f_globals.get(
                func_name
        )
    )

    return func

def main():
    def inner1():
        def inner2():
            print("Current function is %s" % getfunc())
        print("Current function is %s" % getfunc())
        inner2()
    print("Current function is %s" % getfunc())
    inner1()

#entry point: parse arguments and call main()
if __name__ == "__main__":
    main()
</code>```

Output:

```<code>Current function is <function main at 0x2aec09fe2ed8>
Current function is <function inner1 at 0x2aec09fe2f50>
Current function is <function inner2 at 0x2aec0a0635f0>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I get a variable that contains the currently executing function in Python? I don't want the function's name. I know I can use inspect.stack to get the current function name. I want the actual callable object. Can this be done without using inspect.stack to retrieve the function's name and then evaling the name to get the callable object?

Edit: I have a reason to do this, but it's not even a remotely good one. I'm using plac to parse command-line arguments. You use it by doing plac.call(main), which generates an ArgumentParser object from the function signature of "main". Inside "main", if there is a problem with the arguments, I want to exit with an error message that includes the help text from the ArgumentParser object, which means that I need to directly access this object by calling plac.parser_from(main).print_help(). It would be nice to be able to say instead: plac.parser_from(get_current_function()).print_help(), so that I am not relying on the function being named "main". Right now, my implementation of "get_current_function" would be:

import inspect
def get_current_function():
    return eval(inspect.stack()[1][3])

But this implementation relies on the function having a name, which I suppose is not too onerous. I'm never going to do plac.call(lambda ...).

In the long run, it might be more useful to ask the author of plac to implement a print_help method to print the help text of the function that was most-recently called using plac, or something similar.

Body:
This is what you asked for, as close as I can come. Tested in python versions 2.4, 2.6, 3.0.

#!/usr/bin/python
def getfunc():
    from inspect import currentframe, getframeinfo
    caller = currentframe().f_back
    func_name = getframeinfo(caller)[2]
    caller = caller.f_back
    from pprint import pprint
    func = caller.f_locals.get(
            func_name, caller.f_globals.get(
                func_name
        )
    )

    return func

def main():
    def inner1():
        def inner2():
            print("Current function is %s" % getfunc())
        print("Current function is %s" % getfunc())
        inner2()
    print("Current function is %s" % getfunc())
    inner1()

#entry point: parse arguments and call main()
if __name__ == "__main__":
    main()

Output:

Current function is <function main at 0x2aec09fe2ed8>
Current function is <function inner1 at 0x2aec09fe2f50>
Current function is <function inner2 at 0x2aec0a0635f0>


问:
React-Redux API documentation symbols
I'm reading the react-redux documentation and I found this:

[mapStateToProps(state, [ownProps]): stateProps] (Function)

I don't understand exactly what "[ ]" means, or what is the ":" symbol used for in this context.
I remember that jQuery also uses this for it's API documentation. Example:

.slideToggle([duration][,complete])

Is there any convention for writing/reading these?

答:
Brackets indicate that a parameter is optional, colons indicate some kind of type declaration.

So, for mapStateToProps: it is an optional argument to connect.  It should always be declared with a first parameter which will be the Redux state tree, and may be declared to take a second parameter which will be the props given to the wrapper component.

Title: React-Redux API documentation symbols


问:
PhotoSwipe build bootstrap grid like justifiedgrid
I'm using photoswipe. I just started the tutorial on the documentation I have the basic code. There is no design for the thumbnails grid and I didn't see any templates for the thumbnails in photoswipe.

I would like something like this justifiedgrid lightbox the design is really cool. The space between each thumbnail is really little I like that and the portrait picture has the same height as the landscape picture.

Any CSS genius can help me to build this grid template ?

We can work on this fiddle.

```<code> <h2>First gallery:</h2>
    <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
      <a href="https://farm3.staticflickr.com/2567/5697107145_a4c2eaa0cd_o.jpg" itemprop="contentUrl" data-size="1024x1024">
          <img src="https://farm3.staticflickr.com/2567/5697107145_3c27ff3cd1_m.jpg" itemprop="thumbnail" alt="Image description" />
      </a>
       <figcaption itemprop="caption description">Image caption  1</figcaption>

    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
      <a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
          <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
      </a>
      <figcaption itemprop="caption description">Image caption 2</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
      <a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" itemprop="contentUrl" data-size="1024x683">
          <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" itemprop="thumbnail" alt="Image description" />
      </a>
      <figcaption itemprop="caption description">Image caption 3</figcaption>
    </figure>

    <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
      <a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" itemprop="contentUrl" data-size="1024x768">
          <img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" itemprop="thumbnail" alt="Image description" />
      </a>
      <figcaption itemprop="caption description">Image caption 4</figcaption>
    </figure>

  </div>

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe.
         It's a separate element, as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
        <!-- don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo https://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

          </div>

        </div>

    </div>
</code>```

答: For all guys in my situation I found an alternative. We can use this library over Photoswipe to get a better thumbnails layout. </p>

Body:
I'm using photoswipe. I just started the tutorial on the documentation I have the basic code. There is no design for the thumbnails grid and I didn't see any templates for the thumbnails in photoswipe.

I would like something like this justifiedgrid lightbox the design is really cool. The space between each thumbnail is really little I like that and the portrait picture has the same height as the landscape picture.

Any CSS genius can help me to build this grid template ?

We can work on this fiddle.

First gallery:

Image caption  1

Image caption 2

Image caption 3

Image caption 4

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>


问:
How to mix decorators in autofac?
I'd like to be able to mix and match decorators with Autofac.

For example, let's say I have an IRepository interface, implemented by the Repository class.

I could have the following decorators: RepositoryLocalCache, RepositoryDistributedCache, RepositorySecurity, RepositoryLogging..., you get the ideea.

Based on config settings, I'd like to decorate the basic implementation with the needed decorators. That can be none, one or multiple decorators.

I am familiar with the syntax of registering one decorator, or a chain of them in a fixed order, but how can I make this dynamic?

答:
I've just stumbled upon this thread and would like to share how I do this:

A while ago, I wrote a couple of extension methods to simplify this problem. The methods are similar to @Steven's answer in the sense that they create names for the implementations on the fly. However, they don't use RegisterDecorator, which means that there is no need for the "pass through" implementation.

The methods can be used like this:

```<code>builder.RegisterDecorated<EnquiryService, IEnquiryService>();

builder.RegisterDecorator<ServiceBusEnquiryServiceDecorator, IEnquiryService>();
builder.RegisterDecorator<EmailNotificationDecorator, IEnquiryService>();
</code>```

There are several advantages to this implementation:

The decorators can be conditionally turned on or off

There can be zero, one, or many decorators registered so long as there is at least one registration that is not a decorator

Once RegisterDecorated has been called, you are free to call RegisterDecorator from anywhere you are building up your registrations. This means that you can register decorators from within an entirely separate Autofac module that lives in a different assembly or project from the original implementation to decorate.

You can have control of the order that the decorators are nested by changing the order of the registrations. The outermost decorator will be the last decorator to be registered.

The extension methods look like this:

```<code>public static class ContainerBuilderExtensions
{
    private static readonly IDictionary<Type, string> _implementationNames = new ConcurrentDictionary<Type, string>();

    public static void RegisterDecorated<T, TImplements>(this ContainerBuilder builder) where T : TImplements
    {
        builder.RegisterType<T>()
            .As<TImplements>()
            .Named<TImplements>(GetNameOf<TImplements>());
    }

    public static void RegisterDecorator<T, TImplements>(this ContainerBuilder builder) where T : TImplements
    {
        var nameOfServiceToDecorate = GetOutermostNameOf<TImplements>();

        builder.RegisterType<T>();

        builder.Register(c =>
        {
            var impl = c.ResolveNamed<TImplements>(nameOfServiceToDecorate);

            impl = c.Resolve<T>(TypedParameter.From(impl));

            return impl;
        })
            .As<TImplements>()
            .Named<TImplements>(GetNameOf<TImplements>());
    }

    private static string GetNameOf<T>()
    {
        var type = typeof(T);
        var name = type.FullName + Guid.NewGuid();

        _implementationNames[type] = name;

        return name;
    }

    private static string GetOutermostNameOf<T>()
    {
        var type = typeof(T);

        if (!_implementationNames.ContainsKey(type))
        {
            throw new Exception("Cannot call RegisterDecorator for an implementation that is not decorated. Ensure that you have called RegisterDecorated for this type before calling RegisterDecorator.");
        }

        return _implementationNames[typeof(T)];
    }
}
</code>```

The snippet above is about as simple as it can be, but it has served me well. Of course, it'd be possible to make changes if you have more complex requirements.

This concept formed the basis of my contribution to Orchard CMS that added decorator capabilities: https://github.com/OrchardCMS/Orchard/pull/6233.

Title: How to mix decorators in autofac?

Body:
I've just stumbled upon this thread and would like to share how I do this:

A while ago, I wrote a couple of extension methods to simplify this problem. The methods are similar to @Steven's answer in the sense that they create names for the implementations on the fly. However, they don't use RegisterDecorator, which means that there is no need for the "pass through" implementation.

The methods can be used like this:

builder.RegisterDecorated<EnquiryService, IEnquiryService>();

builder.RegisterDecorator<ServiceBusEnquiryServiceDecorator, IEnquiryService>();
builder.RegisterDecorator<EmailNotificationDecorator, IEnquiryService>();

There are several advantages to this implementation:

The decorators can be conditionally turned on or off

There can be zero, one, or many decorators registered so long as there is at least one registration that is not a decorator

Once RegisterDecorated has been called, you are free to call RegisterDecorator from anywhere you are building up your registrations. This means that you can register decorators from within an entirely separate Autofac module that lives in a different assembly or project from the original implementation to decorate.

You can have control of the order that the decorators are nested by changing the order of the registrations. The outermost decorator will be the last decorator to be registered.

The extension methods look like this:

public static class ContainerBuilderExtensions
{
    private static readonly IDictionary<Type, string> _implementationNames = new ConcurrentDictionary<Type, string>();

    public static void RegisterDecorated<T, TImplements>(this ContainerBuilder builder) where T : TImplements
    {
        builder.RegisterType<T>()
            .As<TImplements>()
            .Named<TImplements>(GetNameOf<TImplements>());
    }

    public static void RegisterDecorator<T, TImplements>(this ContainerBuilder builder) where T : TImplements
    {
        var nameOfServiceToDecorate = GetOutermostNameOf<TImplements>();

        builder.RegisterType<T>();

        builder.Register(c =>
        {
            var impl = c.ResolveNamed<TImplements>(nameOfServiceToDecorate);

            impl = c.Resolve<T>(TypedParameter.From(impl));

            return impl;
        })
            .As<TImplements>()
            .Named<TImplements>(GetNameOf<TImplements>());
    }

    private static string GetNameOf<T>()
    {
        var type = typeof(T);
        var name = type.FullName + Guid.NewGuid();

        _implementationNames[type] = name;

        return name;
    }

    private static string GetOutermostNameOf<T>()
    {
        var type = typeof(T);

        if (!_implementationNames.ContainsKey(type))
        {
            throw new Exception("Cannot call RegisterDecorator for an implementation that is not decorated. Ensure that you have called RegisterDecorated for this type before calling RegisterDecorator.");
        }

        return _implementationNames[typeof(T)];
    }
}

The snippet above is about as simple as it can be, but it has served me well. Of course, it'd be possible to make changes if you have more complex requirements.

This concept formed the basis of my contribution to Orchard CMS that added decorator capabilities: https://github.com/OrchardCMS/Orchard/pull/6233.


问:
Rolling months data by year_month in obiee
I just need to how to create Rolling months in Obiee. If I click for jan 2017,it should show datas from feb 2016.For past previous 12 Months it should show.</p>

答:
You will need a properly configured time dimension. As soon as you have that all the time series functionalities are at your disposal and will work immediately.
https://gerardnico.com/wiki/dat/obiee/obis/time_dimension
https://gerardnico.com/wiki/dat/obiee/obis/logical_sql/function_time</p>


问:
MySQL query ! What's wrong here?
Please tell me what is wrong here :</p>

```<code>INSERT INTO `tbl_verkauf_am`(`fld_kdnr`, `fld_artikelnummer`, `fld_artikelbez1`, `fld_saal_lst`, `fld_anzahl`, `fld_preis`) VALUES
(900000, (SELECT `id`, `fld_besch_0`, `fld_class` FROM `tbl_saal_koord` WHERE `id` < 20300), 1, 50)
</code>```

答:
Your query needs a little tweak.

syntax is :

```<code>INSERT INTO t1(col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
</code>```

Hence your query should be

```<code>INSERT INTO tbl_verkauf_am(fld_kdnr, fld_artikelnummer, fld_artikelbez1, fld_saal_lst, fld_anzahl, fld_preis)
SELECT 900000,id, fld_besch_0, fld_class,1,50
FROM tbl_saal_koord
WHERE id < 20300
</code>```

Title: MySQL query ! What's wrong here?

Body:
Please tell me what is wrong here :

INSERT INTO `tbl_verkauf_am`(`fld_kdnr`, `fld_artikelnummer`, `fld_artikelbez1`, `fld_saal_lst`, `fld_anzahl`, `fld_preis`) VALUES
(900000, (SELECT `id`, `fld_besch_0`, `fld_class` FROM `tbl_saal_koord` WHERE `id` < 20300), 1, 50)

Body:
Your query needs a little tweak.

syntax is :

INSERT INTO t1(col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table

Hence your query should be

INSERT INTO tbl_verkauf_am(fld_kdnr, fld_artikelnummer, fld_artikelbez1, fld_saal_lst, fld_anzahl, fld_preis)
SELECT 900000,id, fld_besch_0, fld_class,1,50
FROM tbl_saal_koord
WHERE id < 20300


问:
posting uploaded file name
I want to output the filename. I also want to check the length of the filename. I have tried the following which didn't work.</p>

```<code>echo $_POST[$_FILES['file']['name']];

echo (strlen($_POST[$_FILES['file']['name']]);
</code>```

答:
Solved. </p>

```<code> echo $_FILES['file']['name'][0];
</code>```

Title: posting uploaded file name

Body:
I want to output the filename. I also want to check the length of the filename. I have tried the following which didn't work.

echo $_POST[$_FILES['file']['name']];

echo (strlen($_POST[$_FILES['file']['name']]);

Body:
Solved.

 echo $_FILES['file']['name'][0];


问:
Convert Oracle SQL statement into SQL Server statement
A bookings project now requires the same data extract - but from an SQL Server database - instead of Oracle. Can anyone assist converting the following into SQL Server syntax?</p>

```<code>SELECT *
FROM (
            SELECT o.ot_outlet_code
                             ,v.lab_site_code ot_outlet_code
                             ,v.brand
                             ,v.region
                            , bd.cd_day_date booking_date, dd.cd_day_date dining_date
                            , f.last_change_date, f.created_date
                            , f.modified_date, t15.ts_timeslot_desc
                           , t.TIME, s.session_type
                            , tbs.booking_status, f.ADDED_BY_USER
                            , bp.product, bs.booking_source
                            , f.SPECIAL_OFFER, f.SEATING_PREFERENCE
                            , f.Tables_guest_id, covers
                            , booking_occurrence, breakfast_flag
                            , row_number() OVER (PARTITION BY f.Tables_guest_id ORDER BY f.last_change_date DESC, f.last_change_time DESC) rank_latest_record
                            , f.title, f.emailoptout
                            , f.MOBILE_OPT_IN, f.HIGH_CHAIR_COVERS
                            , f.GUEST_TYPE, f.Booking_ID
            FROM owbi.whs_fact_rest_booking f
                            , owbi.whs_dim_cal_date bd
                            , owbi.whs_dim_cal_date dd
                            , owbi.whs_dim_bat_booking_source bs
                            , owbi.whs_dim_time_of_day t
                            , owbi.whs_dim_bat_product bp
                            , owbi.whs_dim_15_timeslot t15
                            , owbi.whs_dim_bat_booking_status tbs
                            , owbi.whs_dim_bat_session s
                            , owbi.bat_restaurants_v v
       WHERE f.whs_dim_outlet = v.outlet
    AND f.whs_dim_booking_date = bd.dimension_Key
    AND f.whs_dim_dining_date = dd.dimension_key
    AND f.whs_dim_bat_session = s.dimension_key
    AND f.whs_dim_bat_booking_status = tbs.dimension_key
    AND f.whs_dim_bat_product = bp.dimension_Key
    AND f.whs_dim_bat_booking_source = bs.dimension_key
    AND f.whs_dim_booking_time = t.dimension_Key
    AND f.whs_dim_dining_15_timeslot = t15.dimension_key
    AND dd.ey_year_code in ('2018')
    AND f.whs_dim_dining_date >= 20170303
        )
WHERE rank_latest_record = 1
ORDER BY BOOKING_DATE DESC;
</code>```

答:
The derived table must have an alias.  eg

```<code>SELECT *
FROM (
            SELECT o.ot_outlet_code
                             ,v.lab_site_code ot_outlet_code
                             ,v.brand
                             ,v.region
                            , bd.cd_day_date booking_date, dd.cd_day_date dining_date
                            , f.last_change_date, f.created_date
                            , f.modified_date, t15.ts_timeslot_desc
                           , t.TIME, s.session_type
                            , tbs.booking_status, f.ADDED_BY_USER
                            , bp.product, bs.booking_source
                            , f.SPECIAL_OFFER, f.SEATING_PREFERENCE
                            , f.Tables_guest_id, covers
                            , booking_occurrence, breakfast_flag
                            , row_number() OVER (PARTITION BY f.Tables_guest_id ORDER BY f.last_change_date DESC, f.last_change_time DESC) rank_latest_record
                            , f.title, f.emailoptout
                            , f.MOBILE_OPT_IN, f.HIGH_CHAIR_COVERS
                            , f.GUEST_TYPE, f.Booking_ID
            FROM owbi.whs_fact_rest_booking f
                            , owbi.whs_dim_cal_date bd
                            , owbi.whs_dim_cal_date dd
                            , owbi.whs_dim_bat_booking_source bs
                            , owbi.whs_dim_time_of_day t
                            , owbi.whs_dim_bat_product bp
                            , owbi.whs_dim_15_timeslot t15
                            , owbi.whs_dim_bat_booking_status tbs
                            , owbi.whs_dim_bat_session s
                            , owbi.bat_restaurants_v v
       WHERE f.whs_dim_outlet = v.outlet
    AND f.whs_dim_booking_date = bd.dimension_Key
    AND f.whs_dim_dining_date = dd.dimension_key
    AND f.whs_dim_bat_session = s.dimension_key
    AND f.whs_dim_bat_booking_status = tbs.dimension_key
    AND f.whs_dim_bat_product = bp.dimension_Key
    AND f.whs_dim_bat_booking_source = bs.dimension_key
    AND f.whs_dim_booking_time = t.dimension_Key
    AND f.whs_dim_dining_15_timeslot = t15.dimension_key
    AND dd.ey_year_code in ('2018')
    AND f.whs_dim_dining_date >= 20170303
        ) dt
WHERE rank_latest_record = 1
ORDER BY BOOKING_DATE DESC;
</code>```

In SQL Server it's considered poor form not use ANSI-style JOINs, although it's perfectly legal for inner joins to write them as a cross-join with the join criteria in the WHERE clause.

And it's generally better to use CTEs instead of subqueries/inline views/derived tables in the FROM clause.

Body:
A bookings project now requires the same data extract - but from an SQL Server database - instead of Oracle. Can anyone assist converting the following into SQL Server syntax?

SELECT *
FROM (
            SELECT o.ot_outlet_code
                             ,v.lab_site_code ot_outlet_code
                             ,v.brand
                             ,v.region
                            , bd.cd_day_date booking_date, dd.cd_day_date dining_date
                            , f.last_change_date, f.created_date
                            , f.modified_date, t15.ts_timeslot_desc
                           , t.TIME, s.session_type
                            , tbs.booking_status, f.ADDED_BY_USER
                            , bp.product, bs.booking_source
                            , f.SPECIAL_OFFER, f.SEATING_PREFERENCE
                            , f.Tables_guest_id, covers
                            , booking_occurrence, breakfast_flag
                            , row_number() OVER (PARTITION BY f.Tables_guest_id ORDER BY f.last_change_date DESC, f.last_change_time DESC) rank_latest_record
                            , f.title, f.emailoptout
                            , f.MOBILE_OPT_IN, f.HIGH_CHAIR_COVERS
                            , f.GUEST_TYPE, f.Booking_ID
            FROM owbi.whs_fact_rest_booking f
                            , owbi.whs_dim_cal_date bd
                            , owbi.whs_dim_cal_date dd
                            , owbi.whs_dim_bat_booking_source bs
                            , owbi.whs_dim_time_of_day t
                            , owbi.whs_dim_bat_product bp
                            , owbi.whs_dim_15_timeslot t15
                            , owbi.whs_dim_bat_booking_status tbs
                            , owbi.whs_dim_bat_session s
                            , owbi.bat_restaurants_v v
       WHERE f.whs_dim_outlet = v.outlet
    AND f.whs_dim_booking_date = bd.dimension_Key
    AND f.whs_dim_dining_date = dd.dimension_key
    AND f.whs_dim_bat_session = s.dimension_key
    AND f.whs_dim_bat_booking_status = tbs.dimension_key
    AND f.whs_dim_bat_product = bp.dimension_Key
    AND f.whs_dim_bat_booking_source = bs.dimension_key
    AND f.whs_dim_booking_time = t.dimension_Key
    AND f.whs_dim_dining_15_timeslot = t15.dimension_key
    AND dd.ey_year_code in ('2018')
    AND f.whs_dim_dining_date >= 20170303
        )
WHERE rank_latest_record = 1
ORDER BY BOOKING_DATE DESC;

Body:
The derived table must have an alias.  eg

SELECT *
FROM (
            SELECT o.ot_outlet_code
                             ,v.lab_site_code ot_outlet_code
                             ,v.brand
                             ,v.region
                            , bd.cd_day_date booking_date, dd.cd_day_date dining_date
                            , f.last_change_date, f.created_date
                            , f.modified_date, t15.ts_timeslot_desc
                           , t.TIME, s.session_type
                            , tbs.booking_status, f.ADDED_BY_USER
                            , bp.product, bs.booking_source
                            , f.SPECIAL_OFFER, f.SEATING_PREFERENCE
                            , f.Tables_guest_id, covers
                            , booking_occurrence, breakfast_flag
                            , row_number() OVER (PARTITION BY f.Tables_guest_id ORDER BY f.last_change_date DESC, f.last_change_time DESC) rank_latest_record
                            , f.title, f.emailoptout
                            , f.MOBILE_OPT_IN, f.HIGH_CHAIR_COVERS
                            , f.GUEST_TYPE, f.Booking_ID
            FROM owbi.whs_fact_rest_booking f
                            , owbi.whs_dim_cal_date bd
                            , owbi.whs_dim_cal_date dd
                            , owbi.whs_dim_bat_booking_source bs
                            , owbi.whs_dim_time_of_day t
                            , owbi.whs_dim_bat_product bp
                            , owbi.whs_dim_15_timeslot t15
                            , owbi.whs_dim_bat_booking_status tbs
                            , owbi.whs_dim_bat_session s
                            , owbi.bat_restaurants_v v
       WHERE f.whs_dim_outlet = v.outlet
    AND f.whs_dim_booking_date = bd.dimension_Key
    AND f.whs_dim_dining_date = dd.dimension_key
    AND f.whs_dim_bat_session = s.dimension_key
    AND f.whs_dim_bat_booking_status = tbs.dimension_key
    AND f.whs_dim_bat_product = bp.dimension_Key
    AND f.whs_dim_bat_booking_source = bs.dimension_key
    AND f.whs_dim_booking_time = t.dimension_Key
    AND f.whs_dim_dining_15_timeslot = t15.dimension_key
    AND dd.ey_year_code in ('2018')
    AND f.whs_dim_dining_date >= 20170303
        ) dt
WHERE rank_latest_record = 1
ORDER BY BOOKING_DATE DESC;

In SQL Server it's considered poor form not use ANSI-style JOINs, although it's perfectly legal for inner joins to write them as a cross-join with the join criteria in the WHERE clause.

And it's generally better to use CTEs instead of subqueries/inline views/derived tables in the FROM clause.


问:
Stored Procedure error handling using java
How do you handle error condition  while writing stored procedure or accessing stored procedure from java?</p>

答:
```<code>this piece of code is taken from oracle [docs][1] to answer.

public void
    createProcedureShowSuppliers()
    throws SQLException {
    String createProcedure = null;

    String queryDrop =
        "DROP PROCEDURE IF EXISTS SHOW_SUPPLIERS";

    createProcedure =
        "create procedure SHOW_SUPPLIERS() " +
        "begin " +
            "select SUPPLIERS.SUP_NAME, " +
            "COFFEES.COF_NAME " +
            "from SUPPLIERS, COFFEES " +
            "where SUPPLIERS.SUP_ID = " +
            "COFFEES.SUP_ID " +
            "order by SUP_NAME; " +
        "end";
    Statement stmt = null;
    Statement stmtDrop = null;

    try {
        System.out.println("Calling DROP PROCEDURE");
        stmtDrop = con.createStatement();
        stmtDrop.execute(queryDrop);
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmtDrop != null)
        {
            stmtDrop.close();
        }
    }

    try {
        stmt = con.createStatement();
        stmt.executeUpdate(createProcedure);
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) { stmt.close(); }
    }
}

  [1]: https://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html
</code>```


问:
Deploying node.js, gulp, bower app on Cloud Foundry application start issue
I am deploying node js application consist of bower, gulp etc.
I am able to deploy it and build it successfully at Cloud Foundry but appilcation is not starting. my issue is may be the gulp file is having code with browser sync
is

```<code> browserSync.init({
        server: {
            baseDir: dist,
            startPath: '/',
            middleware: [proxyMiddleware]
        }
    });
</code>```

I am not sure what is missing, in fact I am not getting any error but app is not running on cf . by using cfenv I am able to give port in browser syc but how I provide 'host' because by default it is working on localhost ?

logs are:

```<code>2016-11-19T18:23:09.45+0530 [CELL/0]     OUT Creating container
2016-11-19T18:23:10.49+0530 [CELL/0]     OUT Successfully created container
2016-11-19T18:23:11.50+0530 [CELL/0]     OUT Starting health monitoring of container
2016-11-19T18:23:11.94+0530 [APP/0]      OUT > NodejsStarterApp@0.0.1 start /home/vcap/app
2016-11-19T18:23:11.94+0530 [APP/0]      OUT > node app.js
2016-11-19T18:23:12.02+0530 [HEALTH/0]   OUT healthcheck failed
2016-11-19T18:23:12.03+0530 [HEALTH/0]   OUT Exit status 1
2016-11-19T18:23:12.13+0530 [APP/0]      OUT port8080
2016-11-19T18:23:12.13+0530 [APP/0]      OUT bind0.0.0.0
2016-11-19T18:23:12.13+0530 [APP/0]      OUT server starting on https://myapp.u1.app.cloud.myorg.net
2016-11-19T18:23:12.56+0530 [HEALTH/0]   OUT healthcheck failed
2016-11-19T18:23:12.56+0530 [HEALTH/0]   OUT Exit status 1
2016-11-19T18:23:13.09+0530 [HEALTH/0]   OUT healthcheck failed
2016-11-19T18:23:13.09+0530 [HEALTH/0]   OUT Exit status 1
2016-11-19T18:23:13.62+0530 [HEALTH/0]   OUT healthcheck failed
</code>```

any suggestion I welcome..

答:
I had this issue deploying as well. I fixed it by putting -u process in my cf push command.

Example:

cf push APP-NAME -b nodejs_buildpack -p . -u process and it fixed the problem.

-u specifies to CF what level of health check to perform.

Body:
I am deploying node js application consist of bower, gulp etc.
I am able to deploy it and build it successfully at Cloud Foundry but appilcation is not starting. my issue is may be the gulp file is having code with browser sync
is

 browserSync.init({
        server: {
            baseDir: dist,
            startPath: '/',
            middleware: [proxyMiddleware]
        }
    });

I am not sure what is missing, in fact I am not getting any error but app is not running on cf . by using cfenv I am able to give port in browser syc but how I provide 'host' because by default it is working on localhost ?

logs are:

2016-11-19T18:23:09.45+0530 [CELL/0]     OUT Creating container
2016-11-19T18:23:10.49+0530 [CELL/0]     OUT Successfully created container
2016-11-19T18:23:11.50+0530 [CELL/0]     OUT Starting health monitoring of container
2016-11-19T18:23:11.94+0530 [APP/0]      OUT > NodejsStarterApp@0.0.1 start /home/vcap/app
2016-11-19T18:23:11.94+0530 [APP/0]      OUT > node app.js
2016-11-19T18:23:12.02+0530 [HEALTH/0]   OUT healthcheck failed
2016-11-19T18:23:12.03+0530 [HEALTH/0]   OUT Exit status 1
2016-11-19T18:23:12.13+0530 [APP/0]      OUT port8080
2016-11-19T18:23:12.13+0530 [APP/0]      OUT bind0.0.0.0
2016-11-19T18:23:12.13+0530 [APP/0]      OUT server starting on https://myapp.u1.app.cloud.myorg.net
2016-11-19T18:23:12.56+0530 [HEALTH/0]   OUT healthcheck failed
2016-11-19T18:23:12.56+0530 [HEALTH/0]   OUT Exit status 1
2016-11-19T18:23:13.09+0530 [HEALTH/0]   OUT healthcheck failed
2016-11-19T18:23:13.09+0530 [HEALTH/0]   OUT Exit status 1
2016-11-19T18:23:13.62+0530 [HEALTH/0]   OUT healthcheck failed

any suggestion I welcome..


问:
Parallel path in SVN overwriting each other's files
I have two paths, let's say:

root\folder1
root\folder2

While the folder names are different, both contain files with the same names, just some of their contents differ. I have all the paths and all their files added to SVN. Now, I make a change to root\folder1\fileA and commit it. If I try to make a change to root\folder2\fileA, I get an error citing I need to update first. When I do update, my local copy is overwritten with the changes I just made to fileA under root\folder1. And this works vice versa.

I don't know why this is happening. I even deleted root\folder2 and recreated it and re-added it to SVN. But the same thing is still happening...

答:
It sounds like folder1 and folder2 are two working copies of the same repository directory. If you check svn info (or the equivalent in tortoisesvn) for folder1 and folder2, that should
give a clue as to what's going on.</p>


问:
Size Discrepancy: Powershell ISE vs Batch Launcher
I have a XAML GUI that is created in Powershell using the XML Node Reader. All of my controls are exactly where I want them when I run the script in the ISE. I then created a batch file to launch it:

```<code>Powershell.exe -STA -File "C:\Scripts\Study App\Core.ps1"
</code>```

After running the batch file, I notice that the GUI itself is larger than when in the ISE and as a result, a few of my buttons are misaligned. I also noticed this behavior when I right click the ps1 file and click Run with Powershell. What is it about the ISE that results in a smaller window size and is there a way for me to combat this?

There is an almost identical question here but there is a significant difference: My form is of type System.Windows.Window and doesn't have the needed properties that System.Windows.Forms.Form has.

答:
The PowerShell ISE loads additional libraries that are not loaded when using straight PowerShell. I did a quick search and found this issue on another site:

[https://social.msdn.microsoft.com/Forums/en-US/56352ca7-3e6e-452a-a1c8-09ab65c07089/powershell-wpf-window-sizes-different-when-run-outside-of-ps-ise?forum=wpf][1]

It appears that the solution may be using SizeToContent="WidthAndHeight".

Body:
I have a XAML GUI that is created in Powershell using the XML Node Reader. All of my controls are exactly where I want them when I run the script in the ISE. I then created a batch file to launch it:

Powershell.exe -STA -File "C:\Scripts\Study App\Core.ps1"

After running the batch file, I notice that the GUI itself is larger than when in the ISE and as a result, a few of my buttons are misaligned. I also noticed this behavior when I right click the ps1 file and click Run with Powershell. What is it about the ISE that results in a smaller window size and is there a way for me to combat this?

There is an almost identical question here but there is a significant difference: My form is of type System.Windows.Window and doesn't have the needed properties that System.Windows.Forms.Form has.


问:
invalid operands of types 'const char [26]' and 'LPSTR '
My code is

```<code>string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );
</code>```

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

答:
You cannot add together a const char[26] (that is, your "The selected folder is : " literal) and a char* pointer (that is, your lp variable of type LPSTR, which is char*). Concatenate the strings first and then obtain a const char*, which you can pass to the function:

```<code>std::string str = R"(C:\Users\mardare\Downloads\config)"; //don't care about escape sequences, use raw string literals.
MessageBox(nullptr, ("The selected folder is : " + str).c_str(), "Bye!", MB_OK);
</code>```

Body:
My code is

string  str = "C:\\Users\\mardare\\Downloads\\config";
LPSTR lp = const_cast<char *>(str.c_str());
MessageBox ( NULL, "The selected folder is : "+lp, "Bye!", MB_OK );

And when I try to build it and run i get this error

invalid operands of types 'const char [26]' and 'LPSTR'

Body:
You cannot add together a const char[26] (that is, your "The selected folder is : " literal) and a char* pointer (that is, your lp variable of type LPSTR, which is char*). Concatenate the strings first and then obtain a const char*, which you can pass to the function:

std::string str = R"(C:\Users\mardare\Downloads\config)"; //don't care about escape sequences, use raw string literals.
MessageBox(nullptr, ("The selected folder is : " + str).c_str(), "Bye!", MB_OK);


问:
Perl unexpected result
Imagine I have this Perl script

```<code>my $name = "   foo    ";
my $sn   = "     foosu";

trim($name, \$sn);

print "name: [$name]\n";
print "sn: [$sn]\n";
exit 0;

sub trim{

   my $fref_trim = sub{
                          my ($ref_input) = @_;
                          ${$ref_input} =~ s/^\s+// ;
                          ${$ref_input} =~ s/\s+$// ;
    };

   foreach my $input (@_){
       if (ref($input) eq "SCALAR"){
            $fref_trim->($input);
       } else {
            $fref_trim->(\$input);
       }
   }
}
</code>```

Result:

```<code>name: [foo]
sn: [foosu]
</code>```

I would expect $name to be "[   foo    ]" when printing the value after calling trim, but the sub is setting $name as I would want it. Why is this working, when it really shouldn't?

I'm not passing $name by reference and the trim sub is not returning anything. I'd expect the trim sub to create a copy of the $name value, process the copy, but then the original $name would still have the leading and trailing white spaces when printed in the main code.

I assume it is because of the alias with @_, but shouldn't the foreach my $input (@_) force the sub to copy the value and only treat the value not the alias?

I know I can simplify this sub and I used it only as an example.

答:
I assume it is because of the alias with @_, but shouldn't the foreach my $input (@_) force the sub to copy the value and only treat the value not the alias?

You're right that @_ contains aliases. The part that's missing is that foreach also aliases the loop variable to the current list element. Quoting perldoc perlsyn:

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

So ultimately $input is an alias for $_[0], which is an alias for $name, which is why you see the changes appearing in $name.

Title: Perl unexpected result

Body:
Imagine I have this Perl script

my $name = "   foo    ";
my $sn   = "     foosu";

trim($name, \$sn);

print "name: [$name]\n";
print "sn: [$sn]\n";
exit 0;

sub trim{

   my $fref_trim = sub{
                          my ($ref_input) = @_;
                          ${$ref_input} =~ s/^\s+// ;
                          ${$ref_input} =~ s/\s+$// ;
    };

   foreach my $input (@_){
       if (ref($input) eq "SCALAR"){
            $fref_trim->($input);
       } else {
            $fref_trim->(\$input);
       }
   }
}

Result:

name: [foo]
sn: [foosu]

I would expect $name to be "[   foo    ]" when printing the value after calling trim, but the sub is setting $name as I would want it. Why is this working, when it really shouldn't?

I'm not passing $name by reference and the trim sub is not returning anything. I'd expect the trim sub to create a copy of the $name value, process the copy, but then the original $name would still have the leading and trailing white spaces when printed in the main code.

I assume it is because of the alias with @_, but shouldn't the foreach my $input (@_) force the sub to copy the value and only treat the value not the alias?

I know I can simplify this sub and I used it only as an example.


问:
How to get id or name of iframe using javascript?
I have one iframe:

```<code><iframe id="frame" name="frame" src="test.html"></iframe>
</code>```

Now, I want to get id or name that iframe and alert it, I used:

```<code>if (document.getelementbyid('frame') = frame) alert('OK');
</code>```

But it doesn't work.

答:
Just simply scanning the DOM for the element is one thing:

```<code>var iframe = document.getElementById("frame"); // Note the captialization!
</code>```

But, that won't get you the id or name attribute values. You'd need to go a little further for that:

```<code>console.log(iframe.id, iframe.name);
</code>```

Also, JavaScript is case-sensitive and you have a few capitalization errors in your invocations of .getElementById().

Additionally, getting an element by its id only to compare it to the same id is pointless. Whatever you are trying to do, there is a better way to do it.

Lastly, document.write() has very limited use cases. When you want to dynamically output content, prepare a placeholder for that output and then dynamically inject the content into that previously prepared container. In many cases, using document.write() will cause the entire currently loaded document to be unloaded.

var p = document.getElementById("output");

var iframe = document.getElementById("frame"); // Note the captialization!
console.log(iframe.id, iframe.name);

// When comparing values in JavaScript, you need the double equal sign operator (==)
// which converts the types of the operands to the same type and then compares them,
// or the triple equal sign (===) operator which just compares the operands without
// data type conversion. A single equal sign will assign a value and, if used like
// you had it, would cause your if condition to always be true
if (document.getElementById('frame').id === "frame"){
  // Update the output area with the dynamic content
  output.textContent = "OK!";
} else {
  output.textContent = "NOT OK!";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe id="frame" name="frame" src="test.html"></iframe>
<p id="output"></p></code>```

Body:
I have one iframe:

Now, I want to get id or name that iframe and alert it, I used:

if (document.getelementbyid('frame') = frame) alert('OK');

But it doesn't work.

Body:
Just simply scanning the DOM for the element is one thing:

var iframe = document.getElementById("frame"); // Note the captialization!

But, that won't get you the id or name attribute values. You'd need to go a little further for that:

console.log(iframe.id, iframe.name);

Also, JavaScript is case-sensitive and you have a few capitalization errors in your invocations of .getElementById().

Additionally, getting an element by its id only to compare it to the same id is pointless. Whatever you are trying to do, there is a better way to do it.

Lastly, document.write() has very limited use cases. When you want to dynamically output content, prepare a placeholder for that output and then dynamically inject the content into that previously prepared container. In many cases, using document.write() will cause the entire currently loaded document to be unloaded.

var p = document.getElementById("output");

var iframe = document.getElementById("frame"); // Note the captialization!
console.log(iframe.id, iframe.name);

// When comparing values in JavaScript, you need the double equal sign operator (==)
// which converts the types of the operands to the same type and then compares them,
// or the triple equal sign (===) operator which just compares the operands without
// data type conversion. A single equal sign will assign a value and, if used like
// you had it, would cause your if condition to always be true
if (document.getElementById('frame').id === "frame"){
  // Update the output area with the dynamic content
  output.textContent = "OK!";
} else {
  output.textContent = "NOT OK!";
}

<iframe id="frame" name="frame" src="test.html"></iframe>
<p id="output"></p>


问:
How i can Do dynamic checkboxes for java jsp?
i need to do six checkboxes for one image , and this image need to change if one or more checkboxes is cheked , how i can do it? please help me , i attach my code.

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <form name="form1" onsubmit="checkBoxValidation()">

<input type="checkbox" name="chbdiente1" value="1"/>Vestibular

<input type="checkbox" name="chbdiente1" value="2"/>Mesial

<input type="checkbox" name="chbdiente1" value="3"/>Oclusal

<input type="checkbox" name="chbdiente1" value="4"/>Distal

<input type="checkbox" name="chbdiente1" value="5"/>Palatino

<input type="checkbox" name="chbdiente1" value="6"/>Lingual

<input type="submit" value="submit"/>
        </form>
        <%String chbdiente1[] = request.getParameterValues("chbdiente1");
            if (chbdiente1 != null) {%>

<%for (int i = 0; i < chbdiente1.length; i++) {%>

<%=chbdiente1[i]%>
<%}%>

<%}%>

```

i have this code and send me the value of selected checkboxes , but the image not change. help please. thanks

答:
function changeImage1() {

    var image = document.getElementById('diente1');
    var checkboxes = document.getElementById("form1");
    var cont = 0;

    try {
        for (var x = 0; x < checkboxes.length; x++) {
            if (checkboxes[x].checked) {
                cont = cont + 1;
            }
        }
    } catch (e) {

    }
    try {
        if (cont > 0) {
            image.src = "img/fotodiente/1.1.jpg";
            d1 = 2;
            array.push("Pieza 1");
            var chb2 = document.getElementsByName("form1");
        } else if (cont === 0) {
            image.src = "img/fotodiente/1.jpg";
            d1 = 1;
            array.splice(1, 1);
        }
    } catch (e) {

    }
}
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <img src="img/fotodiente/1.jpg" class="item_thumb" width="78" height="107" alt="1" id="diente1" onclick="changeImage1()"/>

                <form id="form1" method="post" action="">
                    <input type="checkbox" id="chbdiente1" value="1" onclick="changeImage1();" /><label>Vestibular</label>
                    <input type="checkbox" id="chbdiente1" value="2" onclick="changeImage1();" /><label>Mesial</label>
                    <input type="checkbox" id="chbdiente1" value="3" onclick="changeImage1();" /><label>Oclusal</label>
                    <input type="checkbox" id="chbdiente1" value="4" onclick="changeImage1();" /><label>Distal</label>
                    <input type="checkbox" id="chbdiente1" value="5" onclick="changeImage1();" /><label>Palatino</label>
                    <input type="checkbox" id="chbdiente1" value="6" onclick="changeImage1();" /><label>Lingual</label>
                    <input type="button" name="Submit" value="Contar" hidden="">
                </form></code>```

Well, this changes the image when there are 1 or more checkboxes clicked, if all the checkboxes are unchecked the image returns to the first one.
I hope also I can help others and thanks

Body:
i need to do six checkboxes for one image , and this image need to change if one or more checkboxes is cheked , how i can do it? please help me , i attach my code.

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <form name="form1" onsubmit="checkBoxValidation()">

<input type="checkbox" name="chbdiente1" value="1"/>Vestibular

<input type="checkbox" name="chbdiente1" value="2"/>Mesial

<input type="checkbox" name="chbdiente1" value="3"/>Oclusal

<input type="checkbox" name="chbdiente1" value="4"/>Distal

<input type="checkbox" name="chbdiente1" value="5"/>Palatino

<input type="checkbox" name="chbdiente1" value="6"/>Lingual

<input type="submit" value="submit"/>
        </form>
        <%String chbdiente1[] = request.getParameterValues("chbdiente1");
            if (chbdiente1 != null) {%>

<%for (int i = 0; i < chbdiente1.length; i++) {%>

<%=chbdiente1[i]%>
<%}%>

<%}%>

i have this code and send me the value of selected checkboxes , but the image not change. help please. thanks

Body:
function changeImage1() {

    var image = document.getElementById('diente1');
    var checkboxes = document.getElementById("form1");
    var cont = 0;

    try {
        for (var x = 0; x < checkboxes.length; x++) {
            if (checkboxes[x].checked) {
                cont = cont + 1;
            }
        }
    } catch (e) {

    }
    try {
        if (cont > 0) {
            image.src = "img/fotodiente/1.1.jpg";
            d1 = 2;
            array.push("Pieza 1");
            var chb2 = document.getElementsByName("form1");
        } else if (cont === 0) {
            image.src = "img/fotodiente/1.jpg";
            d1 = 1;
            array.splice(1, 1);
        }
    } catch (e) {

    }
}
;

 <img src="img/fotodiente/1.jpg" class="item_thumb" width="78" height="107" alt="1" id="diente1" onclick="changeImage1()"/>

                <form id="form1" method="post" action="">
                    <input type="checkbox" id="chbdiente1" value="1" onclick="changeImage1();" /><label>Vestibular</label>
                    <input type="checkbox" id="chbdiente1" value="2" onclick="changeImage1();" /><label>Mesial</label>
                    <input type="checkbox" id="chbdiente1" value="3" onclick="changeImage1();" /><label>Oclusal</label>
                    <input type="checkbox" id="chbdiente1" value="4" onclick="changeImage1();" /><label>Distal</label>
                    <input type="checkbox" id="chbdiente1" value="5" onclick="changeImage1();" /><label>Palatino</label>
                    <input type="checkbox" id="chbdiente1" value="6" onclick="changeImage1();" /><label>Lingual</label>
                    <input type="button" name="Submit" value="Contar" hidden="">
                </form>

Well, this changes the image when there are 1 or more checkboxes clicked, if all the checkboxes are unchecked the image returns to the first one.
I hope also I can help others and thanks