问:
Python readability through descriptive naming
I have been using Python for about a year now, coming from a mostly Java background. I found Python quite easy to learn because of its focus on readability and simple design. The thing I don't understand about python is why for a language that focuses so heavily on readability, it often uses very non-descriptive names for modules, functions, constants etc.. One thing I like about Java is its very descriptive class/attribute/method names (I like objective-C even more for this reason). It seems python programmers in general seem to have taken a C type approach to naming where they use as short names as possible for everything. I know everyone wants to do as little typing as possible but I like a lot of programmers spend the majority of my time reading code rather that writing it so I find the choice between short non-descriptive names and long descriptive names, an easy one to make. (I like longer descriptive names xD)

A few examples, just looking at some modules in the standard library,

sched — Event scheduler, Could this have been EventScheduler?

asyncore — Asynchronous socket handler, AsynchronousSocketHandler?

imghdr — Determine the type of an image, DetermineImageType?

Pickle?

I know this isn't a huge issue but I find myself more often than not having to look up the meaning of any new (or forgotten) module I come across when in other languages like Objective-C or Java I can get this meaning straight away from the modules/functions/attributes definition.
On another note, people tend to write code similar to the way the standard library is written so you can be sure that if the standard library uses non-descriptive names the average developer will use even more non-descriptive names.

I was just wondering does anyone know why this is?

答:
Take a look at PEP 8

Highlights:

Modules should have short, all-lowercase names

Almost without exception, class names use the CapWords convention.  Classes for internal use have a leading underscore in addition.

Function names should be lowercase, with words separated by underscores as necessary to improve readability.

And then there's the Zen of Python.  In any case, AFAIK there is no prescription for using explicit, descriptive, obvious names driven by the Python community - it's left up to the developer.


来源: stackexchange

问:
How to remove a part of all strings in an array in javascript?
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.

答:
The below code is not tested but should probably work, with maybe minor tweaks

var splitStr = ''
var correctCarArr = []
for(let i = 0; i < gUser.length; i++){
  splitStr = gUser[i].split('.')
  let temp = ''
  for(let j = 1; j < splitStr.length; j++){
    temp += splitStr[j]
  }
  correctCarArr.push(temp)
}```

ContentLicense: CC BY-SA 3.0


问:
why can't we do Html.ActionLink("Edit Dinner", "Edit", new { dinner=Model })?
```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        <%:Model.Title %></h2>
    <fieldset>
        <legend>
            <%: Model.HostedBy %></legend>
        <p>
            <strong>When: </strong>
            <%: Model.EventDate.ToShortDateString() %>
            <strong>at: </strong>
            <%: Model.EventDate.ToShortTimeString() %>
        </p>
        <p>
            <strong>Description: </strong>
            <%: Model.Description %>
        </p>
    </fieldset>
    <p>
        <%: Html.ActionLink("Edit Dinner", "Edit", new { dinner=Model }) %>
        |
        <%: Html.ActionLink("Delete Dinner", "Delete", new { id=Model.DinnerId }) %>
        |
        <%: Html.ActionLink("Back to Dinner list", "Index") %>
    </p>
</asp:Content>
</code>```

<hr>

```<code>public ActionResult Edit(Dinner dinner)
{
    //Dinner dinner = dinnerRepository.GetDinnerById(id);

    if (dinner == null)
        return View("NotFound");
    else
        return View(dinner);
}

[HttpPost]
public ActionResult Edit(Dinner dinner, object dummy)
{
    Dinner temp = dinnerRepository.GetDinnerById(dinner.DinnerId);

    if (TryUpdateModel(temp))
    {
        dinnerRepository.Save();

        return RedirectToAction("Details", new { id = dinner.DinnerId });
    }
    else
        return View(temp);
}
</code>```

答: If you did that then the entire Dinner object and all of its properties would have to be passed in the URL. I find that less desirable than passing in a simple ID and obtaining the Dinner object from that.

Body:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<NerdDinner.Models.Dinner>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Details
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

        <%:Model.Title %>

    <fieldset>
        <legend>
            <%: Model.HostedBy %></legend>

            When:
            <%: Model.EventDate.ToShortDateString() %>
            at:
            <%: Model.EventDate.ToShortTimeString() %>

            Description:
            <%: Model.Description %>

    </fieldset>

        <%: Html.ActionLink("Edit Dinner", "Edit", new { dinner=Model }) %>
        |
        <%: Html.ActionLink("Delete Dinner", "Delete", new { id=Model.DinnerId }) %>
        |
        <%: Html.ActionLink("Back to Dinner list", "Index") %>

</asp:Content>

public ActionResult Edit(Dinner dinner)
{
    //Dinner dinner = dinnerRepository.GetDinnerById(id);

    if (dinner == null)
        return View("NotFound");
    else
        return View(dinner);
}

[HttpPost]
public ActionResult Edit(Dinner dinner, object dummy)
{
    Dinner temp = dinnerRepository.GetDinnerById(dinner.DinnerId);

    if (TryUpdateModel(temp))
    {
        dinnerRepository.Save();

        return RedirectToAction("Details", new { id = dinner.DinnerId });
    }
    else
        return View(temp);
}

ContentLicense: CC BY-SA 2.5


答:
var gUser = [];
gUser[1] = "CAR.BENZ.CCLASS.1962";
var gu1 = gUser[1].split(".");
gu1.shift();
console.log(gu1.join("."));```

Title: How to remove a part of all strings in an array in javascript?

Body:
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.


问:
looping a curl data using php
need your help... how can I convert it on looping:

```<code>//first
    $url1="https://www.zopim.com/api/v2/chats";
    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, $url1);
    curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    $output1 = curl_exec($ch1);
    $info1 = curl_getinfo($ch1);
    curl_close($ch1);

    $chats1 = json_decode($output1,true);
</code>```

for example there's a specific number count to loop like 4 or more numbers...
then i would like to get all the $chats... and merge..

like this:

```<code>$merge_array = array_merge_recursive($chats1, $chats2, $chats3, $chats4);
</code>```

hope you can help me guy's thanks...

答:
Try to do it like this:

```<code>$chats = [];
for($i=1; $i<= $n; $i++){
    $url1="https://www.zopim.com/api/v2/chats";
    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, $url1);
    curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    $output1 = curl_exec($ch1);
    $info1 = curl_getinfo($ch1);
    curl_close($ch1);

    $chats[] = json_decode($output1,true);
}
$merge_array = call_user_func_array('array_merge_recursive', $chats);
echo json_encode($merge_array);
</code>```

Hope this is what you need.

Title: looping a curl data using php

Body:
need your help... how can I convert it on looping:

//first
    $url1="https://www.zopim.com/api/v2/chats";
    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, $url1);
    curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    $output1 = curl_exec($ch1);
    $info1 = curl_getinfo($ch1);
    curl_close($ch1);

    $chats1 = json_decode($output1,true);

for example there's a specific number count to loop like 4 or more numbers...
then i would like to get all the $chats... and merge..

like this:

$merge_array = array_merge_recursive($chats1, $chats2, $chats3, $chats4);

hope you can help me guy's thanks...

Body:
Try to do it like this:

$chats = [];
for($i=1; $i<= $n; $i++){
    $url1="https://www.zopim.com/api/v2/chats";
    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, $url1);
    curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
    curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    $output1 = curl_exec($ch1);
    $info1 = curl_getinfo($ch1);
    curl_close($ch1);

    $chats[] = json_decode($output1,true);
}
$merge_array = call_user_func_array('array_merge_recursive', $chats);
echo json_encode($merge_array);

Hope this is what you need.


问:
Color cycling for multiple matplotlib pyplot contour plots
It is possible to cycle line colors with basic plots in matplotlib.pyplot:

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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.plot(x, np.sin(x * f))
plt.show()
</code>```

This results in each partial sinewave plot having the next color from the cycler list, and it will wrap as necessary:

I am using the contour plot to draw a single contour. For each case I want to draw a single contour but I want the color shown to automatically cycle through a specified palette (so I can show a readable color-coded legend). However ax.set_prop_cycle doesn't seem to have the same effect here:

```<code>fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

