问:
SQL: Replace Some Strings with other String Values in One Column and Write to Temp Table
UPDATE: Followed syntax provided by forum answers ... hit errors

```<code>SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A' THEN 'ANT'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a
</code>```

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

I'm trying to clean up text data in one column of my temp table.  Afterwards, I want to write the table into another temp table.

Below is the code I used ... but I'm getting an error.

```<code>SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             ELSE WHEN [COL] = 'Art' THEN 'Artwork'
    FROM #test_a
</code>```

The error I received was: Incorrect syntax near the keyword 'CASE'

答: Write the INTO "#test_b" before the "FROM #test_a" And End before that</p>

Body:
UPDATE: Followed syntax provided by forum answers ... hit errors

SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A' THEN 'ANT'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

I'm trying to clean up text data in one column of my temp table.  Afterwards, I want to write the table into another temp table.

Below is the code I used ... but I'm getting an error.

SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             ELSE WHEN [COL] = 'Art' THEN 'Artwork'
    FROM #test_a

The error I received was: Incorrect syntax near the keyword 'CASE'


来源: stackexchange

问:
Hitting directly a controller in codeigniter and getting json response
I am doing this in my codeigniter controller

```<code>public function getprice($origin,$destination){
    $this->load->model("flights");
    $query['data']=$this->flights->giveprice($origin,$destination);  //model gives fine result
     $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => $query['data'])));   //data is printed correctly

   }
</code>```

I have hitted this url with the exact this url :-

```<code>localhost/codeIgniter/index.php/booking/getprice?origin="Karachi"&destination="Lahore"
</code>```

and i am getting this as response:-

```<code> <div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>An uncaught Exception was encountered</h4>
<p>Type: ArgumentCountError</p>
<p>Message: Too few arguments to function Booking::getprice(), 0 passed in /opt/lampp/htdocs/codeIgniter/system/core/CodeIgniter.php on line 532 and exactly 2 expected</p>
<p>Filename: /opt/lampp/htdocs/codeIgniter/application/controllers/Booking.php</p>
<p>Line Number: 22</p>
<p>Backtrace:</p>
<p style="margin-left:10px">
        File: /opt/lampp/htdocs/codeIgniter/index.php
    <br />
        Line: 315
    <br />
        Function: require_once
</p>
</code>```

Another function of mine without parameters runs fine, but when parameters ("GET") are involved it says "too few arguements given", I am providing 2 arguments. Please correct me where I am doing wrong.

答:
You have call function using get parameters.
But calling in codeigniter is different than ordinary function calling when parameters are given.
Example :
localhost/codeIgniter/index.php/booking/getprice/Karachi/Lahore

See this: Passing multiple variables in URL using codeigniter

ContentLicense: CC BY-SA 3.0

Body:
I am doing this in my codeigniter controller

public function getprice($origin,$destination){
    $this->load->model("flights");
    $query['data']=$this->flights->giveprice($origin,$destination);  //model gives fine result
     $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => $query['data'])));   //data is printed correctly

   }

I have hitted this url with the exact this url :-

localhost/codeIgniter/index.php/booking/getprice?origin="Karachi"&destination="Lahore"

and i am getting this as response:-

An uncaught Exception was encountered

Type: ArgumentCountError

Message: Too few arguments to function Booking::getprice(), 0 passed in /opt/lampp/htdocs/codeIgniter/system/core/CodeIgniter.php on line 532 and exactly 2 expected

Filename: /opt/lampp/htdocs/codeIgniter/application/controllers/Booking.php

Line Number: 22

Backtrace:

        File: /opt/lampp/htdocs/codeIgniter/index.php

        Line: 315

        Function: require_once

Another function of mine without parameters runs fine, but when parameters ("GET") are involved it says "too few arguements given", I am providing 2 arguments. Please correct me where I am doing wrong.


问:
Sending a POST query in JSON using JQuery and Django
I'm very confused about the urls when it comes to sending/receiving data.

The snippet I'm trying in my views is very simple:

```<code>class EditGetInfo(View):
    def post(self, request, *args, **kwargs):
            response_data = {}
            response_data['test'] = 'Test message'
            return HttpResponse(json.dumps(response_data), content_type="application/json")
</code>```

In my urls I have:

```<code>urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^edit/getInfo$', EditGetInfo.as_view()),
    url(r'^edit/', Edit.as_view()),
    url(r'^$', Home.as_view()),
]
</code>```

My goal is to send the request to website.com/edit/getInfo.

And I try to do it as (this is loaded when I open website.com/edit):

```<code>$.post("edit/getInfo",function(data) {
        alert(data);
});
</code>```

答:
I guess you are facing issue with urls. so your post request is going in Edit view instead of EditGetInfo.
If this is the case then you have issue with urls.
change following url

```<code>url(r'^edit/getInfo$', EditGetInfo.as_view()),
</code>```

with

```<code>url(r'^edit/getInfo/$', EditGetInfo.as_view()),
</code>```

Body:
I'm very confused about the urls when it comes to sending/receiving data.

The snippet I'm trying in my views is very simple:

class EditGetInfo(View):
    def post(self, request, *args, **kwargs):
            response_data = {}
            response_data['test'] = 'Test message'
            return HttpResponse(json.dumps(response_data), content_type="application/json")

In my urls I have:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^edit/getInfo$', EditGetInfo.as_view()),
    url(r'^edit/', Edit.as_view()),
    url(r'^$', Home.as_view()),
]

My goal is to send the request to website.com/edit/getInfo.

And I try to do it as (this is loaded when I open website.com/edit):

$.post("edit/getInfo",function(data) {
        alert(data);
});

Body:
I guess you are facing issue with urls. so your post request is going in Edit view instead of EditGetInfo.
If this is the case then you have issue with urls.
change following url

url(r'^edit/getInfo$', EditGetInfo.as_view()),

with

url(r'^edit/getInfo/$', EditGetInfo.as_view()),


问:
How to read XML using XPath in Java
I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

here is what I want to do:

Get XML file from online via its URL, then use XPath to parse it, I want to create two methods in it. One is in which I enter a specific node attribute id, and I get all the child nodes as result, and second is suppose I just want to get a specific child node value only

```<code><?xml version="1.0"?>
<howto>
  <topic name="Java">
      <url>http://www.rgagnonjavahowto.htm</url>
  <car>taxi</car>
  </topic>
  <topic name="PowerBuilder">
       <url>http://www.rgagnon/pbhowto.htm</url>
       <url>http://www.rgagnon/pbhowtonew.htm</url>
  </topic>
  <topic name="Javascript">
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
 <topic name="VBScript">
       <url>http://www.rgagnon/vbshowto.htm</url>
 </topic>
 </howto>
</code>```

In above example I want to read all the elements if I search via @name and also one function in which I just want the url from @name 'Javascript' only return one node element.

答:
Read XML file using XPathFactory, SAXParserFactory  and StAX (JSR-173).

Using XPath get node and its child data.

```<code>public static void main(String[] args) {
    String xml = "<soapenv:Body xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>"
            + "<Yash:Data xmlns:Yash='http://Yash.stackoverflow.com/Services/Yash'>"
            + "<Yash:Tags>Java</Yash:Tags><Yash:Tags>Javascript</Yash:Tags><Yash:Tags>Selenium</Yash:Tags>"
            + "<Yash:Top>javascript</Yash:Top><Yash:User>Yash-777</Yash:User>"
            + "</Yash:Data></soapenv:Body>";
    String jsonNameSpaces = "{'soapenv':'http://schemas.xmlsoap.org/soap/envelope/',"
            + "'Yash':'http://Yash.stackoverflow.com/Services/Yash'}";
    String xpathExpression = "//Yash:Data";

    Document doc1 = getDocument(false, "fileName", xml);
    getNodesFromXpath(doc1, xpathExpression, jsonNameSpaces);
    System.out.println("\n===== ***** =====");
    Document doc2 = getDocument(true, "./books.xml", xml);
    getNodesFromXpath(doc2, "//person", "{}");
}
static Document getDocument( boolean isFileName, String fileName, String xml ) {
    Document doc = null;
    try {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        if( isFileName ) {
            File file = new File( fileName );
            FileInputStream stream = new FileInputStream( file );
            doc = builder.parse( stream );
        } else {
            doc = builder.parse( string2Source( xml ) );
        }
    } catch (SAXException | IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return doc;
}

/**
 * ELEMENT_NODE[1],ATTRIBUTE_NODE[2],TEXT_NODE[3],CDATA_SECTION_NODE[4],
 * ENTITY_REFERENCE_NODE[5],ENTITY_NODE[6],PROCESSING_INSTRUCTION_NODE[7],
 * COMMENT_NODE[8],DOCUMENT_NODE[9],DOCUMENT_TYPE_NODE[10],DOCUMENT_FRAGMENT_NODE[11],NOTATION_NODE[12]
 */
public static void getNodesFromXpath( Document doc, String xpathExpression, String jsonNameSpaces ) {
    try {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();

        JSONObject namespaces = getJSONObjectNameSpaces(jsonNameSpaces);
        if ( namespaces.size() > 0 ) {
            NamespaceContextImpl nsContext = new NamespaceContextImpl();

            Iterator<?> key = namespaces.keySet().iterator();
            while (key.hasNext()) { // Apache WebServices Common Utilities
                String pPrefix = key.next().toString();
                String pURI = namespaces.get(pPrefix).toString();
                nsContext.startPrefixMapping(pPrefix, pURI);
            }
            xpath.setNamespaceContext(nsContext );
        }

        XPathExpression compile = xpath.compile(xpathExpression);
        NodeList nodeList = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);
        displayNodeList(nodeList);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}

static void displayNodeList( NodeList nodeList ) {
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        String NodeName = node.getNodeName();

        NodeList childNodes = node.getChildNodes();
        if ( childNodes.getLength() > 1 ) {
            for (int j = 0; j < childNodes.getLength(); j++) {

                Node child = childNodes.item(j);
                short nodeType = child.getNodeType();
                if ( nodeType == 1 ) {
                    System.out.format( "\n\t Node Name:[%s], Text[%s] ", child.getNodeName(), child.getTextContent() );
                }
            }
        } else {
            System.out.format( "\n Node Name:[%s], Text[%s] ", NodeName, node.getTextContent() );
        }

    }
}
static InputSource string2Source( String str ) {
    InputSource inputSource = new InputSource( new StringReader( str ) );
    return inputSource;
}
static JSONObject getJSONObjectNameSpaces( String jsonNameSpaces ) {
    if(jsonNameSpaces.indexOf("'") > -1)    jsonNameSpaces = jsonNameSpaces.replace("'", "\"");
    JSONParser parser = new JSONParser();
    JSONObject namespaces = null;
    try {
        namespaces = (JSONObject) parser.parse(jsonNameSpaces);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return namespaces;
}
</code>```

