问:
What does "del sys.modules[module]" actually do?
As everyone knows, you can do del sys.modules[module] to delete an imported module. So I was thinking: how is this different from rewriting sys.modules? An interesting fact is, rewriting sys.modules can't truely delete a module.

```<code># a_module.py
print("a module imported")
</code>```

Then

```<code>import sys

def func1():
    import a_module
    # del sys.modules['a_module']
    sys.modules = {
        k: v for k, v in sys.modules.items() if 'a_module' not in k}
    print('a_module' not in sys.modules)  # True

def func2():
    import a_module

func1()  # a module imported
func2()  # no output here
</code>```

If I use del sys.modules['a_module'], calling func2() also prints a module imported, which implies that a_module is successfully deleted.

My question is: What does del sys.modules[module] actually do, besides changing the dictionary?

答:
sys.modules is the Python-accessible reference to the canonical data structure for tracking what modules are imported. Removing a name from that dictionary means that any future attempts to import the module will result in Python loading the module from scratch.

In other words, whenever you use an import statement, the first thing Python does is check if the dictionary that sys.modules references already has an entry for that module and proceed with the next step (binding names in the current namespace) without loading the module first. If you delete entries from sys.modules, then Python won't find the already-loaded module and loads again.

Note the careful wording about Python-accessible here. The actual dictionary lives on the Python heap and sys.modules is just one reference to it. You replaced that reference with another dictionary by assigning to sys.modules. However, the interpreter has more references to it; they just are not accessible from Python code, not without ctypes trickery to access the C-API anyway.

Note that this is explicitly documented:

However, replacing the dictionary will not necessarily work as expected and deleting essential items from the dictionary may cause Python to fail.

From the C-API, you'd have to use PyThreadState_Get()->interp->modules to get the internal reference to the dictionary.

Body:
As everyone knows, you can do del sys.modules[module] to delete an imported module. So I was thinking: how is this different from rewriting sys.modules? An interesting fact is, rewriting sys.modules can't truely delete a module.

# a_module.py
print("a module imported")

Then

import sys

def func1():
    import a_module
    # del sys.modules['a_module']
    sys.modules = {
        k: v for k, v in sys.modules.items() if 'a_module' not in k}
    print('a_module' not in sys.modules)  # True

def func2():
    import a_module

func1()  # a module imported
func2()  # no output here

If I use del sys.modules['a_module'], calling func2() also prints a module imported, which implies that a_module is successfully deleted.

My question is: What does del sys.modules[module] actually do, besides changing the dictionary?


来源: stackexchange

问:
event stop propagation issue with children event
I have an issue with jquery stop propagation.
To close a cart modal when i click on the page except on the cart modal, i had to do :

```<code>        $('html').click(function() {
            $('.cart-block').css('display','none');
        });

        $('.mycart, .cart-block').click(function(event){
            event.stopPropagation();

        });
</code>```

But i have an issue, i have an AJAX call to delete an item inside my cart div (cart-block) but the stop propagation is stopping the event.

```<code>$(document).on('click', '.deleteItem', function() {
    //ajax call
});
</code>```

Is anyone can help me ?
thanks a lot
(sorry for my english)

EDIT : HTML STRUCTURE
//button cart

```<code>  <div class="center cart mycart" >
           //icon and cart item counter
            </div>

        <div id="cartcaption" class="cart-block">
    //modal : content of the cart
<div class="productsPanier">
 <span id="{{$cart->rowId}}" class="deleteItem">delete</span>
    </div>
</div>
</code>```

答:
Instead of what you're doing (binding 2 handlers with one stopping propagation), just bind one handler and check whether the target of event has class .cart-block

So something like this:

```<code>$('html').click(function(event) {
   if (!$(event.target).hasClass('cart-block'))
      $('.cart-block').css('display','none');
});
</code>```

And remove the following part

```<code> $('.mycart, .cart-block').click(function(event){
    event.stopPropagation();
 });
</code>```

Your events will now properly propagate and the 'display: none;' won't get added to cart block if you're clicking within cart-block element

EDIT: if the outermost class is named 'mycart', you could alternatively try it like this:

```<code>$('html').click(function(event) {
   if (!($(event.target).closest('.mycart').length))
      $('.cart-block').css('display','none');
});
</code>```

What this will do is check if the target element of your click has a parent with class 'mycart'. This solution assumes that whatever you click inside the cart has a container with class 'mycart'. Obviously, without seeing your DOM, I cannot be sure this will solve your specific case. If it's different to what I assumed, it should point you in the right direction at least.

ContentLicense: CC BY-SA 3.0

Body:
I have an issue with jquery stop propagation.
To close a cart modal when i click on the page except on the cart modal, i had to do :

        $('html').click(function() {
            $('.cart-block').css('display','none');
        });

        $('.mycart, .cart-block').click(function(event){
            event.stopPropagation();

        });

But i have an issue, i have an AJAX call to delete an item inside my cart div (cart-block) but the stop propagation is stopping the event.

$(document).on('click', '.deleteItem', function() {
    //ajax call
});

Is anyone can help me ?
thanks a lot
(sorry for my english)

EDIT : HTML STRUCTURE
//button cart

           //icon and cart item counter

    //modal : content of the cart

 rowId}}" class="deleteItem">delete

Body:
Instead of what you're doing (binding 2 handlers with one stopping propagation), just bind one handler and check whether the target of event has class .cart-block

So something like this:

$('html').click(function(event) {
   if (!$(event.target).hasClass('cart-block'))
      $('.cart-block').css('display','none');
});

And remove the following part

 $('.mycart, .cart-block').click(function(event){
    event.stopPropagation();
 });

Your events will now properly propagate and the 'display: none;' won't get added to cart block if you're clicking within cart-block element

EDIT: if the outermost class is named 'mycart', you could alternatively try it like this:

$('html').click(function(event) {
   if (!($(event.target).closest('.mycart').length))
      $('.cart-block').css('display','none');
});

What this will do is check if the target element of your click has a parent with class 'mycart'. This solution assumes that whatever you click inside the cart has a container with class 'mycart'. Obviously, without seeing your DOM, I cannot be sure this will solve your specific case. If it's different to what I assumed, it should point you in the right direction at least.


问:
OrderBy nothing happens mysql
```<code>SELECT *, count(spieler) as 'Anzahl'

FROM spieler, teilnehmer, durchfuehrung

WHERE spieler.id = teilnehmer.spieler and teilnehmer.istErschienen = 1 and teilnehmer.durchfuehrung = durchfuehrung.id and durchfuehrung.wurdeUeberprueft = 1

GROUP BY  teilnehmer.spieler

ORDER BY 'Anzahl' DESC;
</code>```

ORDER BY is useless in this way... Please help me to correct this mysql Query, so that the Alias Anzahl ist ordered desc....

答:
I think you should not quote your alias Anzahl

You should be carefully, if you are using aggregate Functions like count() with a SELECT *. You can't group it very well and it is forbidden by convention.

Better try something like this:

```<code>SELECT
    spieler.id,
    teilnehmer.durchfuehrung,
    COUNT(*) AS anzahl
FROM
    spieler,
    teilnehmer,
    durchfuehrung
WHERE
    spieler.id = teilnehmer.spieler
AND
    teilnehmer.istErschienen = 1
AND
    teilnehmer.durchfuehrung = durchfuehrung.id
AND
    durchfuehrung.wurdeUeberprueft = 1
GROUP BY
    spieler.id,
    teilnehmer.durchfuehrung
ORDER BY
    anzahl DESC;
</code>```

Title: OrderBy nothing happens mysql

Body:
SELECT *, count(spieler) as 'Anzahl'

FROM spieler, teilnehmer, durchfuehrung

WHERE spieler.id = teilnehmer.spieler and teilnehmer.istErschienen = 1 and teilnehmer.durchfuehrung = durchfuehrung.id and durchfuehrung.wurdeUeberprueft = 1

GROUP BY  teilnehmer.spieler

ORDER BY 'Anzahl' DESC;

ORDER BY is useless in this way... Please help me to correct this mysql Query, so that the Alias Anzahl ist ordered desc....

Body:
I think you should not quote your alias Anzahl

You should be carefully, if you are using aggregate Functions like count() with a SELECT *. You can't group it very well and it is forbidden by convention.

Better try something like this:

SELECT
    spieler.id,
    teilnehmer.durchfuehrung,
    COUNT(*) AS anzahl
FROM
    spieler,
    teilnehmer,
    durchfuehrung
WHERE
    spieler.id = teilnehmer.spieler
AND
    teilnehmer.istErschienen = 1
AND
    teilnehmer.durchfuehrung = durchfuehrung.id
AND
    durchfuehrung.wurdeUeberprueft = 1
GROUP BY
    spieler.id,
    teilnehmer.durchfuehrung
ORDER BY
    anzahl DESC;


