问:
Apache ODE BPEL soapenv:Server axis2ns1:selectionFailure
I am new to BPEL and struggling to get started.

I created a simple If/Else workflow, but getting the following error when I am testing the wsdl file with eclipse web services explorer:

```<code>soapenv:Server axis2ns1:selectionFailure
</code>```

My understanding from other similar questions is its probably something very simple and related to namespace or variable name in the if condition, but I can't understand why, and how to solve it.

I am using Apache ODE 1.3.7 on Eclipse 4.7.1 Oxygen and Tomcat 8.5.

This is my workflow design:

BPEL FILE:

```<code><!-- Flow1 BPEL Process [Generated by the Eclipse BPEL Designer] -->
<!-- Date: Mon Nov 13 23:18:38 AST 2017 -->
<bpel:process name="Flow1"
         targetNamespace="http://Flow1"
         suppressJoinFailure="yes"
         xmlns:tns="http://Flow1"
         xmlns:bpel="http://docs.oasis-open.org/wsbpel/2.0/process/executable"
         >

    <!-- Import the client WSDL -->
    <bpel:import location="Flow1Artifacts.wsdl" namespace="http://Flow1"
            importType="http://schemas.xmlsoap.org/wsdl/" />

    <!-- ================================================================= -->
    <!-- PARTNERLINKS                                                      -->
    <!-- List of services participating in this BPEL process               -->
    <!-- ================================================================= -->
    <bpel:partnerLinks>
        <!-- The 'client' role represents the requester of this service. -->
        <bpel:partnerLink name="client"
                     partnerLinkType="tns:Flow1"
                     myRole="Flow1Provider"
                     />
    </bpel:partnerLinks>

    <!-- ================================================================= -->
    <!-- VARIABLES                                                         -->
    <!-- List of messages and XML documents used within this BPEL process  -->
    <!-- ================================================================= -->
    <bpel:variables>
        <!-- Reference to the message passed as input during initiation -->
        <bpel:variable name="input"
                  messageType="tns:Flow1RequestMessage"/>

        <!--
          Reference to the message that will be returned to the requester
          -->
        <bpel:variable name="output"
                  messageType="tns:Flow1ResponseMessage"/>
    </bpel:variables>

    <!-- ================================================================= -->
    <!-- ORCHESTRATION LOGIC                                               -->
    <!-- Set of activities coordinating the flow of messages across the    -->
    <!-- services integrated within this business process                  -->
    <!-- ================================================================= -->
    <bpel:sequence name="main">

        <!-- Receive input from requester.
             Note: This maps to operation defined in Flow1.wsdl
             -->
        <bpel:receive name="receiveInput" partnerLink="client"
                 portType="tns:Flow1"
                 operation="process" variable="input"
                 createInstance="yes"/>

        <!-- Generate reply to synchronous request -->

        <bpel:if name="If">
            <bpel:condition expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[$input.payload/tns:input="John"]]></bpel:condition>
        <bpel:sequence name="Sequence">
                <bpel:assign validate="no" name="Assign">
                    <bpel:copy>
                        <bpel:from>
                            <bpel:literal xml:space="preserve">Hi John</bpel:literal>
                        </bpel:from>
                        <bpel:to part="payload" variable="output">
                            <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:result]]></bpel:query>
                        </bpel:to>
                    </bpel:copy>
                </bpel:assign>
                <bpel:reply name="replyOutput" partnerLink="client" portType="tns:Flow1" operation="process" variable="output" />

            </bpel:sequence>
            <bpel:else>
                <bpel:sequence name="Sequence1">
                    <bpel:assign validate="no" name="Assign1">
                        <bpel:copy>
                            <bpel:from>
                                <bpel:literal xml:space="preserve">Not john</bpel:literal>
                            </bpel:from>
                            <bpel:to part="payload" variable="output">
                                <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:result]]></bpel:query>
                            </bpel:to>
                        </bpel:copy>
                    </bpel:assign>
                    <bpel:reply name="Reply" partnerLink="client" operation="process" portType="tns:Flow1" variable="output"></bpel:reply>
                </bpel:sequence>
            </bpel:else>

        </bpel:if>
    </bpel:sequence>
</bpel:process>
</code>```

WSDL FILE:

```<code><?xml version="1.0"?>
<definitions name="Flow1"
        targetNamespace="http://Flow1"
        xmlns:tns="http://Flow1"
        xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype"
        xmlns="http://schemas.xmlsoap.org/wsdl/"
        xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
        >

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     TYPE DEFINITION - List of types participating in this BPEL process
     The BPEL Designer will generate default request and response types
     but you can define or import any XML Schema type and use them as part
     of the message types.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <types>
        <schema attributeFormDefault="unqualified" elementFormDefault="qualified"
                targetNamespace="http://Flow1"
                xmlns="http://www.w3.org/2001/XMLSchema">

            <element name="Flow1Request">
                <complexType>
                    <sequence>
                        <element name="input" type="string"/>
                    </sequence>
                </complexType>
            </element>

            <element name="Flow1Response">
                <complexType>
                    <sequence>
                        <element name="result" type="string"/>
                    </sequence>
                </complexType>
            </element>
        </schema>
    </types>

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     MESSAGE TYPE DEFINITION - Definition of the message types used as
     part of the port type defintions
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <message name="Flow1RequestMessage">
        <part name="payload" element="tns:Flow1Request"/>
    </message>
    <message name="Flow1ResponseMessage">
        <part name="payload" element="tns:Flow1Response"/>
    </message>

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     PORT TYPE DEFINITION - A port type groups a set of operations into
     a logical service unit.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->

    <!-- portType implemented by the Flow1 BPEL process -->
    <portType name="Flow1">
        <operation name="process">
            <input  message="tns:Flow1RequestMessage" />
            <output message="tns:Flow1ResponseMessage"/>
        </operation>
    </portType>
<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     PARTNER LINK TYPE DEFINITION
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <plnk:partnerLinkType name="Flow1">
        <plnk:role name="Flow1Provider" portType="tns:Flow1"/>
    </plnk:partnerLinkType>

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     BINDING DEFINITION - Defines the message format and protocol details
     for a web service.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <binding name="Flow1Binding" type="tns:Flow1">
        <soap:binding style="document"
            transport="http://schemas.xmlsoap.org/soap/http" />
        <operation name="process">
            <soap:operation
                soapAction="http://Flow1/process" />
            <input>
                <soap:body use="literal" />
            </input>
            <output>
                <soap:body use="literal" />
            </output>
        </operation>
    </binding>

<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     SERVICE DEFINITION - A service groups a set of ports into
     a service unit.
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
    <service name="Flow1Service">
        <port name="Flow1Port" binding="tns:Flow1Binding">
            <soap:address location="http://localhost:8084/ode/processes/Flow1" />
        </port>
    </service>
</definitions>
</code>```

and Deploy.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<deploy xmlns="http://www.apache.org/ode/schemas/dd/2007/03" xmlns:Flow1="http://Flow1">
  <process name="Flow1:Flow1">
    <active>true</active>
    <retired>false</retired>
    <process-events generate="all"/>
    <provide partnerLink="client">
      <service name="Flow1:Flow1Service" port="Flow1Port"/>
    </provide>
  </process>
</deploy>
</code>```

答:
SelectionFailure indicates that xml element that is being queried is not found.   Looking at your BPEL, I assume the output variable is being queried before initializing it.

Initialize the output variable before the if/else:

```<code><bpel:assign validate="no" name="initialize">
    <bpel:copy>
        <bpel:from>
            <bpel:literal xml:space="preserve">
                <tns:Flow1Response xmlns:tns="http://Flow1"><tns:result /></tns:Flow1Response>
            </bpel:literal>
        </bpel:from>
        <bpel:to part="payload" variable="output" />
    </bpel:copy>