XML Document

```<code><?xml version="1.0" encoding="UTF-8"?>
<book>
<person>
  <first>Yash</first>
  <last>M</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</book>
</code>```

Out put for the given XPathExpression:

```<code>String xpathExpression = "//person/first";
/*OutPut:
 Node Name:[first], Text[Yash]
 Node Name:[first], Text[Bill]
 Node Name:[first], Text[Steve] */

String xpathExpression = "//person";
/*OutPut:
     Node Name:[first], Text[Yash]
     Node Name:[last], Text[M]
     Node Name:[age], Text[22]
     Node Name:[first], Text[Bill]
     Node Name:[last], Text[Gates]
     Node Name:[age], Text[46]
     Node Name:[first], Text[Steve]
     Node Name:[last], Text[Jobs]
     Node Name:[age], Text[40] */

String xpathExpression = "//Yash:Data";
/*OutPut:
     Node Name:[Yash:Tags], Text[Java]
     Node Name:[Yash:Tags], Text[Javascript]
     Node Name:[Yash:Tags], Text[Selenium]
     Node Name:[Yash:Top], Text[javascript]
     Node Name:[Yash:User], Text[Yash-777] */
</code>```

See this link  for our own Implementation of NamespaceContext

ContentLicense: CC BY-SA 4.0

Title: How to read XML using XPath in Java

Body:
I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

here is what I want to do:

Get XML file from online via its URL, then use XPath to parse it, I want to create two methods in it. One is in which I enter a specific node attribute id, and I get all the child nodes as result, and second is suppose I just want to get a specific child node value only

<?xml version="1.0"?>
<howto>
  <topic name="Java">
      <url>http://www.rgagnonjavahowto.htm</url>
  <car>taxi</car>
  </topic>
  <topic name="PowerBuilder">
       <url>http://www.rgagnon/pbhowto.htm</url>
       <url>http://www.rgagnon/pbhowtonew.htm</url>
  </topic>
  <topic name="Javascript">
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
 <topic name="VBScript">
       <url>http://www.rgagnon/vbshowto.htm</url>
 </topic>
 </howto>

In above example I want to read all the elements if I search via @name and also one function in which I just want the url from @name 'Javascript' only return one node element.

Body:
Read XML file using XPathFactory, SAXParserFactory  and StAX (JSR-173).

Using XPath get node and its child data.

public static void main(String[] args) {
    String xml = "<soapenv:Body xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>"
            + "<Yash:Data xmlns:Yash='http://Yash.stackoverflow.com/Services/Yash'>"
            + "<Yash:Tags>Java</Yash:Tags><Yash:Tags>Javascript</Yash:Tags><Yash:Tags>Selenium</Yash:Tags>"
            + "<Yash:Top>javascript</Yash:Top><Yash:User>Yash-777</Yash:User>"
            + "</Yash:Data></soapenv:Body>";
    String jsonNameSpaces = "{'soapenv':'http://schemas.xmlsoap.org/soap/envelope/',"
            + "'Yash':'http://Yash.stackoverflow.com/Services/Yash'}";
    String xpathExpression = "//Yash:Data";

    Document doc1 = getDocument(false, "fileName", xml);
    getNodesFromXpath(doc1, xpathExpression, jsonNameSpaces);
    System.out.println("\n===== ***** =====");
    Document doc2 = getDocument(true, "./books.xml", xml);
    getNodesFromXpath(doc2, "//person", "{}");
}
static Document getDocument( boolean isFileName, String fileName, String xml ) {
    Document doc = null;
    try {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);

        DocumentBuilder builder = factory.newDocumentBuilder();
        if( isFileName ) {
            File file = new File( fileName );
            FileInputStream stream = new FileInputStream( file );
            doc = builder.parse( stream );
        } else {
            doc = builder.parse( string2Source( xml ) );
        }
    } catch (SAXException | IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return doc;
}

/**
 * ELEMENT_NODE[1],ATTRIBUTE_NODE[2],TEXT_NODE[3],CDATA_SECTION_NODE[4],
 * ENTITY_REFERENCE_NODE[5],ENTITY_NODE[6],PROCESSING_INSTRUCTION_NODE[7],
 * COMMENT_NODE[8],DOCUMENT_NODE[9],DOCUMENT_TYPE_NODE[10],DOCUMENT_FRAGMENT_NODE[11],NOTATION_NODE[12]
 */
public static void getNodesFromXpath( Document doc, String xpathExpression, String jsonNameSpaces ) {
    try {
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();

        JSONObject namespaces = getJSONObjectNameSpaces(jsonNameSpaces);
        if ( namespaces.size() > 0 ) {
            NamespaceContextImpl nsContext = new NamespaceContextImpl();

            Iterator<?> key = namespaces.keySet().iterator();
            while (key.hasNext()) { // Apache WebServices Common Utilities
                String pPrefix = key.next().toString();
                String pURI = namespaces.get(pPrefix).toString();
                nsContext.startPrefixMapping(pPrefix, pURI);
            }
            xpath.setNamespaceContext(nsContext );
        }

        XPathExpression compile = xpath.compile(xpathExpression);
        NodeList nodeList = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);
        displayNodeList(nodeList);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}

static void displayNodeList( NodeList nodeList ) {
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        String NodeName = node.getNodeName();

        NodeList childNodes = node.getChildNodes();
        if ( childNodes.getLength() > 1 ) {
            for (int j = 0; j < childNodes.getLength(); j++) {

                Node child = childNodes.item(j);
                short nodeType = child.getNodeType();
                if ( nodeType == 1 ) {
                    System.out.format( "\n\t Node Name:[%s], Text[%s] ", child.getNodeName(), child.getTextContent() );
                }
            }
        } else {
            System.out.format( "\n Node Name:[%s], Text[%s] ", NodeName, node.getTextContent() );
        }

    }
}
static InputSource string2Source( String str ) {
    InputSource inputSource = new InputSource( new StringReader( str ) );
    return inputSource;
}
static JSONObject getJSONObjectNameSpaces( String jsonNameSpaces ) {
    if(jsonNameSpaces.indexOf("'") > -1)    jsonNameSpaces = jsonNameSpaces.replace("'", "\"");
    JSONParser parser = new JSONParser();
    JSONObject namespaces = null;
    try {
        namespaces = (JSONObject) parser.parse(jsonNameSpaces);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return namespaces;
}

XML Document

<?xml version="1.0" encoding="UTF-8"?>
<book>
<person>
  <first>Yash</first>
  <last>M</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</book>

Out put for the given XPathExpression:

String xpathExpression = "//person/first";
/*OutPut:
 Node Name:[first], Text[Yash]
 Node Name:[first], Text[Bill]
 Node Name:[first], Text[Steve] */

String xpathExpression = "//person";
/*OutPut:
     Node Name:[first], Text[Yash]
     Node Name:[last], Text[M]
     Node Name:[age], Text[22]
     Node Name:[first], Text[Bill]
     Node Name:[last], Text[Gates]
     Node Name:[age], Text[46]
     Node Name:[first], Text[Steve]
     Node Name:[last], Text[Jobs]
     Node Name:[age], Text[40] */

String xpathExpression = "//Yash:Data";
/*OutPut:
     Node Name:[Yash:Tags], Text[Java]
     Node Name:[Yash:Tags], Text[Javascript]
     Node Name:[Yash:Tags], Text[Selenium]
     Node Name:[Yash:Top], Text[javascript]
     Node Name:[Yash:User], Text[Yash-777] */

See this link  for our own Implementation of NamespaceContext


问:
Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf
What is the bare minimum and Angular4's native way to slide in and slide out a container element?

e.g.

```<code><div ngIf="show">
    <!-- Content -->
</div>
</code>```

Slide In Content (from top to down just like jQuery.slideDown()) when show turns to true.

Slide Out Content (suitably with ease-out effect) when show turns to false.

答:
I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.

animations.ts

```<code>import { trigger, state, style, transition,
    animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
    trigger('slideInOut', [
        state('in', style({
            'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
        })),
        state('out', style({
            'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
        })),
        transition('in => out', [group([
            animate('400ms ease-in-out', style({
                'opacity': '0'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '0px'
            })),
            animate('700ms ease-in-out', style({
                'visibility': 'hidden'
            }))
        ]
        )]),
        transition('out => in', [group([
            animate('1ms ease-in-out', style({
                'visibility': 'visible'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '500px'
            })),
            animate('800ms ease-in-out', style({
                'opacity': '1'
            }))
        ]
        )])
    ]),
]
</code>```

Then in your app.component, we import the animation and create the method that will toggle the animation state.

app.component.ts

```<code>import { SlideInOutAnimation } from './animations';

@Component({
  ...
  animations: [SlideInOutAnimation]
})
export class AppComponent  {
  animationState = 'in';

  ...

  toggleShowDiv(divName: string) {
    if (divName === 'divA') {
      console.log(this.animationState);
      this.animationState = this.animationState === 'out' ? 'in' : 'out';
      console.log(this.animationState);
    }
  }
}
</code>```

And here is how your app.component.html would look like :

```<code><div class="wrapper">
  <button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
  <div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
  THIS DIV IS ANIMATED</div>
  <div class="content">THIS IS CONTENT DIV</div>
</div>
</code>```

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

```<code>import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [ ..., BrowserAnimationsModule ],
  ...
})
</code>```

Body:
What is the bare minimum and Angular4's native way to slide in and slide out a container element?

e.g.

Slide In Content (from top to down just like jQuery.slideDown()) when show turns to true.

Slide Out Content (suitably with ease-out effect) when show turns to false.

Body:
I answered a very similar question, and here is a way of doing this :

First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts

In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.

This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.

animations.ts

import { trigger, state, style, transition,
    animate, group, query, stagger, keyframes
} from '@angular/animations';

export const SlideInOutAnimation = [
    trigger('slideInOut', [
        state('in', style({
            'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
        })),
        state('out', style({
            'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
        })),
        transition('in => out', [group([
            animate('400ms ease-in-out', style({
                'opacity': '0'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '0px'
            })),
            animate('700ms ease-in-out', style({
                'visibility': 'hidden'
            }))
        ]
        )]),
        transition('out => in', [group([
            animate('1ms ease-in-out', style({
                'visibility': 'visible'
            })),
            animate('600ms ease-in-out', style({
                'max-height': '500px'
            })),
            animate('800ms ease-in-out', style({
                'opacity': '1'
            }))
        ]
        )])
    ]),
]

Then in your app.component, we import the animation and create the method that will toggle the animation state.

app.component.ts

import { SlideInOutAnimation } from './animations';

@Component({
  ...
  animations: [SlideInOutAnimation]
})
export class AppComponent  {
  animationState = 'in';

  ...

  toggleShowDiv(divName: string) {
    if (divName === 'divA') {
      console.log(this.animationState);
      this.animationState = this.animationState === 'out' ? 'in' : 'out';
      console.log(this.animationState);
    }
  }
}

And here is how your app.component.html would look like :

<div class="wrapper">
  <button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
  <div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
  THIS DIV IS ANIMATED</div>
  <div class="content">THIS IS CONTENT DIV</div>
</div>

slideInOut refers to the animation trigger defined in animations.ts

Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/

Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  imports: [ ..., BrowserAnimationsModule ],
  ...
})