# plot for multiple values of `f`
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2)
plt.show()
</code>```

Each plot (ring) has the same color - it hasn't automatically cycled. I would like to have each plot a different color. I know that each "full" contour plot does cycle through colors for each contour drawn as part of a single plot, but in my case I'm just drawing a single contour at a fixed "level".

Is there a reasonably straightforward way to do this without explicitly specifying a color for each plot? I eventually plan to plot a dynamic number of plots, so it is not really practical to specify them all, and I need it to wrap around when required.

Perhaps there is a way to set or rotate the starting offset of a contour plot's color map?

答:
You can specify the keyword colors in plt.contour. I don't know if this is the best possible solution, but I wrote a small cycler function for your color values, so that I can feed them to plt.contour upon each iteration of the for-loop:

```<code>from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
##ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

def col_cycler(cols):
    count = 0
    while True:
        yield cols[count]
        count = (count + 1)%len(cols)

# plot for multiple values of `f`
col_iter = col_cycler(['c','m', 'y','k'])
for f in [1.0, 2.0, 3.0, 4.0, 5.0]:
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2, colors=next(col_iter))
plt.show()
</code>```

The result looks like this:

Tested on Python 3.5

Body:
It is possible to cycle line colors with basic plots in matplotlib.pyplot:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.plot(x, np.sin(x * f))
plt.show()

This results in each partial sinewave plot having the next color from the cycler list, and it will wrap as necessary:

I am using the contour plot to draw a single contour. For each case I want to draw a single contour but I want the color shown to automatically cycle through a specified palette (so I can show a readable color-coded legend). However ax.set_prop_cycle doesn't seem to have the same effect here:

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

# plot for multiple values of `f`
for f in [1.0, 2.0, 3.0, 4.0]:
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2)
plt.show()

Each plot (ring) has the same color - it hasn't automatically cycled. I would like to have each plot a different color. I know that each "full" contour plot does cycle through colors for each contour drawn as part of a single plot, but in my case I'm just drawing a single contour at a fixed "level".

Is there a reasonably straightforward way to do this without explicitly specifying a color for each plot? I eventually plan to plot a dynamic number of plots, so it is not really practical to specify them all, and I need it to wrap around when required.

Perhaps there is a way to set or rotate the starting offset of a contour plot's color map?

Body:
You can specify the keyword colors in plt.contour. I don't know if this is the best possible solution, but I wrote a small cycler function for your color values, so that I can feed them to plt.contour upon each iteration of the for-loop:

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
##ax.set_prop_cycle(plt.cycler('color', ['c', 'm', 'y', 'k']))

x = np.linspace(-1.0, 1.0, 50)
y = np.linspace(-1.0, 1.0, 50)
z = np.zeros((len(x), len(y)))

# simple function to create useful contours:
def get_z(x, y, f):
    for i, u in enumerate(x):
        for j, v in enumerate(y):
            z[i, j] = (f * u) ** 2 + (f * v) ** 2
    return z

def col_cycler(cols):
    count = 0
    while True:
        yield cols[count]
        count = (count + 1)%len(cols)

# plot for multiple values of `f`
col_iter = col_cycler(['c','m', 'y','k'])
for f in [1.0, 2.0, 3.0, 4.0, 5.0]:
    ax.contour(x, y, get_z(x, y, f), levels=[1], linewidth=2, colors=next(col_iter))
plt.show()

The result looks like this:

Tested on Python 3.5


问:
select from two mysql tables where column value is similar and id is retrieved from previous page
i have a question. my english isn't well. so i hope i explain well...

i have two tables, tbl_home and tbl_office, the question is

how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..

```<code>$a=$_POST['home_id']
</code>```

the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form

```<code>    <?php
        $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);

         while($row = $result2->fetch_assoc()){
         $a=$row['case_no'];
        $bc=$row['colour'];

         echo " $a <br/> ";
         echo " $bc2 <br/>";
        ?>
</code>```

is the select statement above correct??

soo, i just want anybody to take a look a this specific statement and how to make it right

```<code>  $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";
</code>```

答:
u can use "inner join"  for example:
"SELECT t.home_id,t.case_no,t.name FROM tbl_office
t INNER JOIN tbl_home h ON h.case_no = h.case_no"</p>

Body:
i have a question. my english isn't well. so i hope i explain well...

i have two tables, tbl_home and tbl_office, the question is

how do i make a select statement from 2 tables which have identical value from column 'case_no' where it is referenced in both table..

$a=$_POST['home_id']

the code above is where i get the home_id from,
while the statement below is how i try to select both tables based on value in column 'case_no' of both table. but it is based on variable $a which i retrieved from form

    <?php
        $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$
$result2=$conn->query($sql2);

         while($row = $result2->fetch_assoc()){
         $a=$row['case_no'];
        $bc=$row['colour'];

         echo " $a
 ";
         echo " $bc2
";
        ?>

is the select statement above correct??

soo, i just want anybody to take a look a this specific statement and how to make it right

  $sql2 = "SELECT * FROM tbl_office WHERE case_no IN (SELECT * FROM tbl_home WHERE home_id = '$a'";


问:
"Online" validation with TensorFlow
My data is a set of matches and outcomes, listed chronologically. Normally, for purposes of "offline" validation, I'd run something like this to test how well my algorithm works:

```<code># train
for matches_batch, outcomes_bach in train_data:
    sess.run(optimizer, feed_dict={matches: matches_batch, outcomes: outcomes_batch})

# offline validation (just compute accuracy on test set)
test_accuracy = sess.run(accuracy, feed_dict={matches: test_matches, outcomes: test_outcomes})
print 'test accuracy = {:.2%}'.format(test_accuracy)
</code>```

However, in the real world. Things would be done "online", where I train on a bunch of matches offline, and then every time I predict a new match, I also update my model parameters by running the optimizer using the outcome, like this:

```<code># train
for matches_batch, outcomes_bach in train_data:
    sess.run(optimizer, feed_dict={matches: matches_batch, outcomes: outcomes_batch})

# online validation (update accuracy and model with each new data point)
test_accuracy = 0.0
for match, outcome in zip(test_matches, test_outcomes):
    _, acc = sess.run([optimizer, accuracy], feed_dict={matches: [match], outcomes: [outcome])
    test_accuracy += acc / len(test_matches)
print 'test accuracy = {:.2%}'.format(test_accuracy)
</code>```

The problem is that the above implementation of online testing (which is part of the validation scheme here) is slow.

Is there a way to speed up online validation like this with tensorflow?

答:
After having a quick look at the paper, here is what I think:

They update their model with a few (number unknown) samples, rather than one -- one could say they take enough samples to fill a minibatch.

They then validate on one fold.

What it means with respect to your implementation:

You don't need to retrain online on the entire fold, just on a minibatch

You don't have to compute the validation accuracy one sample at a time, take whichever approach is faster (minibatches, or even the whole dataset as in your code if you can afford it).

Both points above should speed up things significantly.

Finally, don't use test in lieu of validation, especially when it involves training on it.

Title: "Online" validation with TensorFlow

Body:
My data is a set of matches and outcomes, listed chronologically. Normally, for purposes of "offline" validation, I'd run something like this to test how well my algorithm works:

# train
for matches_batch, outcomes_bach in train_data:
    sess.run(optimizer, feed_dict={matches: matches_batch, outcomes: outcomes_batch})

# offline validation (just compute accuracy on test set)
test_accuracy = sess.run(accuracy, feed_dict={matches: test_matches, outcomes: test_outcomes})
print 'test accuracy = {:.2%}'.format(test_accuracy)

However, in the real world. Things would be done "online", where I train on a bunch of matches offline, and then every time I predict a new match, I also update my model parameters by running the optimizer using the outcome, like this:

# train
for matches_batch, outcomes_bach in train_data:
    sess.run(optimizer, feed_dict={matches: matches_batch, outcomes: outcomes_batch})

# online validation (update accuracy and model with each new data point)
test_accuracy = 0.0
for match, outcome in zip(test_matches, test_outcomes):
    _, acc = sess.run([optimizer, accuracy], feed_dict={matches: [match], outcomes: [outcome])
    test_accuracy += acc / len(test_matches)
print 'test accuracy = {:.2%}'.format(test_accuracy)

The problem is that the above implementation of online testing (which is part of the validation scheme here) is slow.

Is there a way to speed up online validation like this with tensorflow?


问:
How to remove elements from an array using filter() in JavaScript?
I need to remove all the elements from an array , and all the elements that are to be removed are being passed as arguments.
I am trying to use the filter method to remove them but it is not working properly.
The code is  :

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
   var arr1 = arr.filter(function(v){
    for(var i= 0;i < args.length;i++){
        if(arr.indexOf(args[i]) !== -1)
            return false;

    }
  });
    console.log(arr1);
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);```

I am using args array to store all the arguments into array.The first argument is the array from which elements are to be removed and the following arguments are the ones that are to deleted(It is sure they are present in the array) but somehow the filter function is not working properly and also for more info see,
FreeCodeCamp challenge

答:
Just for the record, the problem with your code is that you're looping over all elements of args every time, so you return false if any element of arr matches any element of args (the actual value passed to the callback is ignored).

To fix your code, get rid of that loop and test v against args:

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
  var arr1 = arr.filter(function(v) {
//    for (var i=0; i < args.length; i++) {
      if (args.indexOf(v) !== -1) {
        return false;
      }
      return true;
//    }
  });
  console.log(arr1);
  return arr1;    // return correct array
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);```
</div>
</div>
</p>

<p>Once you've done that, it's simple to see how it can be reduced (using rest parameters and an arrow function) to:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function destroyer(arr, ...args) {
  return arr.filter(v => !args.includes(v));
}

console.log( destroyer([1, 2, 3, 1, 2, 3], 2, 3) );</code>```

Body:
I need to remove all the elements from an array , and all the elements that are to be removed are being passed as arguments.
I am trying to use the filter method to remove them but it is not working properly.
The code is  :

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
   var arr1 = arr.filter(function(v){
    for(var i= 0;i < args.length;i++){
        if(arr.indexOf(args[i]) !== -1)
            return false;

    }
  });
    console.log(arr1);
  return arr;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

I am using args array to store all the arguments into array.The first argument is the array from which elements are to be removed and the following arguments are the ones that are to deleted(It is sure they are present in the array) but somehow the filter function is not working properly and also for more info see,
FreeCodeCamp challenge

Body:
Just for the record, the problem with your code is that you're looping over all elements of args every time, so you return false if any element of arr matches any element of args (the actual value passed to the callback is ignored).

To fix your code, get rid of that loop and test v against args:

function destroyer(arr) {
  // Remove all the values
  var args = Array.from(arguments);
  args.shift();
  console.log(args);
  var arr1 = arr.filter(function(v) {
//    for (var i=0; i < args.length; i++) {
      if (args.indexOf(v) !== -1) {
        return false;
      }
      return true;
//    }
  });
  console.log(arr1);
  return arr1;    // return correct array
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Once you've done that, it's simple to see how it can be reduced (using rest parameters and an arrow function) to:

function destroyer(arr, ...args) {
  return arr.filter(v => !args.includes(v));
}

console.log( destroyer([1, 2, 3, 1, 2, 3], 2, 3) );


问:
wholesale replacement of options html string within select?
I would like to 'toggle' the list of options in a select box.

I have the two sets of options as strings (American states and Canadian Provinces). However, I notice that in the DOM, the select object has no 'innerhtml' property (at least not according to w3schools).

Do I have to go and remove and replace the options one by one? How do I do this?

答:
What I would do is create both, each in a DIV; then just hide whichever is not needed. This eliminates the need for heavy DOM manipulation (as you're only doing that once, on page load, there are fewer opportunities to leak memory in certain browsers cough cough), and is harder to accidentally mess up the app state (what with Alberta and Alabama sharing the same code and all that).

This would be the initial page:

```<code><input type="radio" id="country_usa" name="country" value="USA"> USA
<input type="radio" id="country_canada" name="country" value="Canada"> Canada
<div id="usa_select"></div>
<div id="canada_select"></div>
</code>```

and JavaScript to go with it (jQuery used here for brevity):

```<code>$(document).ready(function(){
  // hide both <div> containers on page load
  $('#canada_select').hide();
  $('#usa_select').hide();
  // create and populate both <select> boxes:
  $('#canada_select').append('<select name="province_canada">'
      + '<option value="AL">Alberta</option>'
      + '<option value="BC">British Columbia</option>...'
      + '</select>'
  );
  $('#usa_select').append('<select name="state_usa">'
      + '<option value="AL">Alabama</option>'
      + '<option value="AK">Alaska</option>...'
      + '</select>'
  );
};

// we'll also need handlers to show the correct list,
//  depending on the selected country
$('#country_usa').click(function(){
  // we want US states
  $('#canada_select').hide();
  $('#usa_select').show();
});
$('#country_canada').click(function(){
  // we want Canadian provinces
  $('#usa_select').hide();
  $('#canada_select').show();
});
</code>```

This should be the result:

```<code><input type="radio" id="country_usa" name="country" value="USA"> USA
<input type="radio" id="country_canada" name="country" value="Canada"> Canada
<div id="usa_select">
  <select name="state_usa">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    ...
  </select>
</div>
<div id="canada_select">
  <select name="province_canada">
    <option value="AL">Alberta</option>
    <option value="BC">British Columbia</option>
    ...
  </select>
</div>
</code>```

At the backend, process state_usa iff country=='USA'; process province_canada iff country=='Canada'.

Body:
What I would do is create both, each in a DIV; then just hide whichever is not needed. This eliminates the need for heavy DOM manipulation (as you're only doing that once, on page load, there are fewer opportunities to leak memory in certain browsers cough cough), and is harder to accidentally mess up the app state (what with Alberta and Alabama sharing the same code and all that).

This would be the initial page:

<input type="radio" id="country_usa" name="country" value="USA"> USA
<input type="radio" id="country_canada" name="country" value="Canada"> Canada
<div id="usa_select"></div>
<div id="canada_select"></div>

and JavaScript to go with it (jQuery used here for brevity):

$(document).ready(function(){
  // hide both <div> containers on page load
  $('#canada_select').hide();
  $('#usa_select').hide();
  // create and populate both <select> boxes:
  $('#canada_select').append('<select name="province_canada">'
      + '<option value="AL">Alberta</option>'
      + '<option value="BC">British Columbia</option>...'
      + '</select>'
  );
  $('#usa_select').append('<select name="state_usa">'
      + '<option value="AL">Alabama</option>'
      + '<option value="AK">Alaska</option>...'
      + '</select>'
  );
};

// we'll also need handlers to show the correct list,
//  depending on the selected country
$('#country_usa').click(function(){
  // we want US states
  $('#canada_select').hide();
  $('#usa_select').show();
});
$('#country_canada').click(function(){
  // we want Canadian provinces
  $('#usa_select').hide();
  $('#canada_select').show();
});

This should be the result:

<input type="radio" id="country_usa" name="country" value="USA"> USA
<input type="radio" id="country_canada" name="country" value="Canada"> Canada
<div id="usa_select">
  <select name="state_usa">
    <option value="AL">Alabama</option>
    <option value="AK">Alaska</option>
    ...
  </select>
</div>
<div id="canada_select">
  <select name="province_canada">
    <option value="AL">Alberta</option>
    <option value="BC">British Columbia</option>
    ...
  </select>
</div>

At the backend, process state_usa iff country=='USA'; process province_canada iff country=='Canada'.


答:
Its easier split then shift the array to remove the first item like this:

gUser = ["CAR.BENZ.CCLASS.1962"];
var benz = gUser[0].split(".");
benz.shift();
alert(benz.join('.'));```

There are other options from shift like slice(1) but In terms of performance, shift is apparently faster https://jsperf.com/shift-pop-vs-slice/4

Body:
Its easier split then shift the array to remove the first item like this:

gUser = ["CAR.BENZ.CCLASS.1962"];
var benz = gUser[0].split(".");
benz.shift();
alert(benz.join('.'));

There are other options from shift like slice(1) but In terms of performance, shift is apparently faster https://jsperf.com/shift-pop-vs-slice/4


问:
Swift iOS: Set Gradient Background To A UITextView?
I'm trying to apply gradient background to a UITextView object, not sure if it's possible because I get white background instead.

Here is my UIView extension:

```<code>extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}
</code>```

Here where I assign gradient to the text view:

```<code>        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt
</code>```

Here are the colors in the Constants class:

```<code>    struct Colors{
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}
</code>```

I always get white background when using the gradient method. Appreciate any suggestions.

答:
You need to use locations property of CAGradientLayer

```<code>extension UIView{

    func setGriadientBackrnd(color1: UIColor, color2: UIColor){
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = [color1.cgColor, color2.cgColor]
        gradientLayer.locations = [0.5 , 0.5] //here you can set percentage of color part are display betwin 0 to 1
        layer.insertSublayer(gradientLayer, at: 0)
    }
}
</code>```

Body:
I'm trying to apply gradient background to a UITextView object, not sure if it's possible because I get white background instead.

Here is my UIView extension:

extension UIView{

func setTextGradient(startColor:UIColor,endColor:UIColor)
{
    let gradient:CAGradientLayer = CAGradientLayer()
    gradient.colors = [startColor.cgColor, endColor.cgColor]
    gradient.locations = [0.0 , 1.0]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
    gradient.endPoint = CGPoint(x: 0.0, y: 1.0)
    gradient.frame = self.bounds
    self.layer.insertSublayer(gradient, at: 0)
}

Here where I assign gradient to the text view:

        detailTxtView.translatesAutoresizingMaskIntoConstraints = false
    detailTxtView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
    detailTxtView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -8).isActive = true
    detailTxtView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 8).isActive = true
    detailTxtView.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.5).isActive = true

    detailTxtView.setTextGradient(startColor: Constants.Colors.bluLight, endColor: Constants.Colors.silver)

    // Set up text
    let attributedTxt = NSMutableAttributedString(string: titleStr, attributes:[NSFontAttributeName: UIFont(name: "Jazeel-Bold", size: 24)!, NSForegroundColorAttributeName: Constants.Colors.bluLight])

    attributedTxt.append(NSAttributedString(string: "\n\n\(detailStr)", attributes:[NSFontAttributeName: UIFont(name: "HacenTunisia", size: 20)!, NSForegroundColorAttributeName: Constants.Colors.aluminum]))

    let txtStyle = NSMutableParagraphStyle()
    txtStyle.alignment = .center
    let length = attributedTxt.string.count
    attributedTxt.addAttribute(NSParagraphStyleAttributeName, value: txtStyle, range: NSRange(location: 0, length: length))

    detailTxtView.attributedText = attributedTxt

Here are the colors in the Constants class:

    struct Colors{
    static let bluDark      = UIColor(colorLiteralRed: 51/255, green: 50/255, blue: 80/255, alpha: 1)
    static let bluLight     = UIColor(colorLiteralRed: 68/255, green: 85/255, blue: 138/255, alpha: 1)
    static let greenLight   = UIColor(colorLiteralRed: 200/255, green: 255/255, blue: 132/255, alpha: 1)
    static let mercury      = UIColor(colorLiteralRed: 235/255, green: 235/255, blue: 235/255, alpha: 1)
    static let silver       = UIColor(colorLiteralRed: 214/255, green: 214/255, blue: 214/255, alpha: 1)
    static let magnesium    = UIColor(colorLiteralRed: 192/255, green: 192/255, blue: 192/255, alpha: 1)
    static let aluminum     = UIColor(colorLiteralRed: 169/255, green: 169/255, blue: 169/255, alpha: 1)
    static let blu2         = UIColor(colorLiteralRed: 88/255, green: 120/255, blue: 166/255, alpha: 0.2)
    static let bluLighter = #colorLiteral(red: 0.451, green: 0.5569, blue: 0.8314, alpha: 1) /* #738ed4 */
}

I always get white background when using the gradient method. Appreciate any suggestions.

Body:
You need to use locations property of CAGradientLayer

extension UIView{

    func setGriadientBackrnd(color1: UIColor, color2: UIColor){
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = [color1.cgColor, color2.cgColor]
        gradientLayer.locations = [0.5 , 0.5] //here you can set percentage of color part are display betwin 0 to 1
        layer.insertSublayer(gradientLayer, at: 0)
    }
}


问:
Shared User Certificates Required for Application but disallowed in Store
I have written a simple UWP application to play media triggered by RFID tags. This function requires the Shared User Certificates capability to be enabled to connect to the card reader using:

```<code>smartCardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id);
</code>```

If I remove this capability I get a System.UnauthorizedAccessException (Access is denied).

When I run the application certification I get:

```<code>   Warning: The app has declared the following special use capabilities:
   *The app has declared the sharedUserCertificates capability.*
   Impact if not fixed: If you don’t have a company account with the Windows Store, you won’t be able to upload this app.
</code>```

As I have no company account it means that I cannot upload this application to the store for private distribution. Is there anything I can do to work around this limitation besides side-loading this application onto the required machines?

答:
Is there anything I can do to work around this limitation besides
  side-loading this application onto the required machines?

For private distribution, Hockey App can be an option if you're not able to upload the Store submission.

It still makes your app installed onto user's machine via sideloading. But it can be convenient for your distribution and it can help to collect crash report as well as get feedback from users.

Body:
I have written a simple UWP application to play media triggered by RFID tags. This function requires the Shared User Certificates capability to be enabled to connect to the card reader using:

smartCardReader = await SmartCardReader.FromIdAsync(deviceInfo.Id);

If I remove this capability I get a System.UnauthorizedAccessException (Access is denied).

When I run the application certification I get:

   Warning: The app has declared the following special use capabilities:
   *The app has declared the sharedUserCertificates capability.*
   Impact if not fixed: If you don’t have a company account with the Windows Store, you won’t be able to upload this app.

As I have no company account it means that I cannot upload this application to the store for private distribution. Is there anything I can do to work around this limitation besides side-loading this application onto the required machines?


问:
Cannot determine current directory
I am trying to run a .jar file that was created successfully in Netbeans and I am receiving the following error:

Error occurred during initialization of VM java.lang.Error:
  Properties init: Could not determine current working directory. at
  java.lang.System.initProperties(Native Method) at
  java.lang.System.initializeSystemClass(System.java:1070)

The command that I type to run the .jar is

```<code>java -jar "/path to the dist forlder/EOPPrototype.jar"
</code>```

My classpath is as follows:

```<code>CLASSPATH=/opt/netbeans-7.1.2/ide/modules/ext/mysql-connector-java-5.1.13-     bin.jar:/h/USERS/local/pagola/NetBeansProjects/mylib/dist/mylib.jar:/h/USERS/local/pagola/NetBeansProjects/EOPPrototype/build/classes:.
</code>```

What am i missing?

答:
maybe you did not config java environment on your workstation correctly

the following configurations were what I did in my mac

```<code>vi ~/.bash_profile
</code>```

and add those in it

```<code>JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
PATH=$JAVA_HOME/bin:$PATH:.
CLASSPATH=$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:.
export JAVA_HOME
export PATH
export CLASSPATH
</code>```

replace

```<code>JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
</code>```

with your jdk version
and then run

```<code>source ~/.bash_profile
</code>```

to use these config immediately
then you can check by

```<code>java -version
</code>```

Title: Cannot determine current directory

Body:
I am trying to run a .jar file that was created successfully in Netbeans and I am receiving the following error:

Error occurred during initialization of VM java.lang.Error:
  Properties init: Could not determine current working directory. at
  java.lang.System.initProperties(Native Method) at
  java.lang.System.initializeSystemClass(System.java:1070)

The command that I type to run the .jar is

java -jar "/path to the dist forlder/EOPPrototype.jar"

My classpath is as follows:

CLASSPATH=/opt/netbeans-7.1.2/ide/modules/ext/mysql-connector-java-5.1.13-     bin.jar:/h/USERS/local/pagola/NetBeansProjects/mylib/dist/mylib.jar:/h/USERS/local/pagola/NetBeansProjects/EOPPrototype/build/classes:.

What am i missing?

Body:
maybe you did not config java environment on your workstation correctly

the following configurations were what I did in my mac

vi ~/.bash_profile

and add those in it

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home
PATH=$JAVA_HOME/bin:$PATH:.
CLASSPATH=$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar:.
export JAVA_HOME
export PATH
export CLASSPATH

replace

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home

with your jdk version
and then run

source ~/.bash_profile

to use these config immediately
then you can check by

java -version


问:
Drupal "You are not authorized to access this page"
I've taken over managing our site from MIA developers and have spent the day trying to find this answer.

After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).

Here's what I know:

Drupal Version 7.56

PHP 7.0.20

No errors when status report is run

Chron - no errors

Here's what I've done:

added $cookie_domain = '.example.com'; to settings.php

cleared browser cache and cookies

ensured admin has access to everything

cleared site cache

made sure code on page(s) was exactly the same as it was before I did the update

Not sure what to do or where to go from here. Any help is much appreciated.

UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.

Image 1: viewing page as admin

Image 2: viewing page as superadmin

```<code>function custom_reports_menu() {

    $items['administration/upcoming-classes'] = array(
    'title' => 'Upcoming Classes',
    'page callback' => 'custom_reports_upcoming_classes_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.upcoming-classes.inc',
    'type' => MENU_CALLBACK,
    );

    $items['administration/class-details'] = array(
    'title' => 'Class Details',
    'page callback' => 'custom_reports_class_details_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.class-details.inc',
    'type' => MENU_CALLBACK,
    );
    return $items;

}

function custom_reports_upcoming_classes_page() {

    drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));

    global $user;
    $uid = $user->uid;

    $output = '';

    $upcoming_classes = custom_reports_get_upcoming_classes();
    $attendee_count = custom_reports_get_attendee_count();

    // upcoming classes
    $output .= '<h2>Upcoming Classes</h2>';
    $output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);

    return $output;
}

