答:
I think this will give you what you want in one step:

```<code>def windowFunc(a, window, f = np.max):
    return np.array([f(i) for i in np.split(a, range(window, a.size, window))])
</code>```

with default f, that will give you a array of maximums for your windows.

Generally, using np.split and range, this will let you split into a (possibly ragged) list of arrays:

```<code>def shapeshifter(num_col, my_array=data):
    return np.split(my_array, range(num_col, my_array.size, num_col))
</code>```

You need a list of arrays because a 2D array can't be ragged (every row needs the same number of columns)

If you really want to pad with zeros, you can use np.lib.pad:

```<code>def shapeshifter(num_col, my_array=data):
    return np.lib.pad(my_array, (0, num_col - my.array.size % num_col), 'constant',  constant_values = 0).reshape(-1, num_col)
</code>```

Warning:

It is also technically possible to use, for example, a.resize(32,2) which will create an ndArray padded with zeros (as you requested).  But there are some big caveats:

You would need to calculate the second axis because -1 tricks don't work with resize.

If the original array a is referenced by anything else, a.resize will fail with the following error:

```<code>ValueError: cannot resize an array that references or is referenced
by another array in this way.  Use the resize function
</code>```

The resize function (i.e. np.resize(a)) is not equivalent to a.resize, as instead of padding with zeros it will loop back to the beginning.

Since you seem to want to reference a by a number of windows, a.resize isn't very useful.  But it's a rabbit hole that's easy to fall into.

EDIT:

Looping through a list is slow.  If your input is long and windows are small, the windowFunc above will bog down in the for loops.  This should be more efficient:

```<code>def windowFunc2(a, window, f = np.max):
    tail = - (a.size % window)
    if tail == 0:
        return f(a.reshape(-1, window), axis = -1)
    else:
        body = a[:tail].reshape(-1, window)
        return np.r_[f(body, axis = -1), f(a[tail:])]
</code>```

Title: Is there a way to reshape an array that does not maintain the original size (or a convenient work-around)?

Body:
I think this will give you what you want in one step:

def windowFunc(a, window, f = np.max):
    return np.array([f(i) for i in np.split(a, range(window, a.size, window))])

with default f, that will give you a array of maximums for your windows.

Generally, using np.split and range, this will let you split into a (possibly ragged) list of arrays:

def shapeshifter(num_col, my_array=data):
    return np.split(my_array, range(num_col, my_array.size, num_col))

You need a list of arrays because a 2D array can't be ragged (every row needs the same number of columns)

If you really want to pad with zeros, you can use np.lib.pad:

def shapeshifter(num_col, my_array=data):
    return np.lib.pad(my_array, (0, num_col - my.array.size % num_col), 'constant',  constant_values = 0).reshape(-1, num_col)

Warning:

It is also technically possible to use, for example, a.resize(32,2) which will create an ndArray padded with zeros (as you requested).  But there are some big caveats:

You would need to calculate the second axis because -1 tricks don't work with resize.

If the original array a is referenced by anything else, a.resize will fail with the following error:

ValueError: cannot resize an array that references or is referenced
by another array in this way.  Use the resize function

The resize function (i.e. np.resize(a)) is not equivalent to a.resize, as instead of padding with zeros it will loop back to the beginning.

Since you seem to want to reference a by a number of windows, a.resize isn't very useful.  But it's a rabbit hole that's easy to fall into.

EDIT:

Looping through a list is slow.  If your input is long and windows are small, the windowFunc above will bog down in the for loops.  This should be more efficient:

def windowFunc2(a, window, f = np.max):
    tail = - (a.size % window)
    if tail == 0:
        return f(a.reshape(-1, window), axis = -1)
    else:
        body = a[:tail].reshape(-1, window)
        return np.r_[f(body, axis = -1), f(a[tail:])]


来源: stackexchange

问:
How to get a bufio.Writer that implements io.WriteCloser
I want to extend existing code that writes data to a file in an unbuffered way.

The code expects a writer that implements the io.WriteCloser interface. Therefore just wrapping the existing file with a bufio.Writer does not work, as it does not implement this interface.

How can I make a bufio.Writer to implement and pass the necessary close call to the underlaying file?

答:
io.WriteCloser is the interface:

```<code>type WriteCloser interface {
        Writer
        Closer
}
</code>```

Which ultimately "prescribes" these 2 methods:

```<code>Write(p []byte) (n int, err error)

Close() error
</code>```

bufio.Writer already has a Write() method, so to make it a WriteCloser, only a Close() method is needed.

Extending bufio.Writer with a noop Close() method:

```<code>type MyWriteCloser struct {
    *bufio.Writer
}

func (mwc *MyWriteCloser) Close() error {
    // Noop
    return nil
}
</code>```

A value of type *MyWriteCloser is now a WriteCloser. This is the easiest extension. Using it:

```<code>bw := bufio.NewWriter(w)

mwc := &MyWriteCloser{bw}
</code>```

Although we can –and we should– add a more meaningful Close() method. As bufio.Write does buffered writes, we should flush its internal buffer before we declare it closed:

```<code>func (mwc *MyWriteCloser) Close() error {
    return mwc.Flush()
}
</code>```

Also note that since bufio.Write cannot be closed (does not provide a Close() method), this will not close its underlying io.Writer, this is just to conform to the io.Closer and io.WriteCloser interfaces.

If you also want to close the underlying file, you also have to store it, and after calling bufio.Flush() (to make sure everything is written out), given it's not returning any errors, you may proceed to also close the file.

This is how it could look like:

```<code>type MyWriteCloser struct {
    f *os.File
    *bufio.Writer
}

func (mwc *MyWriteCloser) Close() error {
    if err := mwc.Flush(); err != nil {
        return err
    }
    return mwc.f.Close()
}
</code>```

Using it:

```<code>// Open a file:
f, err := os.Open("myfile.txt")
if err != nil {
    panic(err) // Handle error
}

mwc := &MyWriteCloser{f, bufio.NewWriter(f)}
defer mwc.Close()

// use mwc
</code>```

ContentLicense: CC BY-SA 3.0

Body:
io.WriteCloser is the interface:

type WriteCloser interface {
        Writer
        Closer
}

Which ultimately "prescribes" these 2 methods:

Write(p []byte) (n int, err error)

Close() error

bufio.Writer already has a Write() method, so to make it a WriteCloser, only a Close() method is needed.

Extending bufio.Writer with a noop Close() method:

type MyWriteCloser struct {
    *bufio.Writer
}

func (mwc *MyWriteCloser) Close() error {
    // Noop
    return nil
}

A value of type *MyWriteCloser is now a WriteCloser. This is the easiest extension. Using it:

bw := bufio.NewWriter(w)

mwc := &MyWriteCloser{bw}

Although we can –and we should– add a more meaningful Close() method. As bufio.Write does buffered writes, we should flush its internal buffer before we declare it closed:

func (mwc *MyWriteCloser) Close() error {
    return mwc.Flush()
}

Also note that since bufio.Write cannot be closed (does not provide a Close() method), this will not close its underlying io.Writer, this is just to conform to the io.Closer and io.WriteCloser interfaces.

If you also want to close the underlying file, you also have to store it, and after calling bufio.Flush() (to make sure everything is written out), given it's not returning any errors, you may proceed to also close the file.

This is how it could look like:

type MyWriteCloser struct {
    f *os.File
    *bufio.Writer
}

func (mwc *MyWriteCloser) Close() error {
    if err := mwc.Flush(); err != nil {
        return err
    }
    return mwc.f.Close()
}

Using it:

// Open a file:
f, err := os.Open("myfile.txt")
if err != nil {
    panic(err) // Handle error
}

mwc := &MyWriteCloser{f, bufio.NewWriter(f)}
defer mwc.Close()

// use mwc

ContentLicense: CC BY-SA 4.0


问:
SQL if/case statement - returning value from db
I have trouble with sql command in MS Sql server .....
I would like to  check names in table. in Column are e.g. Carl, Loius, Manfred, Jenny ....
Is there any way, to create case or if statement :

```<code>Case  when name = 'Carl' then 'Man'
else Return original value(name) from table?
</code>```

(Louis, Manfred, Jenny) ?

If yes, how can i achieve that ? Case statement? If statement?
Thanks in advance

答:
Another (shorter to write) option is to use nullif and isnull:

```<code>SELECT ISNULL(NULLIF(name, 'Carl'), name)) as name
FROM yourTable.
</code>```

The NULLIF function will return null if both arguments are equale, and the ISNULL will return the first argument unless it's null - in that case it will return the second argument.

Body:
I have trouble with sql command in MS Sql server .....
I would like to  check names in table. in Column are e.g. Carl, Loius, Manfred, Jenny ....
Is there any way, to create case or if statement :

Case  when name = 'Carl' then 'Man'
else Return original value(name) from table?

(Louis, Manfred, Jenny) ?

If yes, how can i achieve that ? Case statement? If statement?
Thanks in advance

Body:
Another (shorter to write) option is to use nullif and isnull:

SELECT ISNULL(NULLIF(name, 'Carl'), name)) as name
FROM yourTable.

The NULLIF function will return null if both arguments are equale, and the ISNULL will return the first argument unless it's null - in that case it will return the second argument.


问:
Html table with data from mysql
I'm making a form like this one:

```<code><?php
    echo '<tr>
    <td><strong>Kamp</strong></td>
    <td width="80px"><strong>1X2</strong></td>
    <td><strong>Resultat</strong></td></tr>';
    $no = 1;
    while ($row = mysqli_fetch_array($query))
    {
        echo '<tr>
            <td>'.$row['kamp'].'</td>
            <td><input type="radio" name="k1" id="k11" value="1" />1<input type="radio" name="k1" id="k1x" value="X" />X<input type="radio" name="k1" id="k12" value="2" />2</td>
            <td><input name="k1r" type="text" id="k1r" placeholder="X-X" /></td>
        </tr>

    ';
    $no++;

}?>
</code>```