问:
Use-case actor with many behaviors
I'm trying to imagine how a use-case actor with multiple behaviors actually shows up in the application.

Take the following real world but oversimplified case:

An environmental consulting organization has a project manager responsible for: creating and managing clients; projects; facilities and buildings, and equipment and supplies. A lot of this is just CRUD, but there's quite a bit more.

Does it make sense to have a ProjectManager class with all the behaviors implied? Just looking at the use-case diagram, I can see 20+ methods that would be required.

Project Management Use-Case

答:
We can also imagine like this. Adding to answer from @Alp

A project manager has X number of responsibilities.(Customer
  Relations, Office Management)

Interface: CustomerRelations Responsibilities: customer related ops (e.g. Get-feedback from customer, and other)

Interface: OfficeManagement Responsibilities:

Class: ProjectManager can have ICustomerRelations, IOfficeManagement and IProjectManagement.

```<code>Class ProjectManager
{
   IOfficeManagerment officeManagement;
   ICustomerRelations  customerRelations;

    public ProjectManager(IOfficeManagerment management, ICustomerRelations)
    {
          \\Inject your dependencies
    }

    public void GetFeedBack()
    {
        customerRelations.GetFeedback();
    }

    public void GetEquipements()
    {
        officeManagement.GetAvailableEquipments();
    }
}
</code>```

Considerations

Project-manager doesn't have to know internals how the office is
managed. He delegate the duty to some other. eg. How to get
available resources. He just want to know the available resources.

Title: Use-case actor with many behaviors

Body:
We can also imagine like this. Adding to answer from @Alp

A project manager has X number of responsibilities.(Customer
  Relations, Office Management)

Interface: CustomerRelations Responsibilities: customer related ops (e.g. Get-feedback from customer, and other)

Interface: OfficeManagement Responsibilities:

Class: ProjectManager can have ICustomerRelations, IOfficeManagement and IProjectManagement.

Class ProjectManager
{
   IOfficeManagerment officeManagement;
   ICustomerRelations  customerRelations;

    public ProjectManager(IOfficeManagerment management, ICustomerRelations)
    {
          \\Inject your dependencies
    }

    public void GetFeedBack()
    {
        customerRelations.GetFeedback();
    }

    public void GetEquipements()
    {
        officeManagement.GetAvailableEquipments();
    }
}

Considerations

Project-manager doesn't have to know internals how the office is
managed. He delegate the duty to some other. eg. How to get
available resources. He just want to know the available resources.


问:
How to give dynamic filepath in appender tag in log4j_config.xml?
Hi I am using log4j api to log the informations. I have used log4j_conffig.xml file for creating the log files. I have given the absolute path for each log file in param tag value.

eg :

```<code>appender name="GPREPROCESSOR_DEBUG" class="org.apache.log4j.DailyRollingFileAppender"><br>
        param name="DatePattern" value="'_'yyyyMMdd"/><br>
        param name="File" value="D:/logFiles/GPreprocessor_Debug.log"/><br>
        layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/><br>
/appender><br>
</code>```

i do not want to give "D:/logFiles/" directly.Actually that path is dynamic based on my project location. so how can i give that

答:
You can create your own appender by extending from RollingFileAppender and adding a "prefix" attribute that can be defined according to your project. The filename that log4j uses is http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/FileAppender.html#setFile(java.lang.String), so it should be easy in ur appender class to use this and set the name of the file.

The other option is to use some property thats defined and available to log4j.xml (any java system property would do) and reference the filename as ${my.project.location}/logs/Preprocessor_Debug.log

OwnerDisplayName: raja

Body:
Hi I am using log4j api to log the informations. I have used log4j_conffig.xml file for creating the log files. I have given the absolute path for each log file in param tag value.

eg :

appender name="GPREPROCESSOR_DEBUG" class="org.apache.log4j.DailyRollingFileAppender">

        param name="DatePattern" value="'_'yyyyMMdd"/>

        param name="File" value="D:/logFiles/GPreprocessor_Debug.log"/>

        layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/>

/appender>

i do not want to give "D:/logFiles/" directly.Actually that path is dynamic based on my project location. so how can i give that

OwnerDisplayName: rajasaur

ContentLicense: CC BY-SA 2.5


问:
Select option, on click event not working in IE11
This is the HTML code :

```<code><select multiple="multiple" id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select>
</code>```

JQuery click event :

```<code>$('select option').on('click', function (event) {
            alert('Hello');
});
</code>```

This code is not working in IE 11, but working in google crome and firefox. Please suggest any solution.

答:
Try to use correct ID identifier # in the jQuery selector.
Try this:

```<code>$('#selectPartType').on('click', function (event) {
  alert('Hello');
});
</code>```

Or this:

```<code>$('#selectPartType').on('change', function (event) {
  alert('Hello');
});
</code>```

Body:
This is the HTML code :

<select multiple="multiple" id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select>

JQuery click event :

$('select option').on('click', function (event) {
            alert('Hello');
});

This code is not working in IE 11, but working in google crome and firefox. Please suggest any solution.

Body:
Try to use correct ID identifier # in the jQuery selector.
Try this:

$('#selectPartType').on('click', function (event) {
  alert('Hello');
});

Or this:

$('#selectPartType').on('change', function (event) {
  alert('Hello');
});


答:
You should be listening to the change event. It is fired when any of the options is selected/deselected.

Also, instead of binding to select option, you should bind to select for the change event.