</bpel:assign>
</code>```

Body:
I am new to BPEL and struggling to get started.

I created a simple If/Else workflow, but getting the following error when I am testing the wsdl file with eclipse web services explorer:

soapenv:Server axis2ns1:selectionFailure

My understanding from other similar questions is its probably something very simple and related to namespace or variable name in the if condition, but I can't understand why, and how to solve it.

I am using Apache ODE 1.3.7 on Eclipse 4.7.1 Oxygen and Tomcat 8.5.

This is my workflow design:

BPEL FILE:

<bpel:process name="Flow1"
         targetNamespace="http://Flow1"
         suppressJoinFailure="yes"
         xmlns:tns="http://Flow1"
         xmlns:bpel="http://docs.oasis-open.org/wsbpel/2.0/process/executable"
         >

    <bpel:import location="Flow1Artifacts.wsdl" namespace="http://Flow1"
            importType="http://schemas.xmlsoap.org/wsdl/" />

    <bpel:partnerLinks>

        <bpel:partnerLink name="client"
                     partnerLinkType="tns:Flow1"
                     myRole="Flow1Provider"
                     />
    </bpel:partnerLinks>

    <bpel:variables>

        <bpel:variable name="input"
                  messageType="tns:Flow1RequestMessage"/>

        <bpel:variable name="output"
                  messageType="tns:Flow1ResponseMessage"/>
    </bpel:variables>

    <bpel:sequence name="main">

        <bpel:receive name="receiveInput" partnerLink="client"
                 portType="tns:Flow1"
                 operation="process" variable="input"
                 createInstance="yes"/>

        <bpel:if name="If">
            <bpel:condition expressionLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[$input.payload/tns:input="John"]]></bpel:condition>
        <bpel:sequence name="Sequence">
                <bpel:assign validate="no" name="Assign">
                    <bpel:copy>
                        <bpel:from>
                            <bpel:literal xml:space="preserve">Hi John</bpel:literal>
                        </bpel:from>
                        <bpel:to part="payload" variable="output">
                            <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:result]]></bpel:query>
                        </bpel:to>
                    </bpel:copy>
                </bpel:assign>
                <bpel:reply name="replyOutput" partnerLink="client" portType="tns:Flow1" operation="process" variable="output" />

            </bpel:sequence>
            <bpel:else>
                <bpel:sequence name="Sequence1">
                    <bpel:assign validate="no" name="Assign1">
                        <bpel:copy>
                            <bpel:from>
                                <bpel:literal xml:space="preserve">Not john</bpel:literal>
                            </bpel:from>
                            <bpel:to part="payload" variable="output">
                                <bpel:query queryLanguage="urn:oasis:names:tc:wsbpel:2.0:sublang:xpath1.0"><![CDATA[tns:result]]></bpel:query>
                            </bpel:to>
                        </bpel:copy>
                    </bpel:assign>
                    <bpel:reply name="Reply" partnerLink="client" operation="process" portType="tns:Flow1" variable="output"></bpel:reply>
                </bpel:sequence>
            </bpel:else>

        </bpel:if>
    </bpel:sequence>
</bpel:process>

WSDL FILE:

<?xml version="1.0"?>
<definitions name="Flow1"
        targetNamespace="http://Flow1"
        xmlns:tns="http://Flow1"
        xmlns:plnk="http://docs.oasis-open.org/wsbpel/2.0/plnktype"
        xmlns="http://schemas.xmlsoap.org/wsdl/"
        xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
        >

    <types>
        <schema attributeFormDefault="unqualified" elementFormDefault="qualified"
                targetNamespace="http://Flow1"
                xmlns="http://www.w3.org/2001/XMLSchema">

            <element name="Flow1Request">
                <complexType>
                    <sequence>
                        <element name="input" type="string"/>
                    </sequence>
                </complexType>
            </element>

            <element name="Flow1Response">
                <complexType>
                    <sequence>
                        <element name="result" type="string"/>
                    </sequence>
                </complexType>
            </element>
        </schema>
    </types>

    <message name="Flow1RequestMessage">
        <part name="payload" element="tns:Flow1Request"/>
    </message>
    <message name="Flow1ResponseMessage">
        <part name="payload" element="tns:Flow1Response"/>
    </message>

    <portType name="Flow1">
        <operation name="process">
            <input  message="tns:Flow1RequestMessage" />
            <output message="tns:Flow1ResponseMessage"/>
        </operation>
    </portType>

    <plnk:partnerLinkType name="Flow1">
        <plnk:role name="Flow1Provider" portType="tns:Flow1"/>
    </plnk:partnerLinkType>

    <binding name="Flow1Binding" type="tns:Flow1">
        <soap:binding style="document"
            transport="http://schemas.xmlsoap.org/soap/http" />
        <operation name="process">
            <soap:operation
                soapAction="http://Flow1/process" />
            <input>
                <soap:body use="literal" />
            </input>
            <output>
                <soap:body use="literal" />
            </output>
        </operation>
    </binding>

    <service name="Flow1Service">
        <port name="Flow1Port" binding="tns:Flow1Binding">
            <soap:address location="http://localhost:8084/ode/processes/Flow1" />
        </port>
    </service>
</definitions>

and Deploy.xml

<?xml version="1.0" encoding="UTF-8"?>
<deploy xmlns="http://www.apache.org/ode/schemas/dd/2007/03" xmlns:Flow1="http://Flow1">
  <process name="Flow1:Flow1">
    <active>true</active>
    <retired>false</retired>
    <process-events generate="all"/>
    <provide partnerLink="client">
      <service name="Flow1:Flow1Service" port="Flow1Port"/>
    </provide>
  </process>
</deploy>

Body:
SelectionFailure indicates that xml element that is being queried is not found.   Looking at your BPEL, I assume the output variable is being queried before initializing it.

Initialize the output variable before the if/else:

<bpel:assign validate="no" name="initialize">
    <bpel:copy>
        <bpel:from>
            <bpel:literal xml:space="preserve">
                <tns:Flow1Response xmlns:tns="http://Flow1"><tns:result /></tns:Flow1Response>
            </bpel:literal>
        </bpel:from>
        <bpel:to part="payload" variable="output" />
    </bpel:copy>
</bpel:assign>


来源: stackexchange

问:
trying to draw a sprite onto canvas but I am missing something

window.onload = function(){
  theVideo();
  playVideo();
  Move();
  Draw();
};
let objectInfo = {
    canvas: null,
    context: null,
    // Number of sprites
    numberOfFrames: 16,
    image: null,
    imageWidth: 128,
    imageHeight: 192,
    frameIndex: 0,
    frameWidth: 0,
    // Animation interval (ms)
    msInterval: 1000,
    x: 10,
    y: 10,
};
const imageFile = "shaggy.png";
 function Draw(){
  objectInfo.context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 120, 25, frameWidth, frameHeight);
 }
//image setup
window.onload= function () {

    // Canvas setup
    objectInfo.canvas = document.querySelector("#myCanvas");
    objectInfo.context = objectInfo.canvas.getContext("2d");

    // Image setup
    objectInfo.image = new Image();
    objectInfo.image.onload = function() {

        // The this object refers to image because within image onload event handler
        objectInfo.imageWidth = this.width;
        objectInfo.imageHeight = this.height;

        // Calculate framewidth (size of each sprite)
        objectInfo.frameWidth = objectInfo.imageWidth / objectInfo.numberOfFrames;
    };
    // Load image
    objectInfo.image.src = imageFile;

};

var xPos = 0;
var yPos = 0;

//move image
function Move(e){
  //right
  if(e.keyCode==39){
      xPos+=5;
  }
  //left
  if(e.keyCode==37){
      xPos-=5;
  }
  //up
   if(e.keyCode==38){
      yPos-=5;
   }
   //down
    if(e.keyCode==40){
      yPos+=5;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <title>Sprite</title>
    <meta charset="utf-8">
    <meta name="author" content="Peyton">
    <meta name="description" content="115">
    <link rel= 'stylesheet' href="p4.css">
    <script src="p4.js"> </script>
      <style>canvas { border: 1px solid black; }</style>
<body>
    <canvas width= "1300" height= "600" id= "myCanvas">

    <video id="video" controls >
        <source src="ScoobyDooV.mp4"/>
        <source src="ScoobyDooV.ogv"/>
    </video>

    </canvas>
    </body>

    </html>
    <nav>
    </nav>
    <main id="#wrapper"><br>

    </main>
</body>
</html></code>```

I'm really new to coding and am not sure what I am missing to call my sprite and draw the first image onto the canvas. I later have to call each measurement of my sprite and assign to a function keydown event to make it look like its walking each direction so if I could get any guidance on that too that would be great.

答:
Your code is completely not suited to the task you are attempting. Animations require regular rendering. There is a huge amount of missing code in your example so i can really solve any problems directly.

So just thought I would give an example of how to load, animate, and render sprites sheets.

Sprite sheets

There are many ways to handle sprite sheets, though I find that using a standard method for all sprite sheets makes life easy.

Some sprite sheets have a regular layout and evenly spaced sprites, other sprite sheets, have been packed together to conserve pixels and memory.

Each sprite has a location on the sheet, the top left corner and the size as width and height.

You can attach an array of these locations to an image

For example the next function creates sprites for a regular layout (like image in your question)

```<code>function createSprites(width, height, columns, rows, image) {
  const sprites = [];
  var w = width / columns;
  var h = height / rows;
  var ix, iy;
  for (iy = 0; iy < rows; iy++) {
    for (ix = 0; ix < columns; ix++) {
      const x = ix * w;
      const y = iy * h;
      sprites.push({ x, y, w, h });
    }
  }
  image.sprites = sprites;
}
</code>```

The array is added to the img so you don't have to add additional management

You can then draw the sprite by creating a custom draw function.

```<code>function drawSprite(img, sprIndex, x, y) {
  const spr = img.sprites[sprIndex];
  ctx.drawImage(img,
    spr.x, spr.y, spr.w, spr.h, // location on sprite sheet
    x , y  ,       // location on canvas
    spr.w, spr.h, // size on canvas;
  );

}
</code>```

You pass the sprite sheet image, the sprite index in the sprite array, and the location you want to draw the sprite.

Easy as

Because you likely know the size of the sprite sheet, and the location of the sprites you don't have to wait for the image to load to attach the sprite data.

const ctx = canvas.getContext("2d");
const spriteSheet = new Image;
spriteSheet.src = "https://i.stack.imgur.com/hOrC1.png";
// The image size is known so you dont have to wait for it to load
createSprites(128, 192, 4, 4, spriteSheet); // add a array of sprite locations

// It is important that the sprite sizes are integers
// width must be divisible by columns and height by rows
function createSprites(width, height, columns, rows, image) {
  const sprites = [];
  var w = width / columns;
  var h = height / rows;
  var ix, iy;
  for (iy = 0; iy < rows; iy++) {
    for (ix = 0; ix < columns; ix++) {
      const x = ix * w;
      const y = iy * h;
      sprites.push({ x, y, w, h });
    }
  }
  image.sprites = sprites;
}