function custom_reports_permission() {

  return array(
    'admin wdcc reports' => array(
      'title' => t('Admin WDCC Reports'),
      'description' => t('Perform administration tasks for WDCC.'),
      //'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

function custom_reports_get_upcoming_classes() {

    $today = date('Y-m-d');

    $x = 0;
    $classes = '';

    // get classes from new db tables
    $today = date('Y-m-d H:i:s');

    $result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {

            $nid = $row->nid;
            $node = node_load($nid);

            $product_id = $nid;
            $product_title = $node->title;
            $product_type = 'public_class_date';
            $product_date = $node->field_date[$node->language][0]['value'];
            $product_datestamp = strtotime($product_date);
            //$product_datestamp = strtotime($product_date);

            // set vars
            $classes[$x]['product_id'] = $product_id;
            $classes[$x]['product_title'] = $product_title;
            $classes[$x]['product_type'] = $product_type;
            $classes[$x]['product_date'] = $product_date;
            $classes[$x]['product_datestamp'] = $product_datestamp;

            $x++;
        }
    }

    return $classes;
}

function custom_reports_get_attendee_count() {

    $attendees = array();
    $old_attendees = array();
    $new_attendees = array();

    $result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $item_id = $row->itemID;
            $attendee_id = 'B'.$row->attendeeID;
            $attendee_name = $row->attendeeName;

            $old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;

            if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
            } else {
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
            }
        }
    }
    if (is_array($old_attendees)) {
        $connect_class_ids = custom_accounts_connect_class_ids();
        foreach ($old_attendees as $old_item_id => $attendee_list) {
            if (isset($connect_class_ids[$old_item_id])) {
                $product_id = $connect_class_ids[$old_item_id];
                foreach ($attendee_list as $attendee_id => $attendee) {
                    $old_attendee_id = $attendee['old_attendee_id'];
                    $attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
                }
            }
        }
    }
    $result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->id;
            $product_id = $row->product_id;
            $attendees[$product_id][$attendee_id]['total_attendees'] = 1;
        }
    }
    $cancelled_attendees = array();
    $result = db_query("SELECT * FROM wdcc_attendees_cancelled");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->attendee_id;
            $old_attendee_id = 'B'.$row->old_attendee_id;

            if ($attendee_id > 0) {
                $cancelled_attendees[] = $attendee_id;
            } else {
                $cancelled_attendees[] = $old_attendee_id;
            }
        }
    }
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (in_array($attendee_id, $cancelled_attendees)) {
                unset($attendees[$product_id][$attendee_id]);
            }
        }
    }
    $attendee_count = array();
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (!isset($attendee_count[$product_id])) {
                $attendee_count[$product_id] = $attendee['total_attendees'];
            } else {
                $attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
            }
        }
    }

    return $attendee_count;
}