And it echo a nice form with 3 rows from my database in the first . It is like a betting-game, so I have the mathes in my database. But as it is right now, the user will check the radiobuttons at 3 different mathes, but submit the same, if you understand. How can I make it 3 different inputs?

答:
if you want multiple input fields with the same name you can create an array of input values with brakets

```<code><input type="radio" name="k1[]" id="k11" value="1" />
</code>```

See: http://www.php.net/manual/en/faq.html.php#faq.html.arrays for more infomation.

Title: Html table with data from mysql

Body:
I'm making a form like this one:

<?php
    echo '

    Kamp
    1X2
    Resultat
';
    $no = 1;
    while ($row = mysqli_fetch_array($query))
    {
        echo '

            '.$row['kamp'].'
            <input type="radio" name="k1" id="k11" value="1" />1<input type="radio" name="k1" id="k1x" value="X" />X<input type="radio" name="k1" id="k12" value="2" />2
            <input name="k1r" type="text" id="k1r" placeholder="X-X" />

    ';
    $no++;

}?>

And it echo a nice form with 3 rows from my database in the first . It is like a betting-game, so I have the mathes in my database. But as it is right now, the user will check the radiobuttons at 3 different mathes, but submit the same, if you understand. How can I make it 3 different inputs?

Body:
if you want multiple input fields with the same name you can create an array of input values with brakets

<input type="radio" name="k1[]" id="k11" value="1" />

See: http://www.php.net/manual/en/faq.html.php#faq.html.arrays for more infomation.


问:
send mail via php yii until success on time
i have php function that send mail on special time ever 7 days but when i send mail its sometimes not sent because server busy or not available ,my question is how to try send my email many times when its something wrong every 10 minute until its send success </p>

```<code>    private function sendEMailMessage($args) {
    $failed = true;
    for($i = 0; $i < 5 && $failed; $i ++) {
        $failed = Utilities::sendEMailMessage ( $args ) != '';
        if ($failed) {
            sleep ( 15 );
        }
    }
}
</code>```

<p>//its this work or not ???</p>

答:
The best way to deal with this problem would be to set up cron jobs for every 7 days.And for the mail sometimes getting not sent purpose you could use this,      </p>

```<code>    if (Yii::$app->mailer->getTransport()->isStarted()) {
    Yii::$app->mailer->getTransport()->stop();}
    Yii::$app->mailer->getTransport()->start();
</code>```

<p>If this is included in your yii app then once the mail is sent it should clear the ssl socket layer and open a fresh socket again for the next time.With the combined use of these I think it should work. </p>

Body:
i have php function that send mail on special time ever 7 days but when i send mail its sometimes not sent because server busy or not available ,my question is how to try send my email many times when its something wrong every 10 minute until its send success

    private function sendEMailMessage($args) {
    $failed = true;
    for($i = 0; $i < 5 && $failed; $i ++) {
        $failed = Utilities::sendEMailMessage ( $args ) != '';
        if ($failed) {
            sleep ( 15 );
        }
    }
}

//its this work or not ???

Body:
The best way to deal with this problem would be to set up cron jobs for every 7 days.And for the mail sometimes getting not sent purpose you could use this,

    if (Yii::$app->mailer->getTransport()->isStarted()) {
    Yii::$app->mailer->getTransport()->stop();}
    Yii::$app->mailer->getTransport()->start();

If this is included in your yii app then once the mail is sent it should clear the ssl socket layer and open a fresh socket again for the next time.With the combined use of these I think it should work.


问:
How to reset editor for fields in Model View in MVC
I have a web page in which i can input values. For that, i have provided code something like this

```<code><td colspan="2">
    @Html.EditorFor(model => model.Line1, new { id= "txtLine1" })
</td>
</code>```

which creates an editor field in the view in the web page for Address Line1. Now , on click of reset button, i want whatever is filled in the editor for Line1, it should be cleared. For this i am using a reset button and javascript as below

```<code><input type="button" value="reset" id="btnReset" />

<script type="text/javascript">
 $(document).ready(function () {
    $("#btnReset").click(function () {
            $("#txtLine1").val("");
        });
     });
</script>
</code>```

but this is not working for me. Have tried a lot, googled a lot but no solution seems to work. have even tried giving input type= "reset". Please provide the best solution for this

答:
I preferred to put the code inside element if it contains only one line, instead of creating new function.

see, maybe this code works for you.

```<code><input id="btnReset" type="button" value="reset"
        onclick="javascript: $('#Line1').val('');" />
</code>```

Body:
I have a web page in which i can input values. For that, i have provided code something like this

    @Html.EditorFor(model => model.Line1, new { id= "txtLine1" })

which creates an editor field in the view in the web page for Address Line1. Now , on click of reset button, i want whatever is filled in the editor for Line1, it should be cleared. For this i am using a reset button and javascript as below

<input type="button" value="reset" id="btnReset" />

but this is not working for me. Have tried a lot, googled a lot but no solution seems to work. have even tried giving input type= "reset". Please provide the best solution for this

Body:
I preferred to put the code inside element if it contains only one line, instead of creating new function.

see, maybe this code works for you.

<input id="btnReset" type="button" value="reset"
        onclick="javascript: $('#Line1').val('');" />


问:
Why swapping integer variable by XOR doesn't work in a single line?
I want to swap the value of two integer variables in java using the XOR operator.

This is my code:

```<code>int i = 24;
int j = 17;

i ^= j;
j ^= i;
i ^= j;

System.out.println("i : " + i + "\t j : " + j);
</code>```

It will work fine but the following equivalent code doesn't work:

```<code>int i = 24;
int j = 17;

i ^= j ^= i ^= j;

System.out.println("i : " + i + "\t j : " + j);
</code>```

Output is like this:

```<code>i : 0    j : 24
</code>```

First variable is zero! What's wrong with Java?

答:
Here is a little shorter solution compared to @nhahtdh . I know it's an old question but just wanted to document it on Stackoverflow :P

i = i ^ j ^ (j = i)

Body:
I want to swap the value of two integer variables in java using the XOR operator.

This is my code:

int i = 24;
int j = 17;

i ^= j;
j ^= i;
i ^= j;

System.out.println("i : " + i + "\t j : " + j);

It will work fine but the following equivalent code doesn't work:

int i = 24;
int j = 17;

i ^= j ^= i ^= j;

System.out.println("i : " + i + "\t j : " + j);

Output is like this:

i : 0    j : 24

First variable is zero! What's wrong with Java?


问:
Transform array by cutting in half but extend elements
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

```<code># source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]
</code>```

How would you achieve it?

答:
```<code>s.each_slice((s.size + 1) / 2).reduce(&:zip).map(&:flatten)
</code>```

Body:
I want to transform an existing array to display it. Therefore I cut the array in half but add the content of the cut element to the remained elements.

# source structure
s = [[1, 'blue'],
     [2, 'red'],
     [3, 'yellow'],
     [4, 'green'],
     [5, 'orange'],
     [6, 'black']]

# result structure
format_array(s)
# [[1, 'blue', 4, 'green'],
#  [2, 'red', 5, 'orange'],
#  [3, 'yellow', 6, 'black']]

How would you achieve it?


问:
how to parse multiple attributes in xml jquery
i have created a autocomplete search box and that display only name list , i want to show all data using xml file. for example- name, city, country, etc.
how to solve this...? please help me.

my code is...
 in html

```<code><form name="search_form" id="searchForm" method="GET" action="search_results.html">
<label for="searchBox">Keyword Search</label>
<input type="text" id="searchBox" name="searchString" />

<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>
</code>```

and jquery

```<code>$(document).ready(function() {
    var myArr = [];

    $.ajax({
        type: "GET",
        url: "data.xml", // change to full path of file on server
        dataType: "xml",
        success: parseXml,
        complete: setupAC,
        failure: function(data) {
            alert("XML File could not be found");
            }
    });

    function parseXml(xml)
    {
        //find every query value
        $(xml).find("info").each(function()
        {
            myArr.push($(this).attr("name"));
        });
    }

    function setupAC() {
        $("input#searchBox").autocomplete({
                source: myArr,
                minLength: 1,
                select: function(event, ui) {
                    $("input#searchBox").val(ui.item.value);
                    $("#searchForm").submit();
                }
        });
    }
 });
</code>```

and in xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<data>
<info name="jatin" value="IP"  city="Pune" country="india" />
<info name="kishor" value="WY" city="Mumbai" country="india" />
<info name="rahul" value="AL" city="Latur" country="india" />
<info name="dnyanesh" value="WY" city="punjab" country="india" />
</data>
</code>```

答:
Try this,

```<code>$.ajax({
    type: "GET",
    url: "data.xml", // change to full path of file on server
    dataType: "xml",
    success: function(xml) {
        parseXml(xml); // calling parseXml and pass xml into it.
        setupAC();
    },
    failure: function(data) {
        alert("XML File could not be found");
    }
});
</code>```

Updated for city/country/name search with snippet,

$(function() {

  var myArr = [],
    xml = '<?xml version="1.0" encoding="UTF-8"?><data><info name="jatin" value="IP"  city="Pune" country="india" /><info name="kishor" value="WY" city="Mumbai" country="india" /><info name="rahul" value="AL" city="Latur" country="india" /><info name="dnyanesh" value="WY" city="punjab" country="india" /></data>';

  function parseXml(xml) {
    //find every query value
    $(xml).find("info").each(function() {
      myArr.push({
        name: $(this).attr('name'),
        city: $(this).attr('city'),
        country: $(this).attr('country'),
        value: $(this).attr('value')
      });
    });
  }

  function setupAC() {
    $("input#searchBox").autocomplete({
      source: function(request, response) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
        response($.grep(myArr, function(v) {
          return matcher.test(v.name) || matcher.test(v.city) || matcher.test(v.country);
        }));
      },
      minLength: 1,
      select: function(event, ui) {
        $("input#searchBox").val(ui.item.value);
      }
    });
  }
  parseXml(xml);
  setupAC();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="searchBox" type="text"></code>```