问:
Multi-dimensional array return keys with duplicate values
Please Help! I want to validate array with duplicate sub-array values. I have an multi-dimensional array. I want to return keys of sub-array with duplicate product_id value. Example: In my array, I have sub-array with duplicate product_id = 124. I want to return their key.

```<code>[purchase_order_products] => Array
    (
        [0] => Array
            (
                [product_id] => 124
                [barcode] => 480001407081
                [item_code] =>
                [name] => Brew Kettle Can 330mL
                [qty] =>
                [unit] => 2
                [pcs_have] => 1
                [total_pcs] => 1
                [cost] => 34.83
                [total_item_price] => 34.83
                [stocks] =>
                [po_qty] =>
            )

        [1] => Array
            (
                [product_id] => 125
                [barcode] => 480001416108
                [item_code] =>
                [name] => Colt 45 Can 330mL
                [qty] =>
                [unit] => 2
                [pcs_have] => 1
                [total_pcs] => 1
                [cost] => 29.58
                [total_item_price] => 29.58
                [stocks] =>
                [po_qty] =>
            )

        [2] => Array
            (
                [product_id] => 124
                [barcode] => 480001407081
                [item_code] =>
                [name] => Brew Kettle Can 330mL
                [qty] =>
                [unit] => 2
                [pcs_have] => 1
                [total_pcs] => 1
                [cost] => 34.83
                [total_item_price] => 34.83
                [stocks] =>
                [po_qty] =>
            )
)
</code>```

The output I want is:

```<code>Array(0,2)
</code>```

答:
Edit: I've updated the answer quite a bit.

Edit 2: Now utilizing the built in array functions to find the duplicates

```<code>$products = [
  0 => ['product-id' => 124],
  1 => ['product-id' => 125],
  2 => ['product-id' => 124],
  3 => ['product-id' => 126],
  4 => ['product-id' => 126],
  8 => ['product-id' => 124],
];

// Find the duplicates
$product_ids = array_column($products, 'product-id');
$count = array_count_values($product_ids);
$duplicates = array_filter($count, function($var) {
  return $var > 1;
});

// List all the entries with duplicate ids:
foreach ( array_flip($duplicates) as $product_id ) {
  $filter = array_filter($products, function($var) use ($product_id) {
    return ( $var['product-id'] === $product_id );
  });
  print_r('Product-id: ' . $product_id . ' is duplicated in entries: ');
  print_r(array_keys($filter));
}
</code>```

The output:

```<code>// Product-id: 124 is duplicated in entries: Array
// (
//     [0] => 0
//     [1] => 2
//     [2] => 8
// )
// Product-id: 126 is duplicated in entries: Array
// (
//     [0] => 3
//     [1] => 4
// )
</code>```

Body:
Please Help! I want to validate array with duplicate sub-array values. I have an multi-dimensional array. I want to return keys of sub-array with duplicate product_id value. Example: In my array, I have sub-array with duplicate product_id = 124. I want to return their key.

[purchase_order_products] => Array
    (
        [0] => Array
            (
                [product_id] => 124
                [barcode] => 480001407081
                [item_code] =>
                [name] => Brew Kettle Can 330mL
                [qty] =>
                [unit] => 2
                [pcs_have] => 1
                [total_pcs] => 1
                [cost] => 34.83
                [total_item_price] => 34.83
                [stocks] =>
                [po_qty] =>
            )

        [1] => Array
            (
                [product_id] => 125
                [barcode] => 480001416108
                [item_code] =>
                [name] => Colt 45 Can 330mL
                [qty] =>
                [unit] => 2
                [pcs_have] => 1
                [total_pcs] => 1
                [cost] => 29.58
                [total_item_price] => 29.58
                [stocks] =>
                [po_qty] =>
            )

        [2] => Array
            (
                [product_id] => 124
                [barcode] => 480001407081
                [item_code] =>
                [name] => Brew Kettle Can 330mL
                [qty] =>
                [unit] => 2
                [pcs_have] => 1
                [total_pcs] => 1
                [cost] => 34.83
                [total_item_price] => 34.83
                [stocks] =>
                [po_qty] =>
            )
)

The output I want is:

Array(0,2)

Body:
Edit: I've updated the answer quite a bit.

Edit 2: Now utilizing the built in array functions to find the duplicates

$products = [
  0 => ['product-id' => 124],
  1 => ['product-id' => 125],
  2 => ['product-id' => 124],
  3 => ['product-id' => 126],
  4 => ['product-id' => 126],
  8 => ['product-id' => 124],
];

// Find the duplicates
$product_ids = array_column($products, 'product-id');
$count = array_count_values($product_ids);
$duplicates = array_filter($count, function($var) {
  return $var > 1;
});

// List all the entries with duplicate ids:
foreach ( array_flip($duplicates) as $product_id ) {
  $filter = array_filter($products, function($var) use ($product_id) {
    return ( $var['product-id'] === $product_id );
  });
  print_r('Product-id: ' . $product_id . ' is duplicated in entries: ');
  print_r(array_keys($filter));
}

The output:

// Product-id: 124 is duplicated in entries: Array
// (
//     [0] => 0
//     [1] => 2
//     [2] => 8
// )
// Product-id: 126 is duplicated in entries: Array
// (
//     [0] => 3
//     [1] => 4
// )


问:
ASP .NET MVC Controller Injection issue
In my ASP .NET MVC WebApi project I have controller constructor that receive a parameter, I don't have a prameterless constructor.

The dependecies are injected using Ninject:

Ninject 3.2.0.0 (3.2.2)

Ninject.Web.Common 3.2.0.0 (3.2.3)

Ninject.Web.WebApi 3.2.0.0 (3.2.4)

When I call the API I get:

An exception of type 'Ninject.ActivationException' occurred in
  Ninject.dll but was not handled in user code

Additional information: Error activating IHubRepository

No matching bindings are available, and the type is not self-bindable.

Activation path:

2) Injection of dependency IHubRepository into parameter
  repHub of constructor of type ResultController

1) Request for ResultController

Suggestions:

1) Ensure that you have defined a binding for IHubRepository.

2) If the binding was defined in a module, ensure that the module
  has been loaded into the kernel.

3) Ensure you have not accidentally created more than one kernel.

4) If you are using constructor arguments, ensure that the parameter
  name matches the constructors parameter name.

5) If you are using automatic module loading, ensure the search path
  and filters are correct.

The code is the following.

Controller:

```<code>public class ResultController : BaseHubController
{
    public ResultController(IHubRepository repHub)
    {
        _rep = repHub;
    }

    public async Task<IHttpActionResult> Get(string fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            return BadRequest();

        return Ok();
    }
}
</code>```

NinjectResolver

```<code>public sealed class NinjectResolver : NinjectScope, IDependencyResolver
{
    private IKernel kernel;

    public NinjectResolver(IKernel kernelParam)
        : base(kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(kernel.BeginBlock());
    }

    public void AddBindings()
    {
        kernel.Bind<Hub.Dal.IHubRepository>().To<Hub.Dal.HubRepository>();
        kernel.Bind<System.Data.Entity.DbContext>().To<Hub.Dal.Context>();
    }
}

public class NinjectScope : IDependencyScope
{
    protected IResolutionRoot resolutionRoot;
    public NinjectScope(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }
    public object GetService(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).SingleOrDefault();
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).ToList();
    }
    public void Dispose()
    {
        IDisposable disposable = (IDisposable)resolutionRoot;
        if (disposable != null) disposable.Dispose();
        resolutionRoot = null;
    }
}
</code>```

IHubRepository

```<code>public interface IHubRepository
{
    bool LogRequest(SHApiLog logData);
}
</code>```

HubRepository

```<code>public class HubRepository : IHubRepository
{
    private DbContext _ctx;

    public HubRepository(DbContext curCtx)
    {
        this._ctx = curCtx;
    }

    public bool LogRequest(SHApiLog logData)
    {
        try
        {
            _ctx.Set<SHApiLog>().Add(logData);
            _ctx.SaveChanges();
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}
</code>```

I can't understand why it won't work.

答:
I banged my head for two days, by adding, changing and removing references to Ninject, changing the code and so on..

Solved with a complete delete of the solution and a new, clear get from TFS.

Probably there was a pesky reference somewhere in the code; I'm so sad.

Title: ASP .NET MVC Controller Injection issue

Body:
In my ASP .NET MVC WebApi project I have controller constructor that receive a parameter, I don't have a prameterless constructor.

The dependecies are injected using Ninject:

Ninject 3.2.0.0 (3.2.2)

Ninject.Web.Common 3.2.0.0 (3.2.3)

Ninject.Web.WebApi 3.2.0.0 (3.2.4)

When I call the API I get:

An exception of type 'Ninject.ActivationException' occurred in
  Ninject.dll but was not handled in user code

Additional information: Error activating IHubRepository

No matching bindings are available, and the type is not self-bindable.

Activation path:

2) Injection of dependency IHubRepository into parameter
  repHub of constructor of type ResultController