function drawSprite(img, sprIndex, x, y) {
  const spr = img.sprites[sprIndex];
  ctx.drawImage(img,
    spr.x, spr.y, spr.w, spr.h, // location on sprite sheet
    x , y , // location on canvas
    spr.w, spr.h, // size on canvas;
  );

}

const walkerInfo = {
  framesPerDir: 4,
  movements: [{x: 0,y: 3 },{ x: -5, y: 0 }, { x: 5, y: 0 }, { x: 0, y: -3 } ],
}
const walker = {
  dir: 0, // 0,1,2,3
  time: 0, // time in Frames
  rate: 0, // steps per frame
  x: 0, // position
  y: 0, //
  update() {
    this.time += 1;
    // only move when sprite frame changes
    if ((this.time % this.rate) === 0) {
      this.x += walkerInfo.movements[this.dir].x;
      this.y += walkerInfo.movements[this.dir].y;
      if(this.x < -128 || this.x > canvas.width ||
         this.y < -192 || this.y > canvas.height) {
         this.x = randI(canvas.width);
         this.y = randI(canvas.height);
         this.dir = randI(4)
         this.rate = randI(6, 12)

      }
    }
    if(randI(1000) === 0){
          this.dir = (this.dir + (randI(2) ? 2 : 1)) % 4;
          this.rate = randI(6, 12)
    }

  },
  draw() {
    var index = this.dir * walkerInfo.framesPerDir;
    index += (this.time / this.rate | 0) % walkerInfo.framesPerDir;
    drawSprite(
      spriteSheet, index,
      this.x, this.y
    );
  }

}

function createWalker(x = randI(w), y = randI(h), dir = randI(4), rate = randI(6, 18)) {
  return { ...walker, x, y, dir, rate, time: randI(100) };
}
const walkers = [];

// main update function
function update(timer) {
  globalTime = timer;
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  ctx.globalAlpha = 1; // reset alpha
  if (w !== innerWidth || h !== innerHeight) {
    cw = (w = canvas.width = innerWidth) / 2;
    ch = (h = canvas.height = innerHeight) / 2;
  } else {
    ctx.clearRect(0, 0, w, h);
  }

  if (spriteSheet.complete) { // has the image loaded
    if (randI(walkers.length) === 0) { // odd 1/100 to create a walker
      walkers.push(createWalker());
    }
    walkers.sort((a,b)=>a.y - b.y);
    eachOf(walkers, walk => walk.update());
    eachOf(walkers, walk => walk.draw());

  }
  requestAnimationFrame(update);
}
requestAnimationFrame(update);

var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var globalTime;

const randI = (min, max = min + (min = 0)) => (Math.random() * (max - min) + min) | 0;
const rand = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const eachOf = (array, cb) => {
  var i = 0;
  const len = array.length;
  while (i < len && cb(array[i], i++, len) !== true);
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}</code>```

<canvas id="canvas"></canvas>```

ContentLicense: CC BY-SA 3.0

Body:
window.onload = function(){
  theVideo();
  playVideo();
  Move();
  Draw();
};
let objectInfo = {
    canvas: null,
    context: null,
    // Number of sprites
    numberOfFrames: 16,
    image: null,
    imageWidth: 128,
    imageHeight: 192,
    frameIndex: 0,
    frameWidth: 0,
    // Animation interval (ms)
    msInterval: 1000,
    x: 10,
    y: 10,
};
const imageFile = "shaggy.png";
 function Draw(){
  objectInfo.context.drawImage(myImage, shift, 0, frameWidth, frameHeight, 120, 25, frameWidth, frameHeight);
 }
//image setup
window.onload= function () {

    // Canvas setup
    objectInfo.canvas = document.querySelector("#myCanvas");
    objectInfo.context = objectInfo.canvas.getContext("2d");

    // Image setup
    objectInfo.image = new Image();
    objectInfo.image.onload = function() {

        // The this object refers to image because within image onload event handler
        objectInfo.imageWidth = this.width;
        objectInfo.imageHeight = this.height;

        // Calculate framewidth (size of each sprite)
        objectInfo.frameWidth = objectInfo.imageWidth / objectInfo.numberOfFrames;
    };
    // Load image
    objectInfo.image.src = imageFile;

};

var xPos = 0;
var yPos = 0;

//move image
function Move(e){
  //right
  if(e.keyCode==39){
      xPos+=5;
  }
  //left
  if(e.keyCode==37){
      xPos-=5;
  }
  //up
   if(e.keyCode==38){
      yPos-=5;
   }
   //down
    if(e.keyCode==40){
      yPos+=5;
    }
}

<!DOCTYPE html>

    <title>Sprite</title>
    <meta charset="utf-8">
    <meta name="author" content="Peyton">
    <meta name="description" content="115">
    <link rel= 'stylesheet' href="p4.css">

    <canvas width= "1300" height= "600" id= "myCanvas">

    <video id="video" controls >
        <source src="ScoobyDooV.mp4"/>
        <source src="ScoobyDooV.ogv"/>
    </video>

    </canvas>

I'm really new to coding and am not sure what I am missing to call my sprite and draw the first image onto the canvas. I later have to call each measurement of my sprite and assign to a function keydown event to make it look like its walking each direction so if I could get any guidance on that too that would be great.

Body:
Your code is completely not suited to the task you are attempting. Animations require regular rendering. There is a huge amount of missing code in your example so i can really solve any problems directly.

So just thought I would give an example of how to load, animate, and render sprites sheets.

Sprite sheets

There are many ways to handle sprite sheets, though I find that using a standard method for all sprite sheets makes life easy.

Some sprite sheets have a regular layout and evenly spaced sprites, other sprite sheets, have been packed together to conserve pixels and memory.

Each sprite has a location on the sheet, the top left corner and the size as width and height.

You can attach an array of these locations to an image

For example the next function creates sprites for a regular layout (like image in your question)

function createSprites(width, height, columns, rows, image) {
  const sprites = [];
  var w = width / columns;
  var h = height / rows;
  var ix, iy;
  for (iy = 0; iy < rows; iy++) {
    for (ix = 0; ix < columns; ix++) {
      const x = ix * w;
      const y = iy * h;
      sprites.push({ x, y, w, h });
    }
  }
  image.sprites = sprites;
}

The array is added to the img so you don't have to add additional management

You can then draw the sprite by creating a custom draw function.

function drawSprite(img, sprIndex, x, y) {
  const spr = img.sprites[sprIndex];
  ctx.drawImage(img,
    spr.x, spr.y, spr.w, spr.h, // location on sprite sheet
    x , y  ,       // location on canvas
    spr.w, spr.h, // size on canvas;
  );

}

You pass the sprite sheet image, the sprite index in the sprite array, and the location you want to draw the sprite.

Easy as

Because you likely know the size of the sprite sheet, and the location of the sprites you don't have to wait for the image to load to attach the sprite data.

const ctx = canvas.getContext("2d");
const spriteSheet = new Image;
spriteSheet.src = "https://i.stack.imgur.com/hOrC1.png";
// The image size is known so you dont have to wait for it to load
createSprites(128, 192, 4, 4, spriteSheet); // add a array of sprite locations

// It is important that the sprite sizes are integers
// width must be divisible by columns and height by rows
function createSprites(width, height, columns, rows, image) {
  const sprites = [];
  var w = width / columns;
  var h = height / rows;
  var ix, iy;
  for (iy = 0; iy < rows; iy++) {
    for (ix = 0; ix < columns; ix++) {
      const x = ix * w;
      const y = iy * h;
      sprites.push({ x, y, w, h });
    }
  }
  image.sprites = sprites;
}

function drawSprite(img, sprIndex, x, y) {
  const spr = img.sprites[sprIndex];
  ctx.drawImage(img,
    spr.x, spr.y, spr.w, spr.h, // location on sprite sheet
    x , y , // location on canvas
    spr.w, spr.h, // size on canvas;
  );

}

const walkerInfo = {
  framesPerDir: 4,
  movements: [{x: 0,y: 3 },{ x: -5, y: 0 }, { x: 5, y: 0 }, { x: 0, y: -3 } ],
}
const walker = {
  dir: 0, // 0,1,2,3
  time: 0, // time in Frames
  rate: 0, // steps per frame
  x: 0, // position
  y: 0, //
  update() {
    this.time += 1;
    // only move when sprite frame changes
    if ((this.time % this.rate) === 0) {
      this.x += walkerInfo.movements[this.dir].x;
      this.y += walkerInfo.movements[this.dir].y;
      if(this.x < -128 || this.x > canvas.width ||
         this.y < -192 || this.y > canvas.height) {
         this.x = randI(canvas.width);
         this.y = randI(canvas.height);
         this.dir = randI(4)
         this.rate = randI(6, 12)

      }
    }
    if(randI(1000) === 0){
          this.dir = (this.dir + (randI(2) ? 2 : 1)) % 4;
          this.rate = randI(6, 12)
    }

  },
  draw() {
    var index = this.dir * walkerInfo.framesPerDir;
    index += (this.time / this.rate | 0) % walkerInfo.framesPerDir;
    drawSprite(
      spriteSheet, index,
      this.x, this.y
    );
  }

}

function createWalker(x = randI(w), y = randI(h), dir = randI(4), rate = randI(6, 18)) {
  return { ...walker, x, y, dir, rate, time: randI(100) };
}
const walkers = [];