Body:
i have created a autocomplete search box and that display only name list , i want to show all data using xml file. for example- name, city, country, etc.
how to solve this...? please help me.

my code is...
 in html

<form name="search_form" id="searchForm" method="GET" action="search_results.html">
Keyword Search
<input type="text" id="searchBox" name="searchString" />

<button name="searchKeyword" id="searchKeyword">Sumbit</button>
</form>

and jquery

$(document).ready(function() {
    var myArr = [];

    $.ajax({
        type: "GET",
        url: "data.xml", // change to full path of file on server
        dataType: "xml",
        success: parseXml,
        complete: setupAC,
        failure: function(data) {
            alert("XML File could not be found");
            }
    });

    function parseXml(xml)
    {
        //find every query value
        $(xml).find("info").each(function()
        {
            myArr.push($(this).attr("name"));
        });
    }

    function setupAC() {
        $("input#searchBox").autocomplete({
                source: myArr,
                minLength: 1,
                select: function(event, ui) {
                    $("input#searchBox").val(ui.item.value);
                    $("#searchForm").submit();
                }
        });
    }
 });

and in xml

<?xml version="1.0" encoding="UTF-8"?>
<data>
<info name="jatin" value="IP"  city="Pune" country="india" />
<info name="kishor" value="WY" city="Mumbai" country="india" />
<info name="rahul" value="AL" city="Latur" country="india" />
<info name="dnyanesh" value="WY" city="punjab" country="india" />
</data>

Body:
Try this,

$.ajax({
    type: "GET",
    url: "data.xml", // change to full path of file on server
    dataType: "xml",
    success: function(xml) {
        parseXml(xml); // calling parseXml and pass xml into it.
        setupAC();
    },
    failure: function(data) {
        alert("XML File could not be found");
    }
});

Updated for city/country/name search with snippet,

$(function() {

  var myArr = [],
    xml = '<?xml version="1.0" encoding="UTF-8"?><data><info name="jatin" value="IP"  city="Pune" country="india" /><info name="kishor" value="WY" city="Mumbai" country="india" /><info name="rahul" value="AL" city="Latur" country="india" /><info name="dnyanesh" value="WY" city="punjab" country="india" /></data>';

  function parseXml(xml) {
    //find every query value
    $(xml).find("info").each(function() {
      myArr.push({
        name: $(this).attr('name'),
        city: $(this).attr('city'),
        country: $(this).attr('country'),
        value: $(this).attr('value')
      });
    });
  }

  function setupAC() {
    $("input#searchBox").autocomplete({
      source: function(request, response) {
        var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
        response($.grep(myArr, function(v) {
          return matcher.test(v.name) || matcher.test(v.city) || matcher.test(v.country);
        }));
      },
      minLength: 1,
      select: function(event, ui) {
        $("input#searchBox").val(ui.item.value);
      }
    });
  }
  parseXml(xml);
  setupAC();

});

<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<input id="searchBox" type="text">


问:
How to convert the time from AM/PM to 24 hour format in PHP?
For example, I have a time in this format:

```<code>eg.

09:15 AM
04:25 PM
11:25 AM
</code>```

How do I convert it to :

```<code>09:15
16:25
23:25
</code>```

Currently my code is :

```<code>$format_time = str_replace(" AM", "", $time, $count);
if ($count === 0){
    $format_time = strstr($time, ' PM', true);
    $format_time = ......
}
</code>```

However, it seems there are some easier and more elegant way to do this?

```<code>$time = '23:45';
echo date('g:i a', strtotime($time));
</code>```

How do I fit the above sample in my case? Thanks.

答:
PHP 5.3+ solution.

```<code>$new_time = DateTime::createFromFormat('h:i A', '01:00 PM');
$time_24 = $new_time->format('H:i:s');
</code>```

Output: 13:00:00

Works great when formatting of date is required. Check This Answer for details.

Body:
For example, I have a time in this format:

eg.

09:15 AM
04:25 PM
11:25 AM

How do I convert it to :

09:15
16:25
23:25

Currently my code is :

$format_time = str_replace(" AM", "", $time, $count);
if ($count === 0){
    $format_time = strstr($time, ' PM', true);
    $format_time = ......
}

However, it seems there are some easier and more elegant way to do this?

$time = '23:45';
echo date('g:i a', strtotime($time));

How do I fit the above sample in my case? Thanks.

Body:
PHP 5.3+ solution.

$new_time = DateTime::createFromFormat('h:i A', '01:00 PM');
$time_24 = $new_time->format('H:i:s');

Output: 13:00:00

Works great when formatting of date is required. Check This Answer for details.


问:
JavaScript unexpected NaN?
So I have to make some code that, when the user types a number from 1-4, it will do either + - * or /, depending on what number they choose.

```<code>console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");

var choice = prompt ("What is your choice?");

if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  console.log(number1 / number2);
}

var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");
</code>```

The user is meant to put the numbers in after they have chosen a function, however when the user types in the first number, a NaN appears.

I assume this is because the user has not even types in the 2 numbers, but I need the user to type the numbers last.

Any help and advice would be very appreciated, thanks

答:
```<code>var x = function() {
console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");

var choice = prompt ("What is your choice?");

var number1 = Number(prompt("Type in a number"));
var number2 = Number(prompt("Type in another number"));

if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  (number2 !== 0) && console.log(number1 / number2);
}

}
</code>```

Title: JavaScript unexpected NaN?

Body:
So I have to make some code that, when the user types a number from 1-4, it will do either + - * or /, depending on what number they choose.

console.log("Calculator program");
console.log("1. Add numbers");
console.log("2. Subtract numbers");
console.log("3. Multiply numbers");
console.log("4. Divide numbers");

var choice = prompt ("What is your choice?");

if (choice == 1)
{
  console.log(number1 + number2);
}
if (choice == 2)
{
  console.log(number1 - number2);
}
if (choice == 3)
{
  console.log(number1 * number2);
}
if (choice == 4)
{
  console.log(number1 / number2);
}

var number1 = prompt("Type in a number");
var number2 = prompt("Type in another number");

The user is meant to put the numbers in after they have chosen a function, however when the user types in the first number, a NaN appears.

I assume this is because the user has not even types in the 2 numbers, but I need the user to type the numbers last.

Any help and advice would be very appreciated, thanks


问:
Communication between interactive ocaml interpreter and another process
I need to load a *.ml file into the Ocaml toplevel (the interactive interpreter, when you type 'ocaml' in a shell) and then send an instruction from a Matlab process, get back the result of the instruction, send back another instruction, ...

I've made this C program. The parent process gets the Matlab's instruction from a named pipe, sends it to the child process (with ocaml running) and gets the response back so it can send it to Matlab.

But there is some kind of bug: when I send an instruction, I get back some weird characters, I send another instruction and then I receive the response of the first instruction...

(I didn't copy the perror() test to have less text)

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void) {

    // Parent -> Child
    int pipe_in[2];
    // Child -> parent
    int pipe_out[2];

    /*
        pipe[0] = output
        pipe[1] = input
    */

    pipe(pipe_in);
    pipe(pipe_out);

    pid_t pid;
    if ((pid = fork()) == 0) {
        // CHILD SIDE

        close(pipe_in[1]);
        close(pipe_out[0]);

        dup2(pipe_in[0], STDIN_FILENO);
        dup2(pipe_out[1], STDOUT_FILENO);
        dup2(pipe_out[1], STDERR_FILENO);

        close(pipe_in[0]);
        close(pipe_out[1]);

        char *args[] = {"ocaml", NULL};
        execvp("ocaml", args);

        printf("FAIL\n");

        exit(EXIT_FAILURE);

    } else {
        // PARENT SIDE

        printf("[*] PID : %d\n", (int) pid);

        close(pipe_in[0]);
        close(pipe_out[1]);

        char cmd[1024];
        char feedback[1024];
        ssize_t cmd_read;
        ssize_t feedback_read = sizeof(feedback);

        while (1) {

            // Get the instruction from Matlab.
            printf("[>] ");
            int fifo_in = open("/tmp/pipe_in", O_RDONLY);
            cmd_read = read(fifo_in, cmd, sizeof(cmd));
            close(fifo_in);
            printf("%s\n", cmd);

            // Send the instruction to the ocaml interpreter.
            write(pipe_in[1], cmd, cmd_read);

            // Read the response of the ocaml interpreter.
            while (feedback_read == sizeof(feedback)) {
                feedback_read = read(pipe_out[0], feedback, sizeof(feedback));
                printf("[-] %d\n", (int) feedback_read);
            }

            printf("[<] %s\n", feedback);

            // Send to Matlab the response.
            int fifo_out = open("/tmp/pipe_out", O_WRONLY);
            write(fifo_out, feedback, feedback_read);
            close(fifo_out);

            cmd_read = 0;
            feedback_read = sizeof(feedback);

        }

        close(pipe_in[1]);
        close(pipe_out[0]);
    }
}
</code>```

I compile the code with gcc -Wall -std=c99 -o tphr tphr.c
I run the programm in one shell and in another :

```<code>> printf 'let x = 10;;\n' > /tmp/pipe_in

> cat /tmp/pipe_out
OCaml version 4.03.0

# %

> printf 'let y = 5;;\n' > /tmp/pipe_in