$('select').on('change', function (event) {
      alert('Hello');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select multiple="multiple" id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select></code>```

Title: Select option, on click event not working in IE11

Body:
You should be listening to the change event. It is fired when any of the options is selected/deselected.

Also, instead of binding to select option, you should bind to select for the change event.

$('select').on('change', function (event) {
      alert('Hello');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select multiple="multiple" id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select>


问:
ReactJS - Loading undesirable repeated data from the API
I'm fetching Data from a Dribbble API. It is almost succefully but it is loading 12 shots from the API, and after this it is occurring a problem by repeating the same 12 again and then it after this it is loading the others in a right way: 13,14,15...

The shots' return:
1,2,3,4,5,6,7,8,9,10,11,12.
OK RIGHT
1,2,3,4,5,6,7,8,9,10,11,12.
repetition problem!!! WRONG
13,14,15,16... OK RIGHT

What is the solution for this undesirable repetition?

Here is the code:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Waypoint from 'react-waypoint';
import Dribbble from './Dribbble';

export default class Dribbbles extends Component {
    constructor(props) {
        super(props);
        this.state = { page: 1, shots: [] };
        this.getShots = this.getShots.bind(this);
    }

    componentDidMount() {
        this.getShots();
    }

    getShots() {
        return $.getJSON('https://api.dribbble.com/v1/shots?page='+ this.state.page + '&access_token=ACCESS_TOKEN_HERE&callback=?')
        .then((resp) => {
            var newShots = this.state.shots.concat(resp.data);
            this.setState({
                page: this.state.page + 1,
                shots: newShots
            });
        });
    }

    render() {
        const shots = this.state.shots.map((val, i) => {
            return <Dribbble dados={val} key={i} />
        });

        return (

{shots}

        <Waypoint
        onEnter={this.getShots}
        />

        );
    }
}
```

答:
Why

I think the onEnter event from your Waypoint component is triggered unexpectedly, which has caused the getShots() function being called multiple times.

How

My suggestion is to specify a dataFecthed state to control whether the Waypoint component mount or not.Just like below:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Waypoint from 'react-waypoint'
import Dribbble from './Dribbble'

export default class Dribbbles extends Component {
  constructor(props) {
    super(props)
    this.state = { page: 1, shots: [], dataFetched: true }
    this.getShots = this.getShots.bind(this)
  }

  componentDidMount() {
    this.getShots()
  }

  getShots() {
    this.setState({
      dataFetched: false,
    })
    return $.getJSON(
      'https://api.dribbble.com/v1/shots?page=' +
        this.state.page +
        '&access_token=41ff524ebca5e8d0bf5d6f9f2c611c1b0d224a1975ce37579326872c1e7900b4&callback=?'
    ).then(resp => {
      var newShots = this.state.shots.concat(resp.data)
      this.setState({
        page: this.state.page + 1,
        shots: newShots,
        dataFetched: true,
      })
    })
  }

  render() {
    const shots = this.state.shots.map((val, i) => {
      return <Dribbble dados={val} key={i} />
    })

    return (

{shots}

        {this.state.dataFetched && <Waypoint onEnter={this.getShots} />}

    )
  }
}
```

Body:
Why

I think the onEnter event from your Waypoint component is triggered unexpectedly, which has caused the getShots() function being called multiple times.

How

My suggestion is to specify a dataFecthed state to control whether the Waypoint component mount or not.Just like below:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import Waypoint from 'react-waypoint'
import Dribbble from './Dribbble'

export default class Dribbbles extends Component {
  constructor(props) {
    super(props)
    this.state = { page: 1, shots: [], dataFetched: true }
    this.getShots = this.getShots.bind(this)
  }

  componentDidMount() {
    this.getShots()
  }

  getShots() {
    this.setState({
      dataFetched: false,
    })
    return $.getJSON(
      'https://api.dribbble.com/v1/shots?page=' +
        this.state.page +
        '&access_token=41ff524ebca5e8d0bf5d6f9f2c611c1b0d224a1975ce37579326872c1e7900b4&callback=?'
    ).then(resp => {
      var newShots = this.state.shots.concat(resp.data)
      this.setState({
        page: this.state.page + 1,
        shots: newShots,
        dataFetched: true,
      })
    })
  }

  render() {
    const shots = this.state.shots.map((val, i) => {
      return <Dribbble dados={val} key={i} />
    })

    return (
      <div>
        <ul>{shots}</ul>
        {this.state.dataFetched && <Waypoint onEnter={this.getShots} />}
      </div>
    )
  }
}


问:
How to post image file type in postman or rest client form data?
I did one project in Android (Retrofit) ,I could have gotten response fine in APP,but I don't know how to get response in Postman and Advanced REST client , my issue is how do I send file Type(I don't know what to call it is),In project I achieved by putting  new TypedFile("image/png",... but how would I put these parameters in Postman and Advanced REST client? I want to check and know about it, I searched lot and I tried lot but no result. Please help me...

 Here is project code:

```<code> MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
    try {
        multipartTypedOutput.addPart("originalImgBlob", new TypedFile("image/png", files.get(0)));
        multipartTypedOutput.addPart("img430Blog", new TypedFile("image/png;base64", files.get(1)));
        multipartTypedOutput.addPart("img200Blog", new TypedFile("image/png;base64", files.get(2)));
        multipartTypedOutput.addPart("img100Blog", new TypedFile("image/png;base64", files.get(3)));
        multipartTypedOutput.addPart("blurResponseBlob", new TypedFile("image/png;base64", files.get(4)));
        Log.d("UploadActivity", "postNewsFeed() returned: " + "" + files.get(2));
    } catch (Exception e) {
        e.printStackTrace();
    }
    doServereCall(multipartTypedOutput);
</code>```

```<code>/* Set profile pic in registration */
@Headers("Accept:application/json")
@POST("/api/mbrphotos/prfImgIU/{memberId}/{actionType}")
public void sendMultiImages(@Path("memberId") String memberId,
                            @Path("actionType") String actionType,
                            @Body MultipartTypedOutput multipartTypedOutput, Callback<JsonObject> callback);
</code>```

答:
You can check API response in postman by following steps :

selecting post method .

Then in that select body option .

now select form-data option. after that you have new view that available for enter key and value .

Here you can check your API . I also attach image as source for your help. And select file type in key field to post as File Type  . After selecting file type Choose files Browse button is available to you to select file.

Body:
I did one project in Android (Retrofit) ,I could have gotten response fine in APP,but I don't know how to get response in Postman and Advanced REST client , my issue is how do I send file Type(I don't know what to call it is),In project I achieved by putting  new TypedFile("image/png",... but how would I put these parameters in Postman and Advanced REST client? I want to check and know about it, I searched lot and I tried lot but no result. Please help me...

 Here is project code:

 MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
    try {
        multipartTypedOutput.addPart("originalImgBlob", new TypedFile("image/png", files.get(0)));
        multipartTypedOutput.addPart("img430Blog", new TypedFile("image/png;base64", files.get(1)));
        multipartTypedOutput.addPart("img200Blog", new TypedFile("image/png;base64", files.get(2)));
        multipartTypedOutput.addPart("img100Blog", new TypedFile("image/png;base64", files.get(3)));
        multipartTypedOutput.addPart("blurResponseBlob", new TypedFile("image/png;base64", files.get(4)));
        Log.d("UploadActivity", "postNewsFeed() returned: " + "" + files.get(2));
    } catch (Exception e) {
        e.printStackTrace();
    }
    doServereCall(multipartTypedOutput);

/* Set profile pic in registration */
@Headers("Accept:application/json")
@POST("/api/mbrphotos/prfImgIU/{memberId}/{actionType}")
public void sendMultiImages(@Path("memberId") String memberId,
                            @Path("actionType") String actionType,
                            @Body MultipartTypedOutput multipartTypedOutput, Callback<JsonObject> callback);


问:
". was unexpected at this time" generated from batch script line 'if exist [file] (...
relevant code looks like this:

```<code>cd /d %~dp0

if exist filename.txt (
    echo %date% %time% *** text... >> filename2.txt
    echo ==============================
    echo ===  text.......           ===
    echo ===  text.......           ===
    echo ===  text....... (text...) ===
    echo ===  text (text...
    echo ===  text...).
    :loop
        set /p "varx= text: "
    if "%varx%" neq "xxxx" goto loop

 ... more script...

)
</code>```

Have searched high and low for solutions...

was pointed in direction of If statement groupings here:
https://www.petri.com/forums/forum/windows-scripting/general-scripting/57625-if-exists-file-was-unexpected-at-this-time  - NO GO

was pointed in direction of problems with loops in If blocks, here:
(Windows batch) Goto within if block behaves very strangely  - NO GO

Was pointed in direction of using @setlocal enabledelayedexpansion or @setlocal enableextensions (can't track down where) - NO GO

tried passing filename via set /p varfile="filename" and if exist %varfile% - NO GO

of course thought there were other parts of code causing error -- NO GO

The thing is that this WAS working for a long while...then I changed what I thought was some innocuous stuff and cannot figure out where the problem lies...

such an obscure problem to solve..ugh!

答:
WELL...I am posting this as a Q & A...because I solved my own problem (took me a couple of days of trial and error to narrow down and fix the problem). I am hoping this will help some poor soul too and save them a lot of heartache, and a few hair strands...

The thing that got me thinking the most was the second bullet regarding poor handling of loops inside If statements...BUT that was not the real reason but something similar...

It turns out the problem was with the use of "(' and/or ')' on the ECHO lines...

I thought this was innocuous... I use brackets in ECHO lines in lots of places, and these lines were about 10-15 lines down from where the error message was being generated, so naturally I was not thinking that this was at all the source.

BUT it turns out that the interpreter clearly does not like the use of '(' or ')' even on ECHO lines if they are used within the If statement blocks. It must still treat them as special characters in that context...it clearly does not ignore them...

Solution:

Either taking the '(' and ')' out of those 3 lines above OR simply REM those lines out solved the problem and the error message  went away...all is finally well...

BTW it is possible that the a similar thing may apply to FOR statements too (I vaguely recall reading something about FOR acting strangely too).

So food for thought.

Body:
relevant code looks like this:

cd /d %~dp0

if exist filename.txt (
    echo %date% %time% *** text... >> filename2.txt
    echo ==============================
    echo ===  text.......           ===
    echo ===  text.......           ===
    echo ===  text....... (text...) ===
    echo ===  text (text...
    echo ===  text...).
    :loop
        set /p "varx= text: "
    if "%varx%" neq "xxxx" goto loop

 ... more script...

)

Have searched high and low for solutions...

was pointed in direction of If statement groupings here:
https://www.petri.com/forums/forum/windows-scripting/general-scripting/57625-if-exists-file-was-unexpected-at-this-time  - NO GO

was pointed in direction of problems with loops in If blocks, here:
(Windows batch) Goto within if block behaves very strangely  - NO GO

Was pointed in direction of using @setlocal enabledelayedexpansion or @setlocal enableextensions (can't track down where) - NO GO

tried passing filename via set /p varfile="filename" and if exist %varfile% - NO GO

of course thought there were other parts of code causing error -- NO GO

The thing is that this WAS working for a long while...then I changed what I thought was some innocuous stuff and cannot figure out where the problem lies...

such an obscure problem to solve..ugh!


问:
how to set footer at the bottom when there is no content

Designed by Wiredelta

```

not getting footer at bottom of the page when there is no content is present in the body.so i need to fix footer at the bottom only, when i run the code the code.plzz give suggestion how to fix footer at the bottom exactly.

答:
```<code>footer {
  position: fixed;
  bottom: 0;
}
</code>```

just add this in your css.

Body:
Designed by Wiredelta

not getting footer at bottom of the page when there is no content is present in the body.so i need to fix footer at the bottom only, when i run the code the code.plzz give suggestion how to fix footer at the bottom exactly.

Body:
footer {
  position: fixed;
  bottom: 0;
}

just add this in your css.


问:
Form variable does not refresh with ajax call
I'm building a simple email sending form and wanted to make it with ajax. The form submits correctly the first time but if you make any subsequent changes to the text in the form and then submit again then jquery does not pick up on the changes and posts the old data. Whats going on?

```<code><script type="text/javascript">
var $j = jQuery.noConflict();

$j(document).ready(function() {
    var submit_url = "mail_submit.php";
    var send_email = $j("#sendemail");

    send_email.click(function() {
        var form = $j("#post");

        $j.post(submit_url, form.serialize(), function(data) {
            alert(data);
        });

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

答:
I ran into this problem again.

To solve it you need to use tinyMCE.triggerSave();
The method is outlined here http://maestric.com/doc/javascript/tinymce_jquery_ajax_form

My final code is:

```<code><script type="text/javascript">
var $j = jQuery.noConflict();

$j(document).ready(function() {
    var submit_url = "mail_submit.php?action=";
    var actions = $j("#sendEmail, a#previewEmail, a#saveEmail, a#updateEmail");
    var loading = $j("img#ajax-loading");
    var status = $j("span#post-status-display");

    actions.click(function() {
        tinyMCE.triggerSave();
        var form = $j("#post");
        var action = $j(this).attr("id");
        var update_div = $j("#update-div");
        loading.show();

        $j.post(submit_url + action, form.serialize(), function(data){
            update_div.html(data);
            update_div.fadeIn();
            loading.hide();
        });

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

Body:
I ran into this problem again.

To solve it you need to use tinyMCE.triggerSave();
The method is outlined here http://maestric.com/doc/javascript/tinymce_jquery_ajax_form

My final code is:

<script type="text/javascript">
var $j = jQuery.noConflict();

$j(document).ready(function() {
    var submit_url = "mail_submit.php?action=";
    var actions = $j("#sendEmail, a#previewEmail, a#saveEmail, a#updateEmail");
    var loading = $j("img#ajax-loading");
    var status = $j("span#post-status-display");

    actions.click(function() {
        tinyMCE.triggerSave();
        var form = $j("#post");
        var action = $j(this).attr("id");
        var update_div = $j("#update-div");
        loading.show();

        $j.post(submit_url + action, form.serialize(), function(data){
            update_div.html(data);
            update_div.fadeIn();
            loading.hide();
        });

    });
});


问:
Can't get double curly brackets to display
I have some markdown in Morea which includes an example Jinja2 template. It looks like this:

```<code>{% highlight html linenos %}
<!doctype html>
<html>
<body>
    <p> {{ greet }}, {{ place }} </p>
</body>
</html>
{% endhighlight %}
</code>```

I would like to be able to display the double curly braces, but they get swallowed up, displaying nothing but the paragraph tags and the comma, like this:

```<code><p>  ,   </p>
</code>```

I followed some advice to use the {% raw %} and {% endraw %} tags around that line, but nothing changes. Seems like a bug. Anyone have any tricks?

答:
This should work :</p>

```<code>```
{% raw %}
<!doctype html>
<html>
<body>
    <p> {{ greet }}, {{ place }} </p>
</body>
</html>
{% endraw %}
```
</code>```

Body:
I have some markdown in Morea which includes an example Jinja2 template. It looks like this:

{% highlight html linenos %}
<!doctype html>

 {{ greet }}, {{ place }}

{% endhighlight %}

I would like to be able to display the double curly braces, but they get swallowed up, displaying nothing but the paragraph tags and the comma, like this:

  ,

I followed some advice to use the {% raw %} and {% endraw %} tags around that line, but nothing changes. Seems like a bug. Anyone have any tricks?

Body:
This should work :

```
{% raw %}
<!doctype html>
<html>
<body>
    <p> {{ greet }}, {{ place }} </p>
</body>
</html>
{% endraw %}
```


问:
Error in regression in r
I have two data frames df1 and df2. both of them have 240 obs. of 204 variables. I have checked and there are no missing or NA values in those files. However when I regress by this formula:

```<code>library(broom)
fit4 <- lapply(names(df1), function(x){
  dd = tidy(lm(df1[[x]] ~ df2[[x]]))
  data.frame(name = x, dd)})
</code>```

It shows the following error messages:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...)
  :    NA/NaN/Inf in 'y'

答:
As the error itself states, it might be due to NaN values or to infinite values, so you will need to delete those values or assign a zero to them.

To remove NaN from the whole data frame, you will need to create a function (as described here).

```<code>is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))

dd[is.nan(dd)] <- 0
</code>```

For the infinite numbers, you can refer to this question. The two faster methods are to remove all infinite values:

```<code>dd[!rowSums(!is.finite(dd)),]
</code>```

or to replace them with 0:

```<code>dd[!is.finite(dd)] <- 0
</code>```

Title: Error in regression in r

Body:
I have two data frames df1 and df2. both of them have 240 obs. of 204 variables. I have checked and there are no missing or NA values in those files. However when I regress by this formula:

library(broom)
fit4 <- lapply(names(df1), function(x){
  dd = tidy(lm(df1[[x]] ~ df2[[x]]))
  data.frame(name = x, dd)})

It shows the following error messages:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...)
  :    NA/NaN/Inf in 'y'

Body:
As the error itself states, it might be due to NaN values or to infinite values, so you will need to delete those values or assign a zero to them.

To remove NaN from the whole data frame, you will need to create a function (as described here).

is.nan.data.frame <- function(x)
do.call(cbind, lapply(x, is.nan))

dd[is.nan(dd)] <- 0

For the infinite numbers, you can refer to this question. The two faster methods are to remove all infinite values:

dd[!rowSums(!is.finite(dd)),]

or to replace them with 0:

dd[!is.finite(dd)] <- 0


问:
How to call action method by clicking on row inside foreach?
I use mvc5 project and I use bootstrap 3.

I have this partial page:

```<code>        @model IEnumerable<GeomindEnterprise.Models.ApplicationGroup>
        @foreach (var item in Model)
        {
            <div class="container-fluid">
                <div class="row margin-bottom-8">
                    <div class="col-sm-2">@Html.DisplayFor(modelItem => item.Name)</div>
                    <div class="col-sm-3">@Html.DisplayFor(modelItem => item.Description)</div>
                    <div class="col-sm-7">@Html.DisplayFor(modelItem => item.LayoutID)</div>
                </div>
            </div>
        }
    </div>
</code>```

whenever I click generated row above I need to call this action method:

```<code>    public ActionResult GetLayers(ApplicationGroup model)
    {
       //some logic
    }
</code>```

I tried this way:

```<code>           @foreach (var item in Model)
        {
        Html.ActionLink(<div class="container-fluid">
                        <div class="row margin-bottom-8">
                            <div class="col-sm-2">@Html.DisplayFor(modelItem => item.Name)</div>
                            <div class="col-sm-3">@Html.DisplayFor(modelItem => item.Description)</div>
                            <div class="col-sm-7">@Html.DisplayFor(modelItem => item.LayoutID)</div>
                        </div>
                        </div>,
                        new { controller = "Articles", action = "Details",model = item })}
                    </div>
</code>```

But the attitude above didnt work.

How do I implement it?

答:
You cannot use @Html.ActionLink() to generate you  element because the first parameter is a string and it will be encoded (your html will not be rendered as html). In addition, its generally not advisable to send the whole model in a query string. Apart from the ugly query string it creates, you risk exceeding the query string limit and throwing an exception. Instead pass just the ID of the record and get it again in the GET method

If you want to handle clicking the
 rather than adding an additional column for a 'Details' link, then add a class name and a data- attribute for the url to your
 and use javascript/jquery to handle the .click() event, for example

```<code>@foreach (var item in Model)
{
    <div class="container-fluid details" data-id="@item.yourIdProperty">
        ....
    </div>
}
</code>```

and the jQuery script would be

```<code>var baseUrl = '@Url.Action("Details", "Articles")
$('.details').click(function() {
    var id = $(this).data('id');
    location.href = baseUrl + '/' + id;
});
</code>```

Which would post back to (assuming your using the default route)

```<code>public ActionResult Details(int id) // not GetLayers as per your question
</code>```

If you really do want to post back the whole model, then

```<code>@foreach (var item in Model)
{
    <div class="container-fluid details" data-url="@Url.Action"Details", "Articles", item)">
        ....
    </div>
}

$('.details').click(function() {
    location.href = $(this).data('url');
});
</code>```

Note that the 3rd parameter of Url.Action() is your model, not an anonymous object containing your model. The method serializes each property of your model to a query string value.

Body:
I use mvc5 project and I use bootstrap 3.

I have this partial page:

        @model IEnumerable<GeomindEnterprise.Models.ApplicationGroup>
        @foreach (var item in Model)
        {

@Html.DisplayFor(modelItem => item.Name)

@Html.DisplayFor(modelItem => item.Description)

@Html.DisplayFor(modelItem => item.LayoutID)

        }

whenever I click generated row above I need to call this action method:

    public ActionResult GetLayers(ApplicationGroup model)
    {
       //some logic
    }

I tried this way:

           @foreach (var item in Model)
        {
        Html.ActionLink(

@Html.DisplayFor(modelItem => item.Name)

@Html.DisplayFor(modelItem => item.Description)

@Html.DisplayFor(modelItem => item.LayoutID)

,
                        new { controller = "Articles", action = "Details",model = item })}

But the attitude above didnt work.

How do I implement it?

Body:
You cannot use @Html.ActionLink() to generate you <a> element because the first parameter is a string and it will be encoded (your html will not be rendered as html). In addition, its generally not advisable to send the whole model in a query string. Apart from the ugly query string it creates, you risk exceeding the query string limit and throwing an exception. Instead pass just the ID of the record and get it again in the GET method

If you want to handle clicking the <div> rather than adding an additional column for a 'Details' link, then add a class name and a data- attribute for the url to your <div> and use javascript/jquery to handle the .click() event, for example

@foreach (var item in Model)
{
    <div class="container-fluid details" data-id="@item.yourIdProperty">
        ....
    </div>
}

and the jQuery script would be

var baseUrl = '@Url.Action("Details", "Articles")
$('.details').click(function() {
    var id = $(this).data('id');
    location.href = baseUrl + '/' + id;
});

Which would post back to (assuming your using the default route)

public ActionResult Details(int id) // not GetLayers as per your question

If you really do want to post back the whole model, then

@foreach (var item in Model)
{
    <div class="container-fluid details" data-url="@Url.Action"Details", "Articles", item)">
        ....
    </div>
}

$('.details').click(function() {
    location.href = $(this).data('url');
});

Note that the 3rd parameter of Url.Action() is your model, not an anonymous object containing your model. The method serializes each property of your model to a query string value.


问:
NodeJS - Multiple Timeouts vs one Interval for sessions in bots
I would like the messenger bot to notify the user that their session ended if they did not write/give input to the bot for some time. In order to do so, I first thought about using setTimeout() for each user which will reset upon activity. But that means if there will be 100 active users, there will be 100 Timeouts at the same time.

I wanted to know, if having one Interval instead that checks through each user`s session end timestamp every 30-60 seconds a better approach? The active users are stored in memory.

答:
setTimeout is more precise in your case: each session will be ended independently and closer to the time it was supposed to end. It will also spread the activity more evenly. Since JS is single-threaded, the timeouts will not fire in parallel, even though there will be hundreds of them at the same time.

setInterval will create spikes of activity every 30-60 seconds, and will sometimes let the sessions stay alive longer than they should.

As per the cost of multiple timeouts running at the same time, please see this answer.


问:
How to get Data from specified 'Year' where the 'Year' is DATETIME Column
I would like to get every data from a table where the year is specified. But the problem is i put my date in DATETIME type.

I'm trying something like:

```<code>SELECT
    *
FROM
    table
WHERE
    entrytime = 2017 //entrytime is datetime type.
</code>```

But, it's wrong.

Is there any way to get the data or maybe a better approach ?

Thank you.

答:
You can use the year function to extract the year of a datetime:

```<code>SELECT *
FROM   mytable
WHERE  YEAR(entrytime) = 2017
</code>```

Body:
I would like to get every data from a table where the year is specified. But the problem is i put my date in DATETIME type.

I'm trying something like:

SELECT
    *
FROM
    table
WHERE
    entrytime = 2017 //entrytime is datetime type.

But, it's wrong.

Is there any way to get the data or maybe a better approach ?

Thank you.

Body:
You can use the year function to extract the year of a datetime:

SELECT *
FROM   mytable
WHERE  YEAR(entrytime) = 2017


答:
You can use the YEAR function, theres a document on it here.

So...

```<code>SELECT
*
FROM Table
WHERE YEAR(DateColumn) = 2017
</code>```

Title: How to get Data from specified 'Year' where the 'Year' is DATETIME Column

Body:
You can use the YEAR function, theres a document on it here.

So...

SELECT
*
FROM Table
WHERE YEAR(DateColumn) = 2017


问:
Allow only 3 rows to be added to a table for a specific value
I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

```<code>Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)
</code>```

Can anyone suggest what approach to take to implement this?

答:
"How do I implement the restrict to 0,3?"

This requires an assertion, which is defined in the SQL standard but not implemented in Oracle. (Although there are moves to have them introduced).

What you can do is use a materialized view to enforce it transparently.

```<code>create materialized view project_manager
refresh on commit
as
select Project_manager_employee_id
        , count(*) as no_of_projects
from project
group by Project_manager_employee_id
/
</code>```

The magic is:

```<code>alter table project_manager
   add constraint project_manager_limit_ck check
       ( no_of_projects <= 3 )
/
</code>```

This check constraint will prevent the materialized view being refreshed if the count of projects for a manager exceeds three, which failure will cause the triggering insert or update to fail. Admittedly it's not elegant.

Because the mview is refreshed on commit (i.e. transactionally) you will need to build a log on project table:

```<code>create materialized view log on project
</code>```

Body:
I have a question in hand where i need to restrict the number of projects assigned to a manager to only 3. The tables are:

Manager:
Manager_employee_id(PK)
Manager_Bonus

Project:
project_number(PK)
Project_cost
Project_manager_employee_id(FK)

Can anyone suggest what approach to take to implement this?

Body:
"How do I implement the restrict to 0,3?"

This requires an assertion, which is defined in the SQL standard but not implemented in Oracle. (Although there are moves to have them introduced).

What you can do is use a materialized view to enforce it transparently.

create materialized view project_manager
refresh on commit
as
select Project_manager_employee_id
        , count(*) as no_of_projects
from project
group by Project_manager_employee_id
/

The magic is:

alter table project_manager
   add constraint project_manager_limit_ck check
       ( no_of_projects <= 3 )
/

This check constraint will prevent the materialized view being refreshed if the count of projects for a manager exceeds three, which failure will cause the triggering insert or update to fail. Admittedly it's not elegant.

Because the mview is refreshed on commit (i.e. transactionally) you will need to build a log on project table:

create materialized view log on project


问:
Go through undetermined number of Promises sequentially
I have this class that has method next returning a Promise.

class PromiseGenerator {
    constructor() {
        this.limit = 100;
        this.counter = 0;
    }
    next() {
        this.counter++;
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(this.counter <= this.limit ? this.counter : false);
            }, 500);
        });
    }
}
```

<p>Though example shows <code>100</code> it could return unlimited number of promises.</p>

<p>I need to execute all the promises in sequential order.</p>

<p>How can I achieve it?</p>

<p>Only solution I came up so far is recursive:</p>

<pre class="lang-js prettyprint-override"><code>const source = new PromiseGenerator();

(function loop() {
    source.next().then(counter => {
        if (counter) {
            console.log(counter);
            loop();
        } else {
            console.log('Done');
        }
    });
})();
</code>```

As I understand Node at the moment does not optimize tail calls and it may lead to stack growth.

Is there a better way of doing this?

if some Promise library has it it will work but it would be nice to understand how to achieve it without library as well.

Update 1: Sorry I didn't make it clear right away: I am not in control of PromiseGenerator class, it is something I can use but cannot change. So the question is how to handle this situation.

Update 2: I went with @eikooc solution: Without generators but just with async/await. See example below.

Thanks!

答:
Generators are a perfect match for this. Construct a generator with the function* keyword:

```<code>function* promiseGenerator() {
  while(!someCondition) {
    yield new Promise((resolve, reject) => {})
  }
}
</code>```

And then call it with:

```<code>const source = promiseGenerator()
source.next()
</code>```

This will continue to give you new values. The return looks like this {value: Promise, done: false} until it is finished.
When the generator finishes the done value will change to true

If you want to keep using the class and just want a loop. You can also combine your class with a async function:

```<code>async function loop() {
  const source = new PromiseGenerator()
  while (true) {
    const result = await source.next()
    if (result) {
      console.log(result)
    } else {
      console.log('done')
      break
    }
  }
}

loop()
</code>```

Body:
I have this class that has method next returning a Promise.

class PromiseGenerator {
    constructor() {
        this.limit = 100;
        this.counter = 0;
    }
    next() {
        this.counter++;
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(this.counter <= this.limit ? this.counter : false);
            }, 500);
        });
    }
}

Though example shows 100 it could return unlimited number of promises.

I need to execute all the promises in sequential order.

How can I achieve it?

Only solution I came up so far is recursive:

const source = new PromiseGenerator();

(function loop() {
    source.next().then(counter => {
        if (counter) {
            console.log(counter);
            loop();
        } else {
            console.log('Done');
        }
    });
})();

As I understand Node at the moment does not optimize tail calls and it may lead to stack growth.

Is there a better way of doing this?

if some Promise library has it it will work but it would be nice to understand how to achieve it without library as well.

Update 1: Sorry I didn't make it clear right away: I am not in control of PromiseGenerator class, it is something I can use but cannot change. So the question is how to handle this situation.

Update 2: I went with @eikooc solution: Without generators but just with async/await. See example below.

Thanks!

Body:
Generators are a perfect match for this. Construct a generator with the function* keyword:

function* promiseGenerator() {
  while(!someCondition) {
    yield new Promise((resolve, reject) => {})
  }
}

And then call it with:

const source = promiseGenerator()
source.next()

This will continue to give you new values. The return looks like this {value: Promise, done: false} until it is finished.
When the generator finishes the done value will change to true

If you want to keep using the class and just want a loop. You can also combine your class with a async function:

async function loop() {
  const source = new PromiseGenerator()
  while (true) {
    const result = await source.next()
    if (result) {
      console.log(result)
    } else {
      console.log('done')
      break
    }
  }
}

loop()


问:
C++ variable declation syntax
I recently came across this construct:
    int(m);
which seems to be equivalent to:
    int m;

Oddly, I have never seen this particular idiom before.  Can someone point me to a reference where I can read the spec on this, or just explain directly?  Does this also work in straight C?

Thanks,
ConfusedDeveloper

答:
It is not an "idiom". It is just a redundant pair of parentheses. Grammatically, they can be there, but they serve no purpose.

Sometimes similar seemingly superfluous parentheses can be used to resolve ambiguity in C++ declarations, like

```<code>int a(int());
</code>```

which declares a function can be turned into

```<code>int a((int()));
</code>```

which is equivalent to

```<code>int a = int();
</code>```

and defines a variable. But this is not exactly what you have in your case.

Title: C++ variable declation syntax

Body:
It is not an "idiom". It is just a redundant pair of parentheses. Grammatically, they can be there, but they serve no purpose.

Sometimes similar seemingly superfluous parentheses can be used to resolve ambiguity in C++ declarations, like

int a(int());

which declares a function can be turned into

int a((int()));

which is equivalent to

int a = int();

and defines a variable. But this is not exactly what you have in your case.


问:
Unindent lines in Sublime Text
You know when you have a bunch of text marked and predd TAB the text moves to the right (I can't remember what this is called...). How can I make the text do the opposite?</p>

答:
You can try Shift+TAB to un-indent multiple selected lines. If you want to un-indent a single line where the cursor is in, you need to set

```<code> "shift_tab_unindent": true,
</code>```

in your user settings.

Title: Unindent lines in Sublime Text

Body:
You can try Shift+TAB to un-indent multiple selected lines. If you want to un-indent a single line where the cursor is in, you need to set

 "shift_tab_unindent": true,

in your user settings.


问:
How to use redis dockerhub as a service in Gitlab CI .gitlab-ci.yml?
My .gitlab-ci.yml is this:

```<code>image: "python:3.5"

services:
  - redis:4.0.2
  - mongo:3.4.10

stages:
  - checkEverythingRuns

checkEverythingRuns:
  stage: checkEverythingRuns
  script:
    - "python --version"
    - "pip --version"
    - "redis-server -v"
    - "mongod --version"
</code>```

The redis image downloads correctly:

```<code>Using docker image redis:4.0.2 ID=sha256:blablabla
</code>```

But it throws the next error:

```<code>$ redis-server -v
/bin/bash: line 14: redis-server: command not found
ERROR: Job failed: exit code 1
</code>```

答:
The redis-server command is not found on the image you are running your job in: python:3.5. The redis server is a container auto-linked to your job-container, python:3.5.

You could install redis-tools with apt-get install redis-tools and then run:

redis-cli -h redis ping

redis is the default hostname your service gets, if you want to change it take a look here to specify a service alias.

Body:
My .gitlab-ci.yml is this:

image: "python:3.5"

services:
  - redis:4.0.2
  - mongo:3.4.10

stages:
  - checkEverythingRuns

checkEverythingRuns:
  stage: checkEverythingRuns
  script:
    - "python --version"
    - "pip --version"
    - "redis-server -v"
    - "mongod --version"

The redis image downloads correctly:

Using docker image redis:4.0.2 ID=sha256:blablabla

But it throws the next error:

$ redis-server -v
/bin/bash: line 14: redis-server: command not found
ERROR: Job failed: exit code 1


答:
You can achieve the same in plain JavaScript to avoid any JQuery when considering IE.

document.getElementById('selectPartType').onchange = function() {
  alert("Hello!");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select multiple id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select></code>```

Body:
This is the HTML code :

<select multiple="multiple" id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select>

JQuery click event :

$('select option').on('click', function (event) {
            alert('Hello');
});

This code is not working in IE 11, but working in google crome and firefox. Please suggest any solution.

Body:
You can achieve the same in plain JavaScript to avoid any JQuery when considering IE.

document.getElementById('selectPartType').onchange = function() {
  alert("Hello!");
}

<select multiple id="selectPartType">
      <option value = 'FG'>FG</option>
      <option value = 'SFG'>SFG</option>
      <option value = 'RM'>RM</option>
</select>


问:
How to detect a network was broken down with ZeroMQ monitor mechanism?

A. Description

I am using ZeroMQ monitor and I find that it works when logic disconnection but does not work when network broken down (unplug my cable).

For example:

I launch client app on an android pad, then launch a server app on my windows laptop. They are connected through a router with cables.

Everything will be OK with monitor if I close or open either client app or server app manually. Namely, the monitor on both sides can receive a 'Connect' or an 'Accept' and a 'Disconnect' event.

But If I unplug cable on the server side, while the client and server are connected and running, the monitors on both sides can not detect the 'Disconnect' event.

Is the monitor designed like this?

If so, are there any solutions to detect network broken down ( a cable unplug event ) except heartbeats?

If not, how to use the ZeroMQ's original monitor mechanism to solve this problem? Can a setTCPKeepAlive() interface be useful?

B. System environment

My scenario is as below.

Client

OS: Android, running on a pad, IDE: Android studio 2.3, lib:jeromq-0.4.3

```<code>// Java Code

String monitorAddr = "inproc://client.req";
ZContext ctx = new ZContext();
ZMQ.Socket clientSocket = ctx.createSocket(ZMQ.REQ);
clientSocket.monitor(monitorAddr,ZMQ.EVENT_ALL);

// Then start a montitor thread which is implemented by my own.
</code>```

Server

OS: Windows 7 ( 64 bit ), running on my laptop, IDE: VS2013, lib: Clrzmq4

```<code>// C# Code

const string MonitorEndpoint = "inproc://server.rep";

var ctx = new ZContext();
var serverSocket = new ZSocket(ctx,ZSocketType.REP);
ZError error;

// Create serverSocket pair socket
if (!serverSocket.Monitor(MonitorEndpoint, ZMonitorEvents.AllEvents, out error))
{

    if (error == ZError.ETERM)
          return ;    // Interrupted
    throw new ZException(error);
}

// Create a monitor
ZMonitor _monitor = ZMonitor.Create(ctx, MonitorEndpoint);
_monitor.AllEvents += _monitor_AllEvents;
_monitor.Start();
</code>```

答:
AFAIK there is no built in heartbeat within ZeroMQ. I know there was some discussion on the topic within the ZMQ community some years ago, and that discussion may still be going on.

It is comparatively simple to incorporate your own heartbeat messaging in your application's use of ZeroMQ, especially if you use something like Google Protocol Buffers to encode different message types; the heartbeat is just another message.

Doing heartbeats in your application (rather than relying on some inbuilt mechanism) is ultimately more flexible; you can choose the heartbeat rate, you can choose what to do if the heartbeat fails, you can decide when heartbeating is important and not important, etc.

Consider heartbeats within a PUB/SUB pattern; it's a bit difficult for the ZMQ authors to decide on your behalf what connection / disconnection / connection-break events matter to you. And if they do build in a mechanism, but an application developer didn't want it, then it is a waste of bandwidth.

It's far easier for the ZMQ authors to leave that kind of application architectural issue to the application author (that's you!) to deal with.

With your specific example, an unplugged network cable simply looks (so far as any software can determine) like no traffic is flowing; it's the same as the application not sending anything. ZMQ doesn't send anything if the application hasn't sent anything.

If you look at the events that the socket monitor can report on, they're all the consequence of something flowing over the network connection, or something done to the socket by the application.

Body:
A. Description

I am using ZeroMQ monitor and I find that it works when logic disconnection but does not work when network broken down (unplug my cable).

For example:

I launch client app on an android pad, then launch a server app on my windows laptop. They are connected through a router with cables.

Everything will be OK with monitor if I close or open either client app or server app manually. Namely, the monitor on both sides can receive a 'Connect' or an 'Accept' and a 'Disconnect' event.

But If I unplug cable on the server side, while the client and server are connected and running, the monitors on both sides can not detect the 'Disconnect' event.

Is the monitor designed like this?

If so, are there any solutions to detect network broken down ( a cable unplug event ) except heartbeats?

If not, how to use the ZeroMQ's original monitor mechanism to solve this problem? Can a setTCPKeepAlive() interface be useful?

B. System environment

My scenario is as below.

Client

OS: Android, running on a pad, IDE: Android studio 2.3, lib:jeromq-0.4.3

// Java Code

String monitorAddr = "inproc://client.req";
ZContext ctx = new ZContext();
ZMQ.Socket clientSocket = ctx.createSocket(ZMQ.REQ);
clientSocket.monitor(monitorAddr,ZMQ.EVENT_ALL);

// Then start a montitor thread which is implemented by my own.

Server

OS: Windows 7 ( 64 bit ), running on my laptop, IDE: VS2013, lib: Clrzmq4

// C# Code

const string MonitorEndpoint = "inproc://server.rep";

var ctx = new ZContext();
var serverSocket = new ZSocket(ctx,ZSocketType.REP);
ZError error;

// Create serverSocket pair socket
if (!serverSocket.Monitor(MonitorEndpoint, ZMonitorEvents.AllEvents, out error))
{

    if (error == ZError.ETERM)
          return ;    // Interrupted
    throw new ZException(error);
}

// Create a monitor
ZMonitor _monitor = ZMonitor.Create(ctx, MonitorEndpoint);
_monitor.AllEvents += _monitor_AllEvents;
_monitor.Start();


问:
nodejs token is empty
I started studying nodejs and I ran into a problem,
when i post my login on 'postman' i got success message, but the token content is empty.
this is my server.js code:

```<code>var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config');
var mongoose = require('mongoose');
var app = express();
.......
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
</code>```

and this is my api code:

```<code>var jsonwebtoken = require('jsonwebtoken');

function createToken(user){
    jsonwebtoken.sign({
        _id: user._id,
        name: user.name,
        username: user.username
    }, secretKey,{
        expiresIn: '144000000m'
    });

    return jsonwebtoken;
};
    api.post('/login',function(req,res){

        User.findOne({
            username: req.body.username
            }).select('password').exec(function(err,user){
                if (err)
                {
                    res.send(err);
                }
                else if (!user) {
                    res.send({message : "User dosen't exist."});
                }
                else if (user){
                    var validPassword = user.comparePassword(req.body.password);
                    if (!validPassword)
                    {
                        res.send({ message : "Password is incorrect." });
                    }
                    else
                    {
                        ///// token
                        var token= createToken(user);
                        if (token)
                        {
                        res.json({
                            success: true,
                            message: "Successfuly login!",
                            token: token
                        });
                        }

                        else
                        {
                            console.log('error');
                        }
                    }
                }
            })
        });
</code>```

In fact at the end I get this message from 'postman':

```<code>{
    "success": true,
    "message": "Successfuly login!",
    "token": {}
}
</code>```

as you can see, the token is empty.
thanks!

答:
In createToken(), you need to return the token itself instead of the imported library, e.g:</p>

```<code>function createToken(user){
    return jsonwebtoken.sign({
        _id: user._id,
        name: user.name,
        username: user.username
    }, secretKey,{
        expiresIn: '144000000m'
    });
}
</code>```

Title: nodejs token is empty

Body:
I started studying nodejs and I ran into a problem,
when i post my login on 'postman' i got success message, but the token content is empty.
this is my server.js code:

var express = require('express');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var config = require('./config');
var mongoose = require('mongoose');
var app = express();
.......
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());

and this is my api code:

var jsonwebtoken = require('jsonwebtoken');

function createToken(user){
    jsonwebtoken.sign({
        _id: user._id,
        name: user.name,
        username: user.username
    }, secretKey,{
        expiresIn: '144000000m'
    });

    return jsonwebtoken;
};
    api.post('/login',function(req,res){

        User.findOne({
            username: req.body.username
            }).select('password').exec(function(err,user){
                if (err)
                {
                    res.send(err);
                }
                else if (!user) {
                    res.send({message : "User dosen't exist."});
                }
                else if (user){
                    var validPassword = user.comparePassword(req.body.password);
                    if (!validPassword)
                    {
                        res.send({ message : "Password is incorrect." });
                    }
                    else
                    {
                        ///// token
                        var token= createToken(user);
                        if (token)
                        {
                        res.json({
                            success: true,
                            message: "Successfuly login!",
                            token: token
                        });
                        }

                        else
                        {
                            console.log('error');
                        }
                    }
                }
            })
        });

In fact at the end I get this message from 'postman':

{
    "success": true,
    "message": "Successfuly login!",
    "token": {}
}

as you can see, the token is empty.
thanks!

Body:
In createToken(), you need to return the token itself instead of the imported library, e.g:

function createToken(user){
    return jsonwebtoken.sign({
        _id: user._id,
        name: user.name,
        username: user.username
    }, secretKey,{
        expiresIn: '144000000m'
    });
}


问:
How to find the branch a git commit is on? (Using libgit2sharp)
For a research project, I've been trying to replicate the graph view present in version control software like SourceTree or TortoiseGit.

The graph view I'm trying to implement

The biggest problem I'm having is finding what branch a commit belongs to. If I have this, I can assign the commit dot a column and a color. This is difficult because under the hood, Git doesn't store the branch the commit was initially on.

Looking at other solutions on StackOverflow, I found it is possible to get a list of branches that contain the commit, but I need a method of isolating a single one to display in my graph. In the same way SourceTree or TortoiseGit somehow manage to do it.

My problem is also identical to this one, Find out the branch a commit belongs to in LibGit2Sharp?

It looks like they discovered the actual solution in a private discussion room. However, I don't have the reputation to comment and ask what they found.

Does anyone have any ideas on how I could do this?

Or, @nulltoken if by chance you see this and remember, do you know what you guys discovered in that discussion room?

答:
Not sure how much of helpful this answer would prove to you. The LibGit2Sharp equivalent call for "git branch --contains $SHA1" is a requested feature on GitHub, an open one!

Long back, I used a query over all refs like this, but for your use-case it might be prohibitively slow.

I was trying to think for possible ways to mitigate this problem, could not come up with any guiding light. :(  And then I discovered this comment which asserts that you need to traverse the DAG and validate the actual branch which has the commit. It all hints that you would need to go the slow traverse-all-refs approach.


问:
How to apply query to model if field not filtered
I have a range of modules running on generator.yml. In some of those I would like to hide records by default of Status: CLOSED (being the last of a range of Statuses). OF course if the user filters for CLOSED i want to show these records.

I thought it would make sense to apply andWhere('status_id=?',Status::CLOSED) in a specific table_method , but how do I access the filters of the module from within the model?

Is there a better way to do this?

答:
I think you can create a new field e.g. 'showClosedStatus' (you ll need to add the widget and validator in the form)
then add getFilterDefaults() in the generatorconfiguration with

public function getFilterDefaults() {

    return array('showClosedStatus' => 'false');

}

then add the
function addShowClosedStatusColumnQuery(Doctrine_Query $q, $field, $value){

if($value == false){

$q->andWhere('status!=closed')

}


问:
Are services also destroyed when the component providing them gets destroyed?
Suppose we have the following code:

```<code>@Component(
    // ..
    providers: [SomeService]
)
export class SomeComponent {
    constructor(someService: SomeService) {}
}
</code>```

Will the someService instance be destroyed whenever SomeComponent is destroyed? Or should one manually destroy it through onDestroy() hook?

答:
Yes they do, check out this example

You can check yourself with the ngOnDestroy hook in your service:

```<code>class SomeService{
  ngOnDestroy() {
    console.log('Service destroy')
  }
}
</code>```

Body:
Suppose we have the following code:

@Component(
    // ..
    providers: [SomeService]
)
export class SomeComponent {
    constructor(someService: SomeService) {}
}

Will the someService instance be destroyed whenever SomeComponent is destroyed? Or should one manually destroy it through onDestroy() hook?

Body:
Yes they do, check out this example

You can check yourself with the ngOnDestroy hook in your service:

class SomeService{
  ngOnDestroy() {
    console.log('Service destroy')
  }
}


问:
Convert Scatter to Contour, every dot turns into a highland
How to build a Contour plot (specifically, topographic map) based on a Scatter plot, so that every scatter dot is converted into a circular area being the highest one in a given radius, i.e., any adjoining area is lower than the original dot’s area?

On the exemplary image, the yellow adjoining area is lower than the highland #6. Note, I am not trying to build a data density plot.

All input scatter dots are higher than the green grass level.

I tried to interpolate the x, y, and z coordinates using matplotlib’s griddata as proposed in question Make contour of scatter.
On the second figure you see the original superimposed scatter plot and contour plot generated after interpolation. However, the dot #6 is not the highest one like it is on the first image, and the snow-capped mountain is shifted from the original white dot #1.

Here are my coordinates:

```<code>x = [34, 74, 34, 70, 4, 42, 10, 56, 50, 0, 15, 104, 53, 27]
y = [44, 52, 21, 25, 34, 54, 70, 77, 0, 50, 5, 53, 18, 86]
z = [0.9, 0.8, 0.8, 0.8, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6]
</code>```

Any ideas are highly appreciated.

答:
I use bivariate_normal function to get elevation for each point. Here is the working code to try:

```<code>import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

# data
x = np.array([34, 74, 34, 70, 4, 42, 10, 56, 50, 0, 15, 104, 53, 27])
y = np.array([44, 52, 21, 25, 34, 54, 70, 77, 0, 50, 5, 53, 18, 86])
z = np.array([0.9, 0.8, 0.8, 0.9, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6])

# the radius that needs to specified for each point
# radius = sigmax=sigmay for bivariate_normal
#rad = [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]  # OK
rad = [4, 6, 7, 3, 5, 5, 7, 6, 6, 7, 6, 7, 6, 7]   # better

# get limits of plot
xmin, xmax = x.min(), x.max()
ymin, ymax = y.min(), y.max()

# some settings
delta = 0.5

# create mesh grid for plotting area
xs = np.arange(xmin-delta, xmax+delta*2, delta)
ys = np.arange(ymin-delta, ymax+delta*2, delta)
XX, YY = np.meshgrid(xs, ys)

# compute elevation Z for each point in the grid mesh
ZZ=0
for mx, my, mz, mr in zip(x, y, z, rad):
    sigmax = mr
    sigmay = mr
    vm = mlab.bivariate_normal(0, 0, sigmax, sigmay, 0, 0)  # max value

    # mz and vm are used to correct the elevation obtained from bivar-normal
    ZZ += mlab.bivariate_normal(XX, YY, sigmax, sigmay, mx, my) * mz / vm

# prep fig, ax
fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111)

# choose cmap as you need
ctf=plt.contourf(XX, YY, ZZ, linewidth=1, cmap=cm.gist_earth_r)
plt.scatter(x, y, s=rad, color='r', zorder=10)

plt.xlim(xmin-delta, xmax+delta)
plt.ylim(ymin-delta, ymax+delta)

plt.colorbar(ctf)
plt.show()
</code>```

The resulting plot:

Body:
How to build a Contour plot (specifically, topographic map) based on a Scatter plot, so that every scatter dot is converted into a circular area being the highest one in a given radius, i.e., any adjoining area is lower than the original dot’s area?

On the exemplary image, the yellow adjoining area is lower than the highland #6. Note, I am not trying to build a data density plot.

All input scatter dots are higher than the green grass level.

I tried to interpolate the x, y, and z coordinates using matplotlib’s griddata as proposed in question Make contour of scatter.
On the second figure you see the original superimposed scatter plot and contour plot generated after interpolation. However, the dot #6 is not the highest one like it is on the first image, and the snow-capped mountain is shifted from the original white dot #1.

Here are my coordinates:

x = [34, 74, 34, 70, 4, 42, 10, 56, 50, 0, 15, 104, 53, 27]
y = [44, 52, 21, 25, 34, 54, 70, 77, 0, 50, 5, 53, 18, 86]
z = [0.9, 0.8, 0.8, 0.8, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6]

Any ideas are highly appreciated.

Body:
I use bivariate_normal function to get elevation for each point. Here is the working code to try:

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

# data
x = np.array([34, 74, 34, 70, 4, 42, 10, 56, 50, 0, 15, 104, 53, 27])
y = np.array([44, 52, 21, 25, 34, 54, 70, 77, 0, 50, 5, 53, 18, 86])
z = np.array([0.9, 0.8, 0.8, 0.9, 0.7, 0.7, 0.7, 0.7, 0.7, 0.6, 0.6, 0.6, 0.6, 0.6])

# the radius that needs to specified for each point
# radius = sigmax=sigmay for bivariate_normal
#rad = [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7]  # OK
rad = [4, 6, 7, 3, 5, 5, 7, 6, 6, 7, 6, 7, 6, 7]   # better

# get limits of plot
xmin, xmax = x.min(), x.max()
ymin, ymax = y.min(), y.max()

# some settings
delta = 0.5

# create mesh grid for plotting area
xs = np.arange(xmin-delta, xmax+delta*2, delta)
ys = np.arange(ymin-delta, ymax+delta*2, delta)
XX, YY = np.meshgrid(xs, ys)

# compute elevation Z for each point in the grid mesh
ZZ=0
for mx, my, mz, mr in zip(x, y, z, rad):
    sigmax = mr
    sigmay = mr
    vm = mlab.bivariate_normal(0, 0, sigmax, sigmay, 0, 0)  # max value

    # mz and vm are used to correct the elevation obtained from bivar-normal
    ZZ += mlab.bivariate_normal(XX, YY, sigmax, sigmay, mx, my) * mz / vm

# prep fig, ax
fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111)

# choose cmap as you need
ctf=plt.contourf(XX, YY, ZZ, linewidth=1, cmap=cm.gist_earth_r)
plt.scatter(x, y, s=rad, color='r', zorder=10)

plt.xlim(xmin-delta, xmax+delta)
plt.ylim(ymin-delta, ymax+delta)

plt.colorbar(ctf)
plt.show()

The resulting plot:


问:
How to print a 2d array horizontally multiple times
I am using java and I would like to print a 2d array horizontally multiple time based on user input. However, my array prints vertically, can anyone help? </p>

```<code>    n=3; //user input
    char[][] board = new char[2][3];
    char[][] f = new char[board.length][n * board[0].length];
    for (int i = 1; i < n + 1; i++) {
        int Start = (i * board[0].length) - board[0].length;
        int End = i * board[0].length;
        for (int row = 0; row < f.length; row++) {
            for (int col = nStart; col < nEnd; col++) {
                f[row][col] = board[row][col - nStart];
                System.out.print(f[row][col]);
            }
            System.out.println();
        }
    }
For example board array =
xx
xx
I would like
xxxxxx
xxxxxx
</code>```

答:
If you want to print 2d array horizontally, you have to repeat printing row n times before next row:

```<code>int n = 3; // user input
char[][] board = new char[][] { { 'x', 'x', 'x' }, { '0', '0', '0' } }; //example board

for (int row = 0; row < board.length; row++)
{
    for (int i = 0; i < n; i++)
    {
        for (int col = 0; col < board[row].length; col++)
        {
            System.out.print(board[row][col]);
        }
        System.out.print("\t"); //arrays separated by tab
    }
    System.out.println();
}
</code>```

Output:

```<code>xxx xxx xxx
000 000 000
</code>```

I hope this help.

Body:
I am using java and I would like to print a 2d array horizontally multiple time based on user input. However, my array prints vertically, can anyone help?

    n=3; //user input
    char[][] board = new char[2][3];
    char[][] f = new char[board.length][n * board[0].length];
    for (int i = 1; i < n + 1; i++) {
        int Start = (i * board[0].length) - board[0].length;
        int End = i * board[0].length;
        for (int row = 0; row < f.length; row++) {
            for (int col = nStart; col < nEnd; col++) {
                f[row][col] = board[row][col - nStart];
                System.out.print(f[row][col]);
            }
            System.out.println();
        }
    }
For example board array =
xx
xx
I would like
xxxxxx
xxxxxx

Body:
If you want to print 2d array horizontally, you have to repeat printing row n times before next row:

int n = 3; // user input
char[][] board = new char[][] { { 'x', 'x', 'x' }, { '0', '0', '0' } }; //example board

for (int row = 0; row < board.length; row++)
{
    for (int i = 0; i < n; i++)
    {
        for (int col = 0; col < board[row].length; col++)
        {
            System.out.print(board[row][col]);
        }
        System.out.print("\t"); //arrays separated by tab
    }
    System.out.println();
}

Output:

xxx xxx xxx
000 000 000

I hope this help.


答:
You can use year function on datetime:

```<code>SELECT *
FROM table
WHERE year(entrytime) = 2017
</code>```

or better:

```<code>SELECT *
FROM table
WHERE entrytime >= '2017-01-01'
AND entrytime < '2018-01-01'
</code>```

The latter can make use of index if present on the entrytime column, which can make your query run faster.

Body:
I would like to get every data from a table where the year is specified. But the problem is i put my date in DATETIME type.

I'm trying something like:

SELECT
    *
FROM
    table
WHERE
    entrytime = 2017 //entrytime is datetime type.

But, it's wrong.

Is there any way to get the data or maybe a better approach ?

Thank you.

Body:
You can use year function on datetime:

SELECT *
FROM table
WHERE year(entrytime) = 2017

or better:

SELECT *
FROM table
WHERE entrytime >= '2017-01-01'
AND entrytime < '2018-01-01'

The latter can make use of index if present on the entrytime column, which can make your query run faster.