问:
No getting desired XML output in Java
I am converting CSV file to XML , it is converting but not getting desired structured output .

My java Code :-

```<code>    public static void main(String[] args){
    List<String> headers=new ArrayList<String>(5);

    File file=new File("C:/Users/Admin/Desktop/data.csv");
    BufferedReader reader=null;

    try {

        DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance();
        DocumentBuilder domBuilder=domFactory.newDocumentBuilder();

        Document newDoc=domBuilder.newDocument();
        // Root element
        Element rootElement=newDoc.createElement("root");
        newDoc.appendChild(rootElement);

        reader = new BufferedReader(new FileReader(file));
        int line=0;

        String text=null;
        while ((text=reader.readLine())!=null) {

            StringTokenizer st=new StringTokenizer(text, "?", false);
            String[] rowValues=new String[st.countTokens()];
            int index=0;
            while (st.hasMoreTokens()) {

                String next=st.nextToken();
                rowValues[index++]=next;

            }

            //String[] rowValues = text.split(",");

            if (line == 0) { // Header row
                for (String col:rowValues) {
                    headers.add(col);

                    Element rowElement=newDoc.createElement("header");
                    rootElement.appendChild(rowElement);

                    for (int col1=0;col1<headers.size();col1++) {
                        String header = headers.get(col1);
                        String value = null;

                        if (col1<rowValues.length) {
                            value=rowValues[col1];
                        } else {
                            // ?? Default value
                            value=" ";
                        }
                        rowElement.setTextContent(value);
                        System.out.println(headers+" "+value);
                }

                }} else { // Data row
                Element rowElement=newDoc.createElement("row");
                rootElement.appendChild(rowElement);

                for (int col=0;col<headers.size();col++) {
                    String header = headers.get(col);
                    String value = null;

                    if (col<rowValues.length) {
                        value=rowValues[col];
                    } else {
                        // ?? Default value
                        value=" ";
                    }
                    rowElement.setTextContent(value);
                    System.out.println(header+" "+value);

                }
            }
            line++;
        }

        try {

            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
            aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            Source src = new DOMSource(newDoc);
            Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

          aTransformer.transform(src, result);
          System.out.println("File creation successfully!");

        } catch (Exception exp) {
            exp.printStackTrace();
        } finally {
            try {

            } catch (Exception e1) {
            }
            try {

            } catch (Exception e1) {
            }
        }
    } catch (Exception e1) {
        e1.printStackTrace();
}

}
</code>```

This is my CSV file:-

```<code>Symbol,Open,High,Low,Last Traded Price,Change
"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"
"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"
"BPCL","647.70","665.00","645.95","660.10","10.75"
"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"
"ONGC","159.50","161.75","159.35","160.80","1.70"
</code>```

And this is the output I am getting:-

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    <header>Symbol,Open,High,Low,Last Traded Price,Change</header>
    <row>"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"</row>
    <row>"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"</row>
    <row>"BPCL","647.70","665.00","645.95","660.10","10.75"</row>
    <row>"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"</row>
    <row>"ONGC","159.50","161.75","159.35","160.80","1.70"</row>
</root>
</code>```

Suggest me where am I going wrong ? I tried according to me , but getting confuse where in header and row section should I make changes.

ADDED :-
Expected output

```<code><root>
<header>symbol</header>
 <row>NIFTY 50</row>
 <row>RELIANCE</row>
 <row>BPCL></row>
 .
 .
 <header>Open</header>
 <row>9,645.90</row>
 <row>1,390.00</row>
 .
 .
 </root>