> cat /tmp/pipe_out
val x : int = 10
# %
</code>```

How can I fix the result ?

答:
You don't want to run the interactive ocaml toplevel here for multiple reasons:

the toplevel parses the configfiles of the user and then loads different modules. This can change the available values, change behaviour, and make your matlab process get different results per user.

the output of the toplevel may change between versions making it difficult to parse and return the right reply to matlab

Did you know that you can call the toplevel from ocaml bytecode to interprete strings? I suggest dumping the C code and writing ocaml byte code to read from the pipe, interpret the command and reply with the result.

Body:
I need to load a *.ml file into the Ocaml toplevel (the interactive interpreter, when you type 'ocaml' in a shell) and then send an instruction from a Matlab process, get back the result of the instruction, send back another instruction, ...

I've made this C program. The parent process gets the Matlab's instruction from a named pipe, sends it to the child process (with ocaml running) and gets the response back so it can send it to Matlab.

But there is some kind of bug: when I send an instruction, I get back some weird characters, I send another instruction and then I receive the response of the first instruction...

(I didn't copy the perror() test to have less text)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(void) {

    // Parent -> Child
    int pipe_in[2];
    // Child -> parent
    int pipe_out[2];

    /*
        pipe[0] = output
        pipe[1] = input
    */

    pipe(pipe_in);
    pipe(pipe_out);

    pid_t pid;
    if ((pid = fork()) == 0) {
        // CHILD SIDE

        close(pipe_in[1]);
        close(pipe_out[0]);

        dup2(pipe_in[0], STDIN_FILENO);
        dup2(pipe_out[1], STDOUT_FILENO);
        dup2(pipe_out[1], STDERR_FILENO);

        close(pipe_in[0]);
        close(pipe_out[1]);

        char *args[] = {"ocaml", NULL};
        execvp("ocaml", args);

        printf("FAIL\n");

        exit(EXIT_FAILURE);

    } else {
        // PARENT SIDE

        printf("[*] PID : %d\n", (int) pid);

        close(pipe_in[0]);
        close(pipe_out[1]);

        char cmd[1024];
        char feedback[1024];
        ssize_t cmd_read;
        ssize_t feedback_read = sizeof(feedback);

        while (1) {

            // Get the instruction from Matlab.
            printf("[>] ");
            int fifo_in = open("/tmp/pipe_in", O_RDONLY);
            cmd_read = read(fifo_in, cmd, sizeof(cmd));
            close(fifo_in);
            printf("%s\n", cmd);

            // Send the instruction to the ocaml interpreter.
            write(pipe_in[1], cmd, cmd_read);

            // Read the response of the ocaml interpreter.
            while (feedback_read == sizeof(feedback)) {
                feedback_read = read(pipe_out[0], feedback, sizeof(feedback));
                printf("[-] %d\n", (int) feedback_read);
            }

            printf("[<] %s\n", feedback);

            // Send to Matlab the response.
            int fifo_out = open("/tmp/pipe_out", O_WRONLY);
            write(fifo_out, feedback, feedback_read);
            close(fifo_out);

            cmd_read = 0;
            feedback_read = sizeof(feedback);

        }

        close(pipe_in[1]);
        close(pipe_out[0]);
    }
}

I compile the code with gcc -Wall -std=c99 -o tphr tphr.c
I run the programm in one shell and in another :

> printf 'let x = 10;;\n' > /tmp/pipe_in

> cat /tmp/pipe_out
OCaml version 4.03.0

# %

> printf 'let y = 5;;\n' > /tmp/pipe_in

> cat /tmp/pipe_out
val x : int = 10
# %

How can I fix the result ?


问:
DBF file parallel reading
A foxpro software reads , writes and updates records in a DBF file. I parallely read that same DBF in a c++ application. Will there be any issues if I keep my c++ applications reading DBF file for a long time ?</p>

答:
VFP tables are file based and use shared lock while updating it. If you are doing reading it directly (low level), with only reading there wouldn't be a problem. Since it is data anyway and the best optimised readers are OLEDB\ODBC drivers (ODBC drivers exist for up to version 6. For later versions, Sybase Advantage Server has a driver -local free, remote paid AFAIK but I don't use).

I have been using DBF tables from VFP (yes from VFP) and C# via VFPOLEDB for a long time and I can say I had no issues. Actually, the driver works better from C# vs from within VFP, I don't know why.

Also note that, when you are using VFPOLEDB driver, you are using ANSI mode by default (and shared for read\write unless you change the mode).

Title: DBF file parallel reading


问:
How to trigger onchange input of type file with view model in Angular
I am using input of type file to open file and trigger a function on change like this.

```<code><input type="file" multiple="multiple" class="fileUpload"
              onchange="angular.element(this).scope().fileOpened(this)" />
</code>```

my function is like this right now.

```<code>$scope.fileOpened = function(data) {
  // ...
}
</code>```

it is working fine, but I want to do it in different way. In my controller, I have create a view Modal like

```<code>var vm = this;
</code>```

and initializing all variables and function with that view model like

```<code>vm.fileOpened = fileOpened;
function fileOpened() {

}
</code>```

Now how to trigger it with onchange event, I have tried it like this, but give an error.

```<code>onchange="angular.element(this).vm.fileOpened(this)"
</code>```

答:
Try

```<code>angular.element(this).scope().vm.fileOpened(this);
</code>```

and

```<code>vm.fileOpened = function(data) {
  // ...
}
</code>```

Body:
I am using input of type file to open file and trigger a function on change like this.

<input type="file" multiple="multiple" class="fileUpload"
              onchange="angular.element(this).scope().fileOpened(this)" />

my function is like this right now.

$scope.fileOpened = function(data) {
  // ...
}

it is working fine, but I want to do it in different way. In my controller, I have create a view Modal like

var vm = this;

and initializing all variables and function with that view model like

vm.fileOpened = fileOpened;
function fileOpened() {

}

Now how to trigger it with onchange event, I have tried it like this, but give an error.

onchange="angular.element(this).vm.fileOpened(this)"

Body:
Try

angular.element(this).scope().vm.fileOpened(this);

and

vm.fileOpened = function(data) {
  // ...
}


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答:
In response to question #2 (shouldn't a link be a well defined regular expression) the answer is ... no.

An HTML link structure is a recursive much like parens and braces in programming languages.  There must be an equal number of start and end constructs and the "link" expression can be nested within itself.

To properly match a "link" expression a regex would be required to count the start and end tags.  Regular expressions are a class of Finite Automata.  By definition a Finite Automata cannot "count" constructs within a pattern.  A grammar is required to describe a recursive data structure such as this.  The inability for a regex to "count" is why you see programming languages described with Grammars as opposed to regular expressions.

So it is not possible to create a regex that will positively match 100% of all "link" expressions.  There are certainly regex's that will match a good deal of "link"'s with a high degree of accuracy but they won't ever be perfect.

I wrote a blog article about this problem recently.  Regular Expression Limitations

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

OwnerDisplayName: JaredPar

ContentLicense: CC BY-SA 2.5


问:
Producing a Dialog that will be dismissed automatically
is it possible to create a Dialog that will be dismissed automatically after some time if it doesn't have any user interaction?

答: You can use an activity as dialog box and then finish it after some time(as you want).</p>


问:
Collapse tableView rows on a row select in swift
i have a tableView where i show user created circle name and i want when the user select a circle name rest circle name collapse and show only one circle name. but i don't know how to do that. please help help me guys.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if indexPath.section == 0
    {
        // here is the code to collapse the row
    }
 }
</code>```

Section == 0 have the rows of circle names.

答:
u can do like below, to collapse the other cell, except the selected cell, for this create a new file lets call it as CustomCell.swift and make it a subclass if UITableViewCell and add the below code.

```<code>class CustomCell: UITableViewCell {

  @IBOutlet weak var circleNameTextField: UILabel!
  @IBOutlet weak var holderView: UIView!
  var cellindexPath:IndexPath?
  var selectedIndexPath:IndexPath?

  func animateCell() {
      if self.selectedIndexPath?.row == self.cellindexPath?.row {
          return
      } else {
         let isUpword = (cellindexPath!.row > selectedIndexPath!.row)
        self.animateCellWithDirection(upWord: isUpword)
      }
 }

 func animateCellWithDirection(upWord:Bool) {
     var hideRect = self.bounds
     if upWord {
         hideRect.origin.y = -hideRect.size.height
     } else {
         hideRect.origin.y = hideRect.size.height
     }

     UIView.animate(withDuration: 0.5, animations:{
       self.holderView.frame = hideRect
     })
  }
}
</code>```

and  you need to create a add a prototype cell in storyboard like below, screen

and set the class name to  CustomCell as shown, and in the attribute inspector set the reuse identifier like below screen, and one more thing add a view called holderView to cell's content view and add label inside the holderView and create a outlet in customCell as shown in the below image, see the view hierarchy, inside content view there is one more view and it contains the subview as UILabel circle name label.

now in the ViewController.swift add below code,

```<code>class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var aTableView: UITableView!
var selIndexPath:IndexPath?
    override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
      //self.aTableView.register(CustomCell.self, forCellReuseIdentifier: "CUSTOM_CELL")

   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
     // Dispose of any resources that can be recreated.
   }

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      self.selIndexPath = indexPath
      self.aTableView.reloadData()
   }

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 5
   }

   func numberOfSections(in tableView: UITableView) -> Int {
      return 1
   }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell : CustomCell? = tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL", for: indexPath) as? CustomCell//tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL") as? CustomCell

       cell?.circleNameTextField.text = "Circle Name"

       cell?.cellindexPath = indexPath

       if let selectedIndexPath = self.selIndexPath {
          cell?.selectedIndexPath = selectedIndexPath
          cell?.animateCell()
       }

       return cell!
   }

}
</code>```

if want try out in separate project, i posted the entire code
and final result something like below,

Edit:--)
in the question u asked, when the user select a circle name rest circle name collapse and show only one circle name thats why i did like above, any way, hear is the modification to ViewController.swift class, just define an array called dataSourceArray which holds all the circle name to be displayed in the table view,