function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {

    $output = '';

    if (is_array($upcoming_classes)) {
        $output .= '<div class="table-responsive table-container">';
        $output .= '<table class="table">';
        $output .= '<tr><td>Class</td><td>Guests</td><td>Actions</td></tr>';
        foreach ($upcoming_classes as $class) {
            $nid = $class['product_id'];
            $node_url = url('node/'.$nid, array('absolute' => TRUE));
            $attendees = 0;
            if (isset($attendee_count[$nid])) {
                $attendees = $attendee_count[$nid];
            }

            $output .= '<tr><td><a href="'.$node_url.'">'.$class['product_title'].'</a><br />'.date('m/d/Y - g:i A', $class['product_datestamp']).'</td><td>'.$attendees.'</td><td><a href="/administration/class-details/'.$class['product_id'].'">View roster</a></td></tr>';
        }
        $output .= '</table>';
        $output .= '</div>';
    } else {
        $output .= '<p>No upcoming classes found.</p>';
    }

    return $output;
}
</code>```

答:
In the current menu items you are using access callback attribute in a wrong way. Your menu items do not require to specify access callback. Only access argument is sufficient.

Please add an access argument to which only admin has access.

"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments' (see below).

Source: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_menu/7.x

Body:
I've taken over managing our site from MIA developers and have spent the day trying to find this answer.

After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).

Here's what I know:

Drupal Version 7.56

PHP 7.0.20

No errors when status report is run

Chron - no errors

Here's what I've done:

added $cookie_domain = '.example.com'; to settings.php

cleared browser cache and cookies

ensured admin has access to everything

cleared site cache

made sure code on page(s) was exactly the same as it was before I did the update

Not sure what to do or where to go from here. Any help is much appreciated.

UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.

Image 1: viewing page as admin

Image 2: viewing page as superadmin

function custom_reports_menu() {

    $items['administration/upcoming-classes'] = array(
    'title' => 'Upcoming Classes',
    'page callback' => 'custom_reports_upcoming_classes_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.upcoming-classes.inc',
    'type' => MENU_CALLBACK,
    );

    $items['administration/class-details'] = array(
    'title' => 'Class Details',
    'page callback' => 'custom_reports_class_details_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.class-details.inc',
    'type' => MENU_CALLBACK,
    );
    return $items;

}

function custom_reports_upcoming_classes_page() {

    drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));

    global $user;
    $uid = $user->uid;

    $output = '';

    $upcoming_classes = custom_reports_get_upcoming_classes();
    $attendee_count = custom_reports_get_attendee_count();

    // upcoming classes
    $output .= '
Upcoming Classes
';
    $output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);

    return $output;
}

function custom_reports_permission() {

  return array(
    'admin wdcc reports' => array(
      'title' => t('Admin WDCC Reports'),
      'description' => t('Perform administration tasks for WDCC.'),
      //'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

function custom_reports_get_upcoming_classes() {

    $today = date('Y-m-d');

    $x = 0;
    $classes = '';

    // get classes from new db tables
    $today = date('Y-m-d H:i:s');

    $result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {

            $nid = $row->nid;
            $node = node_load($nid);

            $product_id = $nid;
            $product_title = $node->title;
            $product_type = 'public_class_date';
            $product_date = $node->field_date[$node->language][0]['value'];
            $product_datestamp = strtotime($product_date);
            //$product_datestamp = strtotime($product_date);

            // set vars
            $classes[$x]['product_id'] = $product_id;
            $classes[$x]['product_title'] = $product_title;
            $classes[$x]['product_type'] = $product_type;
            $classes[$x]['product_date'] = $product_date;
            $classes[$x]['product_datestamp'] = $product_datestamp;

            $x++;
        }
    }

    return $classes;
}

function custom_reports_get_attendee_count() {

    $attendees = array();
    $old_attendees = array();
    $new_attendees = array();

    $result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $item_id = $row->itemID;
            $attendee_id = 'B'.$row->attendeeID;
            $attendee_name = $row->attendeeName;

            $old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;

            if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
            } else {
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
            }
        }
    }
    if (is_array($old_attendees)) {
        $connect_class_ids = custom_accounts_connect_class_ids();
        foreach ($old_attendees as $old_item_id => $attendee_list) {
            if (isset($connect_class_ids[$old_item_id])) {
                $product_id = $connect_class_ids[$old_item_id];
                foreach ($attendee_list as $attendee_id => $attendee) {
                    $old_attendee_id = $attendee['old_attendee_id'];
                    $attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
                }
            }
        }
    }
    $result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->id;
            $product_id = $row->product_id;
            $attendees[$product_id][$attendee_id]['total_attendees'] = 1;
        }
    }
    $cancelled_attendees = array();
    $result = db_query("SELECT * FROM wdcc_attendees_cancelled");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->attendee_id;
            $old_attendee_id = 'B'.$row->old_attendee_id;

            if ($attendee_id > 0) {
                $cancelled_attendees[] = $attendee_id;
            } else {
                $cancelled_attendees[] = $old_attendee_id;
            }
        }
    }
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (in_array($attendee_id, $cancelled_attendees)) {
                unset($attendees[$product_id][$attendee_id]);
            }
        }
    }
    $attendee_count = array();
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (!isset($attendee_count[$product_id])) {
                $attendee_count[$product_id] = $attendee['total_attendees'];
            } else {
                $attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
            }
        }
    }

    return $attendee_count;
}

function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {

    $output = '';

    if (is_array($upcoming_classes)) {
        $output .= '
';
        $output .= '
';
        $output .= '
Class	Guests	Actions
';
        foreach ($upcoming_classes as $class) {
            $nid = $class['product_id'];
            $node_url = url('node/'.$nid, array('absolute' => TRUE));
            $attendees = 0;
            if (isset($attendee_count[$nid])) {
                $attendees = $attendee_count[$nid];
            }

            $output .= '
'.$class['product_title'].'
'.date('m/d/Y - g:i A', $class['product_datestamp']).'	'.$attendees.'	View roster
';
        }
        $output .= '
';
        $output .= '
';
    } else {
        $output .= '
No upcoming classes found.
';
    }

    return $output;
}


问:
Figure title with underline by LaTeXStrings.jl and PyPlot.jl
I want to generate a figure whose title is rendered by LaTeXStrings.jl

However, when I try to use \underline, ValueError is returned.

What should I do?

Sample code is

```<code>using PyPlot
using LaTeXStrings