</code>```

答:
For your reference:

```<code>import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CsvToXml {

    public static void main(String[] args) {
        File inputFile = new File("C:/Users/Admin/Desktop/data.csv");
        CSVParser inParser = null;
        Document newDoc = null;
        try {
            inParser = CSVParser.parse(inputFile, StandardCharsets.UTF_8,
                    CSVFormat.EXCEL.withHeader().withQuoteMode(QuoteMode.NON_NUMERIC));
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

            newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("root");
            newDoc.appendChild(rootElement);
            List<CSVRecord> records = inParser.getRecords();
            for (String key : inParser.getHeaderMap().keySet()) {
                Element rowElement = newDoc.createElement("header");
                rootElement.appendChild(rowElement);
                rowElement.setTextContent(key);
                for (CSVRecord record : records) {
                    rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);
                    rowElement.setTextContent(record.get(key));
                }
            }
            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
            aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            Source src = new DOMSource(newDoc);
            Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

            aTransformer.transform(src, result);
            System.out.println("File creation successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inParser != null) {
                try {
                    inParser.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
</code>```

This is using Apache Commons CSV.

Title: No getting desired XML output in Java

Body:
I am converting CSV file to XML , it is converting but not getting desired structured output .

My java Code :-

    public static void main(String[] args){
    List<String> headers=new ArrayList<String>(5);

    File file=new File("C:/Users/Admin/Desktop/data.csv");
    BufferedReader reader=null;

    try {

        DocumentBuilderFactory domFactory =DocumentBuilderFactory.newInstance();
        DocumentBuilder domBuilder=domFactory.newDocumentBuilder();

        Document newDoc=domBuilder.newDocument();
        // Root element
        Element rootElement=newDoc.createElement("root");
        newDoc.appendChild(rootElement);

        reader = new BufferedReader(new FileReader(file));
        int line=0;

        String text=null;
        while ((text=reader.readLine())!=null) {

            StringTokenizer st=new StringTokenizer(text, "?", false);
            String[] rowValues=new String[st.countTokens()];
            int index=0;
            while (st.hasMoreTokens()) {

                String next=st.nextToken();
                rowValues[index++]=next;

            }

            //String[] rowValues = text.split(",");

            if (line == 0) { // Header row
                for (String col:rowValues) {
                    headers.add(col);

                    Element rowElement=newDoc.createElement("header");
                    rootElement.appendChild(rowElement);

                    for (int col1=0;col1<headers.size();col1++) {
                        String header = headers.get(col1);
                        String value = null;

                        if (col1<rowValues.length) {
                            value=rowValues[col1];
                        } else {
                            // ?? Default value
                            value=" ";
                        }
                        rowElement.setTextContent(value);
                        System.out.println(headers+" "+value);
                }

                }} else { // Data row
                Element rowElement=newDoc.createElement("row");
                rootElement.appendChild(rowElement);

                for (int col=0;col<headers.size();col++) {
                    String header = headers.get(col);
                    String value = null;

                    if (col<rowValues.length) {
                        value=rowValues[col];
                    } else {
                        // ?? Default value
                        value=" ";
                    }
                    rowElement.setTextContent(value);
                    System.out.println(header+" "+value);

                }
            }
            line++;
        }

        try {

            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
            aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            Source src = new DOMSource(newDoc);
            Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

          aTransformer.transform(src, result);
          System.out.println("File creation successfully!");

        } catch (Exception exp) {
            exp.printStackTrace();
        } finally {
            try {

            } catch (Exception e1) {
            }
            try {

            } catch (Exception e1) {
            }
        }
    } catch (Exception e1) {
        e1.printStackTrace();
}

}

This is my CSV file:-

Symbol,Open,High,Low,Last Traded Price,Change
"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"
"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"
"BPCL","647.70","665.00","645.95","660.10","10.75"
"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"
"ONGC","159.50","161.75","159.35","160.80","1.70"

And this is the output I am getting:-

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
    Symbol,Open,High,Low,Last Traded Price,Change
    <row>"NIFTY 50","9,645.90","9,650.65","9,600.95","9,609.30","-5.70"</row>
    <row>"RELIANCE","1,390.00","1,414.20","1,389.00","1,407.55","26.50"</row>
    <row>"BPCL","647.70","665.00","645.95","660.10","10.75"</row>
    <row>"ADANIPORTS","368.50","373.80","368.00","372.25","4.25"</row>
    <row>"ONGC","159.50","161.75","159.35","160.80","1.70"</row>
</root>

Suggest me where am I going wrong ? I tried according to me , but getting confuse where in header and row section should I make changes.

ADDED :-
Expected output

<root>
symbol
 <row>NIFTY 50</row>
 <row>RELIANCE</row>
 <row>BPCL></row>
 .
 .
 Open
 <row>9,645.90</row>
 <row>1,390.00</row>
 .
 .
 </root>

Body:
For your reference:

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.csv.QuoteMode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class CsvToXml {

    public static void main(String[] args) {
        File inputFile = new File("C:/Users/Admin/Desktop/data.csv");
        CSVParser inParser = null;
        Document newDoc = null;
        try {
            inParser = CSVParser.parse(inputFile, StandardCharsets.UTF_8,
                    CSVFormat.EXCEL.withHeader().withQuoteMode(QuoteMode.NON_NUMERIC));
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();

            newDoc = domBuilder.newDocument();
            // Root element
            Element rootElement = newDoc.createElement("root");
            newDoc.appendChild(rootElement);
            List<CSVRecord> records = inParser.getRecords();
            for (String key : inParser.getHeaderMap().keySet()) {
                Element rowElement = newDoc.createElement("header");
                rootElement.appendChild(rowElement);
                rowElement.setTextContent(key);
                for (CSVRecord record : records) {
                    rowElement = newDoc.createElement("row");
                    rootElement.appendChild(rowElement);
                    rowElement.setTextContent(record.get(key));
                }
            }
            TransformerFactory tranFactory = TransformerFactory.newInstance();
            Transformer aTransformer = tranFactory.newTransformer();
            aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            aTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
            aTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

            Source src = new DOMSource(newDoc);
            Result result = new StreamResult(new File("C:/Users/Admin/Desktop/data.xml"));

            aTransformer.transform(src, result);
            System.out.println("File creation successfully!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inParser != null) {
                try {
                    inParser.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

This is using Apache Commons CSV.


来源: stackexchange

问:
how do you use the IF COMMAND to convert a date from 5/1/2017 to 05012017 in microsoft access?
how do you use the IF COMMAND to convert a date from 5/1/2017 to 05012017 in microsoft access?</p>

答:
You don't. Format is for this if month is May:

```<code>TextDate = Format(YourDateValue, "mmddyyyy")
</code>```

or, if month is January:

```<code>TextDate = Format(YourDateValue, "ddmmyyyy")
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You don't. Format is for this if month is May:

TextDate = Format(YourDateValue, "mmddyyyy")

or, if month is January:

TextDate = Format(YourDateValue, "ddmmyyyy")


问:
Bootstrap navbar 3 level menu hover issue
I have created a bootstrap menu by referring from Bootstrap 3 dropdown sub menu missing but slightly in a different way. It is working fine on hovering through menus and submenus. However, if I click on any Menu items which has a submenu and then hover to other Menu, then submenus of both menus remain opened( the previous submenu gets closed on click but not on hover on new menu). I tried to fix this issue by adding a click event on hovering on the menu which has submenus.It fixed my problem partially. It closes the submenu of previously clicked(not hovered) menu, but background color of the previous menu doesn't get changed to original color.I am adding working code here with my jquery fix commented. Just copy this code in any HTML file and run. </p>

```<code>    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"  crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"  crossorigin="anonymous"></script>
</head>
<body>
<style typ="text/css">
.nav > li > a, .dropdown-menu > li > a, .nav .open > a
{
    height: auto;
    display: block;
    padding-top: 4px;
    padding-bottom: 4px;
    padding-left: 5px;
    padding-right: 10px;
    text-decoration: none;
    color: #284e36;
    line-height: normal;
    background-color: transparent;
    border-bottom: 2px solid white;
}

.nav > li, .dropdown-menu > li, .nav .open
{
    color: #284e36;
    border: none;
    background-color: #F9F9F9;
}

.nav > li > a:active, .dropdown-menu > li > a:active, .nav .open > a:active, .nav > li > a:focus, .dropdown-menu > li > a:focus, .nav .open > a:focus
{
    background-color: #CCCCCC;
    color: #001e06;
    border: none;
    border-bottom: 2px solid white;
    margin-left:0;
}

.nav > li > a:hover, .dropdown-menu > li > a:hover, .nav .open > a:hover
{
    background-color: #CCCCCC;
    color: #001e06;
    border: none;
    border-bottom: 2px solid white;
    margin-left:0;
}

.navbar-inverse
{
    background-color: white;
    border-color: white;
}

.navbar
{
    border-radius: 0px;
}

.dropdown-menu
{
    padding: 0;
}

/*https://stackoverflow.com/questions/18023493/bootstrap-3-dropdown-sub-menu-missing*/
.dropdown-submenu {
    position:relative;
}
.dropdown-submenu:hover>.dropdown-menu {
    display:block;
}
/* For desktop and ipad */
@media all and (min-width: 768px)
{

    .dropdown-menu
    {
        margin: 0;
        left: 100%;
        top: 0;
    }

    .nav > li > a, .dropdown-menu > li > a, .nav .open > a
    {
        padding-top: 4px;
        padding-bottom: 4px;
    }
}

@media all and (max-width: 767px)
{

    .dropdown-menu
    {
        left: 20%;
        top: 90%;
        width: 100%;
        border: 1px solid white;
    }
}

</style>
<div class="navbar navbar-inverse navbar-default" style="width:300px">
   <ul class="nav">
      <li><a  href="Home.aspx" >Home</a></li>
      <li class="dropdown-submenu">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown"  role="button" aria-haspopup="true" aria-expanded="false"  >Menu 1 <span class="caret"></span>  </a>
         <ul class="dropdown-menu" >
            <li><a href="SubMenu1.aspx">SubMenu 11</a></li>
            <li class="dropdown-submenu">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown"  role="button" aria-haspopup="true" aria-expanded="false"  >Sub Menu 12<span class="caret"></span>  </a>
               <ul class="dropdown-menu" >
                  <li><a href="SubMenu121.aspx">Sub Menu 121</a></li>
                  <li><a href="SubMenu122.aspx">Sub Menu 122</a></li>
               </ul>
            </li>
            <li class="dropdown-submenu">
               <a href="#" class="dropdown-toggle" data-toggle="dropdown"  role="button" aria-haspopup="true" aria-expanded="false"  >Sub Menu 13<span class="caret"></span>  </a>
               <ul class="dropdown-menu" >
                  <li><a href="SubMenu131.aspx">Sub Menu 131</a></li>
                  <li><a href="SubMenu132.aspx">Sub Menu 132</a></li>
               </ul>
            </li>
            <li><a href="SubMenu14.aspx">Sub Menu 14</a></li>
            <li><a href="SubMenu15.aspx">Sub Menu 15 </a></li>
            <li><a href="SubMenu16.aspx">Sub Menu 16</a></li>
            <li><a href="SubMenu17.aspx">Sub Menu 17</a></li>
         </ul>
      </li>
      <li class="dropdown-submenu">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown"  role="button" aria-haspopup="true" aria-expanded="false"  >Menu 2<span class="caret"></span>  </a>
         <ul class="dropdown-menu" >
            <li><a href="SubMenu21.aspx">Sub Menu 21</a></li>
            <li><a href="SubMenu22.aspx">Sub Menu 21</a></li>
            <li><a href="SubMenu23.aspx">Sub Menu 23</a></li>
         </ul>
      </li>
      <li class="dropdown-submenu">
         <a href="#" class="dropdown-toggle" data-toggle="dropdown"  role="button" aria-haspopup="true" aria-expanded="false"  >Menu 3<span class="caret"></span>  </a>
         <ul class="dropdown-menu" >
            <li><a href="SubMenu31.aspx">Sub Menu 31</a></li>
            <li><a href="SubMenu32.aspx">Sub Menu 32</a></li>
            <li><a href="SubMenu33.aspx">Sub Menu 33</a></li>
         </ul>
      </li>
      <li><a  href="Menu.aspx" >Menu 4</a></li>
      <li><a  href="Menu.aspx" >Menu 5</a></li>
   </ul>
</div>
<!--
<script type="text/javascript">
           $(document).ready(function () {
               $('.dropdown-submenu').hover(function () {
                   $(this).click();
               });
           });
</script>
-->
</body>
</code>```

答:
if I understood you correctly. then you need to check this.

```<code> $('li').hover(function() {
      $(this).click();
 });
</code>```

DEMO https://jsfiddle.net/princesodhi/pegzte0h/

Body:
I have created a bootstrap menu by referring from Bootstrap 3 dropdown sub menu missing but slightly in a different way. It is working fine on hovering through menus and submenus. However, if I click on any Menu items which has a submenu and then hover to other Menu, then submenus of both menus remain opened( the previous submenu gets closed on click but not on hover on new menu). I tried to fix this issue by adding a click event on hovering on the menu which has submenus.It fixed my problem partially. It closes the submenu of previously clicked(not hovered) menu, but background color of the previous menu doesn't get changed to original color.I am adding working code here with my jquery fix commented. Just copy this code in any HTML file and run.

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"  crossorigin="anonymous">

Home

         Menu 1

SubMenu 11

               Sub Menu 12

Sub Menu 121

Sub Menu 122

               Sub Menu 13

Sub Menu 131

Sub Menu 132

Sub Menu 14

Sub Menu 15

Sub Menu 16

Sub Menu 17

         Menu 2

Sub Menu 21

Sub Menu 21

Sub Menu 23

         Menu 3

Sub Menu 31

Sub Menu 32

Sub Menu 33

Menu 4

Menu 5

Body:
if I understood you correctly. then you need to check this.

 $('li').hover(function() {
      $(this).click();
 });

DEMO https://jsfiddle.net/princesodhi/pegzte0h/


问:
How to Substract time from datetime
I am using a timezone based script where there is deadline based on timezones. Say for example a deadline is on 7th July at 6PM for a person in IST timezone. The deadline should be 1:30 less than 6pm in Dubai as per their timezone.

I have already calculated the difference between the two timezone difference. I am stuck at deducting that calculated time from the deadline time.

I have saved the timezones in +5:40 +4:00 -4:00 this format instead of using php default ones.

答:
Here's what I use to add and subtract time from a date.
First of all, I get the date from the database and then convert it to a DateTime object.

```<code>$date = new DateTime($date);
</code>```

I use add and a DateInterval to add time. Here's an example to add hours.

```<code>$date->add(new DateInterval("PT{$hoursToAdd}H"));
</code>```

And here's and example to subtract hours intead:

```<code>$date->sub(new DateInterval("PT{$hoursToSubstract}H"));
</code>```

Check this out to know how to work with DateInterval and add/subtract different times: http://php.net/manual/en/class.dateinterval.php

Title: How to Substract time from datetime

Body:
Here's what I use to add and subtract time from a date.
First of all, I get the date from the database and then convert it to a DateTime object.

$date = new DateTime($date);

I use add and a DateInterval to add time. Here's an example to add hours.

$date->add(new DateInterval("PT{$hoursToAdd}H"));

And here's and example to subtract hours intead:

$date->sub(new DateInterval("PT{$hoursToSubstract}H"));

Check this out to know how to work with DateInterval and add/subtract different times: http://php.net/manual/en/class.dateinterval.php


问:
Would this union work if char had stricter alignment requirements than int?
Recently I came across the following snippet, which is an attempt to ensure all bytes of i (nad no more) are accessible as individual elements of c:

```<code>union {
  int i;
  char c[sizeof(int)];
};
</code>```

Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char are more restrictive than that for int.

In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char (it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?

And would this stuff up the use of the union above?

Two things to note.

I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.

I'm using the term "byte" in the ISO C sense, where it's the width of a char, not necessarily 8 bits.

答:
Have a look at this thread. There, I questioned the usefulness of C Unions and there are some interesting insights. The important thing is that the Standard does not ensure the alignment of the different fields at all!

EDIT: paxdiablo, just noticed you were one of the guys answering that question, so you should probably be familiar with this limitation.

ContentLicense: CC BY-SA 2.5

Body:
Recently I came across the following snippet, which is an attempt to ensure all bytes of i (nad no more) are accessible as individual elements of c:

union {
  int i;
  char c[sizeof(int)];
};

Now this seems a good idea, but I wonder if the standard allows for the case where the alignment requirements for char are more restrictive than that for int.

In other words, is it possible to have a four-byte int which is required to be aligned on a four-byte boundary with a one-byte char (it is one byte, by definition, see below) required to be aligned on a sixteen-byte boundary?

And would this stuff up the use of the union above?

Two things to note.

I'm talking specifically about what the standard allows here, not what a sane implementor/architecture would provide.

I'm using the term "byte" in the ISO C sense, where it's the width of a char, not necessarily 8 bits.


问:
Use IF in a SQL view
I am wanting to create a view that calls a table-valued function. I want to use an IF functionX IS NOT NULL then proceed with the rest of the view. So far I can get it to work with a stored procedure which is awesome but the software I am writing this for can apparently not call a stored procedure. So i either need to place that stored procedure inside of a view OR create a view with an IF or CASE WHEN.

Here is my stored procedure with the function call, how can I nestle this into a view or turn it into a view? Whenever I try i get an incorrect syntax error

```<code>CREATE PROCEDURE [dbo].[doSomething]
AS

WITH Events AS (
    SELECT DISTINCT Name FROM taP1
    LEFT OUTER JOIN taP2 ON taP1.Id = taP2.Id
    WHERE (taP1.ADate BETWEEN DATEADD(DAY,3,GETDATE()) AND
    DATEADD(DAY,-1,GETDATE()))
)
    IF  dbo.GetCapacity2('X1') = 1 --FUNCTION
SELECT TOP 100
    taM.Name AS Name,
    taM.TypeId AS MediaTypeId,
    taMS.Name AS SetName,
    taD.Directory AS Directory,
    taMI.Filename AS Filename

FROM taMedia
    INNER JOIN taMI ON taM.Id = taMI.Id
    INNER JOIN taMS ON taMI.SetId = taMSet.SetId
    INNER JOIN taD ON taMI.Id = taD.Id
    LEFT OUTER JOIN taMU ON taM.Name = taMU.MediaName
    LEFT OUTER JOIN Events ON taM.Name = Events.Name
WHERE taMS.Name = 'X1'
    AND taMU.MUId IS NULL
    AND Events.Name IS NULL
    ORDER BY taM.Name
    ELSE return;

   GO
</code>```

答:
look on the sample down below. You can create view with 'if' statement as you need, but place your condition in WHERE. It should work as you want.</p>

```<code>CREATE FUNCTION dbo.ReturnTrue
()
RETURNS INT
AS BEGIN
    RETURN 1
END
GO

CREATE TABLE TableTmp (Id Int)
Insert Into TableTmp Values (1), (2), (4), (8), (16)
GO

CREATE VIEW [dbo].[ViewTmp]
AS
SELECT TOP 100
    *
FROM
    TableTmp T
WHERE
    T.Id > 1
    AND
    dbo.ReturnTrue() = 1
GO

Select *
From [dbo].[ViewTmp]
Go
</code>```

Title: Use IF in a SQL view

Body:
I am wanting to create a view that calls a table-valued function. I want to use an IF functionX IS NOT NULL then proceed with the rest of the view. So far I can get it to work with a stored procedure which is awesome but the software I am writing this for can apparently not call a stored procedure. So i either need to place that stored procedure inside of a view OR create a view with an IF or CASE WHEN.

Here is my stored procedure with the function call, how can I nestle this into a view or turn it into a view? Whenever I try i get an incorrect syntax error

CREATE PROCEDURE [dbo].[doSomething]
AS

WITH Events AS (
    SELECT DISTINCT Name FROM taP1
    LEFT OUTER JOIN taP2 ON taP1.Id = taP2.Id
    WHERE (taP1.ADate BETWEEN DATEADD(DAY,3,GETDATE()) AND
    DATEADD(DAY,-1,GETDATE()))
)
    IF  dbo.GetCapacity2('X1') = 1 --FUNCTION
SELECT TOP 100
    taM.Name AS Name,
    taM.TypeId AS MediaTypeId,
    taMS.Name AS SetName,
    taD.Directory AS Directory,
    taMI.Filename AS Filename

FROM taMedia
    INNER JOIN taMI ON taM.Id = taMI.Id
    INNER JOIN taMS ON taMI.SetId = taMSet.SetId
    INNER JOIN taD ON taMI.Id = taD.Id
    LEFT OUTER JOIN taMU ON taM.Name = taMU.MediaName
    LEFT OUTER JOIN Events ON taM.Name = Events.Name
WHERE taMS.Name = 'X1'
    AND taMU.MUId IS NULL
    AND Events.Name IS NULL
    ORDER BY taM.Name
    ELSE return;

   GO

Body:
look on the sample down below. You can create view with 'if' statement as you need, but place your condition in WHERE. It should work as you want.

CREATE FUNCTION dbo.ReturnTrue
()
RETURNS INT
AS BEGIN
    RETURN 1
END
GO

CREATE TABLE TableTmp (Id Int)
Insert Into TableTmp Values (1), (2), (4), (8), (16)
GO

CREATE VIEW [dbo].[ViewTmp]
AS
SELECT TOP 100
    *
FROM
    TableTmp T
WHERE
    T.Id > 1
    AND
    dbo.ReturnTrue() = 1
GO

Select *
From [dbo].[ViewTmp]
Go


问:
google geocode api returns "zero results" in C#
When I put this URL in the browser, I get an answer: https://maps.googleapis.com/maps/api/geocode/xml?address=15838+Am%20Mellensee%20OT%20Mellensee+Hauptstra%C3%9Fe%2016

But in C# I get "zero results":
DataSet ds = new DataSet();
ds.ReadXml("https://maps.googleapis.com/maps/api/geocode/xml?address=15838+Am%20Mellensee%20OT%20Mellensee+Hauptstra%C3%9Fe%2016");

earlier it works fine!
Has anyone an idea?

答:
Put string address without encoding spaces and other special symbols like</p>

```<code>var str = "https://maps.googleapis.com/maps/api/geocode/xml?address=15838+Am Mellensee OT Mellensee+Hauptstra";
ds.ReadXml(str);
</code>```

Body:
Put string address without encoding spaces and other special symbols like

var str = "https://maps.googleapis.com/maps/api/geocode/xml?address=15838+Am Mellensee OT Mellensee+Hauptstra";
ds.ReadXml(str);


问:
Different between keyword "new" and "default" in create instance of class
I have class like:

```<code> class foo
    {
        public foo(string Text)
        {
        }
    }
</code>```

After run this code for create instance of class the obj1 set to null:

```<code>foo obj1 = default(foo);
</code>```

And by blow code everything work fine:

```<code>foo obj2= new foo("bla bla");
</code>```

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.

答:
Here is how default works:

return null for
  reference types and zero for numeric value types. For structs, it will
  return each member of the struct initialized to zero or null depending
  on whether they are value or reference types. For nullable value
  types, default returns a System.Nullable<T>, which is initialized like
  any struct.

new operator just creates new instance of the class and initialize properties/fields as it's written in the constructor.

Used to create objects and invoke constructors.

Body:
I have class like:

 class foo
    {
        public foo(string Text)
        {
        }
    }

After run this code for create instance of class the obj1 set to null:

foo obj1 = default(foo);

And by blow code everything work fine:

foo obj2= new foo("bla bla");

I have 2 Question :

Whats happen to default contractor when run default(foo);?

Is foo obj1 = default(foo); equal the foo obj1 = null?

Thanks in advance.


问:
How to make this slider auto play
how can i make this java script code to auto play the slider and How to add mouse-over pause function

$(function() {
  $('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['', ''],
    dots: false,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
});```

答:
If you use this plugin https://owlcarousel2.github.io , add autoplay: true property for autoplay.

For pause on "mouseover", add autoplayHoverPause: true property:

```<code>$(function() {
  $('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['<i class="fa fa-chevron-left"></i>', '<i class="fa fa-chevron-right"></i>'],
    dots: false,
    autoplay: true,
    autoplayHoverPause: true,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
});
</code>```

Title: How to make this slider auto play

Body:
If you use this plugin https://owlcarousel2.github.io , add autoplay: true property for autoplay.

For pause on "mouseover", add autoplayHoverPause: true property:

$(function() {
  $('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['<i class="fa fa-chevron-left"></i>', '<i class="fa fa-chevron-right"></i>'],
    dots: false,
    autoplay: true,
    autoplayHoverPause: true,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
});


问:
PHP regular expression
I know a little regular expression. My question is:
I have a string which can be one of the followings-

```<code>$code = "123456 - US";
$code = "12-3456 - US";
$code = "WD123 - US";
$code = "A0-12 - US";
$code = "123456 - Poland";
</code>```

How can I find out the first part(like-123456 or A0-12) and the last part(like-US or Poland)?
In PHP using preg_match function.
Thanks.

答:
you could use explode to split it into two parts.

```<code>$split = explode(" - ",$code);
</code>```

That will give you an array with two elements: "123456" and "US"

Title: PHP regular expression

Body:
I know a little regular expression. My question is:
I have a string which can be one of the followings-

$code = "123456 - US";
$code = "12-3456 - US";
$code = "WD123 - US";
$code = "A0-12 - US";
$code = "123456 - Poland";

How can I find out the first part(like-123456 or A0-12) and the last part(like-US or Poland)?
In PHP using preg_match function.
Thanks.

Body:
you could use explode to split it into two parts.

$split = explode(" - ",$code);

That will give you an array with two elements: "123456" and "US"


问:
DI Constructor Injection Neatness
Okay so I am looking for some specific tips about Dependency Injection and how to use it.

Basically I have a MVC website which uses Ninject (and the Ninject MVC package). So when I am creating the MVC page I use constructor injection in the controllers. This is okay but IMO a bit 'ugly', but the main thing I don't like is having to pass all of the injected repositories into the other classes, it just seems a bit OTT having to pass like 6 repositories-8 repositories into a static method or object constructor.

Not to mention that on some of my pages I am having to work on almost every repository so the controller consructor gets huge and not the most manageable.

Are there any other options that wont clutter my code up as much? I don't really want to pass them in as single 'setting' objects either as that just moves the problem to a different line of code.

I also use the same class libraries for console/desktop applications. I like the idea of using DependencyResolver.Current in the class libraries but everyone says this is an anti-pattern and constructor injection should be used.

Maybe have an MyProjectDIContext class which has a dictionary which i can populate with the injected types in the controller constructors then pass the context to all methods as needed?

I have had a look for the answer bit I can't quite seem to find something that fits well.

答:
One of the great things about Constructor Injection is that it makes design and maintainability problems more obvious. When using constructor injection, it becomes very easy to see the amount of dependencies a class has, whereas without constructor injection, a class still has the same number of dependencies, but they are tucked away.

The problem you are seeing is called Constructor Over-injection and it's a design smell, because it indicates that you are violating the Single Responsibility Principle (SRP). The SRP guides in keeping your classes small, focussed and most of all: maintainable.

Are there any other options that wont clutter my code up as much?

Absolutely: make smaller classes. MVC controllers typically get huge when we use it to group methods of a certain concept, such as 'customer' or 'order'. This however means that a controller is an ever growing class that has to be changed for any new feature that arrives. This is a violation of the Open/closed Principle that tells we should strive to have a system where we can plugin new features without having to touch existing classes.

The solution therefore is not to revert to the Service Locator anti-pattern or Property Injection, but to create smaller classes that do one particular thing. Constructor Injection should be your primary way of applying Dependency Injection, even in class libraries.

Title: DI Constructor Injection Neatness


问:
How to call other REST APIs from your node micro-service and send the result as a response?
I am currently trying to implement a BFF (backend for front end architecture).

Using request-promise library I can successfully hit the other microservice but not able to return the result as a response from BFF microservice.

Each time it is returning this result Promise { pending } pending state, could somebody please help me out on this?

My main issue is to know how to receive data into BFF microservice from the other microservice that we are hitting and returning the result from microservice which is hitting other one.

Or if somebody could help me to let know how to access the result from inside .then of any promise?

The flow is like this:

```<code>client(ios/android)===(sends request)==>BFF Microservice==>BP microservice
</code>```

(BFF Microservice handles the request and returns the response on the basis of result received from other microservice)

Microservice code which is calling another microservice:

```<code>import yagmodel from '../../lib/models/yag-model'
import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'
import config from 'config'

//template below to call the REST APIs of other microservices.

export async function getAllBP (req,res) {
    let yagresponse// this varaible is defined to get data from inside(rs.then )

    const username= req.swagger.params.username.value
    const authheader= req.swagger.params.Authorization.value
    console.log("Authorization:"+authheader)

    let rs= await yagmodel.bp(username,authheader)
    console.log(rs)

    rs.then((response)=>{
        // console.log(response.body)
        yagresponse=response.body
        //console.log(rsp)
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })

    res.status(200).send(yagresponse)
}
</code>```

yag-model.js code:

```<code>import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'

module.exports.bp = async function getBP(username,authheader){
    const options={
        uri: `http://localhost:4000/Health/BP/`+username,
        json: true,
        resolveWithFullResponse: true,
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json; charset=utf-8',
            'Authorization':authheader
        },
        method: 'GET'
    }

    return request(options).then ((response)=>{
        return response.body
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })
}
</code>```

答:
I think you mix to match await oprators with promises, when you can use only await.

I create simplefied version of your code:

yag-model.js

const request = require('request-promise');

module.exports.bp = async function getBP () {

    const options = {

        uri: `https://api.postcodes.io/random/postcodes`,
        json: true,
        resolveWithFullResponse: true,
        method: 'GET'
    };

    return request(options).then((response) => {

        return response.body

    }).catch((err) => {
        console.log(err);
        console.log('errorstatuscode:' + err.statusCode)
    })
};```
</div>
</div>
</p>

<p>and usgae in sample <code>bf.js</code></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const yagmodel = require('./yag-model');

async function getAll(){
    const result = await yagmodel.bp();
    console.log(result);
};

getAll();</code>```

And the result is the response on my console.

```<code>F:\Projekty\Learn\lear-node>node bf
{ status: 200,
result:
 { postcode: 'BH23 5DA',
   quality: 1,
   eastings: 420912,
</code>```

I recommend to look on this great resource about asunc functions http://exploringjs.com/es2016-es2017/ch_async-functions.html from Dr. Axel Rauschmayer

Body:
I am currently trying to implement a BFF (backend for front end architecture).

Using request-promise library I can successfully hit the other microservice but not able to return the result as a response from BFF microservice.

Each time it is returning this result Promise { pending } pending state, could somebody please help me out on this?

My main issue is to know how to receive data into BFF microservice from the other microservice that we are hitting and returning the result from microservice which is hitting other one.

Or if somebody could help me to let know how to access the result from inside .then of any promise?

The flow is like this:

client(ios/android)===(sends request)==>BFF Microservice==>BP microservice

(BFF Microservice handles the request and returns the response on the basis of result received from other microservice)

Microservice code which is calling another microservice:

import yagmodel from '../../lib/models/yag-model'
import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'
import config from 'config'

//template below to call the REST APIs of other microservices.

export async function getAllBP (req,res) {
    let yagresponse// this varaible is defined to get data from inside(rs.then )

    const username= req.swagger.params.username.value
    const authheader= req.swagger.params.Authorization.value
    console.log("Authorization:"+authheader)

    let rs= await yagmodel.bp(username,authheader)
    console.log(rs)

    rs.then((response)=>{
        // console.log(response.body)
        yagresponse=response.body
        //console.log(rsp)
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })

    res.status(200).send(yagresponse)
}

yag-model.js code:

import {errorsList} from '../../lib/errors/errorsList'
import request from 'request-promise'

module.exports.bp = async function getBP(username,authheader){
    const options={
        uri: `http://localhost:4000/Health/BP/`+username,
        json: true,
        resolveWithFullResponse: true,
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Accept': 'application/json; charset=utf-8',
            'Authorization':authheader
        },
        method: 'GET'
    }

    return request(options).then ((response)=>{
        return response.body
    }).catch((err)=>{
        console.log(err)
        console.log('errorstatuscode:'+err.statusCode)
    })
}

Body:
I think you mix to match await oprators with promises, when you can use only await.

I create simplefied version of your code:

yag-model.js

const request = require('request-promise');

module.exports.bp = async function getBP () {

    const options = {

        uri: `https://api.postcodes.io/random/postcodes`,
        json: true,
        resolveWithFullResponse: true,
        method: 'GET'
    };

    return request(options).then((response) => {

        return response.body

    }).catch((err) => {
        console.log(err);
        console.log('errorstatuscode:' + err.statusCode)
    })
};

and usgae in sample bf.js

const yagmodel = require('./yag-model');

async function getAll(){
    const result = await yagmodel.bp();
    console.log(result);
};

getAll();

And the result is the response on my console.

F:\Projekty\Learn\lear-node>node bf
{ status: 200,
result:
 { postcode: 'BH23 5DA',
   quality: 1,
   eastings: 420912,

I recommend to look on this great resource about asunc functions http://exploringjs.com/es2016-es2017/ch_async-functions.html from Dr. Axel Rauschmayer


问:
Get creation date and time of a folder in batch script
I am trying to get the creation date and time of a specific folder in Windows.
Based on this answer, I have tried the following:

```<code>@echo off
set path_of_folder="C:\folderA\folderB\"

if exist %path_of_folder% (
  echo Path exists.
  for /f "skip=5 tokens=1,2 delims= " %%a in ('dir /a-d /tc %path_of_folder%') do set "dt=%%a"
    echo Created on: %%a, %%b
  )
)
else (
  echo Path does not exist.
)

pause
</code>```

Where I get this output:

```<code>Path exists.
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 4, File(s)
Created on: 0, Dir(s)
</code>```

Which I am sure it shows the creation dates for each of the files (4 for my example) inside the folderB.

I am looking on saving the creation date and time only for the top folder folderB; can anyone suggest/show how this can be achieved and not get all the other creation date/times as well?

Note that on the answer given on the attached link, there is a exit /b 0 right after the echo Created on: %%a, %%b command which I cannot add on my script since there are several other commands I want to execute after I get the system date and time.

答:
Check dirtimejs.bat - it can print dir times independent from control panel settings:</p>

```<code>@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "tokens=1* delims=:" %%a in ('dirtimejs.bat "%path_of_folder%" ^| find "Created :"') do (
     echo %%a
)
</code>```

Body:
I am trying to get the creation date and time of a specific folder in Windows.
Based on this answer, I have tried the following:

@echo off
set path_of_folder="C:\folderA\folderB\"

if exist %path_of_folder% (
  echo Path exists.
  for /f "skip=5 tokens=1,2 delims= " %%a in ('dir /a-d /tc %path_of_folder%') do set "dt=%%a"
    echo Created on: %%a, %%b
  )
)
else (
  echo Path does not exist.
)

pause

Where I get this output:

Path exists.
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 05/07/2017, 17:42
Created on: 4, File(s)
Created on: 0, Dir(s)

Which I am sure it shows the creation dates for each of the files (4 for my example) inside the folderB.

I am looking on saving the creation date and time only for the top folder folderB; can anyone suggest/show how this can be achieved and not get all the other creation date/times as well?

Note that on the answer given on the attached link, there is a exit /b 0 right after the echo Created on: %%a, %%b command which I cannot add on my script since there are several other commands I want to execute after I get the system date and time.

Body:
Check dirtimejs.bat - it can print dir times independent from control panel settings:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
set "path_of_folder=C:\folderA\folderB"

for /f "tokens=1* delims=:" %%a in ('dirtimejs.bat "%path_of_folder%" ^| find "Created :"') do (
     echo %%a
)


问:
Determining the object type which send as parameter
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

```<code>public void Insert (City newCity)
</code>```

but I want it be like:

```<code>public void Insert (Entity e)
</code>```

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

答:
In C# 7.0 you could use Pattern Matching</p>

```<code>public void Insert(Entity e)
{
    switch (e)
    {
        case Person p:
            Console.WriteLine("Insert Person");
            break;
        case City c:
            Console.WriteLine("Insert City");
            break;

        default:
            Console.WriteLine("<other>");
            break;
    }
}
</code>```

Body:
I have three classes called Person, City and District, and some other.

I'm sending one of these three classes as a function parameter. I want to do an operation depends on which one of these three has been sended. How can I do that? All these three classes extends an Entity class.

Now it's like:

public void Insert (City newCity)

but I want it be like:

public void Insert (Entity e)

or something like that, and whichever it is (City or Person), I want to use it's properties.

Thank you!

Body:
In C# 7.0 you could use Pattern Matching

public void Insert(Entity e)
{
    switch (e)
    {
        case Person p:
            Console.WriteLine("Insert Person");
            break;
        case City c:
            Console.WriteLine("Insert City");
            break;

        default:
            Console.WriteLine("<other>");
            break;
    }
}


问:
How to change object property in a function with onclick in JavaScript
I am new to programming and I am trying to do something that is a bit overchallenging for me, so any help is appreciated.

I would like to use the Canvas Chess PGN viewer on a website which displays chessgames and make it possible for the users to go through the games. I want to use only one chessboard for different games, so I am trying to create onclick events that change the source property value in the chessboard script and make the script run again, but I cannot figure out how to do that.

It is the "pgn_uri" property that should be changed by clicking on the buttons, e.g. when the user clicks on "Round2" than it changes to "pgn_uri: secondGame", and so on. The script with the CHESS.PgnViewer() function should also run again so the chessboard gets updated.

```<code><button type="button" name="button" id="round1">Round1</button>
<button type="button" name="button" id="round2">Round2</button>
<button type="button" name="button" id="round3">Round3</button>

<script src="canvaschess\canvaschess-0.1.0.min.js"></script>
<script src="canvaschess\pgnviewer-0.1.0.min.js"></script>

<script type="text/javascript">
var firstGame = 'canvaschess/pgns/round1.pgn';
var secondGame = 'canvaschess/pgns/round2.pgn';
var thirdGame = 'canvaschess/pgns/round3.pgn';
</script>

<script>
var viewer = new CHESS.PgnViewer({
pgn_uri: firstGame,
square_color_dark: '#000',
square_color_light: '#fff',
square_uri_dark: 'canvaschess/img/themes/wood/square_dark.jpg',
square_uri_light: 'canvaschess/img/themes/wood/square_light.jpg',
show_labels: false,
show_tags: true
});
</script>
</code>```

答:
Adding click event in each button so probably this code

```<code>// Assume you have global variable name game
$('#btn1, #btn2, #btn3').on('click', function(){
   var btn_clicked = $(this).attr('id'); // get id value
   switch (btn_clicked) {
       case 'btn1':
          game = 'canvaschess/pgns/round1.pgn';
          break;
       case 'btn2':
          game = 'canvaschess/pgns/round2.pgn';
          break;
       case 'btn3':
          game = 'canvaschess/pgns/round3.pgn';
          break;
   }
});
</code>```

You can now pass the global variable to new CHESS.PgnViewer

Note: I didnt test this code hehehe!

Body:
I am new to programming and I am trying to do something that is a bit overchallenging for me, so any help is appreciated.

I would like to use the Canvas Chess PGN viewer on a website which displays chessgames and make it possible for the users to go through the games. I want to use only one chessboard for different games, so I am trying to create onclick events that change the source property value in the chessboard script and make the script run again, but I cannot figure out how to do that.

It is the "pgn_uri" property that should be changed by clicking on the buttons, e.g. when the user clicks on "Round2" than it changes to "pgn_uri: secondGame", and so on. The script with the CHESS.PgnViewer() function should also run again so the chessboard gets updated.

<button type="button" name="button" id="round1">Round1</button>
<button type="button" name="button" id="round2">Round2</button>
<button type="button" name="button" id="round3">Round3</button>

Body:
Adding click event in each button so probably this code

// Assume you have global variable name game
$('#btn1, #btn2, #btn3').on('click', function(){
   var btn_clicked = $(this).attr('id'); // get id value
   switch (btn_clicked) {
       case 'btn1':
          game = 'canvaschess/pgns/round1.pgn';
          break;
       case 'btn2':
          game = 'canvaschess/pgns/round2.pgn';
          break;
       case 'btn3':
          game = 'canvaschess/pgns/round3.pgn';
          break;
   }
});

You can now pass the global variable to new CHESS.PgnViewer

Note: I didnt test this code hehehe!


问:
How to cache googleapis.com using sw-precache runtimeCaching
I make use of material icons and roboto font on my site and I've been trying to cache it using sw-precache runtimeCaching API but it doesn't work, I'm not sure if I'm doing it right. I need my service worker to fetch these files from cache. Here's my code. I integrated it into my gulp task:

```<code>gulp.task('create-sw', ['watchCss', 'watchJS'], callback => {
    preCache.write(path.join('.', 'sw.js'), {
        runtimeCaching: [{
            urlPattern: /^https:\/\/fonts\.googleapis\.com$/,
            handler: 'cacheFirst',
            options: {
                cache: {
                    maxEntries: 10,
                    name: 'google-apis'
            }
        },
    }],
        staticFileGlobs: [
            './script.js',
            './manifest.json',
            './app/**/*.{html,json}',
            './dist/**/*.{js,css,eot,ttf,woff,woff2}',
            './**/*.{png,jpeg,jpg,svg,gif}',
            './index.html',
        ],
        stripPrefix: '.',
        maximumFileSizeToCacheInBytes: 15000000,
    }, callback)
});
</code>```

I'm trying to cache these links:

```<code><link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
</code>```

答:
This is my GULP task that generates cache for Instagram images:

```<code>gulp.task('generate-service-worker', function(callback) {
var swPrecache = require('sw-precache');
var rootDir = 'app';

swPrecache.write(`${rootDir}/service-worker.js`, {
    staticFileGlobs: [rootDir + '/**/*.{php,js,html,css,png,jpg,gif,svg,eot,ttf,woff,json}', './'],
    stripPrefix: rootDir,
    directoryIndex: false,
    maximumFileSizeToCacheInBytes: 10097152,
    runtimeCaching: [{
        urlPattern: /^https:\/\/scontent\.cdninstagram\.com/,
        handler: 'networkFirst',
        options: {
            cache: {
                maxEntries: 50,
                name: 'instagram-images-cache'
            }
        }
    }]
}, callback);
</code>```

});

Body:
I make use of material icons and roboto font on my site and I've been trying to cache it using sw-precache runtimeCaching API but it doesn't work, I'm not sure if I'm doing it right. I need my service worker to fetch these files from cache. Here's my code. I integrated it into my gulp task:

gulp.task('create-sw', ['watchCss', 'watchJS'], callback => {
    preCache.write(path.join('.', 'sw.js'), {
        runtimeCaching: [{
            urlPattern: /^https:\/\/fonts\.googleapis\.com$/,
            handler: 'cacheFirst',
            options: {
                cache: {
                    maxEntries: 10,
                    name: 'google-apis'
            }
        },
    }],
        staticFileGlobs: [
            './script.js',
            './manifest.json',
            './app/**/*.{html,json}',
            './dist/**/*.{js,css,eot,ttf,woff,woff2}',
            './**/*.{png,jpeg,jpg,svg,gif}',
            './index.html',
        ],
        stripPrefix: '.',
        maximumFileSizeToCacheInBytes: 15000000,
    }, callback)
});

I'm trying to cache these links:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">

Body:
This is my GULP task that generates cache for Instagram images:

gulp.task('generate-service-worker', function(callback) {
var swPrecache = require('sw-precache');
var rootDir = 'app';

swPrecache.write(`${rootDir}/service-worker.js`, {
    staticFileGlobs: [rootDir + '/**/*.{php,js,html,css,png,jpg,gif,svg,eot,ttf,woff,json}', './'],
    stripPrefix: rootDir,
    directoryIndex: false,
    maximumFileSizeToCacheInBytes: 10097152,
    runtimeCaching: [{
        urlPattern: /^https:\/\/scontent\.cdninstagram\.com/,
        handler: 'networkFirst',
        options: {
            cache: {
                maxEntries: 50,
                name: 'instagram-images-cache'
            }
        }
    }]
}, callback);

});


问:
Reading uncommitted transactions in Android
I have database heavy operations happening, which adds around 10,000 records to my Database. Since this could take a very long time, it would be better to use transactions.

```<code>db.startTransaction();
....
do write operations.
....
db.setTransactionSuccessful();
db.endTransaction();
</code>```

Now, I have some read operations inside the transactions, and since the inserts are not committed until endTransaction, those records are not fetched. I have heard about something called Transaction Isolation Levels, which enables us to read dirty (uncommitted) records as well. Any idea how to do this?

答:
I would advise call SQLite's SQL statement pragma:

```<code>database.execSQL("PRAGMA read_uncommitted = true;");
</code>```

This statement says that queries will use transaction isolation level READ_UNCOMMITTED instead of READ_SERIALIZABLE (default SQLite's mode).

Look for instance here

Body:
I have database heavy operations happening, which adds around 10,000 records to my Database. Since this could take a very long time, it would be better to use transactions.

db.startTransaction();
....
do write operations.
....
db.setTransactionSuccessful();
db.endTransaction();

Now, I have some read operations inside the transactions, and since the inserts are not committed until endTransaction, those records are not fetched. I have heard about something called Transaction Isolation Levels, which enables us to read dirty (uncommitted) records as well. Any idea how to do this?

Body:
I would advise call SQLite's SQL statement pragma:

database.execSQL("PRAGMA read_uncommitted = true;");

This statement says that queries will use transaction isolation level READ_UNCOMMITTED instead of READ_SERIALIZABLE (default SQLite's mode).

Look for instance here


问:
Javascript Confirm not Stopping request from post back if pressed cancel?
I am using Javascript function with confirm() message box and also having RequiredFieldValidator if I press cancel on my confirm message box but ValidatorGroup is true then it not stopping a request from getting post back.

I want to implement in such a way that If validatorGroup is treu but function return false then request should not get post back

Here is my Code:-

```<code><asp:Button ID="btnStaffSendRequest" runat="server" Text="Send" OnClientClick="UploadRefrrel()"
                        UseSubmitBehavior="false" ValidationGroup="SaveRequestGroup" OnClick="btnStaffSendRequest_OnClick"
                        TabIndex="1000" />
</code>```

Here is my Javascript Function:-

```<code><script language="javascript" type="text/javascript">

                            function UploadRefrrel() {
                                var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
                                var upload = $find("<%= radUploadFiles.ClientID %>");
                                var inputs = upload.getUploadedFiles();
                                var retVal;
                                if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
                                    retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
                                }
                                return retVal;
                            }
                        </script>
</code>```

答:
```<code><asp:CustomValidator ID="validatePostBack" runat="server" Display="None" ClientValidationFunction="Validate_PostBack"
                        ValidationGroup="SaveRequestGroup" ErrorMessage="<br /> Please add other attachment."></asp:CustomValidator>
                    <telerik:RadScriptBlock ID="uploadReferel" runat="server">
                    <script language="javascript" type="text/javascript">
                        function Validate_PostBack(sender, e) {
                            var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
                            var upload = $find("<%= radUploadFiles.ClientID %>");
                            var inputs = upload.getUploadedFiles();

                            if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
                                var retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
                                if (retVal == true) {
                                    e.IsValid = true;
                                }
                                else {
                                    e.IsValid = false;
                                }
                            }
                        }
                    </script>
                    </telerik:RadScriptBlock>
</code>```

<p>Found my solution and working fine </p>

Body:
I am using Javascript function with confirm() message box and also having RequiredFieldValidator if I press cancel on my confirm message box but ValidatorGroup is true then it not stopping a request from getting post back.

I want to implement in such a way that If validatorGroup is treu but function return false then request should not get post back

Here is my Code:-

<asp:Button ID="btnStaffSendRequest" runat="server" Text="Send" OnClientClick="UploadRefrrel()"
                        UseSubmitBehavior="false" ValidationGroup="SaveRequestGroup" OnClick="btnStaffSendRequest_OnClick"
                        TabIndex="1000" />

Here is my Javascript Function:-

Body:
<asp:CustomValidator ID="validatePostBack" runat="server" Display="None" ClientValidationFunction="Validate_PostBack"
                        ValidationGroup="SaveRequestGroup" ErrorMessage="<br /> Please add other attachment."></asp:CustomValidator>
                    <telerik:RadScriptBlock ID="uploadReferel" runat="server">
                    <script language="javascript" type="text/javascript">
                        function Validate_PostBack(sender, e) {
                            var hiddenFile = this.document.getElementById("<%= hfInputForm.ClientID %>");
                            var upload = $find("<%= radUploadFiles.ClientID %>");
                            var inputs = upload.getUploadedFiles();

                            if (hiddenFile != null && hiddenFile.value != "" && inputs.length == 0) {
                                var retVal = confirm("FYI - Only 'Referral Form' is attached. Do you want to proceed without any other attachment?");
                                if (retVal == true) {
                                    e.IsValid = true;
                                }
                                else {
                                    e.IsValid = false;
                                }
                            }
                        }
                    </script>
                    </telerik:RadScriptBlock>

Found my solution and working fine


问:
Script install for SLAPD
I'm working on a debian 8.
I wish install slapd with a script, without any questions from terminal.
I tried :

```<code>debconf-set-selections <<< 'slapd/root_password password 123123'
debconf-set-selections <<< 'slapd/root_password_again 123123'
apt-get install slapd ldap-utils -y
</code>```

But the systeme ask me the ldap password

I wish also use :

```<code>dpkg-reconfigure slapd
</code>```

Is it possible ?

Generally, How can i find all questions during a installation in order to use debconf-set-selections ?

答:
The possible attributes for debconf-set-selections are defined in the slapd.templates file in the debian package, together with a description of what the configuration attribute is about.

For slapd on Debian Jessie, you can find the file here: https://anonscm.debian.org/cgit/pkg-openldap/openldap.git/tree/debian/slapd.templates?h=jessie

Title: Script install for SLAPD

Body:
I'm working on a debian 8.
I wish install slapd with a script, without any questions from terminal.
I tried :

debconf-set-selections <<< 'slapd/root_password password 123123'
debconf-set-selections <<< 'slapd/root_password_again 123123'
apt-get install slapd ldap-utils -y

But the systeme ask me the ldap password

I wish also use :

dpkg-reconfigure slapd

Is it possible ?

Generally, How can i find all questions during a installation in order to use debconf-set-selections ?


问:
I was programming in pig, i'll loaded the below dataset
This is my dataset
Brand Name followed by price in $symbol

```<code>Apple iPhone 6s Plus 16GB Space Gray T-Mobile Smartphone 2 cases + Box:
Iphone 6s 16gb rose gold factory unlocked:$280
iPhone 6s 64gb T-Mobile:$350
Iphone 6S Plus 64 GB Space Gray Sprint International Unlocked:$385
iPhone 6s plus 64gb unlocked.:$600
</code>```

when I load this data using this command:

```<code>grunt> scrap1 = LOAD '/user/vickysmartboy15/hadoop-test1/scrap.txt' USING org.apache.pig.piggybank.storage.MyRegExLoader('([^\\:]+):([^\\:])') as (Name:chararray, price:chararray);
</code>```

after viewing data using: dump operator

my result like this

```<code>(Apple iPhone 6s Plus 16GB Space Gray T-Mobile Smartphone 2 cases + Box,$)

(Iphone 6s 16gb rose gold factory unlocked,$)

(iPhone 6s 64gb T-Mobile,$)

(Iphone 6S Plus 64 GB Space Gray Sprint International Unlocked,$)

(BRAND NEW Apple iPhone 6S 32Gb Silver Verizon UNLOCKED Clean ESN,$)

(iPhone 6s plus 64gb unlocked.,$)
</code>```

Only $ is displayed without the number.

How can I solve this?

答:
```<code>scrap1 = LOAD '/var/opt/teradata/home/fsbappdev/ashish/scrap.txt' using PigStorage(':') AS (Name:chararray, price:chararray);
</code>```

dump scrap1 will give you below data,i hope this is as expected.

(Apple iPhone 6s Plus 16GB Space Gray T-Mobile Smartphone 2 cases + Box, )

(Iphone 6s 16gb rose gold factory unlocked,$280)

(iPhone 6s 64gb T-Mobile,$350)

(Iphone 6S Plus 64 GB Space Gray Sprint International Unlocked,$385)

(iPhone 6s plus 64gb unlocked.,$600)

If you want to remove $ sign you can use next relation like

```<code>scrap2 = foreach scrap1 generate Name, REPLACE(price,'\\\$','')
</code>```

Body:
This is my dataset
Brand Name followed by price in $symbol

Apple iPhone 6s Plus 16GB Space Gray T-Mobile Smartphone 2 cases + Box:
Iphone 6s 16gb rose gold factory unlocked:$280
iPhone 6s 64gb T-Mobile:$350
Iphone 6S Plus 64 GB Space Gray Sprint International Unlocked:$385
iPhone 6s plus 64gb unlocked.:$600

when I load this data using this command:

grunt> scrap1 = LOAD '/user/vickysmartboy15/hadoop-test1/scrap.txt' USING org.apache.pig.piggybank.storage.MyRegExLoader('([^\\:]+):([^\\:])') as (Name:chararray, price:chararray);

after viewing data using: dump operator

my result like this

(Apple iPhone 6s Plus 16GB Space Gray T-Mobile Smartphone 2 cases + Box,$)

(Iphone 6s 16gb rose gold factory unlocked,$)

(iPhone 6s 64gb T-Mobile,$)

(Iphone 6S Plus 64 GB Space Gray Sprint International Unlocked,$)

(BRAND NEW Apple iPhone 6S 32Gb Silver Verizon UNLOCKED Clean ESN,$)

(iPhone 6s plus 64gb unlocked.,$)

Only $ is displayed without the number.

How can I solve this?

Body:
scrap1 = LOAD '/var/opt/teradata/home/fsbappdev/ashish/scrap.txt' using PigStorage(':') AS (Name:chararray, price:chararray);

dump scrap1 will give you below data,i hope this is as expected.

(Apple iPhone 6s Plus 16GB Space Gray T-Mobile Smartphone 2 cases + Box, )

(Iphone 6s 16gb rose gold factory unlocked,$280)

(iPhone 6s 64gb T-Mobile,$350)

(Iphone 6S Plus 64 GB Space Gray Sprint International Unlocked,$385)

(iPhone 6s plus 64gb unlocked.,$600)

If you want to remove $ sign you can use next relation like

scrap2 = foreach scrap1 generate Name, REPLACE(price,'\\\$','')


问:
Shared Preferences get nil after sometime in Samsung S7 Nougat
I am saving in a key in SharedPreferences. When in try to retrieve it at once, it returns me the value. But after some time it returns a nil value. This particularly happens in Samsung S7 Nougat and works fine for almost all other devices such as Nexus, Mi, Oppo, etc. I cross checked several times but i havent altered the value of the key between saving and retrieval.

I have noticed that Samsung doesnt clear Preferences after uninstalling the app (I checked in Samsung S6).So is there any problem with the Samsung devices or is there any loop hole im not considering.
Please help!

```<code><application
        android:name="android.support.multidex.MultiDexApplication"
        android:allowBackup="false"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:launchMode="singleTask"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activities.SplashActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <data
                    android:host=“xx.com"
                    android:scheme=“xx”
                    android:pathPrefix="/"/>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.MainActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.AutomatedTestActivity"
            android:screenOrientation="portrait" />
        <activity android:name=".activities.PasswordCancelActivity"></activity>
    </application>
</code>```

答:
I have noticed that Samsung doesnt clear Preferences after
  uninstalling the app (I checked in Samsung S6).So is there any problem
  with the Samsung devices or is there any loop hole im not considering.
  Please help!

Change android:allowBackup:false in android mainfest application tag.
If its true backup will be stored even if app gets uninstalled.

From android developer docs

android:allowBackup Whether to allow the application to participate in
  the backup and restore infrastructure. If this attribute is set to
  false, no backup or restore of the application will ever be performed,
  even by a full-system backup that would otherwise cause all
  application data to be saved via adb. The default value of this
  attribute is true.

Body:
I am saving in a key in SharedPreferences. When in try to retrieve it at once, it returns me the value. But after some time it returns a nil value. This particularly happens in Samsung S7 Nougat and works fine for almost all other devices such as Nexus, Mi, Oppo, etc. I cross checked several times but i havent altered the value of the key between saving and retrieval.

I have noticed that Samsung doesnt clear Preferences after uninstalling the app (I checked in Samsung S6).So is there any problem with the Samsung devices or is there any loop hole im not considering.
Please help!

<application
        android:name="android.support.multidex.MultiDexApplication"
        android:allowBackup="false"
        android:hardwareAccelerated="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:launchMode="singleTask"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".activities.SplashActivity"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <data
                    android:host=“xx.com"
                    android:scheme=“xx”
                    android:pathPrefix="/"/>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>
        </activity>
        <activity
            android:name=".activities.MainActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait" />
        <activity
            android:name=".activities.AutomatedTestActivity"
            android:screenOrientation="portrait" />
        <activity android:name=".activities.PasswordCancelActivity"></activity>
    </application>


问:
Disclosure indicator to specific cell in static TableView in Swift
I created a static TableView and I would like to add or remove a disclosure indicator depending if we are consulting our own account or a guest account.

This is what I would like :

```<code>let index = IndexPath(row: 4, section: 0)

let cell = tableView.cellForRow(at: index)
if currentUser {
   cell.accessoryType = .none
   //cell.backgroundColor = UIColor.red
}
</code>```

I tried to put it in the viewDidLoad function but it didn't work. I tried cellForRowAt indexPath also and same result.

How could I do that?

答:
Just check if you want to show disclosure indicator in cellForRowAt indexPath method.

```<code>if (wantsToShow){ // Your condition goes here
   cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
else{
   cell.accessoryType = .none
}
</code>```

That's it.

Body:
I created a static TableView and I would like to add or remove a disclosure indicator depending if we are consulting our own account or a guest account.

This is what I would like :

let index = IndexPath(row: 4, section: 0)

let cell = tableView.cellForRow(at: index)
if currentUser {
   cell.accessoryType = .none
   //cell.backgroundColor = UIColor.red
}

I tried to put it in the viewDidLoad function but it didn't work. I tried cellForRowAt indexPath also and same result.

How could I do that?

Body:
Just check if you want to show disclosure indicator in cellForRowAt indexPath method.

if (wantsToShow){ // Your condition goes here
   cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
}
else{
   cell.accessoryType = .none
}

That's it.


答:
Owl Carousel has the two options you are looking for, autoplay and autoplayHoverPause.

Try this:

```<code>$('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['<i class="fa fa-chevron-left"></i>', '<i class="fa fa-chevron-right"></i>'],
    dots: false,
    autoplay: true,
    autoplayHoverPause: true,
    loop: true,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
</code>```

You can find a list of all the available options here: https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html

Title: How to make this slider auto play

Body:
how can i make this java script code to auto play the slider and How to add mouse-over pause function

$(function() {
  $('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['', ''],
    dots: false,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });
});

Body:
Owl Carousel has the two options you are looking for, autoplay and autoplayHoverPause.

Try this:

$('.owl-carousel.testimonial-carousel').owlCarousel({
    nav: true,
    navText: ['<i class="fa fa-chevron-left"></i>', '<i class="fa fa-chevron-right"></i>'],
    dots: false,
    autoplay: true,
    autoplayHoverPause: true,
    loop: true,
    responsive: {
      0: {
        items: 1,
      },
      750: {
        items: 2,
      }
    }
  });

You can find a list of all the available options here: https://owlcarousel2.github.io/OwlCarousel2/docs/api-options.html


问:
Reduce an array of objects in PHP
I have an array of objects. Something like this:

```<code>$my_array = [
    (object) ['name' => 'name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2'],
];
</code>```

And I'd like to reduce it to a concatenation of all name properties like:

name 0 / name 1 / name 2

One way would be:

```<code>$result = [];
foreach ($my_array as $item) {
    $result[] = $item->name;
}
echo implode(' / ', $result);
</code>```

But I'd prefer something more compact, like using array_map:

```<code>implode(' / ', array_map(function($item) {
    return $item->name;
}, $my_array ));
</code>```

Given that in fact I want to reduce and array to a string I thought it would be cleaner with array_reduce but the only solution I can come out with is:

```<code>array_reduce($my_array, function($carry, $obj) {
    return empty($carry) ? $obj->name : $carry .= " / $obj->name";
});
</code>```

Yet it doesn't feel cleaner... So the question is simple:

Can anybody think of an understandable better/cleaner solution?

答:
```<code>trim (array_reduce($my_array, function($carry, $obj) {
    return "$carry / {$obj->name}";
}), " /");
</code>```

Is a bit more cleaner to my taste, but may have some side-effects. If the first name starts with '/' or the last name end with '/', they would be lost. e.g:

```<code>$my_array = [
    (object) ['name' => '/name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2/'],
];
</code>```

results with /name 0 / name 1 / name 2/ with the original code, and name 0 / name 1 / name 2 when trim is used.

Title: Reduce an array of objects in PHP

Body:
I have an array of objects. Something like this:

$my_array = [
    (object) ['name' => 'name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2'],
];

And I'd like to reduce it to a concatenation of all name properties like:

name 0 / name 1 / name 2

One way would be:

$result = [];
foreach ($my_array as $item) {
    $result[] = $item->name;
}
echo implode(' / ', $result);

But I'd prefer something more compact, like using array_map:

implode(' / ', array_map(function($item) {
    return $item->name;
}, $my_array ));

Given that in fact I want to reduce and array to a string I thought it would be cleaner with array_reduce but the only solution I can come out with is:

array_reduce($my_array, function($carry, $obj) {
    return empty($carry) ? $obj->name : $carry .= " / $obj->name";
});

Yet it doesn't feel cleaner... So the question is simple:

Can anybody think of an understandable better/cleaner solution?

Body:
trim (array_reduce($my_array, function($carry, $obj) {
    return "$carry / {$obj->name}";
}), " /");

Is a bit more cleaner to my taste, but may have some side-effects. If the first name starts with '/' or the last name end with '/', they would be lost. e.g:

$my_array = [
    (object) ['name' => '/name 0'],
    (object) ['name' => 'name 1'],
    (object) ['name' => 'name 2/'],
];

results with /name 0 / name 1 / name 2/ with the original code, and name 0 / name 1 / name 2 when trim is used.


问:
Using column value if column exist
I am trying to select the values from column, if the column exist.

This table is going under some modification and some columns are removed and values are extracted to another table.

Query I am using is below. At this stage column can be presented or may be already dropped, so I am doing a column check

```<code>IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END
</code>```

Also tried

```<code>IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'MyColumnName'
          AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END
</code>```

But this give me error when the Column is dropped even with the column exist check

Invalid column name 'MyColumnName'

Is there a way to get around this

答:
I suspect the error originates during the compiling of the query. The compiler doesn't consider IF statements, it evaluates the whole query as if everything is to be executed. When a non-existing column is encountered you get an error, regardless of whether you checked for existence. I think the best solution is to use dynamic SQL to get around that.

Something like:

```<code>IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
    EXEC sys.sp_executesql N'INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
                             SELECT DISTINCT MyColumnName,2
                             FROM MyTableName'
END
</code>```

Title: Using column value if column exist

Body:
I am trying to select the values from column, if the column exist.

This table is going under some modification and some columns are removed and values are extracted to another table.

Query I am using is below. At this stage column can be presented or may be already dropped, so I am doing a column check

IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END

Also tried

IF EXISTS(SELECT 1 FROM sys.columns
          WHERE Name = N'MyColumnName'
          AND Object_ID = Object_ID(N'dbo.MyTableName'))
BEGIN
    INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
    SELECT DISTINCT MyColumnName,2
    FROM MyTableName
END

But this give me error when the Column is dropped even with the column exist check

Invalid column name 'MyColumnName'

Is there a way to get around this

Body:
I suspect the error originates during the compiling of the query. The compiler doesn't consider IF statements, it evaluates the whole query as if everything is to be executed. When a non-existing column is encountered you get an error, regardless of whether you checked for existence. I think the best solution is to use dynamic SQL to get around that.

Something like:

IF COL_LENGTH('MyTableName', 'MyColumnName') IS NOT NULL
BEGIN
    EXEC sys.sp_executesql N'INSERT INTO SOMETABLE VALUES(TITLE,TYPEID)
                             SELECT DISTINCT MyColumnName,2
                             FROM MyTableName'
END


问:
KnockoutJS Template Binding Button Click
I use Knockoutjs template binding. My JavaScript code:

```<code>var viewModel = {
            messages: ko.observableArray()
        };
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });

        $(".like").click(function click  () {
            var Id = $(this).data("id");
            $.ajax({
                url: '/Home/Like/' + Id,
                type: 'POST',
                success: function (data) {
                    alert("Beğendi");
                }
            });
        });
</code>```

And my HTML code is:

```<code><button data-id="MessageId" class="btn btn-default like">
    <span data-bind="text:LikeCount"></span>
    <i class="fa fa-thumbs-o-up"></i>
</button>
</code>```

The .like click() function not working. How can I do it?

答:
I wouldn't use a jquery event listener in this case, as when the messages array update they will not have an event attached to them due to being added after.

Pure Knockout Solution

```<code><button class="btn btn-default like" data-bind="click: like.bind($data)">
    <span data-bind="text:LikeCount"></span>
    <i class="fa fa-thumbs-o-up"></i>
</button>
</code>```

Model

```<code>var MessageModel = function (data) {
   var self = this;
   self.MessageId = ko.observable('');
   self.LikeCount = ko.observable(0);

   self.like = function () {
        var c = self.LikeCount();
        self.LikeCount(c++);
        $.ajax({
            url: '/Home/Like/' + self.MessageId(),
            type: 'POST',
            success: function (data) {
                alert("Beğendi");
            }
        });
   }
};
</code>```

As stated above your like event listener isn't working due to not being rendered. So if you want to use your original code:

Apply bindings after you get data :

```<code>    $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
        viewModel.messages(data);
        ko.applyBindings(viewModel);
    });
</code>```

or apply event listener on get of data (probably more appropiate):

```<code>    $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
        viewModel.messages(data);
        $(".like").click(function click  () {
            var Id = $(this).data("id");
            $.ajax({
               url: '/Home/Like/' + Id,
               type: 'POST',
               success: function (data) {
                  alert("Beğendi");
               }
            });
        });
    });
</code>```

Body:
I use Knockoutjs template binding. My JavaScript code:

var viewModel = {
            messages: ko.observableArray()
        };
        ko.applyBindings(viewModel);
        $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
            viewModel.messages(data);
        });

        $(".like").click(function click  () {
            var Id = $(this).data("id");
            $.ajax({
                url: '/Home/Like/' + Id,
                type: 'POST',
                success: function (data) {
                    alert("Beğendi");
                }
            });
        });

And my HTML code is:

<button data-id="MessageId" class="btn btn-default like">

</button>

The .like click() function not working. How can I do it?

Body:
I wouldn't use a jquery event listener in this case, as when the messages array update they will not have an event attached to them due to being added after.

Pure Knockout Solution

<button class="btn btn-default like" data-bind="click: like.bind($data)">
    <span data-bind="text:LikeCount"></span>
    <i class="fa fa-thumbs-o-up"></i>
</button>

Model

var MessageModel = function (data) {
   var self = this;
   self.MessageId = ko.observable('');
   self.LikeCount = ko.observable(0);

   self.like = function () {
        var c = self.LikeCount();
        self.LikeCount(c++);
        $.ajax({
            url: '/Home/Like/' + self.MessageId(),
            type: 'POST',
            success: function (data) {
                alert("Beğendi");
            }
        });
   }
};

As stated above your like event listener isn't working due to not being rendered. So if you want to use your original code:

Apply bindings after you get data :

    $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
        viewModel.messages(data);
        ko.applyBindings(viewModel);
    });