```<code> let dataSourceArray = ["Circle Name_1","Circle Name_2","Circle Name_3","Circle Name_4","Circle Name_5"]
 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //self.aTableView.register(CustomCell.self, forCellReuseIdentifier: "CUSTOM_CELL")

 }
</code>```

and edit the below methods, like below

```<code> func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.selIndexPath = indexPath
    self.aTableView.reloadSections(IndexSet(integer: 0), with: .fade)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return ((self.selIndexPath) != nil) ?  1 : dataSourceArray.count
 }

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : CustomCell? = tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL", for: indexPath) as? CustomCell//tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL") as? CustomCell

    cell?.cellindexPath = indexPath

    if let selectedIndexPath = self.selIndexPath {
        cell?.selectedIndexPath = selectedIndexPath
        cell?.circleNameTextField.text = dataSourceArray[selectedIndexPath.row]
       // cell?.animateCell()
    } else {
       // cell?.resetCellWith(animate:false)
         cell?.circleNameTextField.text = dataSourceArray[indexPath.row]
    }
    return cell!
}
</code>```

in the method .reloadSections(IndexSet(integer: 0), with: .fade) u can change the animation type according to requirement.

Hope above works as your  requirement :)

Edit:2

for the above code,
just add a member variable, which controls expand and collapse of the cells,

```<code>    var expandCell:Bool = false //initially is false
</code>```

and just replace with below methods,

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.expandCell = !expandCell
    if self.expandCell {
        self.selIndexPath = indexPath
    } else {
        self.selIndexPath = nil;
    }

    self.aTableView.reloadSections(IndexSet(integer: 0), with: .fade)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if self.expandCell {
        return ((self.selIndexPath) != nil) ?  1 : dataSourceArray.count
    } else {
        return dataSourceArray.count
    }
}
</code>```

Body:
i have a tableView where i show user created circle name and i want when the user select a circle name rest circle name collapse and show only one circle name. but i don't know how to do that. please help help me guys.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    if indexPath.section == 0
    {
        // here is the code to collapse the row
    }
 }

Section == 0 have the rows of circle names.

Body:
u can do like below, to collapse the other cell, except the selected cell, for this create a new file lets call it as CustomCell.swift and make it a subclass if UITableViewCell and add the below code.

class CustomCell: UITableViewCell {

  @IBOutlet weak var circleNameTextField: UILabel!
  @IBOutlet weak var holderView: UIView!
  var cellindexPath:IndexPath?
  var selectedIndexPath:IndexPath?

  func animateCell() {
      if self.selectedIndexPath?.row == self.cellindexPath?.row {
          return
      } else {
         let isUpword = (cellindexPath!.row > selectedIndexPath!.row)
        self.animateCellWithDirection(upWord: isUpword)
      }
 }

 func animateCellWithDirection(upWord:Bool) {
     var hideRect = self.bounds
     if upWord {
         hideRect.origin.y = -hideRect.size.height
     } else {
         hideRect.origin.y = hideRect.size.height
     }

     UIView.animate(withDuration: 0.5, animations:{
       self.holderView.frame = hideRect
     })
  }
}

and  you need to create a add a prototype cell in storyboard like below, screen

and set the class name to  CustomCell as shown, and in the attribute inspector set the reuse identifier like below screen, and one more thing add a view called holderView to cell's content view and add label inside the holderView and create a outlet in customCell as shown in the below image, see the view hierarchy, inside content view there is one more view and it contains the subview as UILabel circle name label.

now in the ViewController.swift add below code,

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var aTableView: UITableView!
var selIndexPath:IndexPath?
    override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.
      //self.aTableView.register(CustomCell.self, forCellReuseIdentifier: "CUSTOM_CELL")

   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
     // Dispose of any resources that can be recreated.
   }

   func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      self.selIndexPath = indexPath
      self.aTableView.reloadData()
   }

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 5
   }

   func numberOfSections(in tableView: UITableView) -> Int {
      return 1
   }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      let cell : CustomCell? = tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL", for: indexPath) as? CustomCell//tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL") as? CustomCell

       cell?.circleNameTextField.text = "Circle Name"

       cell?.cellindexPath = indexPath

       if let selectedIndexPath = self.selIndexPath {
          cell?.selectedIndexPath = selectedIndexPath
          cell?.animateCell()
       }

       return cell!
   }

}

if want try out in separate project, i posted the entire code
and final result something like below,

Edit:--)
in the question u asked, when the user select a circle name rest circle name collapse and show only one circle name thats why i did like above, any way, hear is the modification to ViewController.swift class, just define an array called dataSourceArray which holds all the circle name to be displayed in the table view,

 let dataSourceArray = ["Circle Name_1","Circle Name_2","Circle Name_3","Circle Name_4","Circle Name_5"]
 override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //self.aTableView.register(CustomCell.self, forCellReuseIdentifier: "CUSTOM_CELL")

 }

and edit the below methods, like below

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.selIndexPath = indexPath
    self.aTableView.reloadSections(IndexSet(integer: 0), with: .fade)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return ((self.selIndexPath) != nil) ?  1 : dataSourceArray.count
 }

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell : CustomCell? = tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL", for: indexPath) as? CustomCell//tableView.dequeueReusableCell(withIdentifier: "CUSTOM_CELL") as? CustomCell

    cell?.cellindexPath = indexPath

    if let selectedIndexPath = self.selIndexPath {
        cell?.selectedIndexPath = selectedIndexPath
        cell?.circleNameTextField.text = dataSourceArray[selectedIndexPath.row]
       // cell?.animateCell()
    } else {
       // cell?.resetCellWith(animate:false)
         cell?.circleNameTextField.text = dataSourceArray[indexPath.row]
    }
    return cell!
}

in the method .reloadSections(IndexSet(integer: 0), with: .fade) u can change the animation type according to requirement.

Hope above works as your  requirement :)

Edit:2

for the above code,
just add a member variable, which controls expand and collapse of the cells,

    var expandCell:Bool = false //initially is false

and just replace with below methods,

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    self.expandCell = !expandCell
    if self.expandCell {
        self.selIndexPath = indexPath
    } else {
        self.selIndexPath = nil;
    }

    self.aTableView.reloadSections(IndexSet(integer: 0), with: .fade)
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if self.expandCell {
        return ((self.selIndexPath) != nil) ?  1 : dataSourceArray.count
    } else {
        return dataSourceArray.count
    }
}


问:
Concatenation in between records in Access Query
I have a table in Access that lists property IDs and the years each were certified:

```<code>B_ID    CertYear
a   2016
b   2016
c   2015
a   2015
a   2014
</code>```

I want to create a query/table that will count the number of years each building has been certified and also list each year in separate columns to look like this:

```<code>B_ID    Count_CertYear  Detail_CertYear
a   3   2016|2015|2014
b   1   2016
c   1   2015
</code>```

In the query design I was able to calculate the first two columns but am unable to figure out how to do the third. Here is how I currently have the table laid out.

```<code>Field:  B_ID    B_ID
Table:  MyTable MyTable
Total:  Count   Count
Sort:
Show:
Criteria:
Or:
</code>```

答:
To do this in Access, you can either use a crosstab query, or use a function to concatenate the years based on B_ID.

You say that you want to "list each year in separate columns", so I think the crosstab is more appropriate for you here.

Here is the crosstab SQL:

```<code>TRANSFORM Min(t.[CertYear]) AS MinOfCertYear
SELECT t.[B_ID], Count(t.[CertYear]) AS [TotalYears]
FROM (
  SELECT
    t1.B_ID,
    t1.CertYear,
    COUNT(t2.ID) AS YearCount
  FROM YourTable t1
  INNER JOIN YourTable t2
          ON t1.B_ID = t2.B_ID
         AND t1.ID <= t2.ID
  GROUP BY t1.B_ID, t1.CertYear
) t
GROUP BY t.[B_ID]
PIVOT 'Year: ' & t.[YearCount];
</code>```

If you want to just return the years in a comma separated single column then you can use the function found here as part of a regular aggregate query.

Then, your SQL would be:

```<code>SELECT
  t1.B_ID,
  COUNT(t1.ID) AS YearCount,
  SimpleCSV("SELECT t3.CertYear FROM YourTable t3 WHERE t3.B_ID = '" & t1.B_ID & "'") AS [Years]
FROM YourTable t1
GROUP BY t1.B_ID
</code>```

Body:
I have a table in Access that lists property IDs and the years each were certified:

B_ID    CertYear
a   2016
b   2016
c   2015
a   2015
a   2014

I want to create a query/table that will count the number of years each building has been certified and also list each year in separate columns to look like this:

B_ID    Count_CertYear  Detail_CertYear
a   3   2016|2015|2014
b   1   2016
c   1   2015

In the query design I was able to calculate the first two columns but am unable to figure out how to do the third. Here is how I currently have the table laid out.

Field:  B_ID    B_ID
Table:  MyTable MyTable
Total:  Count   Count
Sort:
Show:
Criteria:
Or:

Body:
To do this in Access, you can either use a crosstab query, or use a function to concatenate the years based on B_ID.

You say that you want to "list each year in separate columns", so I think the crosstab is more appropriate for you here.

Here is the crosstab SQL:

TRANSFORM Min(t.[CertYear]) AS MinOfCertYear
SELECT t.[B_ID], Count(t.[CertYear]) AS [TotalYears]
FROM (
  SELECT
    t1.B_ID,
    t1.CertYear,
    COUNT(t2.ID) AS YearCount
  FROM YourTable t1
  INNER JOIN YourTable t2
          ON t1.B_ID = t2.B_ID
         AND t1.ID <= t2.ID
  GROUP BY t1.B_ID, t1.CertYear
) t
GROUP BY t.[B_ID]
PIVOT 'Year: ' & t.[YearCount];

If you want to just return the years in a comma separated single column then you can use the function found here as part of a regular aggregate query.

Then, your SQL would be:

SELECT
  t1.B_ID,
  COUNT(t1.ID) AS YearCount,
  SimpleCSV("SELECT t3.CertYear FROM YourTable t3 WHERE t3.B_ID = '" & t1.B_ID & "'") AS [Years]
FROM YourTable t1
GROUP BY t1.B_ID


问:
Find out if a business is currently open in T-SQL
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

```<code>CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)
</code>```

Sample data in this table includes:

```<code>INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);
</code>```

Now I want to create a function which returns if a business is currently open or closed.

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO
</code>```

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