// main update function
function update(timer) {
  globalTime = timer;
  ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
  ctx.globalAlpha = 1; // reset alpha
  if (w !== innerWidth || h !== innerHeight) {
    cw = (w = canvas.width = innerWidth) / 2;
    ch = (h = canvas.height = innerHeight) / 2;
  } else {
    ctx.clearRect(0, 0, w, h);
  }

  if (spriteSheet.complete) { // has the image loaded
    if (randI(walkers.length) === 0) { // odd 1/100 to create a walker
      walkers.push(createWalker());
    }
    walkers.sort((a,b)=>a.y - b.y);
    eachOf(walkers, walk => walk.update());
    eachOf(walkers, walk => walk.draw());

  }
  requestAnimationFrame(update);
}
requestAnimationFrame(update);

var w = canvas.width;
var h = canvas.height;
var cw = w / 2; // center
var ch = h / 2;
var globalTime;

const randI = (min, max = min + (min = 0)) => (Math.random() * (max - min) + min) | 0;
const rand = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const eachOf = (array, cb) => {
  var i = 0;
  const len = array.length;
  while (i < len && cb(array[i], i++, len) !== true);
};

canvas {
  position: absolute;
  top: 0px;
  left: 0px;
}

<canvas id="canvas"></canvas>


答:
Not sure if I understand correctly as the samples are not explained clearly but I somehow was able to print the desired output. Explanations given thru comments</p>

```<code>// I just simplified your given array
$input[0] = array(
    [1 => 5, 2 => 12, 11 => 15],
    [1 => 5, 2 => 12, 11 => 16],
    [1 => 4, 2 =>  9, 11 => 15],
    [1 => 3, 2 =>  9, 11 => 15],
    [1 => 3, 2 =>  9, 11 => 16],
    [1 => 3, 2 => 13, 11 => 15],
    [1 => 3, 2 => 13, 11 => 16],
    [1 => 3, 2 => 12, 11 => 15],
    [1 => 3, 2 => 12, 11 => 16],
    [1 => 4, 2 =>  9, 11 => 16],
    [1 => 4, 2 => 13, 11 => 15],
    [1 => 4, 2 => 13, 11 => 16],
    [1 => 4, 2 => 12, 11 => 15],
    [1 => 4, 2 => 12, 11 => 16],
    [1 => 5, 2 =>  9, 11 => 15],
    [1 => 5, 2 => 13, 11 => 16]
);

// Declare new output array
$output[0] = [];

// Loop thru each array inside $input[0] array
foreach($input[0] as $key => $value) {

    // Set each array value to variables
    $one = $value[1];
    $two = $value[2];
    $eleven = $value[11];

    // Check if $one key already exist, create if not
    if (!isset($output[0][$one])) {
            $output[0][$one] = [];
    }

    // Check if $two key already exist, create if not
    if (!isset($output[$one][$two])) {
            $output[0][$one][$two] = [];
    }

    // push each $eleven
    $output[0][$one][$two][] = $eleven;
};

// Prints output array
echo '```';
print_r($output);
</code>```

Title: php array merge recursive with same array values and create combinations

Body:
Hello i am new in php and I just stuck in brainstorming array, I have below php array

[0] => Array
    (
        [0] => Array
            (
                [1] => 5
                [2] => 12
                [11] => 15
            )

        [1] => Array
            (
                [1] => 5
                [2] => 12
                [11] => 16
            )

        [2] => Array
            (
                [1] => 4
                [2] => 9
                [11] => 15
            )

        [3] => Array
            (
                [1] => 3
                [2] => 9
                [11] => 15
            )

        [4] => Array
            (
                [1] => 3
                [2] => 9
                [11] => 16
            )

        [5] => Array
            (
                [1] => 3
                [2] => 13
                [11] => 15
            )

        [6] => Array
            (
                [1] => 3
                [2] => 13
                [11] => 16
            )

        [7] => Array
            (
                [1] => 3
                [2] => 12
                [11] => 15
            )

        [8] => Array
            (
                [1] => 3
                [2] => 12
                [11] => 16
            )

        [9] => Array
            (
                [1] => 4
                [2] => 9
                [11] => 16
            )

        [10] => Array
            (
                [1] => 4
                [2] => 13
                [11] => 15
            )

        [11] => Array
            (
                [1] => 4
                [2] => 13
                [11] => 16
            )

        [12] => Array
            (
                [1] => 4
                [2] => 12
                [11] => 15
            )

        [13] => Array
            (
                [1] => 4
                [2] => 12
                [11] => 16
            )

        [14] => Array
            (
                [1] => 5
                [2] => 9
                [11] => 15
            )

        [15] => Array
            (
                [1] => 5
                [2] => 13
                [11] => 16
            )

    )

And I want below out put

[0]=> Array
(
    [5]=> Array
    (
        [12]=> Array
        (
            [0] => 15
            [1] => 16
        )
        [9]=> Array
        (
            [0] => 15
        )
        [13]=> Array
        (
            [0] => 16
        )
    )
    [4]=> Array
    (
        [9]=> Array
        (
            [0] => 15
            [1] => 16
        )
        [13]=> Array
        (
            [0] => 16
        )
        [12]=> Array
        (
            [0] => 15
            [1] => 16
        )
    )
    [3]=> Array
    (
        [9]=> Array
        (
            [0] => 15
            [1] => 16
        )
        [13]=> Array
        (
            [0] => 15
            [1] => 16
        )
        [12]=> Array
        (
            [0] => 15
            [1] => 16

        )
    )
)

Sorry out put not much clear but I want check each array first common value e.g 5,4, and 3 then based on these value traverse though each value and create tree array
As Example simple i want each arrays first element and then recursively array check values and create new
Example have just 3 level but i want recursive n-level and , help would be Appreciate.

Body:
Not sure if I understand correctly as the samples are not explained clearly but I somehow was able to print the desired output. Explanations given thru comments

// I just simplified your given array
$input[0] = array(
    [1 => 5, 2 => 12, 11 => 15],
    [1 => 5, 2 => 12, 11 => 16],
    [1 => 4, 2 =>  9, 11 => 15],
    [1 => 3, 2 =>  9, 11 => 15],
    [1 => 3, 2 =>  9, 11 => 16],
    [1 => 3, 2 => 13, 11 => 15],
    [1 => 3, 2 => 13, 11 => 16],
    [1 => 3, 2 => 12, 11 => 15],
    [1 => 3, 2 => 12, 11 => 16],
    [1 => 4, 2 =>  9, 11 => 16],
    [1 => 4, 2 => 13, 11 => 15],
    [1 => 4, 2 => 13, 11 => 16],
    [1 => 4, 2 => 12, 11 => 15],
    [1 => 4, 2 => 12, 11 => 16],
    [1 => 5, 2 =>  9, 11 => 15],
    [1 => 5, 2 => 13, 11 => 16]
);

// Declare new output array
$output[0] = [];

// Loop thru each array inside $input[0] array
foreach($input[0] as $key => $value) {

    // Set each array value to variables
    $one = $value[1];
    $two = $value[2];
    $eleven = $value[11];

    // Check if $one key already exist, create if not
    if (!isset($output[0][$one])) {
            $output[0][$one] = [];
    }

    // Check if $two key already exist, create if not
    if (!isset($output[$one][$two])) {
            $output[0][$one][$two] = [];
    }

    // push each $eleven
    $output[0][$one][$two][] = $eleven;
};

// Prints output array
echo '<pre>';
print_r($output);


问:
Badge count on Floating action button
I would like to show count badge in front of Floating Action Button in android. I used FrameLayout in order to achieve that. My code is here

```<code>   <FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/send_button"
    android:layout_toLeftOf="@+id/send_button"
    android:layout_toStartOf="@+id/send_button"
    android:layout_gravity="end|bottom"
    android:id="@+id/frameLayout">

    <android.support.design.widget.FloatingActionButton
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/listen_button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:backgroundTint="#e3e3e3" />

   <TextView
        android:id="@+id/textOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="10"
        android:textColor="#FFF"
        android:textSize="10sp"
        android:textStyle="bold"
        android:background="@drawable/badge_circle"
        android:layout_gravity="right|bottom"
        android:layout_alignBottom="@+id/frameLayout"
        android:layout_toLeftOf="@+id/frameLayout"
        android:layout_toStartOf="@+id/frameLayout" />

</FrameLayout>
</code>```

I get the count badge below the FAB, as shown below

I need the count badge to be in front of the FAB.

答:
One can simply use TextView by giving custom style for floating.

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

Title: Badge count on Floating action button

Body:
I would like to show count badge in front of Floating Action Button in android. I used FrameLayout in order to achieve that. My code is here

   <FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/send_button"
    android:layout_toLeftOf="@+id/send_button"
    android:layout_toStartOf="@+id/send_button"
    android:layout_gravity="end|bottom"
    android:id="@+id/frameLayout">

    <android.support.design.widget.FloatingActionButton
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/listen_button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:backgroundTint="#e3e3e3" />

   <TextView
        android:id="@+id/textOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="10"
        android:textColor="#FFF"
        android:textSize="10sp"
        android:textStyle="bold"
        android:background="@drawable/badge_circle"
        android:layout_gravity="right|bottom"
        android:layout_alignBottom="@+id/frameLayout"
        android:layout_toLeftOf="@+id/frameLayout"
        android:layout_toStartOf="@+id/frameLayout" />

</FrameLayout>

I get the count badge below the FAB, as shown below

I need the count badge to be in front of the FAB.

Body:
One can simply use TextView by giving custom style for floating.

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


问:
Perforce changing the default editor
I use perforce for my revision control, when I hit 'p4 change' it always opens up the list on emacs, and we all know the pain of deleting text in it. How do i change it to gedit or vim or anything else? My default text editor is gedit.</p>

答:
For Notepad++ I needed to use this command -multiInst to trigger edits.

```<code>p4 set P4EDITOR="C:\Program Files (x86)\Notepad++\notepad++.exe -multiInst"
</code>```

Title: Perforce changing the default editor

Body:
For Notepad++ I needed to use this command -multiInst to trigger edits.

p4 set P4EDITOR="C:\Program Files (x86)\Notepad++\notepad++.exe -multiInst"


问:
TensorFlow boolean indexing
Let's go straight, currently, I want to index a tensor and change the non-zero term to -1 and zero term to 1. But I don't know how to do it in TensorFlow.

Here is my code:

```<code>y_[y_ != 0].assign(-1)
y_[y_ == 0].assign(1)
</code>```

The reason is TensorFlow doesn't seem to support boolean indexing. How can I fix it?

Btw, it seems boolean_mask doesn't work for me, because I don't want to return a slice of y_, I just want y_ to change its values.

Thanks!

答:
You can use tf.cond (), for the conditional assignment. I have given an example code below,

```<code>import tensorflow as tf