title = L"\underline{\theta}"

fig, ax = subplots()
ax[:plot](randn(100))
ax[:set_title](title, useTex=true)
</code>```

The error is

```<code>PyError (:PyObject_Call) <type 'exceptions.ValueError'>
ValueError(u'\n\\underline{\\theta}\n^\nUnknown symbol: \\underline (at char 0), (line:1, col:1)',)
</code>```

答: Adding rc("text", usetex=true) solves the issue

Body:
I want to generate a figure whose title is rendered by LaTeXStrings.jl

However, when I try to use \underline, ValueError is returned.

What should I do?

Sample code is

using PyPlot
using LaTeXStrings

title = L"\underline{\theta}"

fig, ax = subplots()
ax[:plot](randn(100))
ax[:set_title](title, useTex=true)

The error is

PyError (:PyObject_Call) <type 'exceptions.ValueError'>
ValueError(u'\n\\underline{\\theta}\n^\nUnknown symbol: \\underline (at char 0), (line:1, col:1)',)


问:
Find a Document based on a Reference To the Parent In the Child
There are  2 collections Movie and Rank Movie .This 2 collections having referenced relationship .

Movie model

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

var movieSchema = new mongoose.Schema({
    m_tmdb_id: {
        type: Number,
        unique: true,
        index: true
    },
    m_adult: {
        type: Boolean
    },
    m_backdrop_path: {
        type: String,
    },
    m_title: {
        type: Number
    },
    m_genres: {
        type: Array
    }

});
var MovieModel = mongoose.model('Movie', movieSchema);
module.exports = {
    movie: MovieModel
}
</code>```