```<code>CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;
</code>```

答:
```<code>CREATE TABLE #OpeningHours(
    [openinghoursid] int,
    [businessid] int NOT NULL,
    [daynumber] int NOT NULL,
    [opentime] time NOT NULL,
    [duration] int NOT NULL,
)

INSERT #OpeningHours
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);

DECLARE @Date   DATETIME

SELECT @Date = GETDATE()

SELECT COUNT(*)
FROM
(
    SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + h.opentime) AS Opened,
        DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + h.opentime)) AS Closed
    FROM #OpeningHours h
    WHERE h.daynumber = DATEPART(dw, @Date)

    UNION

    SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + h.opentime) AS Opened,
        DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + h.opentime)) AS Closed
    FROM #OpeningHours h
    WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                             THEN 7
                             ELSE DATEPART(dw, @Date) - 1
                             END
) w
WHERE @Date BETWEEN Opened AND Closed

DROP TABLE #OpeningHours
</code>```

Body:
I am storing business opening hours in this table. Businesses can have multiple opening hours in the same day. The closing time can be after midnight of the current day.

CREATE TABLE [Process].[OpeningHours](
    [openinghoursid] [int] IDENTITY(1,1) NOT NULL,
    [businessid] [int] NOT NULL,
    [daynumber] [int] NOT NULL,
    [opentime] [time](7) NOT NULL,
    [duration] [int] NOT NULL,
    [closetime]  AS (dateadd(minute,[duration],[opentime])
)

Sample data in this table includes:

INSERT [Process].[OpeningHours]
([openinghoursid], [businessid], [daynumber], [opentime], [duration])
VALUES (79, 18, 2, CAST(N'12:00:00' AS Time), 165),
       (80, 18, 2, CAST(N'18:00:00' AS Time), 240),
       (81, 18, 3, CAST(N'12:00:00' AS Time), 165),
       (82, 18, 3, CAST(N'18:00:00' AS Time), 240),
       (83, 18, 4, CAST(N'12:00:00' AS Time), 165),
       (84, 18, 4, CAST(N'18:00:00' AS Time), 240),
       (85, 18, 5, CAST(N'12:00:00' AS Time), 165),
       (86, 18, 5, CAST(N'18:00:00' AS Time), 240),
       (87, 18, 6, CAST(N'12:00:00' AS Time), 165),
       (88, 18, 6, CAST(N'18:00:00' AS Time), 300),
       (89, 18, 7, CAST(N'12:00:00' AS Time), 165),
       (90, 18, 7, CAST(N'18:00:00' AS Time), 600),
       (91, 18, 1, CAST(N'12:00:00' AS Time), 180);

Now I want to create a function which returns if a business is currently open or closed.

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN
    DECLARE @currentdatetime DATETIME = GETDATE();
    DECLARE @dayofweek INT = DATEPART(dw,@currentdatetime);
    DECLARE @currentdate DATETIME = CONVERT(DATE, @currentdatetime);
    DECLARE @isopen BIT;

    SELECT @isopen = COUNT(*)
    FROM Process.OpeningHours
    WHERE
    daynumber = @dayofweek
    AND businessid = @businessid
    AND
    (
        @currentdatetime >= @currentdate + CONVERT(DATETIME, opentime)

        AND

        @currentdatetime <=
            CASE
                WHEN closetime < '00:00:00' THEN @currentdate + CONVERT(DATETIME, closetime)
                ELSE DATEADD(DAY,1,@currentdate) + CONVERT(DATETIME, closetime)
            END
    );

    RETURN @isopen;

END;

GO

I am using the COUNT() to see if any of the rows matches the condition, if 0 match it means it is closed, if COUNT() is greater than 0 it is open. This works when the closing time is within the same day, however it does not work when the closing time is after midnight or if the current time is after midnight.

Any idea how I can fix it?

EDIT: Thank you for all the responses. Finally I went ahead with @DenisRubashkin's solution. For anyone interested this is the final function I used:

CREATE FUNCTION [Process].[ufnIsSpaceOpen](@businessid int)
RETURNS BIT
AS
BEGIN

    DECLARE @isopen BIT;
    DECLARE @Date DATETIME = GETDATE();

    SELECT @isopen = COUNT(*)
    FROM
    (
        SELECT (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(CAST(@Date AS DATE) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = DATEPART(dw, @Date)
        AND businessid = @businessid

        UNION

        SELECT (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME)) AS Opened,
            DATEADD(mi, h.duration, (CAST(DATEADD(day, -1, CAST(@Date AS DATE)) AS DATETIME) + CAST(h.opentime AS DATETIME))) AS Closed
        FROM Process.OpeningHours h
        WHERE h.daynumber = CASE WHEN DATEPART(dw, @Date) = 1
                                 THEN 7
                                 ELSE DATEPART(dw, @Date) - 1
                                 END
        AND businessid = @businessid
    ) w
    WHERE @Date BETWEEN Opened AND Closed

    RETURN @isopen;

END;


问:
calculate method execution time in Visual Studio Express (No profiler available)?
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

```<code>        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);
</code>```

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?

答:
use StopWatch class to start a timer before the code is run and stop it after the code has ended. Do this for both code snippets and find out which takes mroe time.

This is not a perfect solution but it helps

Body:
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.

Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.

How can I do this in VS express? (not only for delegate for methods also)

If it is Duplicate, please link it.

Thanks

I tried Like This:

        /** Start Date time**/
        DateTime startTime = DateTime.Now;
        /********do the square of a number by using LAMBDA EXPRESSIONS********/
        returnSqr myDel = x => x * x;
        Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
        /** Stop Date time**/
        DateTime stopTime = DateTime.Now;
        TimeSpan duration = stopTime - startTime;
        Console.WriteLine("Execution time 1:" + duration.Milliseconds);

        /** Start Date time**/
        DateTime startTime2 = DateTime.Now;
        /*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
        returnSqr myDel1 = delegate(int x) { return x * x;};
        Console.WriteLine("By Anonymous Method Square of  {0} is: {1}", a, myDel1(a));
        /** Stop Date time**/
        DateTime stopTime2 = DateTime.Now;
        TimeSpan duration2 = stopTime2 - startTime2;
        Console.WriteLine("Execution Time 2:" + duration.Milliseconds);

Output gives:

Execution time 1 : 0

Execution time 2 : 0

Why like this?


问:
How to pass Json string with variable in c#?
```<code>string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";
</code>```

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

答:
You can use string.Format or string.concate Method</p>

```<code>string jSonContent = string.Concat("{\"fields\":{\"summary\":","\"",a,"\" , \"description\": \"",b,"\"}}");
</code>```

Body:
string a;

string b;

string jSonContent = @"{""fields"":{""summary"":""summary"" , ""description"": ""modified.""}}";

I want a instead of summary and b instead of modified. It works if I replace summary but gives errors if I replace both.

The edited code is, string jSonContent = @"{""fields"":{""summary"":"+ "\""+ a+ "\"" +" , ""description"": "+ "\""+ b+ "\"" +"}}"; It's not giving any error, summary field is getting updated, but the description field is not.

Please revert. Thanks!

Body:
You can use string.Format or string.concate Method

string jSonContent = string.Concat("{\"fields\":{\"summary\":","\"",a,"\" , \"description\": \"",b,"\"}}");


问:
Errors when installing sugarcrm

These errors happen while I am installing sugarcrm. After finishing installing, its index.php has the same kind of error.
How can I fix it ?

答:
```<code>set display_errors = 0;
</code>```

Determines if the errors will be printed on the webpage as part of the output or if they will remain hidden.

check this out

Title: Errors when installing sugarcrm

Body:
set display_errors = 0;

Determines if the errors will be printed on the webpage as part of the output or if they will remain hidden.

check this out


问:
Got "Access is denied" when I tried to rename the computer
```<code>Rename-Computer -NewName "newname" -DomainCredential CWQWTQ1J\Administrator
</code>```

CWQWTQ1J is computer name and "Administrator" is the username. I am trying to change the name of the local computer. When I run this cmdlet it throws me an error i.e Access is denied. Is there anything I am missing? It will be grateful if someone helps me.

答:
If the computer is joined to a Domain you need to specify an account on the Domain (with suitable permissions) in DomainCredential, the local administrator account will not work here.

```<code>Rename-Computer -NewName "newname" -DomainCredential "Domain\Administrator"
</code>```

If the computer is a workgroup computer (not part of a domain), you do not need to specify credentials. The account you run PowerShell with will just needs to be a Local Administrator.

```<code>Rename-Computer -NewName "newname"
</code>```

Body:
Rename-Computer -NewName "newname" -DomainCredential CWQWTQ1J\Administrator

CWQWTQ1J is computer name and "Administrator" is the username. I am trying to change the name of the local computer. When I run this cmdlet it throws me an error i.e Access is denied. Is there anything I am missing? It will be grateful if someone helps me.

Body:
If the computer is joined to a Domain you need to specify an account on the Domain (with suitable permissions) in DomainCredential, the local administrator account will not work here.

Rename-Computer -NewName "newname" -DomainCredential "Domain\Administrator"

If the computer is a workgroup computer (not part of a domain), you do not need to specify credentials. The account you run PowerShell with will just needs to be a Local Administrator.

Rename-Computer -NewName "newname"


问:
mysql join same table with another table
I have a table name tbl_user

This table contain a column name db_responsibleid contain the id of the responsible of this person and this person is in this table also
example mohammad have db_uid=1 and samir have db_responsibleid=1 this mean that mohammad is responsible for samir

also i have another table name tbl_department the table user contain the id of the department on the column name db_udepartment

I try to have the name of the department and the name and the last name of the responsible where db_uid='$id'

$id will be getting from url

this is the query that i use

```<code>     SELECT
     user.db_uid,
     user.db_fname,
     user.db_lname,
     user.db_username,
     user.db_pass,
     user.db_email,
     user.db_phone,
     user.db_jobtitle,
     user.db_level,
     user.db_isemployee,
     user.db_responsibleid,
     user.db_companyname,
     user.db_udepartment,
     tbl_department.db_department,
     tbl_department.db_did,
     parent.db_responsibleid,
     parent.db_fname as pfname,
     parent.db_lname as plname,
     parent.db_uid
     from tbl_user as user,tbl_department
     join tbl_user as parent
     on
     user.db_responsibleid=parent.db_uid
     where
     user.db_udepartment=tbl_department.db_did
     and
     user.db_uid='$id'
</code>```

But this query give me this error Unknown column 'user.db_responsibleid' in 'on clause'

How can i solve this problem and get all information with the name of the responsible and the name of the department ??

答:
You can not mix implizit and explizit join.
If you decided to use join you have to do it everywhere:

```<code>from tbl_user as user
 join tbl_department on user.db_udepartment=tbl_department.db_did
 join tbl_user as parent
 on
 user.db_responsibleid=parent.db_uid
 where
 user.db_uid='$id'
</code>```

Hint: use prepared Statements to prevent SQL-injection

Body:
I have a table name tbl_user

This table contain a column name db_responsibleid contain the id of the responsible of this person and this person is in this table also
example mohammad have db_uid=1 and samir have db_responsibleid=1 this mean that mohammad is responsible for samir

also i have another table name tbl_department the table user contain the id of the department on the column name db_udepartment

I try to have the name of the department and the name and the last name of the responsible where db_uid='$id'

$id will be getting from url

this is the query that i use

     SELECT
     user.db_uid,
     user.db_fname,
     user.db_lname,
     user.db_username,
     user.db_pass,
     user.db_email,
     user.db_phone,
     user.db_jobtitle,
     user.db_level,
     user.db_isemployee,
     user.db_responsibleid,
     user.db_companyname,
     user.db_udepartment,
     tbl_department.db_department,
     tbl_department.db_did,
     parent.db_responsibleid,
     parent.db_fname as pfname,
     parent.db_lname as plname,
     parent.db_uid
     from tbl_user as user,tbl_department
     join tbl_user as parent
     on
     user.db_responsibleid=parent.db_uid
     where
     user.db_udepartment=tbl_department.db_did
     and
     user.db_uid='$id'

But this query give me this error Unknown column 'user.db_responsibleid' in 'on clause'

How can i solve this problem and get all information with the name of the responsible and the name of the department ??

Body:
You can not mix implizit and explizit join.
If you decided to use join you have to do it everywhere:

from tbl_user as user
 join tbl_department on user.db_udepartment=tbl_department.db_did
 join tbl_user as parent
 on
 user.db_responsibleid=parent.db_uid
 where
 user.db_uid='$id'

Hint: use prepared Statements to prevent SQL-injection


问:
How to reset editor for fields in Model View in MVC
I have a web page in which i can input values. For that, i have provided code something like this

```<code><td colspan="2">
    @Html.EditorFor(model => model.Line1, new { id= "txtLine1" })
</td>
</code>```

which creates an editor field in the view in the web page for Address Line1. Now , on click of reset button, i want whatever is filled in the editor for Line1, it should be cleared. For this i am using a reset button and javascript as below

```<code><input type="button" value="reset" id="btnReset" />

<script type="text/javascript">
 $(document).ready(function () {
    $("#btnReset").click(function () {
            $("#txtLine1").val("");
        });
     });
</script>
</code>```

but this is not working for me. Have tried a lot, googled a lot but no solution seems to work. have even tried giving input type= "reset". Please provide the best solution for this

答:
I've just figured out what is the problem is with your snippet code. You're giving an id to your EditFor() which is not being rendered. You're nearly there and you're using the correct overload too. You'll need to make use of htmlAttributes if you want to assign a custom id to your input. So change your code from

```<code>@Html.EditorFor(model => model.Line1, new { id= "txtLine1" })
</code>```

To

```<code>@Html.EditorFor(model => model.Line1, new { htmlAttributes = new { @id = "txtLine1" } })
</code>```

I have tested this on my local machine and it works as you want it to.

Body:
I have a web page in which i can input values. For that, i have provided code something like this

    @Html.EditorFor(model => model.Line1, new { id= "txtLine1" })

which creates an editor field in the view in the web page for Address Line1. Now , on click of reset button, i want whatever is filled in the editor for Line1, it should be cleared. For this i am using a reset button and javascript as below

<input type="button" value="reset" id="btnReset" />

but this is not working for me. Have tried a lot, googled a lot but no solution seems to work. have even tried giving input type= "reset". Please provide the best solution for this

Body:
I've just figured out what is the problem is with your snippet code. You're giving an id to your EditFor() which is not being rendered. You're nearly there and you're using the correct overload too. You'll need to make use of htmlAttributes if you want to assign a custom id to your input. So change your code from

@Html.EditorFor(model => model.Line1, new { id= "txtLine1" })

To

@Html.EditorFor(model => model.Line1, new { htmlAttributes = new { @id = "txtLine1" } })

I have tested this on my local machine and it works as you want it to.


问:
Pick random property and value from Javascript object
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

```<code>var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}
</code>```

Now I want to add more options for such as books, games.. so I've created an object for it:

```<code>var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}
</code>```

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

答:
Here is another solution using Math.random() to achieve randomness:

```<code>var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

function getRandom(obj, item){
  // 1) select which property to operate on.
  var itemArr = obj[item];

  // 2) we already know that the key can only be an integer(between 0 and length -1 )

  // Math.random()   : to generate a random number(between [0-1]).
  // Math.round()    : to round a number to an integer.
  // number % length : to make sure the result would be an integer between 0 and length -1
  var index = Math.round((Math.random() * itemArr.length)) % itemArr.length;

  return {
    property:itemArr,
    index: index,
    value: itemArr[index],
  }

}

console.log(getRandom(chooseOption,'watch'));
console.log(getRandom(chooseOption,'read'));
console.log(getRandom(chooseOption,'play'));
</code>```

Body:
I've just started learning Javascript and need some help.

I wanted to build a random picker from an array which I accomplished

var movie = ["star wars", "lotr", "moonlight", "avengers"]

function newMovie() {
  var randomNumber = Math.floor(Math.random() * (movie.length));

  document.getElementById("display").innerHTML = "You should watch " + movie[randomNumber];
}

Now I want to add more options for such as books, games.. so I've created an object for it:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

I'm a bit lost on how to proceed - I want it to first pick out one of the properties and then one of the values of the said property, all by random.
And then print it out in a "You should" + [property] + [value]

How would I do that? Is the object a way to go, or any better options?

Body:
Here is another solution using Math.random() to achieve randomness:

var chooseOption = {
    watch: ["star wars", "lotr", "moonlight", "avengers"],
    read: ["scott pilgrim", "harry potter", "eragon"],
    play: ["starbound", "skyrim", "bioshock", "fallout"]
}

function getRandom(obj, item){
  // 1) select which property to operate on.
  var itemArr = obj[item];

  // 2) we already know that the key can only be an integer(between 0 and length -1 )

  // Math.random()   : to generate a random number(between [0-1]).
  // Math.round()    : to round a number to an integer.
  // number % length : to make sure the result would be an integer between 0 and length -1
  var index = Math.round((Math.random() * itemArr.length)) % itemArr.length;

  return {
    property:itemArr,
    index: index,
    value: itemArr[index],
  }

}

console.log(getRandom(chooseOption,'watch'));
console.log(getRandom(chooseOption,'read'));
console.log(getRandom(chooseOption,'play'));


问:
Select from H2 adds "clob:" to texts in clojure
I am using a h2 database with clojure. I made a table and put some data in like this

```<code>(j/create-table :locations
    [:id "bigint primary key auto_increment"]
    [:title "varchar (255)"]
    [:part "clob"])

  (j/insert-records :locations
    {:title "Steven Gerrard: I'm not the new Beckham" :part "He might not have the Becks appeal -- but Steven Gerrard says he's ready to light up Hollywood in his own way..."}))
    )
   )
</code>```

And then I selected the data

```<code>(defn newest []
 (database/mysql-db)
 (let [results (j/with-connection db-spec
                  (j/with-query-results res
                    ["select id, title, part from locations"]
                    (doall res)))]
    results))
</code>```

And I used the data on a clostache page

```<code><div class="container">
    <sections>
         {{#newest}}
           <p style="padding-bottom: 15px;">{{title}}<p>
           <p style="padding-bottom: 15px;">{{part}}<p>
         {{/newest}}
     </sections>
  </div>
</code>```

On the page i get

```<code>Steven Gerrard: I'm not the new Beckham

clob0: 'He might not have the Becks appeal -- but Steven Gerrard says he''s ready to light up Hollywood in his own way...'
</code>```

How can I remove the clob0: string that is attached to the text I have in the database? This happens even if I use text instead of clob for the part column in my database.

答:
You might have noticed that new lines get lost by the above... something like this adds them back in...</p>

```<code>(defn clob-to-string [clob]
        "Turn an Clob into a String, with new new lines"
    (with-open [rdr (java.io.BufferedReader. (.getCharacterStream clob))]
      (let [lseq (line-seq rdr)
            butlast-line (butlast lseq)
            butlast-line-mapped (map (fn [l] (str l "\n")) butlast-line)
            last-line (last lseq)
            all-lines-with-newline (concat butlast-line-mapped last-line)
            ]
        (apply str all-lines-with-newline)
        )))
</code>```

Body:
I am using a h2 database with clojure. I made a table and put some data in like this

(j/create-table :locations
    [:id "bigint primary key auto_increment"]
    [:title "varchar (255)"]
    [:part "clob"])

  (j/insert-records :locations
    {:title "Steven Gerrard: I'm not the new Beckham" :part "He might not have the Becks appeal -- but Steven Gerrard says he's ready to light up Hollywood in his own way..."}))
    )
   )