1) Request for ResultController

Suggestions:

1) Ensure that you have defined a binding for IHubRepository.

2) If the binding was defined in a module, ensure that the module
  has been loaded into the kernel.

3) Ensure you have not accidentally created more than one kernel.

4) If you are using constructor arguments, ensure that the parameter
  name matches the constructors parameter name.

5) If you are using automatic module loading, ensure the search path
  and filters are correct.

The code is the following.

Controller:

public class ResultController : BaseHubController
{
    public ResultController(IHubRepository repHub)
    {
        _rep = repHub;
    }

    public async Task<IHttpActionResult> Get(string fileName)
    {
        if (String.IsNullOrEmpty(fileName))
            return BadRequest();

        return Ok();
    }
}

NinjectResolver

public sealed class NinjectResolver : NinjectScope, IDependencyResolver
{
    private IKernel kernel;

    public NinjectResolver(IKernel kernelParam)
        : base(kernelParam)
    {
        kernel = kernelParam;
        AddBindings();
    }
    public IDependencyScope BeginScope()
    {
        return new NinjectScope(kernel.BeginBlock());
    }

    public void AddBindings()
    {
        kernel.Bind<Hub.Dal.IHubRepository>().To<Hub.Dal.HubRepository>();
        kernel.Bind<System.Data.Entity.DbContext>().To<Hub.Dal.Context>();
    }
}

public class NinjectScope : IDependencyScope
{
    protected IResolutionRoot resolutionRoot;
    public NinjectScope(IResolutionRoot kernel)
    {
        resolutionRoot = kernel;
    }
    public object GetService(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).SingleOrDefault();
    }
    public IEnumerable<object> GetServices(Type serviceType)
    {
        IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
        return resolutionRoot.Resolve(request).ToList();
    }
    public void Dispose()
    {
        IDisposable disposable = (IDisposable)resolutionRoot;
        if (disposable != null) disposable.Dispose();
        resolutionRoot = null;
    }
}

IHubRepository

public interface IHubRepository
{
    bool LogRequest(SHApiLog logData);
}

HubRepository

public class HubRepository : IHubRepository
{
    private DbContext _ctx;

    public HubRepository(DbContext curCtx)
    {
        this._ctx = curCtx;
    }

    public bool LogRequest(SHApiLog logData)
    {
        try
        {
            _ctx.Set<SHApiLog>().Add(logData);
            _ctx.SaveChanges();
        }
        catch (Exception)
        {
            return false;
        }

        return true;
    }
}

I can't understand why it won't work.


问:
importing java com.google.* libraries
I am having issues importing com.google.* libraries.

I am very new to eclipse and do not know how to import these libraries to fix my code errors. Can someone point me in the right direction to importing these libraries?

答:
Import Google libraries the same way you do any others, with the Java import statement. Or in Eclipse, add them to the project build path.

This assumes, of course, you HAVE the Google libraries. If you're asking how to import than from a remote location (e.g., a Google server) that can't be done. You'll need to download them first to your project directory & go from there.

Title: importing java com.google.* libraries

ContentLicense: CC BY-SA 2.5


问:
Set and get checked boxes in MultiSelectListPreference
I'm defining the MultiSelectListPreference in my axml file like this:

```<code> <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>
</code>```

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

The checked values appear there, but I have no idea how to get them...

答:
This was also my first thought, but e.NewValue doesn't contain a public definition for 'GetEnumerator'.

We can simply cast e.NewValue from object to IEnumerable in our code, for example:

```<code>private void PreferenceChange(object sender, Preference.PreferenceChangeEventArgs e)
{
    var selections = e.NewValue as IEnumerable;
    if (selections != null)
    {
        foreach (var selection in selections)
        {
            Console.WriteLine(selection);
        }
    }
}
</code>```

Body:
I'm defining the MultiSelectListPreference in my axml file like this:

 <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

The checked values appear there, but I have no idea how to get them...

Body:
This was also my first thought, but e.NewValue doesn't contain a public definition for 'GetEnumerator'.

We can simply cast e.NewValue from object to IEnumerable in our code, for example:

private void PreferenceChange(object sender, Preference.PreferenceChangeEventArgs e)
{
    var selections = e.NewValue as IEnumerable;
    if (selections != null)
    {
        foreach (var selection in selections)
        {
            Console.WriteLine(selection);
        }
    }
}


问:
Select tag not including options after the first time
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

```<code>$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"<label for='make'>Please select a make:</label>
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }
</code>```

What to d0 here?

答:
simply add name attribute to select tag and remove from option tag.</p>

```<code>$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
$i=0;
echo"<label for='make'>Please select a make:</label>
<select name='make'>
<option value='All'>All</option>";
while($row= mysqli_fetch_row($queryResult)){
echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
}
</code>```

Body:
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("
Unable to query the $TableName table.
"."
Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "
";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"Please select a make:
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }

What to d0 here?

Body:
simply add name attribute to select tag and remove from option tag.

$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
$i=0;
echo"<label for='make'>Please select a make:</label>
<select name='make'>
<option value='All'>All</option>";
while($row= mysqli_fetch_row($queryResult)){
echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
}


问:
Rearrange hierarchy in a list of lists in R
I wonder if there exists a simple way to do the following thing in R:

Suppose I have a bunch of data on four cars: white BMW, black BMW, white GMC and black GMC.

I put them in a list of lists named cars:

data on white BMW is in cars[[1]][[1]],

data on black BMW is in cars[[1]][[2]],

data on white GMC is in cars[[2]][[1]],

data on black GMC is in cars[[2]][[2]].

In this case the first coordinate indicates make of the car, while the second indicates its colour.

I now wish to swap the coordinates so that the first coordinate would indicate colour, while the second would indicate the make of the car:

data on white BMW is in cars[[1]][[1]],

data on black BMW is in cars[[2]][[1]],

data on white GMC is in cars[[1]][[2]],

data on black GMC is in cars[[2]][[2]].

Thus I want to change the hierarchy in a list of lists.

Any help appreciated!

答:
Another solution on the same sample data

cars <- list(list("white BMW", "black BMW"), list("white GMC", "black GMC"))

is

```<code>do.call(function(...) Map(list, ...), cars)
</code>```

which keeps the names of the elements intact.

Body:
Another solution on the same sample data

cars <- list(list("white BMW", "black BMW"), list("white GMC", "black GMC"))

is

do.call(function(...) Map(list, ...), cars)

which keeps the names of the elements intact.


问:
How to rotate a 3d plot in python? (or as a animation) Rotate 3-D view using mouse
I have this code which contains a 3D plot. I run the code in Spyder; I want to know if it is possible to make this plot a rotating one (360 degrees) and save it.
Thanks!
P.s. Sorry if it is a silly question, but I am a newby in Python. </p>

```<code>import matplotlib.pyplot as plt
import numpy as np
from scipy import array
jet = plt.get_cmap('jet')
from matplotlib import animation
fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.linspace(70,40,4)
Y = np.linspace(5,2,4)
X,Y=  np.meshgrid(X, Y)

Z = array ([
        [1223.539555, 1428.075086,1714.479425, 2144.053223],
        [1567.26647,1829.056119,2990.416079,2745.320067],
        [2135.163957,2491.534201, 2990.416079,3738.761638],
        [3257.280827, 3800.655101, 4561.372117, 5702.458776],
        ])

surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = jet,linewidth = 0,alpha= 1)
ax.set_zlim3d(0, Z.max())

fig.colorbar(surf, shrink=0.8, aspect=5)
ax.set_xlabel('Axial Length [mm]')
ax.set_ylabel('nbTurns')
ax.set_zlabel('RPM')

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

答:
You need to define a function in order to get a specific animation. In your case it is a simple rotation:

```<code>def rotate(angle):
    ax.view_init(azim=angle)