Rank movie model

```<code>var mongoose = require('mongoose');
var rankMovieSchema = new mongoose.Schema({
    movie: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Movie',
        unique: true
    },
    rank: {
        type: Number
    },
    count: {
        type: Number
    }
});
var RankMovieModel = mongoose.model('RankMovie', rankMovieSchema);
module.exports = {
    rankmovie: RankMovieModel
}
</code>```

I need to  select all the items from the collection rank movie having  a particular  title[Condition on movie collection ].How can i achieve this?

答:
Actually the "best" way to do this is rather using .aggregate() and $lookup to "join" the data and "filter" on the match conditions. This is very effective since MongoDB actually performs all of this on the "server" itself, as compared to issuing "multiple" queries as .populate() does.

```<code>MovieModel.aggregate([
  { "$match": { "m_title": m_title } },
  { "$lookup": {
    "from": RankMovieModel.collection.name,
    "localField": "_id",
    "foreignField": "movie",
    "as": "rankings"
  }}
])
</code>```

Note: The RankMovieModel.collection.name is a nice way of getting the "underlying" collection name from the Model registered with Mongoose. Since the operation is on the "server", MongoDB needs the "real collection name", so we can either "hardcode" that or just get it from the information registered on the Model itself. As is done here.

If there are "lots" of rankings, then you are best to use $unwind, which will create a document for each related "rankings" item:

```<code>MovieModel.aggregate([
  { "$match": { "m_title": m_title } },
  { "$lookup": {
    "from": RankMovieModel.collection.name,
    "localField": "_id",
    "foreignField": "movie",
    "as": "rankings"
  }},
  { "$unwind": "$rankings" }
])
</code>```

There is also a special handling here of how MongoDB deals with "joining" documents to avoid breaching the 16MB BSON limit. So in fact this special thing happens when $unwind directly follows a $lookup pipeline stage:

```<code>    {
        "$lookup" : {
            "from" : "rankmovies",
            "as" : "rankings",
            "localField" : "_id",
            "foreignField" : "movie",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            }
        }
    }
</code>```

So the $unwind actually "disappears" and instead is "rolled-up" into the $lookup itself as if this were "one" operation. That way we do not create an "array" directly within the parent document which would cause the size to exceed 16MB in extreme cases with many "related" items.

If you do not have a MongoDB that supports $lookup ( MongoDB 3.2 minunum ) then you could use a "virtual" with .populate() instead (requires Mongoose 4.5.0 minimum). But note this actually performs "two" queries to the server:

First add the "virtual" to the schema:

```<code>movieSchema.virtual("rankings",{
  "ref": "Movie",
  "localField": "_id",
  "foreignField": "movie"
});
</code>```

Then issue the query with .populate():

```<code>MovieModel.find({ "m_title": m_title })
  .populate('rankings')
  .exec()
</code>```

Body:
There are  2 collections Movie and Rank Movie .This 2 collections having referenced relationship .

Movie model

var mongoose = require('mongoose');

var movieSchema = new mongoose.Schema({
    m_tmdb_id: {
        type: Number,
        unique: true,
        index: true
    },
    m_adult: {
        type: Boolean
    },
    m_backdrop_path: {
        type: String,
    },
    m_title: {
        type: Number
    },
    m_genres: {
        type: Array
    }

});
var MovieModel = mongoose.model('Movie', movieSchema);
module.exports = {
    movie: MovieModel
}

Rank movie model

var mongoose = require('mongoose');
var rankMovieSchema = new mongoose.Schema({
    movie: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Movie',
        unique: true
    },
    rank: {
        type: Number
    },
    count: {
        type: Number
    }
});
var RankMovieModel = mongoose.model('RankMovie', rankMovieSchema);
module.exports = {
    rankmovie: RankMovieModel
}

I need to  select all the items from the collection rank movie having  a particular  title[Condition on movie collection ].How can i achieve this?

Body:
Actually the "best" way to do this is rather using .aggregate() and $lookup to "join" the data and "filter" on the match conditions. This is very effective since MongoDB actually performs all of this on the "server" itself, as compared to issuing "multiple" queries as .populate() does.