And then I selected the data

(defn newest []
 (database/mysql-db)
 (let [results (j/with-connection db-spec
                  (j/with-query-results res
                    ["select id, title, part from locations"]
                    (doall res)))]
    results))

And I used the data on a clostache page

    <sections>
         {{#newest}}

{{title}}

{{part}}

         {{/newest}}
     </sections>

On the page i get

Steven Gerrard: I'm not the new Beckham

clob0: 'He might not have the Becks appeal -- but Steven Gerrard says he''s ready to light up Hollywood in his own way...'

How can I remove the clob0: string that is attached to the text I have in the database? This happens even if I use text instead of clob for the part column in my database.

Body:
You might have noticed that new lines get lost by the above... something like this adds them back in...

(defn clob-to-string [clob]
        "Turn an Clob into a String, with new new lines"
    (with-open [rdr (java.io.BufferedReader. (.getCharacterStream clob))]
      (let [lseq (line-seq rdr)
            butlast-line (butlast lseq)
            butlast-line-mapped (map (fn [l] (str l "\n")) butlast-line)
            last-line (last lseq)
            all-lines-with-newline (concat butlast-line-mapped last-line)
            ]
        (apply str all-lines-with-newline)
        )))


问:
How do I avoid initializing variables when using recursion?
I'm using a recursive function, but I'm initializing a queue that stores values  within the function. I want to avoid initializing the queue every time I use recursion, because then I lose the values that I need to store. Unfortunately the code I was given is structured in such a way that I can't modify the function definition. </p>

```<code>void function(Graph* graph, int edge_id) {

    Queue * queue = new_queue();

    Edge* temp = graph->vertices[edge_id]->first_edge;

    while(temp!=NULL){
        queue_enqueue(queue, temp->v);
        temp=temp->next_edge;
    }
    queue_print(queue);

    if(temp == NULL){
        function(graph, queue->elements->head->data);
    }
</code>```

答:
Just create another function and call it into function :)
Thanks to that 'trick' you do not change the function called function

```<code>void function_b(Graphe *graph, int edge_id, Queue *queue) {

    Edge* temp = graph->vertices[edge_id]->first_edge;

    while(temp!=NULL){
        queue_enqueue(queue, temp->v);
        temp=temp->next_edge;
    }

    queue_print(queue);

    if(temp == NULL){
        function_b(graph, queue->elements->head->data, queue);
    }

}

void function(Graph* graph, int edge_id) {
    Queue * queue = new_queue();
    function_b(graph, edge_id, queue);
}
</code>```

Body:
I'm using a recursive function, but I'm initializing a queue that stores values  within the function. I want to avoid initializing the queue every time I use recursion, because then I lose the values that I need to store. Unfortunately the code I was given is structured in such a way that I can't modify the function definition.

void function(Graph* graph, int edge_id) {

    Queue * queue = new_queue();

    Edge* temp = graph->vertices[edge_id]->first_edge;

    while(temp!=NULL){
        queue_enqueue(queue, temp->v);
        temp=temp->next_edge;
    }
    queue_print(queue);

    if(temp == NULL){
        function(graph, queue->elements->head->data);
    }

Body:
Just create another function and call it into function :)
Thanks to that 'trick' you do not change the function called function

void function_b(Graphe *graph, int edge_id, Queue *queue) {

    Edge* temp = graph->vertices[edge_id]->first_edge;

    while(temp!=NULL){
        queue_enqueue(queue, temp->v);
        temp=temp->next_edge;
    }

    queue_print(queue);

    if(temp == NULL){
        function_b(graph, queue->elements->head->data, queue);
    }

}

void function(Graph* graph, int edge_id) {
    Queue * queue = new_queue();
    function_b(graph, edge_id, queue);
}


问:
Using parent class object to instantiate a child class object in Scala?
For example, there are two scala class called A and B.

```<code>class A{
  val aVariable:String="a"
}

class B(val newVariable:String) extends A{
  def newMethod(): Unit ={

  }
}
</code>```

The problem is how to use an A object to instantiate a B object with its variable?
For example, a function take an A object and a string to create a B object

```<code>val bObject:B=BuildFunc(new A(),"string")
</code>```

And if A contains much variables, is there a way to avoid setting each of manually?

It seems in Java this could be done by code like super(aObject), is there equivalent method in Scala?

答:
There's multiple solutions here. For example, one would be defining A's promoting the A's constructor parameters into fields:

class A(val foo: String)
class B(override val foo: String, val baz: String) extends A(foo)
```

<p>If you can't change A's definition though then maybe this will help:</p>

<pre class="lang-scala prettyprint-override"><code>class A {
  val foo: String = "foo"
}
class B(override val foo: String, val baz: String) extends A
</code>```

Hope that helps.

Body:
For example, there are two scala class called A and B.

class A{
  val aVariable:String="a"
}

class B(val newVariable:String) extends A{
  def newMethod(): Unit ={

  }
}

The problem is how to use an A object to instantiate a B object with its variable?
For example, a function take an A object and a string to create a B object

val bObject:B=BuildFunc(new A(),"string")

And if A contains much variables, is there a way to avoid setting each of manually?

It seems in Java this could be done by code like super(aObject), is there equivalent method in Scala?

Body:
There's multiple solutions here. For example, one would be defining A's promoting the A's constructor parameters into fields:

class A(val foo: String)
class B(override val foo: String, val baz: String) extends A(foo)

If you can't change A's definition though then maybe this will help:

class A {
  val foo: String = "foo"
}
class B(override val foo: String, val baz: String) extends A

Hope that helps.


问:
Data structures for bioinformatics
What are some data structures that should be known by somebody involved in bioinformatics? I guess that anyone is supposed to know about lists, hashes, balanced trees, etc., but I expect that there are domain specific data structures. Is there any book devoted to this subject?</p>

答:
Spatial hashing datastructures (kd-tree) for example are used often for nearest neighbor queries of arbitrary feature vectors as well as 3d protein structure analysis.

Best book for your $$ is Understanding Bioinformatics by Zvelebil because it covers everything from sequence analysis to structure comparison.

Title: Data structures for bioinformatics


Title: Remove Duplicate Occurance of Values in SQL Server Select Record

Body:
Date    Time    Event   site
2017-03-29  13:09:31.0000000    IN  Old Site
2017-03-29  14:26:32.0000000    OUT Old Site
2017-03-29  14:41:02.0000000    IN  Old Site
2017-03-29  16:21:17.0000000    OUT Old Site
2017-03-29  16:54:18.0000000    IN  Old Site
2017-03-29  16:54:24.0000000    IN  Old Site
2017-03-29  17:45:05.0000000    OUT Old Site
2017-03-29  19:30:03.0000000    IN  Old Site

DECLARE @empTime TABLE ([Date] DATE,[Time] TIME,[Event] VARCHAR(30),[Site] VARCHAR(30))

INSERT INTO @empTime ([Date],[Time],[Event],[Site])
VALUES
('2017-03-29', '13:09:31.0000000', 'IN', 'Old Site'),
('2017-03-29', '14:26:32.0000000', 'OUT', 'Old Site'),
('2017-03-29', '14:41:02.0000000', 'IN', 'Old Site'),
('2017-03-29', '16:21:17.0000000', 'OUT', 'Old Site'),
('2017-03-29', '16:54:18.0000000', 'IN', 'Old Site'),
('2017-03-29', '16:54:24.0000000', 'IN', 'Old Site'),
('2017-03-29', '17:45:05.0000000', 'OUT', 'Old Site'),
('2017-03-29', '19:30:03.0000000', 'IN', 'Old Site')

SELECT *
FROM @empTime

As per above code and output, I want to remove one of the Record for 'IN' '16:54:24.0000000' because I want record in form of continuous IN-OUT-IN-OUT.

I want to remove duplicate occurrence of value in below record. I want record should be in continuous form i.e. In-Out-In-Out.

Body:
DECLARE @empTime TABLE ([Id] Integer,[Date] DATE,[Time] TIME,[Event] VARCHAR(30),[Site] VARCHAR(30))

INSERT INTO @empTime ([Id],[Date],[Time],[Event],[Site])
VALUES
(1,'2017-03-29', '13:09:31.0000000', 'IN', 'Old Site'),
(2,'2017-03-29', '14:26:32.0000000', 'OUT', 'Old Site'),
(3,'2017-03-29', '14:41:02.0000000', 'IN', 'Old Site'),
(4,'2017-03-29', '16:21:17.0000000', 'OUT', 'Old Site'),
(5,'2017-03-29', '16:54:18.0000000', 'IN', 'Old Site'),
(6,'2017-03-29', '16:54:24.0000000', 'IN', 'Old Site'),
(7,'2017-03-29', '17:45:05.0000000', 'OUT', 'Old Site'),
(8,'2017-03-29', '19:30:03.0000000', 'IN', 'Old Site')

SELECT *
FROM @empTime

Select *  from @empTime where Id not in (Select top(1) Id from @empTime where (Id % 2) = 0 and [Event]!='Out')