x_= tf.Variable(5) #non-zero variable
y_= tf.Variable(0) #variable euqals to 0

y_ =tf.cond(tf.equal(y_,0),lambda :y_.assign(1),lambda :y_.assign(-1)) #assign 1 if variable equals to zero else -1
x_ =tf.cond(tf.equal(x_,0),lambda :x_.assign(1),lambda :x_.assign(-1)) #assign 1 if variable equals to zero else -1

sess = tf.Session()
sess.run(tf.global_variables_initializer())

with sess.as_default():
   print(y_.eval()) #prints 1
   print(x_.eval()) #prints -1
</code>```

Hope this helps.

Title: TensorFlow boolean indexing

Body:
Let's go straight, currently, I want to index a tensor and change the non-zero term to -1 and zero term to 1. But I don't know how to do it in TensorFlow.

Here is my code:

y_[y_ != 0].assign(-1)
y_[y_ == 0].assign(1)

The reason is TensorFlow doesn't seem to support boolean indexing. How can I fix it?

Btw, it seems boolean_mask doesn't work for me, because I don't want to return a slice of y_, I just want y_ to change its values.

Thanks!

Body:
You can use tf.cond (), for the conditional assignment. I have given an example code below,

import tensorflow as tf

x_= tf.Variable(5) #non-zero variable
y_= tf.Variable(0) #variable euqals to 0

y_ =tf.cond(tf.equal(y_,0),lambda :y_.assign(1),lambda :y_.assign(-1)) #assign 1 if variable equals to zero else -1
x_ =tf.cond(tf.equal(x_,0),lambda :x_.assign(1),lambda :x_.assign(-1)) #assign 1 if variable equals to zero else -1

sess = tf.Session()
sess.run(tf.global_variables_initializer())

with sess.as_default():
   print(y_.eval()) #prints 1
   print(x_.eval()) #prints -1

Hope this helps.


问:
How can I change the value of input in react test
I'd like to test a form of my react-app.

I have removed 'disabled' property of button when doing following things.

```<code>const component = TestUtils.renderIntoDocument(<Mycomponent/>);
const myDOM =findDOMNode(component);
const input = myDOM.querySelector('input');
input.value = "2017-11-11";
let submitButton = myDOM.querySelector('button');
TestUtils.Simulate.click(submitButton);
...
const newlyAddedDate = record.querySelector('#date').innerHTML;
console.log("newlyAddedDate:"+newlyAddedDate);
</code>```

but the output in console is

```<code>"newlyAddedDate:"
</code>```

This react-app performs correctly in chrome.
I believe it's the problem of

```<code>"input.value="2017-11-11";
</code>```

This sentence failed to change the value in the inputbox.

So how can i set the value in a inputbox when doing react-test?

Here's the repo of this app
https://github.com/zzbslayer/ChargeAccount-React

答:
Well, it totally depends on what libraries you use for testing. Here's a sample using Mocha and Enzyme combination.

```<code> beforeEach(() => {
      _spies = {}
      _props = {
        propOne: 'somepropvalue',
        ...
      }
      _wrapper = mount(<Your Component {..._props} />)
    })

    it('Should change the input box', () => {
      let promptInput = _wrapper.find('textarea')

      promptInput.simulate('change', { target: { value : 'sample2' } })
    })