MovieModel.aggregate([
  { "$match": { "m_title": m_title } },
  { "$lookup": {
    "from": RankMovieModel.collection.name,
    "localField": "_id",
    "foreignField": "movie",
    "as": "rankings"
  }}
])

Note: The RankMovieModel.collection.name is a nice way of getting the "underlying" collection name from the Model registered with Mongoose. Since the operation is on the "server", MongoDB needs the "real collection name", so we can either "hardcode" that or just get it from the information registered on the Model itself. As is done here.

If there are "lots" of rankings, then you are best to use $unwind, which will create a document for each related "rankings" item:

MovieModel.aggregate([
  { "$match": { "m_title": m_title } },
  { "$lookup": {
    "from": RankMovieModel.collection.name,
    "localField": "_id",
    "foreignField": "movie",
    "as": "rankings"
  }},
  { "$unwind": "$rankings" }
])

There is also a special handling here of how MongoDB deals with "joining" documents to avoid breaching the 16MB BSON limit. So in fact this special thing happens when $unwind directly follows a $lookup pipeline stage:

    {
        "$lookup" : {
            "from" : "rankmovies",
            "as" : "rankings",
            "localField" : "_id",
            "foreignField" : "movie",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            }
        }
    }

So the $unwind actually "disappears" and instead is "rolled-up" into the $lookup itself as if this were "one" operation. That way we do not create an "array" directly within the parent document which would cause the size to exceed 16MB in extreme cases with many "related" items.

If you do not have a MongoDB that supports $lookup ( MongoDB 3.2 minunum ) then you could use a "virtual" with .populate() instead (requires Mongoose 4.5.0 minimum). But note this actually performs "two" queries to the server:

First add the "virtual" to the schema:

movieSchema.virtual("rankings",{
  "ref": "Movie",
  "localField": "_id",
  "foreignField": "movie"
});

Then issue the query with .populate():

MovieModel.find({ "m_title": m_title })
  .populate('rankings')
  .exec()


答:
Split it with dot then slice it and join it with dot

var gUser =[];
gUser[1] = "CAR.BENZ.CCLASS.1962";

gUser[2] = "CAR.PORSCHE.911.2001";

console.log(gUser[1].split('.').slice(1).join('.'));
console.log(gUser[2].split('.').slice(1).join('.'));```

Body:
I want split array value .

for example

gUser[1] = CAR.BENZ.CCLASS.1962

gUser[2] = CAR.PORSCHE.911.2001

I want get string only BENZ.CLASS.1962 and PORSCHE.911.2001

How to split array value on java script?

@update.

not always CAR string.
so, not use substring.


问:
Making HTTP Requests using Chrome Developer tools
Is there a way to make an HTTP request using the Chrome Developer tools without using a plugin like POSTER?</p>

答: If you want to do a POST from the same domain, you can always insert a form into the DOM using Developer tools and submit that:


问:
How to pass a deleter to a method in the same class that is held by a shared_ptr
I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps using lambdas?  or bind?

```<code>struct StagingConfigDatabase
{
  static StagingConfigDatabase* create();
  void destroy();
};

template<class T>
    struct RfaDestroyer
    {
        void operator()(T* t)
        {
            if(t) t->destroy();
        }
    };

    int main()
    {
      shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), RfaDestroyer<StagingConfigDatabase>());
    return 1;
    }
</code>```

I was considering something like:

```<code>shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );
</code>```

but that doesn't compile :(

Help!

答:
I'll assume that create is static in StagingConfigDatabase because your initial code wouldn't compile without it. Regarding destruction, you can use a simple std::mem_fun :

```<code>#include <memory>

boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));
</code>```

Body:
I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps using lambdas?  or bind?

struct StagingConfigDatabase
{
  static StagingConfigDatabase* create();
  void destroy();
};

template<class T>
    struct RfaDestroyer
    {
        void operator()(T* t)
        {
            if(t) t->destroy();
        }
    };

    int main()
    {
      shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), RfaDestroyer<StagingConfigDatabase>());
    return 1;
    }

I was considering something like:

shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), [](StagingConfigDatabase* sdb) { sdb->destroy(); } );

but that doesn't compile :(

Help!

Body:
I'll assume that create is static in StagingConfigDatabase because your initial code wouldn't compile without it. Regarding destruction, you can use a simple std::mem_fun :

#include <memory>

boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));


问:
How to make test case parameters invisible or read-only in selenium IDE
I need to give a suite of test cases (Selenium IDE) to a client but I need the case parameters to be invisible or read-only to the client.

Is there any possibility of doing this?

答:
Its quite unclear what you are referring to when saying "parameter". I assume these is the data (ex. values provided to your test cases, like userid, password, etc).

If you have inserted these value in testng.xml or as dataprovider in the code, then NO. There is no way you can hide it from client.

Instead you can fetch this data as from an external excel file and mark it as write protected. This will solve the your problem


问:
how to select id from one table and insert into other table
```<code> $select = "SELECT MAX(order_id) FROM `order`";
       mysql_query($select);

   foreach ($_COOKIE['item'] as $key12 => $value) {
        $value22 = explode("__", $value);

        $query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
        $result2 = mysql_query($query1);
</code>```

The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

答:
one another way to find last inserted id from the db connection:

```<code>mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();
</code>```

then $id will be last inserted id

Body:
 $select = "SELECT MAX(order_id) FROM `order`";
       mysql_query($select);

   foreach ($_COOKIE['item'] as $key12 => $value) {
        $value22 = explode("__", $value);

        $query1 = "INSERT INTO `cart`(`cart_id`, `product_id`, `order_id`, `Quantity`, `total_price`) VALUES ('',$value22[5],'$select','$value22[3]','$value22[4]')";
        $result2 = mysql_query($query1);

The output of this is SELECT MAX(order_id) FROM order, so what is the solution of this selection and insertion of the id

Body:
one another way to find last inserted id from the db connection:

mysql_query('INSERT INTO order(a) VALUES('b'));
$id = mysql_insert_id();

then $id will be last inserted id


问:
YIi2 get records not contained in another table
I would like to retrieve records in one table not contained in another

I have two tables

```<code>tb_users having columns
   id(primary key)
   username,
   firstname,

2. tbl_paychecks
     id(primary key)
     user_id(foreignkey)
     amount
     created_at
     ...
</code>```

NOw i would like to retrieve all the users without paychecks that it all tbl_users whose id's are not in the tbl_paychecks

So in my users model

```<code>public function getNOPaychecks()
  {
    return self::find()
      ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
       ->where(['tbl_paycheks.user_id'=>null])
       ->all();
   }
</code>```

But the above still returns an error of

```<code>unknown column tbl_paycheks.user_id in 'where clause
</code>```

Where am i going wrong?

答:
You have a type in yout table name tbl_paycheks instead of tbl_paychecksand  for null you could use is

```<code>public function getNOPaychecks()
{
  return self::find()
    ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
     ->where(['is', 'tbl_paychecks.user_id', null])
     ->all();
 }
</code>```

Body:
I would like to retrieve records in one table not contained in another

I have two tables

tb_users having columns
   id(primary key)
   username,
   firstname,

2. tbl_paychecks
     id(primary key)
     user_id(foreignkey)
     amount
     created_at
     ...

NOw i would like to retrieve all the users without paychecks that it all tbl_users whose id's are not in the tbl_paychecks

So in my users model

public function getNOPaychecks()
  {
    return self::find()
      ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
       ->where(['tbl_paycheks.user_id'=>null])
       ->all();
   }

But the above still returns an error of

unknown column tbl_paycheks.user_id in 'where clause

Where am i going wrong?

Body:
You have a type in yout table name tbl_paycheks instead of tbl_paychecksand  for null you could use is

public function getNOPaychecks()
{
  return self::find()
    ->leftJoin('tbl_paychecks','`tbl_paychecks`.`user_id` != `tbl_user`.`id`')
     ->where(['is', 'tbl_paychecks.user_id', null])
     ->all();
 }


问:
How to break out column names in MySQL similar to MS SQL Server?
Is there a way to have MySQL break out the individual column names and have them pre-written in your query similar to the "script>table as" function in MS SQL Server?

My workaround has been using "describe 'table'" in MySQL and copying the columns into the query and adding commas, but there has to be an easier way.

Thanks!

答: From MYSQL Workbench: Right click on a table then select 'Send to SQL Editor->Select All Statement'


问:
aspnetboilerplate .NET Core SignalR Integration
I am using ABP's .NET Core template now, and have a need for real time notifications.

I read through ABP's documentation on SignalR, and wish to implement it, but when I tried to install the ABP's SignalR package, it complains that it is not compatible with .NET Core.

Is there something I am missing? Thanks.

答:
SignalR 2 is built for .NET Framework, not for .NET Core. They are still working on SignalR for .NET Core.

https://vimeo.com/204078084


问:
Is this a naming convention or a function declaration
I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

```<code>var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}
</code>```

does test1 is a part of stringFunction or just a naming convention.Thanks in advance

答: in JavaScript every function is a Function Object. see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function. In you sample the code create a property 'test1' on object stringFunction. The new property is itsealf a Function Object.</p>

Body:
I am learning javascript and now started with objects and basic functions. I came across this type of code and was wondering what exactly is this

var stringFunction = function(){};

stringFunction.test1 = function(){
  console.log("Test 1");
}

does test1 is a part of stringFunction or just a naming convention.Thanks in advance


问:
Clearing a jQuery Form
I have been doing some research on a good way to clear a jQuery form.

I have a couple of ideas but I want to know if someone has a better way.

I know about using reset, but sometimes it is necessary to set a field back to a particular value that may not be accomplished by reset. (ie. if a form starts with some pre-filled data and you want to clear it)

I have read some discussion here: Resetting a multi-stage form with jQuery

But I have another idea that I will post as an answer. Please let me know what you think and if you have a better solution.

More Information:

For example I have an address form. It has a couple of inputs, selects, radios, etc. along with a copy into new button and a clear button. By default I want to have this particular radio selected to option 1.

```<code><div id = "AddressList">
<div class = "Address">
<input type="radio"/> --obviously with some options here
<button>copy into new</button>
</div>
</div>
</code>```

The user selected option two and clicks copy into new. So I say something like on the click of the click of the copy into new:

```<code>$("#addressList").append($(this).closest("#Address").html());
</code>```

In the second address the secon radio button is selected. The user selects the third radio button. At this point clicking the reset button would reset the input back to option two not option one.

答:
My solution would be to add the attribute called clear.

Then say $([clear]).val($(this).atrr('clear'))

Title: Clearing a jQuery Form

Body:
I have been doing some research on a good way to clear a jQuery form.

I have a couple of ideas but I want to know if someone has a better way.

I know about using reset, but sometimes it is necessary to set a field back to a particular value that may not be accomplished by reset. (ie. if a form starts with some pre-filled data and you want to clear it)

I have read some discussion here: Resetting a multi-stage form with jQuery

But I have another idea that I will post as an answer. Please let me know what you think and if you have a better solution.

More Information:

For example I have an address form. It has a couple of inputs, selects, radios, etc. along with a copy into new button and a clear button. By default I want to have this particular radio selected to option 1.

<input type="radio"/> --obviously with some options here
<button>copy into new</button>

The user selected option two and clicks copy into new. So I say something like on the click of the click of the copy into new:

$("#addressList").append($(this).closest("#Address").html());

In the second address the secon radio button is selected. The user selects the third radio button. At this point clicking the reset button would reset the input back to option two not option one.


问:
Pagination with "cursors" using Admin-on-rest
My back-end API supports cursor based pagination for the GET_LIST operations.

```<code>API: {apiUrl}/{resource}?fltr={limit:100}