or apply event listener on get of data (probably more appropiate):

    $.getJSON('@Url.Action("statusMessages", "Home")', function (data) {
        viewModel.messages(data);
        $(".like").click(function click  () {
            var Id = $(this).data("id");
            $.ajax({
               url: '/Home/Like/' + Id,
               type: 'POST',
               success: function (data) {
                  alert("Beğendi");
               }
            });
        });
    });


问:
.NET MVC - Ajax POST not calling .Net MVC method
I'm new to .NET MVC. I'm trying to make an Ajax call to a .NET method, but it doesn't work. Please help.

Here is my Ajax code:

```<code>function resendConfirmationEmail()
{
    $("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
    $.ajax({
        url: "/Ultility/ResendConfirmationEmail",
        type: "POST",
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "userID": $('#confirmation-email-userid').text().toString(), "subject": $('#confirmation-email-subject').text().toString() }),
        async: true,
        processData: true,
        cache: false,
        success: function (data) {
            $("#resend-confirmation-email-status").html("Email sent");
        }
    });
}
</code>```

And here is my .Net method in UtilityController:

```<code>[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail(string userID, string subject)
{
    string destination = db.Users.Where(u => u.Id == userID).Select(u => u.Email).FirstOrDefault();
    Task<string> result = new AccountController().SendEmailConfirmationTokenAsync(userID, subject, destination);
    return Json(result, JsonRequestBehavior.DenyGet);
}
</code>```