</code>```

In before method you initialize your component, by passing all the props down. Then inside your test you find that text box inside the wrapper using a selector or HTML id of that element. Then you simulate a change event with the new value.

Notice that Jest has become a defacto framework for testing nowadays in most of the react starter boilerplate. In that case the concepts remains the same, but the syntax differs.

Body:
I'd like to test a form of my react-app.

I have removed 'disabled' property of button when doing following things.

const component = TestUtils.renderIntoDocument(<Mycomponent/>);
const myDOM =findDOMNode(component);
const input = myDOM.querySelector('input');
input.value = "2017-11-11";
let submitButton = myDOM.querySelector('button');
TestUtils.Simulate.click(submitButton);
...
const newlyAddedDate = record.querySelector('#date').innerHTML;
console.log("newlyAddedDate:"+newlyAddedDate);

but the output in console is

"newlyAddedDate:"

This react-app performs correctly in chrome.
I believe it's the problem of

"input.value="2017-11-11";

This sentence failed to change the value in the inputbox.

So how can i set the value in a inputbox when doing react-test?

Here's the repo of this app
https://github.com/zzbslayer/ChargeAccount-React

Body:
Well, it totally depends on what libraries you use for testing. Here's a sample using Mocha and Enzyme combination.

 beforeEach(() => {
      _spies = {}
      _props = {
        propOne: 'somepropvalue',
        ...
      }
      _wrapper = mount(<Your Component {..._props} />)
    })

    it('Should change the input box', () => {
      let promptInput = _wrapper.find('textarea')

      promptInput.simulate('change', { target: { value : 'sample2' } })
    })

In before method you initialize your component, by passing all the props down. Then inside your test you find that text box inside the wrapper using a selector or HTML id of that element. Then you simulate a change event with the new value.

Notice that Jest has become a defacto framework for testing nowadays in most of the react starter boilerplate. In that case the concepts remains the same, but the syntax differs.


问:
Android : Change cart menu badge counter from Recycler Adapter
I am trying to develop e-commerce type of app in which user can add item to cart. But I am unable to update the cart badge counter from adapter.
Here is screenshot of my app.

I am using Recycler view inside fragment. And I am referring this below link for menu item count.

https://mobikul.com/adding-badge-count-on-menu-items-like-cart-notification-etc/

My problem is I cannot access menu item from adapter.

Here is my fragment code.

PriceListFragment.java

```<code>public class PriceListFragment extends Fragment {

    public ArrayList<Design> designList;
    private Single_DesignAdapter adapter;
    private RecyclerView recyclerView;

    public PriceListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);
        View v = inflater.inflate(R.layout.fragment_price_list, container, false);

        recyclerView = (RecyclerView)v.findViewById(R.id.pl_recycler_view);

        designList = new ArrayList<Design>();

        designList = list();

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(true);
        adapter = new Single_DesignAdapter(getContext(), designList);
        recyclerView.setAdapter(adapter);

        return v;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.cart_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);

        MenuItem itemCart = menu.findItem(R.id.menu_cart);
        LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
        setBadgeCount(getContext(), icon, 0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.menu_cart:
                Toast.makeText(getActivity(), "cart", Toast.LENGTH_SHORT). show();
                return false;

            default:
                break;
        }
        return false;

    }

    public ArrayList<Design> list() {
        ArrayList<Design> arrayList = new ArrayList<Design>();

        Design design = new Design();
        design.name = "Black";
        design.image = "http://website/Demo/images/1.jpg";
        design.designName = "11001";
        design.qualityName = "Cotton";
        design.amount = "1000";
        design.discPercent = "5";

        Design design2 = new Design();
        design2.name = "Green";
        design2.image = "http://website/Demo/images/2.jpg";
        design2.designName = "11001";
        design2.qualityName = "Cotton";
        design2.amount = "900";
        design2.discPercent = "9";

        arrayList.add(design);
        arrayList.add(design2);

        return arrayList;
    }

    public static void setBadgeCount(Context context, LayerDrawable icon, int count) {

        BadgeDrawable badge;

        // Reuse drawable if possible
        Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
        if (reuse != null && reuse instanceof BadgeDrawable) {
            badge = (BadgeDrawable) reuse;
        } else {
            badge = new BadgeDrawable(context);
        }

        badge.setCount(count);
        icon.mutate();
        icon.setDrawableByLayerId(R.id.ic_badge, badge);
    }
}
</code>```

Design is my model class

Design.java

```<code>public class Design implements Serializable{

    public String id;
    public String qualityId;
    public String qualityName;
    public String designId;
    public String designName;
    public String image;
    public String name; //use as shade name
    public String discPercent;
    public String amount;
    public String pcs;
    public String qty;
}
</code>```

Single_DesignAdapter.java

```<code>public class Single_DesignAdapter extends RecyclerView.Adapter<Single_DesignAdapter.ViewHolder> {

    public ArrayList<Design> designList;
    private Context context;
    private LayoutInflater layoutInflater;

    public Single_DesignAdapter(Context context, ArrayList<Design> designList) {
        this.designList = designList;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.single_design, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        Design design = designList.get(position);
        holder.tvQuality.setText(design.qualityName);
        holder.tvDesign.setText(design.designName);
        holder.tvShade.setText(design.name);
        if (!design.discPercent.equals("0")) {
            holder.tvDisPer.setText("-"+design.discPercent+"%");
            holder.tvAmount.setPaintFlags(holder.tvAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            int a = Integer.parseInt(design.amount);
            float b = Float.parseFloat(design.discPercent) / 100;
            holder.tvAmount.setText("₹ " + design.amount);
            int c = (int) (a * b);
            int d = a-c;
            holder.tvDiscAmt.setText("₹ " +d);
            Picasso.with(context).load(design.image).into(holder.ivDesign);
        } else {
            holder.tvAmount.setText("₹ " + design.amount);
            Picasso.with(context).load(design.image).into(holder.ivDesign);
            holder.tvDisPer.setVisibility(View.INVISIBLE);
            holder.tvDiscAmt.setVisibility(View.INVISIBLE);
        }

        holder.btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.llAdd.setVisibility(View.GONE);
                holder.llPlusMinus.setVisibility(View.VISIBLE);
            }
        });

        holder.btPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.btPcsCount.getText().toString()) >= 1) {
                    int a = Integer.parseInt(holder.btPcsCount.getText().toString());
                    int x = a++;
                    holder.btPcsCount.setText(Integer.toString(a));
                }
            }
        });

        holder.btMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.btPcsCount.getText().toString()) <= 1) {
                    holder.llAdd.setVisibility(View.VISIBLE);
                    holder.llPlusMinus.setVisibility(View.GONE);
                } else {
                    int a = Integer.parseInt(holder.btPcsCount.getText().toString());
                    a--;
                    holder.btPcsCount.setText(Integer.toString(a));
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return designList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public LinearLayout llPer, llAdd, llPlusMinus;
        public Button btPlus, btMinus, btPcsCount, btAdd;
        public ImageView ivDesign;
        public TextView tvDesign, tvQuality, tvShade, tvAmount, tvDiscAmt, tvDisPer;

        public ViewHolder(View itemView) {
            super(itemView);

            btPlus = (Button) itemView.findViewById(R.id.btPlus);
            //other find view by ids
        }
    }
}
</code>```

Now when user add item to cart it should increment counter. I will add every cart items in ArrayList<Design> and then I will save this list into shared preference. I will manage everything, but I am unable understand that How can I update counter of cart from adapter. I cannot access menu in adapter. If there is other way to do this, Please help.

答:
You can use badge style in TextView now, All you need to do is adjust your textview position to make it look like badge.

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

Body:
I am trying to develop e-commerce type of app in which user can add item to cart. But I am unable to update the cart badge counter from adapter.
Here is screenshot of my app.

I am using Recycler view inside fragment. And I am referring this below link for menu item count.

https://mobikul.com/adding-badge-count-on-menu-items-like-cart-notification-etc/

My problem is I cannot access menu item from adapter.

Here is my fragment code.

PriceListFragment.java

public class PriceListFragment extends Fragment {

    public ArrayList<Design> designList;
    private Single_DesignAdapter adapter;
    private RecyclerView recyclerView;

    public PriceListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        setHasOptionsMenu(true);
        View v = inflater.inflate(R.layout.fragment_price_list, container, false);

        recyclerView = (RecyclerView)v.findViewById(R.id.pl_recycler_view);

        designList = new ArrayList<Design>();

        designList = list();

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setHasFixedSize(true);
        adapter = new Single_DesignAdapter(getContext(), designList);
        recyclerView.setAdapter(adapter);

        return v;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.cart_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);

        MenuItem itemCart = menu.findItem(R.id.menu_cart);
        LayerDrawable icon = (LayerDrawable) itemCart.getIcon();
        setBadgeCount(getContext(), icon, 0);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.menu_cart:
                Toast.makeText(getActivity(), "cart", Toast.LENGTH_SHORT). show();
                return false;

            default:
                break;
        }
        return false;

    }

    public ArrayList<Design> list() {
        ArrayList<Design> arrayList = new ArrayList<Design>();

        Design design = new Design();
        design.name = "Black";
        design.image = "http://website/Demo/images/1.jpg";
        design.designName = "11001";
        design.qualityName = "Cotton";
        design.amount = "1000";
        design.discPercent = "5";

        Design design2 = new Design();
        design2.name = "Green";
        design2.image = "http://website/Demo/images/2.jpg";
        design2.designName = "11001";
        design2.qualityName = "Cotton";
        design2.amount = "900";
        design2.discPercent = "9";

        arrayList.add(design);
        arrayList.add(design2);

        return arrayList;
    }

    public static void setBadgeCount(Context context, LayerDrawable icon, int count) {

        BadgeDrawable badge;

        // Reuse drawable if possible
        Drawable reuse = icon.findDrawableByLayerId(R.id.ic_badge);
        if (reuse != null && reuse instanceof BadgeDrawable) {
            badge = (BadgeDrawable) reuse;
        } else {
            badge = new BadgeDrawable(context);
        }

        badge.setCount(count);
        icon.mutate();
        icon.setDrawableByLayerId(R.id.ic_badge, badge);
    }
}

Design is my model class

Design.java

public class Design implements Serializable{

    public String id;
    public String qualityId;
    public String qualityName;
    public String designId;
    public String designName;
    public String image;
    public String name; //use as shade name
    public String discPercent;
    public String amount;
    public String pcs;
    public String qty;
}

Single_DesignAdapter.java

public class Single_DesignAdapter extends RecyclerView.Adapter<Single_DesignAdapter.ViewHolder> {

    public ArrayList<Design> designList;
    private Context context;
    private LayoutInflater layoutInflater;

    public Single_DesignAdapter(Context context, ArrayList<Design> designList) {
        this.designList = designList;
        this.context = context;
        this.layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.single_design, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        Design design = designList.get(position);
        holder.tvQuality.setText(design.qualityName);
        holder.tvDesign.setText(design.designName);
        holder.tvShade.setText(design.name);
        if (!design.discPercent.equals("0")) {
            holder.tvDisPer.setText("-"+design.discPercent+"%");
            holder.tvAmount.setPaintFlags(holder.tvAmount.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            int a = Integer.parseInt(design.amount);
            float b = Float.parseFloat(design.discPercent) / 100;
            holder.tvAmount.setText("₹ " + design.amount);
            int c = (int) (a * b);
            int d = a-c;
            holder.tvDiscAmt.setText("₹ " +d);
            Picasso.with(context).load(design.image).into(holder.ivDesign);
        } else {
            holder.tvAmount.setText("₹ " + design.amount);
            Picasso.with(context).load(design.image).into(holder.ivDesign);
            holder.tvDisPer.setVisibility(View.INVISIBLE);
            holder.tvDiscAmt.setVisibility(View.INVISIBLE);
        }

        holder.btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                holder.llAdd.setVisibility(View.GONE);
                holder.llPlusMinus.setVisibility(View.VISIBLE);
            }
        });

        holder.btPlus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.btPcsCount.getText().toString()) >= 1) {
                    int a = Integer.parseInt(holder.btPcsCount.getText().toString());
                    int x = a++;
                    holder.btPcsCount.setText(Integer.toString(a));
                }
            }
        });

        holder.btMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.btPcsCount.getText().toString()) <= 1) {
                    holder.llAdd.setVisibility(View.VISIBLE);
                    holder.llPlusMinus.setVisibility(View.GONE);
                } else {
                    int a = Integer.parseInt(holder.btPcsCount.getText().toString());
                    a--;
                    holder.btPcsCount.setText(Integer.toString(a));
                }
            }
        });

    }

    @Override
    public int getItemCount() {
        return designList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public LinearLayout llPer, llAdd, llPlusMinus;
        public Button btPlus, btMinus, btPcsCount, btAdd;
        public ImageView ivDesign;
        public TextView tvDesign, tvQuality, tvShade, tvAmount, tvDiscAmt, tvDisPer;

        public ViewHolder(View itemView) {
            super(itemView);

            btPlus = (Button) itemView.findViewById(R.id.btPlus);
            //other find view by ids
        }
    }
}

Now when user add item to cart it should increment counter. I will add every cart items in ArrayList<Design> and then I will save this list into shared preference. I will manage everything, but I am unable understand that How can I update counter of cart from adapter. I cannot access menu in adapter. If there is other way to do this, Please help.

Body:
You can use badge style in TextView now, All you need to do is adjust your textview position to make it look like badge.

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


问:
i wanted to use this javascript function with asp update panel, Details are bellow

Here is the script that I am using for opening a new tab and it's working without using an update panel:

```<code><script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank';
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</code>```

This is my .aspx page: and i want to use it with update panel please help

```<code><asp:ScriptManager ID="ScriptManager1" runat="server"
</asp:ScriptManager>
<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:Button ID="btnAssign" runat="server" Text="Assign" OnClientClick="SetTarget();" OnClick="btnAssign_Click"/>
     </ContentTemplate>
</asp:UpdatePanel >
</code>```

i want to use it with update panel please help me if there any solution

答:
Now i got solution by using a script and onclient click event

```<code><script language="javascript">
function PopupHistory(url) {
            var width = 550;
            var height = 300;
            var left = (screen.width - width) / 2;
            var top = (screen.height - height) / 2;
            var params = 'width=' + width + ', height=' + height;
            params += ', top=' + top + ', left=' + left;
            params += ', directories=no';
            params += ', location=no';
            params += ', menubar=no';
            params += ', resizable=no';
            params += ', scrollbars=no';
            params += ', status=no';
            params += ', toolbar=no';
            newwin = window.open(url, 'windowname5', params);
            if (window.focus) { newwin.focus() }
            return false
        }