Response:
{
data: [],
next: {reference_url_to_the_next_paginated_data_set}
}
</code>```

What is the best way to supported this sort of pagination with the existing AOR pagination infrastructure ?

答:
You need to write a custom Rest client to handle your response and request type. You need your API to set the X-Total-Count header when your client makes a GET_LIST type request.

https://marmelab.com/admin-on-rest/RestClients.html

Body:
My back-end API supports cursor based pagination for the GET_LIST operations.

API: {apiUrl}/{resource}?fltr={limit:100}

Response:
{
data: [],
next: {reference_url_to_the_next_paginated_data_set}
}

What is the best way to supported this sort of pagination with the existing AOR pagination infrastructure ?


问:
Replace string on a line using sed command
I have following content in a file

```<code>return o.baseUrl="http://info.example.com/api/v1/",a.init=t,o.login=e(o.baseUrl+"login",{email:"@email",password:"@password"}
</code>```

I want to replace info.example.com with api.example.com

Currently I am using

```<code>sed -i "s/^info\.example\.com.*$/api.example.com/g" /var/html/www/index.js
</code>```

But this is not working.
I don't know much about regular expression.
Can somebody help me on this ?

答:
In sed you can provide exact expression to be replaced.

```<code>sed 's/info\.example.com/api.example.com/g' file
</code>```

Body:
I have following content in a file

return o.baseUrl="http://info.example.com/api/v1/",a.init=t,o.login=e(o.baseUrl+"login",{email:"@email",password:"@password"}

I want to replace info.example.com with api.example.com

Currently I am using

sed -i "s/^info\.example\.com.*$/api.example.com/g" /var/html/www/index.js

But this is not working.
I don't know much about regular expression.
Can somebody help me on this ?

Body:
In sed you can provide exact expression to be replaced.

sed 's/info\.example.com/api.example.com/g' file


问:
dropbox.rest.ErrorResponse: [400] 'invalid_grant'
I'm new in Python and start playing around to access different API and now I got to Dropbox APIs.
But I got a "invalid_grant" access when I try to access my own account.

```<code>import dropbox
app_key = 'AAAA'
app_secret = 'BBBB'

flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
authorize_url = flow.start()

print ('1. Go to: ' + authorize_url)
print ('2. Click "Allow" (you might have to log in first)')
print ('3. Copy the authorization code.')
code = 'CCCC'

access_token, user_id = flow.finish(code)
</code>```

When I runt this script I got following output.

Traceback (most recent call last):
  File "PATH/dropboxdownload.py", line 14, in
  access_token, user_id = flow.finish(code)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\client.py", line 1398, in finish
  return self._finish(code, None)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\client.py", line 1265, in _finish
  response = self.rest_client.POST(url, params=params)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\rest.py", line 316, in POST
  return cls.IMPL.POST(*n, **kw)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\rest.py", line 254, in POST
  post_params=params, headers=headers, raw_response=raw_response)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\rest.py", line 227, in request
  raise ErrorResponse(r, r.read())
  dropbox.rest.ErrorResponse: [400] 'invalid_grant'
  Process finished with exit code 1

答:
If this error continues use the following link:

```<code>https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=**your ID**
</code>```

Make sure to add your ID to the client_id parameter.

Body:
I'm new in Python and start playing around to access different API and now I got to Dropbox APIs.
But I got a "invalid_grant" access when I try to access my own account.

import dropbox
app_key = 'AAAA'
app_secret = 'BBBB'

flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
authorize_url = flow.start()

print ('1. Go to: ' + authorize_url)
print ('2. Click "Allow" (you might have to log in first)')
print ('3. Copy the authorization code.')
code = 'CCCC'

access_token, user_id = flow.finish(code)

When I runt this script I got following output.

Traceback (most recent call last):
  File "PATH/dropboxdownload.py", line 14, in
  access_token, user_id = flow.finish(code)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\client.py", line 1398, in finish
  return self._finish(code, None)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\client.py", line 1265, in _finish
  response = self.rest_client.POST(url, params=params)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\rest.py", line 316, in POST
  return cls.IMPL.POST(*n, **kw)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\rest.py", line 254, in POST
  post_params=params, headers=headers, raw_response=raw_response)
  File "PATH\Python35-32\lib\site-packages\dropbox-2.2.0-py3.5.egg\dropbox\rest.py", line 227, in request
  raise ErrorResponse(r, r.read())
  dropbox.rest.ErrorResponse: [400] 'invalid_grant'
  Process finished with exit code 1

Body:
If this error continues use the following link:

https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=**your ID**

Make sure to add your ID to the client_id parameter.