答:
Try this, but if you using asp.net mvc, i guess you don't need [WebMethod] attribute</p>

```<code>    [HttpPost]
    [WebMethod]
public JsonResult ResendConfirmationEmail([FromBody] MyModel model)
{
  ....
}

public class MyModel{
   public string userID {get; set;}
   public string string subject {get; set;}
}
</code>```

Body:
I'm new to .NET MVC. I'm trying to make an Ajax call to a .NET method, but it doesn't work. Please help.

Here is my Ajax code:

function resendConfirmationEmail()
{
    $("#resend-confirmation-email-status").html('');
    $.ajax({
        url: "/Ultility/ResendConfirmationEmail",
        type: "POST",
        datatype: "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ "userID": $('#confirmation-email-userid').text().toString(), "subject": $('#confirmation-email-subject').text().toString() }),
        async: true,
        processData: true,
        cache: false,
        success: function (data) {
            $("#resend-confirmation-email-status").html("Email sent");
        }
    });
}

And here is my .Net method in UtilityController:

[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail(string userID, string subject)
{
    string destination = db.Users.Where(u => u.Id == userID).Select(u => u.Email).FirstOrDefault();
    Task<string> result = new AccountController().SendEmailConfirmationTokenAsync(userID, subject, destination);
    return Json(result, JsonRequestBehavior.DenyGet);
}

Body:
Try this, but if you using asp.net mvc, i guess you don't need [WebMethod] attribute

    [HttpPost]
    [WebMethod]
public JsonResult ResendConfirmationEmail([FromBody] MyModel model)
{
  ....
}

public class MyModel{
   public string userID {get; set;}
   public string string subject {get; set;}
}