</script>
</code>```

on button event

```<code><asp:Button ID="btnUnAssign" runat="server" Text="UnAssign" OnClientClick="return PopupHistory('/PatientAssignment/PatientUnAssign.aspx')" OnClick="btnUnAssign_Click" />
</code>```

Body:
Now i got solution by using a script and onclient click event

<script language="javascript">
function PopupHistory(url) {
            var width = 550;
            var height = 300;
            var left = (screen.width - width) / 2;
            var top = (screen.height - height) / 2;
            var params = 'width=' + width + ', height=' + height;
            params += ', top=' + top + ', left=' + left;
            params += ', directories=no';
            params += ', location=no';
            params += ', menubar=no';
            params += ', resizable=no';
            params += ', scrollbars=no';
            params += ', status=no';
            params += ', toolbar=no';
            newwin = window.open(url, 'windowname5', params);
            if (window.focus) { newwin.focus() }
            return false
        }
</script>

on button event

<asp:Button ID="btnUnAssign" runat="server" Text="UnAssign" OnClientClick="return PopupHistory('/PatientAssignment/PatientUnAssign.aspx')" OnClick="btnUnAssign_Click" />


问:
C# Primitive types (double, int, etc) and Struct differences
I am confused with structs.

```<code>class A
{
  double a { get; set; }
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}
</code>```

Now why I am able to set the value of the structure a, and not of the structure's field b ?
The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

```<code>a = 1.0;
</code>```

? Thank you.

EDIT :

Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

```<code>MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }
</code>```

and then use the field

```<code>_b
</code>```

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

```<code>MyStruct[] b { get; set; }
</code>```

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant.
(Sorry for the bad English.)

答:
This error occurs when you try to modify the value.

When you write a = 1.0, you're replacing the value - you're assigning the entire value type to a new value.  a = 1.0 is equivalent to b = new MyStruct().

This is yet another reason why mutable structs are evil.

ContentLicense: CC BY-SA 2.5

Body:
I am confused with structs.

class A
{
  double a { get; set; }
  MyStruct b { get; set; }

  void Modify()
  {
     a = 1.0;    // This compiles.
     b.c = 2.0;  // Assuming c is a double. This gives the known error.
  }
}

Now why I am able to set the value of the structure a, and not of the structure's field b ?
The answer I read is that I have a copy of b and not b's backing field. By the same logic I must have a copy of a, not a, so how it explains that the a property is changed after the permitted assignement

a = 1.0;

? Thank you.

EDIT :

Also in order to still use b inside the A class, "filtered" by the set and get methods and not directly by using the backing field _b, something which could look like this:

MyStruct _b;
MyStruct b { get { return _b; } set { _b=value; } }

and then use the field

_b

, as correctly stated in the answers, I thinked of a silly method to "wrap" the property in an one dimensional array of size 1.

MyStruct[] b { get; set; }

kind of wrapping the struct with a class. I dont know the computational cost of this, but I preferred it from using the field directly inside the A class.

ANSWERED : Ok, the confusion in this question comes, when you are used to interpret properties as fields in your mind. If you interpret properties the correct way -as the MsIL does-, all things settle down. All the answers and comments below, are relevant.
(Sorry for the bad English.)


问:
using an input variable in multiple functions in python
I would like to know how to use the 'name' variable in the entername() function in the hello() function.

It is an input variable, does anyone know how to use it across multiple functions?

```<code>def entername():
    name = input("Please enter your name: ")
    return

def hello():
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return
</code>```

答:
You can't use a variable defined in the scope of a function, inside another function. You could, however, return the name value, and pass it as a parameter to the next function:

```<code>import sys, time

def entername():
    name = input("Please enter your name: ")
    return name

def hello(name):
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)

hello(entername())   # <- this chains the function calls
                     # and is equivalent to
                     # name = entername()    # not the same 'name' variable as inside the entername() function, these are different scopes
                     # hello(name)
</code>```

Another option would be to use global variables, but you'd rather avoid this antipattern.

ContentLicense: CC BY-SA 4.0

Body:
I would like to know how to use the 'name' variable in the entername() function in the hello() function.

It is an input variable, does anyone know how to use it across multiple functions?

def entername():
    name = input("Please enter your name: ")
    return

def hello():
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)
    return

Body:
You can't use a variable defined in the scope of a function, inside another function. You could, however, return the name value, and pass it as a parameter to the next function:

import sys, time

def entername():
    name = input("Please enter your name: ")
    return name

def hello(name):
    text = "Hello " + name + ", welcome to the simulator..."
    for char in text:
        sys.stdout.write(char)
        sys.stdout.flush()
        char, time.sleep(0.1)
    print(char)

hello(entername())   # <- this chains the function calls
                     # and is equivalent to
                     # name = entername()    # not the same 'name' variable as inside the entername() function, these are different scopes
                     # hello(name)

Another option would be to use global variables, but you'd rather avoid this antipattern.


问:
Icon is not displaying in push notifications in ionic 2
I am trying to display app icon in notification. But it is displaying blank icon.

I have given pushoptions as below:

```<code> const options: PushOptions = {
      android: {
        titleKey: 'App',
        sound: 'true',
        icon: 'res/drawable/notification_icon',
        topics: ['MyTopic']
      },
      ios: {
        alert: 'true',
        badge: false,
        sound: 'true'
      },
      windows: {}
    };
</code>```

and copied the icon image as below which has resolution of 40*40px.

```<code><resource-file src="resources/notification_icon.png" target="res/drawable/notification_icon.png" />
</code>```

Is there anything that I am missing?

Update:

I followed this link : https://github.com/ionic-team/ionic-cli/issues/608 and tried it by copying all the notification icon under resources/android/notification/drawable-XYZ/ic_stat_ac_unit.png to res/drawable-XYZ/ic_stat_ac_unit.png using the following statements:

```<code><resource-file src="resources/android/notification/drawable-hdpi/ic_stat_ac_unit.png" target="res/drawable-hdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-mdpi/ic_stat_ac_unit.png" target="res/drawable-mdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-xhdpi/ic_stat_ac_unit.png" target="res/drawable-xhdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-xxhdpi/ic_stat_ac_unit.png" target="res/drawable-xxhdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-xxxhdpi/ic_stat_ac_unit.png" target="res/drawable-xxxhdpi/ic_stat_ac_unit.png" />
</code>```

and modified PushOptions in app.component.ts to :

```<code>android: {
    titleKey: 'App',
    sound: true,
    vibrate:true,
    icon: 'ic_stat_ac_unit',
    iconColor:'#343434',
    topics: ['MyTopic']
  }