</code>```

Then use the matplotlib animation:

```<code>rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0,362,2),interval=100)
</code>```

This will call the rotate function with the frames argument as angles and with an interval of 100ms, so this will result in a rotation over 360° with a 2° step each 100ms. To save the animation as a gif file:

```<code>rot_animation.save('path/rotation.gif', dpi=80, writer='imagemagick')
</code>```

Body:
I have this code which contains a 3D plot. I run the code in Spyder; I want to know if it is possible to make this plot a rotating one (360 degrees) and save it.
Thanks!
P.s. Sorry if it is a silly question, but I am a newby in Python.

import matplotlib.pyplot as plt
import numpy as np
from scipy import array
jet = plt.get_cmap('jet')
from matplotlib import animation
fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.linspace(70,40,4)
Y = np.linspace(5,2,4)
X,Y=  np.meshgrid(X, Y)

Z = array ([
        [1223.539555, 1428.075086,1714.479425, 2144.053223],
        [1567.26647,1829.056119,2990.416079,2745.320067],
        [2135.163957,2491.534201, 2990.416079,3738.761638],
        [3257.280827, 3800.655101, 4561.372117, 5702.458776],
        ])

surf = ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap = jet,linewidth = 0,alpha= 1)
ax.set_zlim3d(0, Z.max())

fig.colorbar(surf, shrink=0.8, aspect=5)
ax.set_xlabel('Axial Length [mm]')
ax.set_ylabel('nbTurns')
ax.set_zlabel('RPM')

plt.show()

Body:
You need to define a function in order to get a specific animation. In your case it is a simple rotation:

def rotate(angle):
    ax.view_init(azim=angle)

Then use the matplotlib animation:

rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0,362,2),interval=100)

This will call the rotate function with the frames argument as angles and with an interval of 100ms, so this will result in a rotation over 360° with a 2° step each 100ms. To save the animation as a gif file:

rot_animation.save('path/rotation.gif', dpi=80, writer='imagemagick')


问:
Getting around file access protection in Windows to view an active logfile read-only
A customer asked for quick and dirty log viewer for an ASP.NET app, for which I'm using log4net, and I thought somehow we could simply add a controller to read the tail of the active file and spit it back.

If I use the standard .NET API (File.OpenText, etc.) I get access violation (file open by another process), which is what I expect, but I know it is possible to read the file because Ultraedit opens it for viewing read-only. Can I do the same from the .NET API?

```<code>using(StreamReader infile =
         System.IO.File.OpenText(Request.PhysicalApplicationPath + @"\log\my.log"))
{
}
</code>```

答:
Specify That you allow read/write sharing on the file, and put a StreamReader on your stream to get the same behaviour as File.OpenText.

```<code>using( Stream stream = File.Open(@"x:\path\file.log",
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
{
    using(StreamReader sr = new StreamReader(stream))
    {
        //read content
    }
}
</code>```

And since you can open the file with UltraEdit, I assume log4net is not putting an exclusive lock on the file.

Body:
A customer asked for quick and dirty log viewer for an ASP.NET app, for which I'm using log4net, and I thought somehow we could simply add a controller to read the tail of the active file and spit it back.

If I use the standard .NET API (File.OpenText, etc.) I get access violation (file open by another process), which is what I expect, but I know it is possible to read the file because Ultraedit opens it for viewing read-only. Can I do the same from the .NET API?

using(StreamReader infile =
         System.IO.File.OpenText(Request.PhysicalApplicationPath + @"\log\my.log"))
{
}

Body:
Specify That you allow read/write sharing on the file, and put a StreamReader on your stream to get the same behaviour as File.OpenText.

using( Stream stream = File.Open(@"x:\path\file.log",
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
{
    using(StreamReader sr = new StreamReader(stream))
    {
        //read content
    }
}

And since you can open the file with UltraEdit, I assume log4net is not putting an exclusive lock on the file.


问:
Authentication failed to bitbucket
I'm trying to push my project via the https protocol on bitbucket using sourcetree.

But I can't connect to bitbucket with my login and password (which work on the website), I have a fatal error : "Authentication failed".

I read on other posts I can work around the problem using the ssh protocol instead of the https one, so I set up a ssh key following instructions on the source tree faq.
But now I don't know how I can change to the ssh protocol when I want to push my code.
Someone know how I can do this ?
Thank you.

答: None of the above worked for me - the problem lay in my Sourcetree Preferences.  In the Network tab, I had a setting there for 'Default usernames for URLs which do not include one:'.  The username was incorrect where I had entered it incorrectly previously - I had set it to my email rather than username.  I highlighted the entries and clicked Remove for both. Then I returned to my repository page and clicked Push again.  On pushing, it asked me for full username and password, which I was able to enter correctly - the push then finally worked.</p>

Title: Authentication failed to bitbucket


问:
greensock add class to elements one by one
I want to add classes on HTML elements one by one.

```<code>TweenMax.staggerTo(".some-class-name", 0.5, { className: "+=animation-class" }, 0.5);
</code>```

I have this code, but it doesn't work. More precisely it works, but it doesn't add className one by one.

How can I achieve an effect like this codepen but with className?

答:
You have a valid Query and if you just want to add a new class to the element. It can be done with TweenMax or TweenLite.

TweenMax

```<code>TweenLite.to(element, 0.5, {css:{className:'+=newclass'}});
</code>```

or

```<code>TweenMax.to(element, 0.5, {css:{className:'+=newclass'}});
</code>```

or

```<code>TweenMax.staggerTo(element, 0.5, {css:{className:'+=newclass'}});
</code>```

You could make a forloop and then pass the class or do a foreach and add this class like this.

for more check out this link :

https://greensock.com/forums/topic/6376-using-greensock-to-change-classes-without-tweening-styles/

Body:
I want to add classes on HTML elements one by one.

TweenMax.staggerTo(".some-class-name", 0.5, { className: "+=animation-class" }, 0.5);

I have this code, but it doesn't work. More precisely it works, but it doesn't add className one by one.

How can I achieve an effect like this codepen but with className?

Body:
You have a valid Query and if you just want to add a new class to the element. It can be done with TweenMax or TweenLite.

TweenMax

TweenLite.to(element, 0.5, {css:{className:'+=newclass'}});

or

TweenMax.to(element, 0.5, {css:{className:'+=newclass'}});

or

TweenMax.staggerTo(element, 0.5, {css:{className:'+=newclass'}});

You could make a forloop and then pass the class or do a foreach and add this class like this.

for more check out this link :

https://greensock.com/forums/topic/6376-using-greensock-to-change-classes-without-tweening-styles/


问:
Jenkins Configuration change
How to change name of configuration in jenkins it is default . I want to change it to linux.

答:
You need to specify axis to your Multi-Configuration Project; on the project configuration page click "Add axis":

Your choice here depends on what you are trying to achieve. Do you wan't your build to run on a specific Slave/Agent or do you simply wan't to set an environment variables to different values? There is a summary of different axis here.

But for simplicity sake, let's take user-defined axis, this will provide an environment variable which is set to the value provided:

In this case I've entered linux and windows and on the project view I get:

And each time I build the project it will run two instances of the project, one with platform equal to linux and one with platform equal to windows.

Title: Jenkins Configuration change


问:
Run Android Service every 30 seconds
I am creating a Notification using Android Service independent from UI. This works perfectly fine. Below is the code.

```<code>public class SendNotificationService extends Service {
    Context context;
    String test_heading;
    String test_body;

    final class notifThread implements Runnable {
        int service_id;

        notifThread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {
            String requested_method = "LoadBU";
            String bu_status = "1";

            CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);
            checkNewEntry.execute(requested_method, bu_status);

            stopSelf(this.service_id);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Thread thread = new Thread(new notifThread(startId));
        thread.start();

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
    }
}
</code>```

This service also starts automatically on system boot. CheckNewEntry is my AsyncTask that checks the database and sends notification if there is any change. I have not added CheckNewEntry as it is beyond the scope of this question.

Now what I want to do is, run CheckNewEntry every 30 seconds or 1 minute.

Can anyone help?

答:
you can use handler like this.  </p>

```<code>public class SendNotificationService extends Service {
        Context context;
        String test_heading;
        String test_body;
        public static Runnable runn;
        public static Handler hand =new Handler();
        final class notifThread implements Runnable {
            int service_id;

            notifThread(int service_id) {
                this.service_id = service_id;
            }

            @Override
            public void run() {
                String requested_method = "LoadBU";
                String bu_status = "1";

                CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);

     runn = new Runnable() {
                @Override
                public void run() {

                     checkNewEntry.execute(requested_method, bu_status);

                    hand.postDelayed(runn, 30000);
                }
            };

            runn.run();

            stopSelf(this.service_id);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Thread thread = new Thread(new notifThread(startId));
        thread.start();

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
    }
}
</code>```

Title: Run Android Service every 30 seconds

Body:
I am creating a Notification using Android Service independent from UI. This works perfectly fine. Below is the code.

public class SendNotificationService extends Service {
    Context context;
    String test_heading;
    String test_body;

    final class notifThread implements Runnable {
        int service_id;

        notifThread(int service_id) {
            this.service_id = service_id;
        }

        @Override
        public void run() {
            String requested_method = "LoadBU";
            String bu_status = "1";

            CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);
            checkNewEntry.execute(requested_method, bu_status);

            stopSelf(this.service_id);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Thread thread = new Thread(new notifThread(startId));
        thread.start();

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
    }
}

This service also starts automatically on system boot. CheckNewEntry is my AsyncTask that checks the database and sends notification if there is any change. I have not added CheckNewEntry as it is beyond the scope of this question.

Now what I want to do is, run CheckNewEntry every 30 seconds or 1 minute.

Can anyone help?

Body:
you can use handler like this.

public class SendNotificationService extends Service {
        Context context;
        String test_heading;
        String test_body;
        public static Runnable runn;
        public static Handler hand =new Handler();
        final class notifThread implements Runnable {
            int service_id;

            notifThread(int service_id) {
                this.service_id = service_id;
            }

            @Override
            public void run() {
                String requested_method = "LoadBU";
                String bu_status = "1";

                CheckNewEntry checkNewEntry = new CheckNewEntry(SendNotificationService.this);

     runn = new Runnable() {
                @Override
                public void run() {

                     checkNewEntry.execute(requested_method, bu_status);

                    hand.postDelayed(runn, 30000);
                }
            };

            runn.run();

            stopSelf(this.service_id);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Thread thread = new Thread(new notifThread(startId));
        thread.start();

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Toast.makeText(this, "Notifications Stopped...", Toast.LENGTH_LONG).show();
    }
}


问:
resetting a div after animation
I'm having an issue with trying to reset a div, containing an image, to the original value after I have animated it.

So I have a sort of quiz with 6 pictures positioned next to each other.
The user has to select one of 6 pictures. When clicked on that picture I make the picture go fullscreen. Afterwards, when the user doubleclicks on the picture the picture should go back to the original position for the next question.

However the return is not working and I don't understand why.

Beware: the divsare floated divs with specific left-positions so I would need to retain these...

This is the animation-code:

```<code>$(".candidatePicture").click(function(e){
      $(e.target).css('z-index', 1);
      $(e.target).animate({top: '0', left: '0', width: '1920px', height: '1080px'}, 1000);
    });
</code>```

This is the return code:

```<code>$(".candidatePicture").css({ 'width': '250px', 'height': '300px', 'z-index': '0' });
</code>```

You can find the code here: http://jsbin.com/gotuqenoce

Thank you for your help.

答:
please try to change the events handlers as follow:

```<code>$(".candidatePicture").click(function(e){
  var $this = $(this);
  $this.css('z-index', 1);
  $this.animate({top: '0', left: '0', width: '1920px', height: '1080px'}, 1000);
  $this.off("click");
});
$( ".candidatePicture" ).dblclick(function(e) {
  $(this).css({ top: '', left: '', 'width': '', 'height': '', 'z-index': '' });
  showNextQuestion();
});
</code>```

http://jsbin.com/latiqemozo/edit?html,output

Title: resetting a div after animation

Body:
I'm having an issue with trying to reset a div, containing an image, to the original value after I have animated it.

So I have a sort of quiz with 6 pictures positioned next to each other.
The user has to select one of 6 pictures. When clicked on that picture I make the picture go fullscreen. Afterwards, when the user doubleclicks on the picture the picture should go back to the original position for the next question.

However the return is not working and I don't understand why.

Beware: the divsare floated divs with specific left-positions so I would need to retain these...

This is the animation-code:

$(".candidatePicture").click(function(e){
      $(e.target).css('z-index', 1);
      $(e.target).animate({top: '0', left: '0', width: '1920px', height: '1080px'}, 1000);
    });

This is the return code:

$(".candidatePicture").css({ 'width': '250px', 'height': '300px', 'z-index': '0' });

You can find the code here: http://jsbin.com/gotuqenoce

Thank you for your help.

Body:
please try to change the events handlers as follow:

$(".candidatePicture").click(function(e){
  var $this = $(this);
  $this.css('z-index', 1);
  $this.animate({top: '0', left: '0', width: '1920px', height: '1080px'}, 1000);
  $this.off("click");
});
$( ".candidatePicture" ).dblclick(function(e) {
  $(this).css({ top: '', left: '', 'width': '', 'height': '', 'z-index': '' });
  showNextQuestion();
});

http://jsbin.com/latiqemozo/edit?html,output


问:
python sort strings with digits at the end
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

```<code>>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']
</code>```

should  put the 1234 one on the end. is there an easy way to do this?

Body:
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

should  put the 1234 one on the end. is there an easy way to do this?

Body:
l = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
l.sort(cmp=lambda x,y:cmp(int(x[4:]), int(y[4:]))


问:
d3js: How does the "magic" work with fill on hover for a barchart plot?
There are multiple versions of the D3 JS v3 barchart plot around that have the feature of changing the bar color when the mouse hovers over it. I have a minimal working barchart and wanted to add it but it doesn't change the bar fill color upon hovering over it.

Looking at this barchart example that is built on top of v3 I only see that the needed addendum is this css snippet:

```<code>.bar:hover {
  fill: orangered;
}
</code>```

therefore I added this but I can't see the change of fill color on hovering ... where else does the magic come from?

UPDATE: This is my D3 JS barchart plot generating code:

```<code>// delete old
d3.select("#" + divId).select("svg").remove();

var margin = {top: 40, right: 20, bottom: 20, left: 20},
    width = 450 - margin.left - margin.right,
    height = 370 - margin.top - margin.bottom;

var max = d3.max(values);
var min = d3.min(values);
var x = d3.scale.linear()
    .domain([min, max])
    .range([0, width]);

// generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
    .bins(x.ticks(10))
    (values);

var yMax = d3.max(data, function(d){ return d.length });
var yMin = d3.min(data, function(d){ return d.length });
var colorScale = d3.scale.linear()
    .domain([yMin, yMax])
    .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

var y = d3.scale.linear()
    .domain([0, yMax])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var svg = d3.select("#" + divId)
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var bar = svg.selectAll(".bar")
    .data(data)
    .enter()
    .append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

bar.append("rect")
    .attr("x", 1)
    .attr("width", (x(data[0].dx) - x(0)) - 1)
    .attr("height", function(d) { return height - y(d.y); })
    .attr("fill", function(d) { return colorScale(d.y) });

bar.append("text")
    .attr("dy", ".75em")
    .attr("y", -12)
    .attr("x", (x(data[0].dx) - x(0)) / 2)
    .attr("text-anchor", "middle")
    .text(function(d) { return formatCount(d.y); });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("text")
    .attr("x", 0)
    .attr("y", 0 - (margin.top / 2))
    .attr("text-anchor", "left")
    .classed("label", true)
    .text($scope.histogramData.spec[$scope.histogramData.selected]);
</code>```

答:
In the example the class bar is assigned to the rectangles.

In your code, however, the class is assigned to <g> tags, which will not trigger on hover.

If you change the CSS to the following, it should work:

```<code>.bar rect:hover {
  fill: orangered;
}
</code>```

Body:
There are multiple versions of the D3 JS v3 barchart plot around that have the feature of changing the bar color when the mouse hovers over it. I have a minimal working barchart and wanted to add it but it doesn't change the bar fill color upon hovering over it.

Looking at this barchart example that is built on top of v3 I only see that the needed addendum is this css snippet:

.bar:hover {
  fill: orangered;
}

therefore I added this but I can't see the change of fill color on hovering ... where else does the magic come from?

UPDATE: This is my D3 JS barchart plot generating code:

// delete old
d3.select("#" + divId).select("svg").remove();

var margin = {top: 40, right: 20, bottom: 20, left: 20},
    width = 450 - margin.left - margin.right,
    height = 370 - margin.top - margin.bottom;

var max = d3.max(values);
var min = d3.min(values);
var x = d3.scale.linear()
    .domain([min, max])
    .range([0, width]);

// generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
    .bins(x.ticks(10))
    (values);

var yMax = d3.max(data, function(d){ return d.length });
var yMin = d3.min(data, function(d){ return d.length });
var colorScale = d3.scale.linear()
    .domain([yMin, yMax])
    .range([d3.rgb(color).brighter(), d3.rgb(color).darker()]);

var y = d3.scale.linear()
    .domain([0, yMax])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom");

var svg = d3.select("#" + divId)
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var bar = svg.selectAll(".bar")
    .data(data)
    .enter()
    .append("g")
    .attr("class", "bar")
    .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

bar.append("rect")
    .attr("x", 1)
    .attr("width", (x(data[0].dx) - x(0)) - 1)
    .attr("height", function(d) { return height - y(d.y); })
    .attr("fill", function(d) { return colorScale(d.y) });

bar.append("text")
    .attr("dy", ".75em")
    .attr("y", -12)
    .attr("x", (x(data[0].dx) - x(0)) / 2)
    .attr("text-anchor", "middle")
    .text(function(d) { return formatCount(d.y); });

svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

svg.append("text")
    .attr("x", 0)
    .attr("y", 0 - (margin.top / 2))
    .attr("text-anchor", "left")
    .classed("label", true)
    .text($scope.histogramData.spec[$scope.histogramData.selected]);

Body:
In the example the class bar is assigned to the rectangles.

In your code, however, the class is assigned to <g> tags, which will not trigger on hover.

If you change the CSS to the following, it should work:

.bar rect:hover {
  fill: orangered;
}


问:
yii2 listview next page without changing url
Yii2 listview is missing $.fn.yiilistview.update from yii1. Even more, it is dependent on pjax for basic requirements and thus creates all kinds of issues with nested pjax , timeouts etc for simple pagination with listView.

A GET request to controller is rendered by javascript into an HTML ( jSON returned from controller containing listview html ) . Since URL is not changed in this process, I did not use pjax for avoiding complexity and made simple ajax call and based on data returned on success will update container. ( like pjax does only manually using ajax without changing url)

now when I do next page, then URL is updated and also page full refreshes. Initially it was not working as well but once I added an IF check on page GET param inside controller and instead of returning renderAjax output in JSON, would directly return HTML now

How can we avoid updating URL with yii2 listview next page without using pjax and make it work seeemlesly with controller and javascript written in fashion to emulate pjax in manual ajax calls as stated above ?

Controller :

```<code>if($pageParam == null) {
    $page =  $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;

    Yii::$app->response->format = 'json';
    return array("error"=>false,"page"=>$page);
} else {
    return $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;
}
</code>```

List View :

```<code><?php if($dataProvider != null) : ?>
    <?=
    ListView::widget([
        'id'=>'itemList',
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => '_dataListView',
        'summary'=>'',
        'emptyText'=>$emptyPage
    ])
    ?>
<?php endif; ?>
</code>```

js :

ajax success GET callback :

```<code>success     : function(data) {
                    if(!data.error) {
                        $("#list-container").html(data.page);
</code>```

listcontainer itself resides in parent view for _list

答:
you can configure pjax widget like this:

```<code>    <? Pjax::begin(['enablePushState' => false]) ?>
...
    <? Pjax::end() ?>
</code>```

you might also be interested in the 'enableReplaceState' option. doc here

ContentLicense: CC BY-SA 4.0

Body:
Yii2 listview is missing $.fn.yiilistview.update from yii1. Even more, it is dependent on pjax for basic requirements and thus creates all kinds of issues with nested pjax , timeouts etc for simple pagination with listView.

A GET request to controller is rendered by javascript into an HTML ( jSON returned from controller containing listview html ) . Since URL is not changed in this process, I did not use pjax for avoiding complexity and made simple ajax call and based on data returned on success will update container. ( like pjax does only manually using ajax without changing url)

now when I do next page, then URL is updated and also page full refreshes. Initially it was not working as well but once I added an IF check on page GET param inside controller and instead of returning renderAjax output in JSON, would directly return HTML now

How can we avoid updating URL with yii2 listview next page without using pjax and make it work seeemlesly with controller and javascript written in fashion to emulate pjax in manual ajax calls as stated above ?

Controller :

if($pageParam == null) {
    $page =  $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;

    Yii::$app->response->format = 'json';
    return array("error"=>false,"page"=>$page);
} else {
    return $this->renderAjax("_list", [
                        "dataProvider" => $dataProvider
             ]) ;
}

List View :

<?php if($dataProvider != null) : ?>
    <?=
    ListView::widget([
        'id'=>'itemList',
        'dataProvider' => $dataProvider,
        'itemOptions' => ['class' => 'item'],
        'itemView' => '_dataListView',
        'summary'=>'',
        'emptyText'=>$emptyPage
    ])
    ?>
<?php endif; ?>

js :

ajax success GET callback :

success     : function(data) {
                    if(!data.error) {
                        $("#list-container").html(data.page);

listcontainer itself resides in parent view for _list

Body:
you can configure pjax widget like this:

    <? Pjax::begin(['enablePushState' => false]) ?>
...
    <? Pjax::end() ?>

you might also be interested in the 'enableReplaceState' option. doc here


问:
How to get mongo db document size limit for 'find' query?
It looks pretty odd question but let me explain further, I need to query mongodb collection and get documents. The collection size is in TB. I have to do some operation on set of documents periodically (lets say after every 2 hrs). Operation is quite simple find documents (as per criteria), and copy to another collection and delete from original collection.The problem is I can't decide(not aware) what will size of documents to retrieve. I am using MongoTemplate(I have to go with this). I am sure that size of documents must be less than RAM. But still what is the procedure to get exact size of document so I wont get any timeout or out of space error.</p>

答:
I think it fulfilled your purpose- </p>

```<code>Object.bsonsize(db.students.find())
Object.bsonsize(db.students.findOne({*condition*}))
</code>```

<p>It return the size of the particular document (in bytes). </p>

Body:
I think it fulfilled your purpose-

Object.bsonsize(db.students.find())
Object.bsonsize(db.students.findOne({*condition*}))

It return the size of the particular document (in bytes).


问:
XSLT : How to get the value of the parent tag based on the condition which is dependent on the values of its child tags, in a highly nested XML
I've been trying to get the solution for this, but still cannot find a proper solution.
I referred few links Nested for-each loops, accessing outer element with variable from the inner loop and How to extract child tags text and extended text of parent tag from xml using xslt but these questions don't have the nested tags.

My XML:

```<code><catalog title="TitleABC1">
  <cd>
    <title code="Y">Picture book</title>
    <artist>Simply Red</artist>
    <country>EU</country>
  </cd>
  <catalog title="TitleABC2">
    <cd>
      <cd>
        <title code="N">Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
      </cd>
    </cd>
    <cd>
      <cd>
        <cd>
          <title code="Y">Hide your heart</title>
          <artist>Bonnie Tyler</artist>
          <country>UK</country>
        </cd>
      </cd>
    </cd>
    <cd>
      <catalog title="TitleABC3">
        <cd>
          <title code="N">Red</title>
          <artist>The Communards</artist>
          <country>UK</country>
        </cd>
      </catalog>
    </cd>
    <cd>
      <title code="N">Unchain my heart</title>
      <artist>Joe Cocker</artist>
      <country>USA</country>
    </cd>
  </catalog>
</catalog>
</code>```

For above XML, the condition is that titles of only those catalog tags will be displayed if any of the child/descendants title tags have the code attribute as 'Y'.

Hence, the Output should be like:

```<code>TitleABC1
TitleABC2
</code>```

I was trying at the below logic for XSLT, but couldn't get the desired solution.

```<code> <xsl:template match="catalog">
<!-- Store the value in a variable -->
              <xsl:for-each select="//title">
<!-- <xsl:if> to check for the code attrib -->
              </xsl:for-each>
            </xsl:template>
</code>```

答:
only those catalog tags will be displayed if any of the
  child/descendants title tags have the code attribute as 'Y'.

Why don't you do exactly what you said needs to be done:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />

<xsl:template match="/">
    <xsl:for-each select="//catalog[descendant::title/@code='Y']">
        <xsl:value-of select="@title" />
        <xsl:text>
</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>
</code>```

Or, if you prefer a recursive approach:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />

<xsl:template match="catalog[descendant::title/@code='Y']">
    <xsl:value-of select="@title" />
    <xsl:text>
</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="text()"/>

</xsl:stylesheet>
</code>```

You need to know about the built-in template rules in order to understand how this works.

Body:
I've been trying to get the solution for this, but still cannot find a proper solution.
I referred few links Nested for-each loops, accessing outer element with variable from the inner loop and How to extract child tags text and extended text of parent tag from xml using xslt but these questions don't have the nested tags.

My XML:

<catalog title="TitleABC1">
  <cd>
    <title code="Y">Picture book</title>
    <artist>Simply Red</artist>
    <country>EU</country>
  </cd>
  <catalog title="TitleABC2">
    <cd>
      <cd>
        <title code="N">Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
      </cd>
    </cd>
    <cd>
      <cd>
        <cd>
          <title code="Y">Hide your heart</title>
          <artist>Bonnie Tyler</artist>
          <country>UK</country>
        </cd>
      </cd>
    </cd>
    <cd>
      <catalog title="TitleABC3">
        <cd>
          <title code="N">Red</title>
          <artist>The Communards</artist>
          <country>UK</country>
        </cd>
      </catalog>
    </cd>
    <cd>
      <title code="N">Unchain my heart</title>
      <artist>Joe Cocker</artist>
      <country>USA</country>
    </cd>
  </catalog>
</catalog>

For above XML, the condition is that titles of only those catalog tags will be displayed if any of the child/descendants title tags have the code attribute as 'Y'.

Hence, the Output should be like:

TitleABC1
TitleABC2

I was trying at the below logic for XSLT, but couldn't get the desired solution.

 <xsl:template match="catalog">

              <xsl:for-each select="//title">

              </xsl:for-each>
            </xsl:template>

Body:
only those catalog tags will be displayed if any of the
  child/descendants title tags have the code attribute as 'Y'.

Why don't you do exactly what you said needs to be done:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />

<xsl:template match="/">
    <xsl:for-each select="//catalog[descendant::title/@code='Y']">
        <xsl:value-of select="@title" />
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Or, if you prefer a recursive approach:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />

<xsl:template match="catalog[descendant::title/@code='Y']">
    <xsl:value-of select="@title" />
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="text()"/>

</xsl:stylesheet>

You need to know about the built-in template rules in order to understand how this works.


问:
JavaFX: Setting count limit for an ObservableList fulfilling a condition
I'll use an example to explain.

```<code>public class Person
{
    private final ObjectProperty<Gender> gender;
    public final ObjectProperty<Gender> genderProperty()
    {
        return this.gender;
    }
    public final void setGender(Gender value)
    {
        this.genderProperty().set(value);
    }
    public final Gender getGender()
    {
        return this.genderProperty().get();
    }

    public static enum Gender { MALE, FEMALE }

    /* Other properties */
}
</code>```

Somewhere else...

```<code>public class MyClass
{
    private final ObservableList<Person> people;
    public final ObservableList<Person> getPeople()
    {
        return this.people;
    }

    public MyClass()
    {
        // Create observable arraylist with extractor
        this.people = FXCollections.observableArrayList(
            person -> new Observable[]
                {
                    person.genderProperty()
                }
            );
    }
}
</code>```

I need the people list to contain up to a maximum of 10 males, and a maximum of 5 females. Some of the Person object does not have the gender information when it is added to the people list, but my application must:

Pick up such a change when one of these Person object changes its gender, and the change happens to violate this limit.

Undo such a change so that my rule of 10 males / 5 females limits will always apply.

What can I do to ensure this?

答:
First of all you could add a new enum value in Gender that represents the unknown gender:

public enum Gender { MALE, FEMALE, UNKNOWN }.

Then you can use a ListChangeListener like:

```<code>this.people = FXCollections.observableArrayList(person -> new Observable[] {person.genderProperty()});

 ListChangeListener<Person> listener = new ListChangeListener<Person>() {

    private boolean checkCondition(ObservableList<Person> list, Person.Gender gender) {
        int males = 0;
        int females = 0;

        for (Person person : list) {
            switch (person.getGender()) {
                case MALE: males++; break;
                case FEMALE: females++; break;
                default: break;
            }
        }

        return ((males > 10 && gender == Person.Gender.MALE) ||
                (females > 5 && gender == Person.Gender.FEMALE));
    }

    @Override
    public void onChanged(Change<? extends Person> c) {
        while (c.next()) {
            if (c.wasAdded()) {
                for (Person person : c.getAddedSubList()) {
                    if (checkCondition((ObservableList<Person>) c.getList(), person.getGender()))
                        c.getList().remove(person);
                }
            }
            if (c.wasUpdated()) {
                for (int update = c.getFrom(); update < c.getTo(); update++) {
                    Person person = c.getList().get(update);
                    if (checkCondition((ObservableList<Person>) c.getList(), person.getGender()))
                        person.setGender(Person.Gender.UNKNOWN);
                }

            }
        }
    }
};

people.addListener(listener);
</code>```

The only problem with this solution, that it does not really "revert" the update change, but sets the gender to the new unknown value.

If you want to really revert the change, the solution can be something like:

```<code>this.people = FXCollections.observableArrayList();

 ListChangeListener<Person> listener = new ListChangeListener<Person>() {

    private boolean checkCondition(ObservableList<Person> list, Person.Gender gender) {
        int males = 0;
        int females = 0;

        for (Person person : list) {
            switch (person.getGender()) {
                case MALE: males++; break;
                case FEMALE: females++; break;
                default: break;
            }
        }

        return ((males > 10 && gender == Person.Gender.MALE) ||
                (females > 5 && gender == Person.Gender.FEMALE));
    }

    @Override
    public void onChanged(Change<? extends Person> c) {
        while (c.next()) {
            if (c.wasAdded()) {
                for (Person person : c.getAddedSubList()) {

                    if (checkCondition((ObservableList<Person>) c.getList(), person.getGender()))
                        c.getList().remove(person);
                    else
                        person.genderProperty().addListener((obs, oldval, newval) -> {
                            if (checkCondition((ObservableList<Person>) c.getList(), newval))
                                person.setGender(oldval);
                        });
                }
            }
        }
    }
};

people.addListener(listener);
</code>```

Differences: the extractor has been removed, as inside of the ListChangeListener only the addition of the elements are covered. When a new element is added, a listener on its genderProperty has been added which one checks to the gender update, and if the conditions are not met, the gener is reverted to be the original one.

You can also achieve the same functionality by not exposing the list, but methods that manipulate the list: addPersonAt, removePersonAt and updateGenderAt.

Body:
I'll use an example to explain.

public class Person
{
    private final ObjectProperty<Gender> gender;
    public final ObjectProperty<Gender> genderProperty()
    {
        return this.gender;
    }
    public final void setGender(Gender value)
    {
        this.genderProperty().set(value);
    }
    public final Gender getGender()
    {
        return this.genderProperty().get();
    }

    public static enum Gender { MALE, FEMALE }

    /* Other properties */
}

Somewhere else...

public class MyClass
{
    private final ObservableList<Person> people;
    public final ObservableList<Person> getPeople()
    {
        return this.people;
    }

    public MyClass()
    {
        // Create observable arraylist with extractor
        this.people = FXCollections.observableArrayList(
            person -> new Observable[]
                {
                    person.genderProperty()
                }
            );
    }
}

I need the people list to contain up to a maximum of 10 males, and a maximum of 5 females. Some of the Person object does not have the gender information when it is added to the people list, but my application must:

Pick up such a change when one of these Person object changes its gender, and the change happens to violate this limit.

Undo such a change so that my rule of 10 males / 5 females limits will always apply.

What can I do to ensure this?

Body:
First of all you could add a new enum value in Gender that represents the unknown gender:

public enum Gender { MALE, FEMALE, UNKNOWN }.

Then you can use a ListChangeListener like:

this.people = FXCollections.observableArrayList(person -> new Observable[] {person.genderProperty()});

 ListChangeListener<Person> listener = new ListChangeListener<Person>() {

    private boolean checkCondition(ObservableList<Person> list, Person.Gender gender) {
        int males = 0;
        int females = 0;

        for (Person person : list) {
            switch (person.getGender()) {
                case MALE: males++; break;
                case FEMALE: females++; break;
                default: break;
            }
        }

        return ((males > 10 && gender == Person.Gender.MALE) ||
                (females > 5 && gender == Person.Gender.FEMALE));
    }

    @Override
    public void onChanged(Change<? extends Person> c) {
        while (c.next()) {
            if (c.wasAdded()) {
                for (Person person : c.getAddedSubList()) {
                    if (checkCondition((ObservableList<Person>) c.getList(), person.getGender()))
                        c.getList().remove(person);
                }
            }
            if (c.wasUpdated()) {
                for (int update = c.getFrom(); update < c.getTo(); update++) {
                    Person person = c.getList().get(update);
                    if (checkCondition((ObservableList<Person>) c.getList(), person.getGender()))
                        person.setGender(Person.Gender.UNKNOWN);
                }

            }
        }
    }
};

people.addListener(listener);

The only problem with this solution, that it does not really "revert" the update change, but sets the gender to the new unknown value.

If you want to really revert the change, the solution can be something like:

this.people = FXCollections.observableArrayList();

 ListChangeListener<Person> listener = new ListChangeListener<Person>() {

    private boolean checkCondition(ObservableList<Person> list, Person.Gender gender) {
        int males = 0;
        int females = 0;

        for (Person person : list) {
            switch (person.getGender()) {
                case MALE: males++; break;
                case FEMALE: females++; break;
                default: break;
            }
        }

        return ((males > 10 && gender == Person.Gender.MALE) ||
                (females > 5 && gender == Person.Gender.FEMALE));
    }

    @Override
    public void onChanged(Change<? extends Person> c) {
        while (c.next()) {
            if (c.wasAdded()) {
                for (Person person : c.getAddedSubList()) {

                    if (checkCondition((ObservableList<Person>) c.getList(), person.getGender()))
                        c.getList().remove(person);
                    else
                        person.genderProperty().addListener((obs, oldval, newval) -> {
                            if (checkCondition((ObservableList<Person>) c.getList(), newval))
                                person.setGender(oldval);
                        });
                }
            }
        }
    }
};

people.addListener(listener);

Differences: the extractor has been removed, as inside of the ListChangeListener only the addition of the elements are covered. When a new element is added, a listener on its genderProperty has been added which one checks to the gender update, and if the conditions are not met, the gener is reverted to be the original one.

You can also achieve the same functionality by not exposing the list, but methods that manipulate the list: addPersonAt, removePersonAt and updateGenderAt.


问:
Migration: Cannot add foreign key constraint
I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:

```<code>[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `priorities` add constraint priorities_user_id_foreign foreign
key (`user_id`) references `users` (`id`))
</code>```

My migration code is as so:

priorities migration file

```<code>public function up()
{
    //
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('priorities');
}
</code>```

users migration file

```<code>public function up()
{
    //
    Schema::table('users', function($table)
    {
    $table->create();
    $table->increments('id');
    $table->string('email');
    $table->string('first_name');
    $table->string('password');
    $table->string('email_code');
    $table->string('time_created');
    $table->string('ip');
    $table->string('confirmed');
    $table->string('user_role');
    $table->string('salt');
    $table->string('last_login');

    $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
        Schemea::drop('users');
}
</code>```

Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. Users, Clients, Projects, Tasks, Statuses, Priorities, Types, Teams. Ideally I want to create tables which hold this data with the foreign keys, i..e clients_project and project_tasks etc.

Hope someone can help me to get started.

答:
In my case I just change the order migrations are executed manually so table users is created first.

In folder database/migrations/ your migration filename have this format:
year_month_day_hhmmss_create_XXXX_table.php

Just rename create user file so creation date of your table priorities table is set later than user date (even one second later is enough)

Body:
I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `priorities` add constraint priorities_user_id_foreign foreign
key (`user_id`) references `users` (`id`))

My migration code is as so:

priorities migration file

public function up()
{
    //
    Schema::create('priorities', function($table) {
        $table->increments('id', true);
        $table->integer('user_id');
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('priority_name');
        $table->smallInteger('rank');
        $table->text('class');
        $table->timestamps('timecreated');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
    Schema::drop('priorities');
}

users migration file

public function up()
{
    //
    Schema::table('users', function($table)
    {
    $table->create();
    $table->increments('id');
    $table->string('email');
    $table->string('first_name');
    $table->string('password');
    $table->string('email_code');
    $table->string('time_created');
    $table->string('ip');
    $table->string('confirmed');
    $table->string('user_role');
    $table->string('salt');
    $table->string('last_login');

    $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    //
        Schemea::drop('users');
}

Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. Users, Clients, Projects, Tasks, Statuses, Priorities, Types, Teams. Ideally I want to create tables which hold this data with the foreign keys, i..e clients_project and project_tasks etc.

Hope someone can help me to get started.


问:
Excluding Nodes RVest
I am scraping blog text using RVest and am struggling to figure out a simple way to exclude specific nodes. The following pulls the text:

```<code>AllandSundry_test <- read_html
("http://www.sundrymourning.com/2017/03/03/lets-go-back-to-commenting-on-the-weather/")

testpost <- AllandSundry_test %>%
html_node("#contentmiddle") %>%
html_text() %>%
as.character()
</code>```

I want to exclude the two nodes with ID's "contenttitle" and "commentblock". Below, I try excluding just the comments using the tag "commentblock".

```<code> testpost <- AllandSundry_test %>%
   html_node("#contentmiddle") %>%
   html_node(":not(#commentblock)")
   html_text() %>%
   as.character()
</code>```

When I run this, the result is simply the date -- all the rest of the text is gone. Any suggestions?

I have spent a lot of time searching for an answer, but I am new to R (and html), so I appreciate your patience if this is something obvious.

答:
You were almost there. You should use html_nodes instead of html_node.

html_node retrieves the first element it encounter, while html_nodes returns each matching element in the page as a list.

The toString() function collapse the list of strings into one.

library(rvest)

AllandSundry_test <- read_html("http://www.sundrymourning.com/2017/03/03/lets-go-back-to-commenting-on-the-weather/")

testpost <- AllandSundry_test %>%
  html_nodes("#contentmiddle>:not(#commentblock)") %>%
  html_text %>%
  as.character %>%
  toString

testpost
#> [1] "\n\t\tMar\n\t\t3\n\t, Mar, 3, \n\t\tLet's go back to
#> commenting on the weather\n\t\t\n\t\t, Let's go back to commenting on
#> the weather, Let's go back to commenting on the weather, I have just
#> returned from the grocery store, and I need to get something off my chest.
#> When did "Got any big plans for the rest of the day?" become
#> the default small ...<truncated>
```

You still need to clean up the string a bit.

Title: Excluding Nodes RVest

Body:
I am scraping blog text using RVest and am struggling to figure out a simple way to exclude specific nodes. The following pulls the text:

AllandSundry_test <- read_html
("http://www.sundrymourning.com/2017/03/03/lets-go-back-to-commenting-on-the-weather/")

testpost <- AllandSundry_test %>%
html_node("#contentmiddle") %>%
html_text() %>%
as.character()

I want to exclude the two nodes with ID's "contenttitle" and "commentblock". Below, I try excluding just the comments using the tag "commentblock".

 testpost <- AllandSundry_test %>%
   html_node("#contentmiddle") %>%
   html_node(":not(#commentblock)")
   html_text() %>%
   as.character()

When I run this, the result is simply the date -- all the rest of the text is gone. Any suggestions?

I have spent a lot of time searching for an answer, but I am new to R (and html), so I appreciate your patience if this is something obvious.

Body:
You were almost there. You should use html_nodes instead of html_node.

html_node retrieves the first element it encounter, while html_nodes returns each matching element in the page as a list.

The toString() function collapse the list of strings into one.

library(rvest)

AllandSundry_test <- read_html("http://www.sundrymourning.com/2017/03/03/lets-go-back-to-commenting-on-the-weather/")

testpost <- AllandSundry_test %>%
  html_nodes("#contentmiddle>:not(#commentblock)") %>%
  html_text %>%
  as.character %>%
  toString

testpost
#> [1] "\n\t\tMar\n\t\t3\n\t, Mar, 3, \n\t\tLet's go back to
#> commenting on the weather\n\t\t\n\t\t, Let's go back to commenting on
#> the weather, Let's go back to commenting on the weather, I have just
#> returned from the grocery store, and I need to get something off my chest.
#> When did "Got any big plans for the rest of the day?" become
#> the default small ...<truncated>

You still need to clean up the string a bit.


问:
OrderBy nothing happens mysql
```<code>SELECT *, count(spieler) as 'Anzahl'

FROM spieler, teilnehmer, durchfuehrung

WHERE spieler.id = teilnehmer.spieler and teilnehmer.istErschienen = 1 and teilnehmer.durchfuehrung = durchfuehrung.id and durchfuehrung.wurdeUeberprueft = 1

GROUP BY  teilnehmer.spieler

ORDER BY 'Anzahl' DESC;
</code>```

ORDER BY is useless in this way... Please help me to correct this mysql Query, so that the Alias Anzahl ist ordered desc....

答:
you should use this  </p>

```<code>   order by  count(spieler)
</code>```

Title: OrderBy nothing happens mysql

Body:
SELECT *, count(spieler) as 'Anzahl'

FROM spieler, teilnehmer, durchfuehrung

WHERE spieler.id = teilnehmer.spieler and teilnehmer.istErschienen = 1 and teilnehmer.durchfuehrung = durchfuehrung.id and durchfuehrung.wurdeUeberprueft = 1

GROUP BY  teilnehmer.spieler

ORDER BY 'Anzahl' DESC;

ORDER BY is useless in this way... Please help me to correct this mysql Query, so that the Alias Anzahl ist ordered desc....

Body:
you should use this

   order by  count(spieler)


问:
Akka Http retrieve a string value with help of Segment PathMatcher
I'm trying to implement a simple API where I can get path parameter as a String. Here is my test code:

```<code>class SimpleRouteTest extends WordSpec
  with Matchers
  with ScalatestRouteTest {

  val routes: Route = pathPrefix("foo") {
    get {
      complete("GET /foo")
    } ~
    pathPrefix(Segment) { seg =>
      get {
        complete(s"GET /foo/$seg")
      }
    }
  }

  "The routes should handle" should {
    "GET /foo correctly" in {
      Get("/foo") ~> routes ~> check {
        responseAs[String] shouldBe  "GET /foo"
      }
    }
    "GET /foo/any" in {
      Get("/foo/any") ~> routes ~> check {
        responseAs[String] shouldBe  "GET /foo/any"
      }
    }
  }

}
</code>```

Unfortunately the second test fails with message:

"GET /foo[]" was not equal to "GET /foo[/any]"

Who can give a hint, what I'm doing wrong?

Thanks

答:
This is what your code tries to do:

match the path with the prefix /foo

if method is GET, complete with "GET /foo"

otherwise if the remaining path starts with some segment seg, complete with s"GET /foo/$seg"

The ~ operator stops at the first operand, since all the condition are met (starts with /foo and is a GET). You might want to pass the more precise one as first operand, or specify that you want a PathEnd in your first case.

Body:
I'm trying to implement a simple API where I can get path parameter as a String. Here is my test code:

class SimpleRouteTest extends WordSpec
  with Matchers
  with ScalatestRouteTest {

  val routes: Route = pathPrefix("foo") {
    get {
      complete("GET /foo")
    } ~
    pathPrefix(Segment) { seg =>
      get {
        complete(s"GET /foo/$seg")
      }
    }
  }

  "The routes should handle" should {
    "GET /foo correctly" in {
      Get("/foo") ~> routes ~> check {
        responseAs[String] shouldBe  "GET /foo"
      }
    }
    "GET /foo/any" in {
      Get("/foo/any") ~> routes ~> check {
        responseAs[String] shouldBe  "GET /foo/any"
      }
    }
  }

}

Unfortunately the second test fails with message:

"GET /foo[]" was not equal to "GET /foo[/any]"

Who can give a hint, what I'm doing wrong?

Thanks