</code>```

Even this did not worked - Same Issue.

答:
I used the ionic fcm plugin to fix the issue. I just replaced cordova push plugin with Cordova fcm plugin icon displayed. I wasted a lot of time on push plugin.I hope this answer helps others.

Please refer to below links for more information :

https://ionicframework.com/docs/native/fcm/

https://github.com/fechanique/cordova-plugin-fcm

Body:
I am trying to display app icon in notification. But it is displaying blank icon.

I have given pushoptions as below:

 const options: PushOptions = {
      android: {
        titleKey: 'App',
        sound: 'true',
        icon: 'res/drawable/notification_icon',
        topics: ['MyTopic']
      },
      ios: {
        alert: 'true',
        badge: false,
        sound: 'true'
      },
      windows: {}
    };

and copied the icon image as below which has resolution of 40*40px.

<resource-file src="resources/notification_icon.png" target="res/drawable/notification_icon.png" />

Is there anything that I am missing?

Update:

I followed this link : https://github.com/ionic-team/ionic-cli/issues/608 and tried it by copying all the notification icon under resources/android/notification/drawable-XYZ/ic_stat_ac_unit.png to res/drawable-XYZ/ic_stat_ac_unit.png using the following statements:

<resource-file src="resources/android/notification/drawable-hdpi/ic_stat_ac_unit.png" target="res/drawable-hdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-mdpi/ic_stat_ac_unit.png" target="res/drawable-mdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-xhdpi/ic_stat_ac_unit.png" target="res/drawable-xhdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-xxhdpi/ic_stat_ac_unit.png" target="res/drawable-xxhdpi/ic_stat_ac_unit.png" />
        <resource-file src="resources/android/notification/drawable-xxxhdpi/ic_stat_ac_unit.png" target="res/drawable-xxxhdpi/ic_stat_ac_unit.png" />

and modified PushOptions in app.component.ts to :

android: {
    titleKey: 'App',
    sound: true,
    vibrate:true,
    icon: 'ic_stat_ac_unit',
    iconColor:'#343434',
    topics: ['MyTopic']
  }

Even this did not worked - Same Issue.


问:
Why does my C++ vector use a null pointer when I do not deference the pointer.
I am working on a c++ object orientation project. I defined a vector as a private variable in my ListOfShapes class:

```<code>    vector<Shape*> list_of_shapes = {};
</code>```

Shape is another class, and below is the header file of it:

```<code>class Shape{
private:
    string color;//private variable
public:
    Shape(string c);//non-default constructor
    string getColor();//returns color of the object
    virtual void print() = 0;//pure virtual "print" function
};
</code>```

Shape is the parent class of a class called Rectangle:

```<code>class Rectangle:public Shape{
public:
    Rectangle(const string &c,double length,double breadth);
    void print();
private:
    double length, breadth;

};
</code>```

In the main function I create a ListOfShapes object which contains a function that pushes a pointer (pointing to a Shape object) into the vector I mentioned above. Here is the implementation of the called function:

```<code>void ListOfShapes::addShape(Shape* s) {
    list_of_shapes.push_back(s);
}
</code>```

And finally here is the action of calling in the main function:

```<code>int main() {
    ListOfShapes* list;
    Shape* r;
    r = new Rectangle( "red",1,1);
    list->addShape( r);
    return 0;
}
</code>```

My code compiles fine and even runs if I try to create the same vector (that stores pointers to Shape) inside the main function. The issue happens inside the addShape method, when the push_back method inside the vector class is called, it is using a null pointer for some reason. I've spent hours trying to debbug this issue but I cant seem to find the cause of it.
The error I am getting is:

答:
You are accessing an uninitialized pointer list:

```<code>int main() {
    ListOfShapes* list;
    Shape* r;
    r = new Rectangle( "red",1,1);
    list->addShape( r);  // <-- list is not initialized, thus undefined behavior
    return 0;
}
</code>```

If you look at your debugger output, you see that this has a strange value in the addShape function.  This is an indication that the object itself is not valid, and anything done within an invalid object is also invalid.

Simply create a list local object.  There is no need for a pointer:

```<code>int main() {
    ListOfShapes list;
    Shape* r;
    r = new Rectangle( "red",1,1);
    list.addShape( r);
    return 0;
}
</code>```

Also, your Shape class should have a virtual destructor.  If you attempted to delete the objects stored in list by iterating through list, the program will invoke undefined behavior due to Shape not having a virtual destructor.

Body:
I am working on a c++ object orientation project. I defined a vector as a private variable in my ListOfShapes class:

    vector<Shape*> list_of_shapes = {};

Shape is another class, and below is the header file of it:

class Shape{
private:
    string color;//private variable
public:
    Shape(string c);//non-default constructor
    string getColor();//returns color of the object
    virtual void print() = 0;//pure virtual "print" function
};

Shape is the parent class of a class called Rectangle:

class Rectangle:public Shape{
public:
    Rectangle(const string &c,double length,double breadth);
    void print();
private:
    double length, breadth;

};

In the main function I create a ListOfShapes object which contains a function that pushes a pointer (pointing to a Shape object) into the vector I mentioned above. Here is the implementation of the called function:

void ListOfShapes::addShape(Shape* s) {
    list_of_shapes.push_back(s);
}

And finally here is the action of calling in the main function:

int main() {
    ListOfShapes* list;
    Shape* r;
    r = new Rectangle( "red",1,1);
    list->addShape( r);
    return 0;
}

My code compiles fine and even runs if I try to create the same vector (that stores pointers to Shape) inside the main function. The issue happens inside the addShape method, when the push_back method inside the vector class is called, it is using a null pointer for some reason. I've spent hours trying to debbug this issue but I cant seem to find the cause of it.
The error I am getting is:

Body:
You are accessing an uninitialized pointer list:

int main() {
    ListOfShapes* list;
    Shape* r;
    r = new Rectangle( "red",1,1);
    list->addShape( r);  // <-- list is not initialized, thus undefined behavior
    return 0;
}

If you look at your debugger output, you see that this has a strange value in the addShape function.  This is an indication that the object itself is not valid, and anything done within an invalid object is also invalid.

Simply create a list local object.  There is no need for a pointer:

int main() {
    ListOfShapes list;
    Shape* r;
    r = new Rectangle( "red",1,1);
    list.addShape( r);
    return 0;
}

Also, your Shape class should have a virtual destructor.  If you attempted to delete the objects stored in list by iterating through list, the program will invoke undefined behavior due to Shape not having a virtual destructor.


问:
Bootstrap Popover Requires Second Click Before Showing
This makes you click twice before you can get the image and popover to appear, but after you have do that then it works as hoped where when you click on the next one the previous one disappears and the new one appears. Also, I think this can be consolidated. Any help would be appreciated. Here's a codepen example: Boostrap Popover Timeline</p>

```<code>$(".timeline-list-btn").on('click', function() {
  $("[data-toggle='popover']").popover()
  $("[data-toggle='popover']").not(this).popover('hide')

  $("#1-btn").on('click', function() {
    $(this).css({
      'background': 'url(../img/help/help1.svg) no-repeat center center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none',
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)',
    });
  });

  $("#2-btn").on('click', function() {
    $(this).css({
      'background': 'url(../img/help/help2.svg) no-repeat center center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });

  $("#3-btn").on('click', function() {
    $(this).css({
      'background': 'url(../img/help/help3.svg) no-repeat center center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });
});
</code>```

答:
I refactored the functions. The single answer to my issue was .mousedown() on the wrapping function, simple as that. Check it out below:</p>

```<code>$(".timeline-list-btn").mousedown(function() {
  $("[data-toggle='popover']").popover()
  $("[data-toggle='popover']").not(this).popover('hide')
// Wrap the above functions into a trigger function here

  $("#1-btn").click(function() {
    $(this).css({
      'background': 'url(../img/help/help1.svg) no-repeat center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none',
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)',
    });
  });

  $("#2-btn").click(function() {
    $(this).css({
      'background': 'url(../img/help/help2.svg) no-repeat center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });

  $("#3-btn").click(function() {
    $(this).css({
      'background': 'url(../img/help/help3.svg) no-repeat center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });
});
</code>```

Body:
This makes you click twice before you can get the image and popover to appear, but after you have do that then it works as hoped where when you click on the next one the previous one disappears and the new one appears. Also, I think this can be consolidated. Any help would be appreciated. Here's a codepen example: Boostrap Popover Timeline

$(".timeline-list-btn").on('click', function() {
  $("[data-toggle='popover']").popover()
  $("[data-toggle='popover']").not(this).popover('hide')

  $("#1-btn").on('click', function() {
    $(this).css({
      'background': 'url(../img/help/help1.svg) no-repeat center center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none',
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)',
    });
  });

  $("#2-btn").on('click', function() {
    $(this).css({
      'background': 'url(../img/help/help2.svg) no-repeat center center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });

  $("#3-btn").on('click', function() {
    $(this).css({
      'background': 'url(../img/help/help3.svg) no-repeat center center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });
});

Body:
I refactored the functions. The single answer to my issue was .mousedown() on the wrapping function, simple as that. Check it out below:

$(".timeline-list-btn").mousedown(function() {
  $("[data-toggle='popover']").popover()
  $("[data-toggle='popover']").not(this).popover('hide')
// Wrap the above functions into a trigger function here

  $("#1-btn").click(function() {
    $(this).css({
      'background': 'url(../img/help/help1.svg) no-repeat center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none',
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)',
    });
  });

  $("#2-btn").click(function() {
    $(this).css({
      'background': 'url(../img/help/help2.svg) no-repeat center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });

  $("#3-btn").click(function() {
    $(this).css({
      'background': 'url(../img/help/help3.svg) no-repeat center',
      'background-color': '#4359AB',
      'background-size': "65px, 65px",
      'transform': 'scale(0.75, 0.75)',
      'box-shadow': 'none'
    });
    $("[data-toggle='popover']").not(this).css({
      'background': 'white',
      'transform': 'scale(0.25, 0.25)'
    });
  });
});


问:
var_dump() in Scala
Is there any convenient way to dump all members of a specified object in Scala,

like var_dump(), PHP function?

答: You might want to look at ToStringBuilder in commons-lang, specificly ToStringBuilder.reflectionToString().

Title: var_dump() in Scala


问:
Rails find records using an array of hashes
(Select Query by Pair of fields using an in clause)

I have an array of hashes that looks like this:

[ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]

What I would like to return are all the records in the Items table that match the pair of fields in the array.

In SQL it would be retrieved like this:

```<code>SELECT *
FROM items
WHERE (product_id, group_id) IN (VALUES (7629,4), (8202,3))
</code>```

But I am having trouble doing this with a rails .where clause. Is this even possible?

答:
I see no benefit in using SQL's IN in this case.

I would use where for the first condition and chain all other conditions with or (and let Rails take care of sanitizing and heavy lifting):

```<code>array = [{ product_id: 7629, group_id: 4 }, { product_id: 8202, group_id: 3 }]
array[1..-1].inject(Model.where(array[0])) { |m, h| m.or(Model.where(h)) }
</code>```

Body:
(Select Query by Pair of fields using an in clause)

I have an array of hashes that looks like this:

[ {product_id: 7629, group_id: 4}, {product_id: 8202, group_id: 3} ]

What I would like to return are all the records in the Items table that match the pair of fields in the array.

In SQL it would be retrieved like this:

SELECT *
FROM items
WHERE (product_id, group_id) IN (VALUES (7629,4), (8202,3))

But I am having trouble doing this with a rails .where clause. Is this even possible?

Body:
I see no benefit in using SQL's IN in this case.

I would use where for the first condition and chain all other conditions with or (and let Rails take care of sanitizing and heavy lifting):

array = [{ product_id: 7629, group_id: 4 }, { product_id: 8202, group_id: 3 }]
array[1..-1].inject(Model.where(array[0])) { |m, h| m.or(Model.where(h)) }


问:
How to display count of notifications in toolbar icon in android
I would like to make an icon counter for android just like the cart.  I have seen many e-commerce app cart icon count increase. I show flipkart app snapshot.:-

答:
Instead of creating shape and drawable, You can use badge style in TextView itself. Just use custom floating button style as per your theme.

Example-

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

Body:
Instead of creating shape and drawable, You can use badge style in TextView itself. Just use custom floating button style as per your theme.

Example-

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