问:
UWP bind to dependency property
I have created a UWP project using the Template studio, and I am trying to implement a custom control.

This is what it looks like:

.xaml.cs

```<code> public sealed partial class MyButton : UserControl
    {
        public MyButton()
        {
            InitializeComponent();
        }

        public ImageSource Icon
        {
            get => (ImageSource)GetValue(s_iconProperty);
            set => SetValue(s_iconProperty, value);
        }

        public ImageSource Pointer
        {
            get => (ImageSource)GetValue(s_pointerProperty);
            set => SetValue(s_pointerProperty, value);
        }

        public static readonly DependencyProperty s_iconProperty =
          DependencyProperty.Register("Icon", typeof(ImageSource), typeof(MyButton), null);

        public static readonly DependencyProperty s_pointerProperty =
         DependencyProperty.Register("Pointer", typeof(ImageSource), typeof(MyButton), null);
    }
</code>```

.xaml

```<code><UserControl
    x:Class="...Main.Components.MyButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:...Main.Components"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" Width="755.357">
    <Button Margin="0,1,1,-1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <Grid HorizontalAlignment="Stretch" Margin="-375,-152,-375,-148" Width="750" Height="300" VerticalAlignment="Stretch">
            <Image HorizontalAlignment="Left" Height="100" Margin="39,105,0,0" VerticalAlignment="Top" Width="100" Source="{?!?!?!}"/>
            <TextBlock HorizontalAlignment="Left" Margin="160,126,0,0" Text="TextBlock" TextWrapping="Wrap" VerticalAlignment="Top" Height="70" Width="403"/>
            <Image HorizontalAlignment="Left" Height="100" Margin="602,121,0,0" VerticalAlignment="Top" Width="100"/>
        </Grid>
    </Button>
</UserControl>
</code>```

Basically, it has two images inside a grid, which I would like to bind to my dependecy properties, Icon and Pointer.

In the designer of my control I can't see the dependency properties, but I can see them in the designer of  page on which I have the custom button.

I have followed this tutorial, and tried to do the same: https://social.technet.microsoft.com/wiki/contents/articles/32795.uwp-creating-user-control.aspx, but when I click on my first image --> Source in the custom control's designer, the "create data binding" option is not even available - it is disabled.

I have tried to set the data binding like this:

```<code><Image HorizontalAlignment="Left" Height="100" Margin="39,105,0,0" VerticalAlignment="Top" Width="100" Source="{Binding Icon}"/>
</code>```

but I realize that this is probably not the right syntax.

How do I bind to these dependency properties, is there a simple way?

I have created the control by using Add new item... User Control.

答:
I have tried to set the data binding like this:
  <Image HorizontalAlignment="Left" Height="100" Margin="39,105,0,0" VerticalAlignment="Top" Width="100" Source="{Binding Icon}"/>

This way you set the data binding in the XAML of the user control is correct. But you didn't set the DataContext for the binding. Without the data source the binding will not work. Just set the Datacontext inside your user control it will work. Code as follows:

```<code>public MyButton()
{
    InitializeComponent();
    (this.Content as FrameworkElement).DataContext = this;
}

public ImageSource Icon
{
    get => (ImageSource)GetValue(s_iconProperty);
    set => SetValue(s_iconProperty, value);
}
</code>```

Then you can use the user control to set the image source, for example:

```<code><local:MyButton
    Width="600"
    Height="800"
    Icon="Assets/A.jpg" />
</code>```

More details about binding inside user control you could reference this article.

Title: UWP bind to dependency property

Body:
I have created a UWP project using the Template studio, and I am trying to implement a custom control.

This is what it looks like:

.xaml.cs

 public sealed partial class MyButton : UserControl
    {
        public MyButton()
        {
            InitializeComponent();
        }

        public ImageSource Icon
        {
            get => (ImageSource)GetValue(s_iconProperty);
            set => SetValue(s_iconProperty, value);
        }

        public ImageSource Pointer
        {
            get => (ImageSource)GetValue(s_pointerProperty);
            set => SetValue(s_pointerProperty, value);
        }

        public static readonly DependencyProperty s_iconProperty =
          DependencyProperty.Register("Icon", typeof(ImageSource), typeof(MyButton), null);

        public static readonly DependencyProperty s_pointerProperty =
         DependencyProperty.Register("Pointer", typeof(ImageSource), typeof(MyButton), null);
    }

.xaml

<UserControl
    x:Class="...Main.Components.MyButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:...Main.Components"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" Width="755.357">
    <Button Margin="0,1,1,-1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
        <Grid HorizontalAlignment="Stretch" Margin="-375,-152,-375,-148" Width="750" Height="300" VerticalAlignment="Stretch">
            <Image HorizontalAlignment="Left" Height="100" Margin="39,105,0,0" VerticalAlignment="Top" Width="100" Source="{?!?!?!}"/>
            <TextBlock HorizontalAlignment="Left" Margin="160,126,0,0" Text="TextBlock" TextWrapping="Wrap" VerticalAlignment="Top" Height="70" Width="403"/>
            <Image HorizontalAlignment="Left" Height="100" Margin="602,121,0,0" VerticalAlignment="Top" Width="100"/>
        </Grid>
    </Button>
</UserControl>

Basically, it has two images inside a grid, which I would like to bind to my dependecy properties, Icon and Pointer.

In the designer of my control I can't see the dependency properties, but I can see them in the designer of  page on which I have the custom button.

I have followed this tutorial, and tried to do the same: https://social.technet.microsoft.com/wiki/contents/articles/32795.uwp-creating-user-control.aspx, but when I click on my first image --> Source in the custom control's designer, the "create data binding" option is not even available - it is disabled.

I have tried to set the data binding like this:

<Image HorizontalAlignment="Left" Height="100" Margin="39,105,0,0" VerticalAlignment="Top" Width="100" Source="{Binding Icon}"/>

but I realize that this is probably not the right syntax.

How do I bind to these dependency properties, is there a simple way?

I have created the control by using Add new item... User Control.

Body:
I have tried to set the data binding like this:
  <Image HorizontalAlignment="Left" Height="100" Margin="39,105,0,0" VerticalAlignment="Top" Width="100" Source="{Binding Icon}"/>

This way you set the data binding in the XAML of the user control is correct. But you didn't set the DataContext for the binding. Without the data source the binding will not work. Just set the Datacontext inside your user control it will work. Code as follows:

public MyButton()
{
    InitializeComponent();
    (this.Content as FrameworkElement).DataContext = this;
}

public ImageSource Icon
{
    get => (ImageSource)GetValue(s_iconProperty);
    set => SetValue(s_iconProperty, value);
}

Then you can use the user control to set the image source, for example:

<local:MyButton
    Width="600"
    Height="800"
    Icon="Assets/A.jpg" />

More details about binding inside user control you could reference this article.


来源: stackexchange

问:
Storing function pointer in std::function
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

```<code>class DynamicLoader
{
  public:
    DynamicLoader(std::string const& filename);

    template<class Signature>
      std::function<Signature> load(std::string const& functionName);

  private:
    void *itsLibraryHandle;
};

DynamicLoader::DynamicLoader(std::string const& filename)
{
  itsLibraryHandle = dlopen(filename.c_str(), RTLD_LAZY);

  if(!itsLibraryHandle)
  { /* Throw Some Error */ }
}

  template<class Signature>
std::function<Signature> DynamicLoader::load(std::string const& functionName)
{
  return <insert magic here> dlsym(itsHandle, functionName.c_str());
}
</code>```

Is there a way to convert the void* function pointer returned by dlsym into a std::function?

答:
Based on what I see here: http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html

```<code>#include <boost/function_types/components.hpp>
#include <boost/function_types/function_pointer.hpp>

template< typename Signature >
std::function<Signature> DynamicLoader::load(std::string const& name)
{
  namespace ft = boost::function_types;
  typedef typename ft::function_pointer< typename ft::components<Signature>::type >::type fp_t;
  fp_t fun_ptr;

  *reinterpret_cast<void**>(&fun_ptr) = dlsym(itsHandle, name.c_str());

  return fun_ptr;
}
</code>```

I've never used dlsym so I don't understand why the cast is being done that way and not simply casting dlsym's return like so:

```<code>fun_ptr = reinterpret_cast<fp_t>(dlsym(itsHandle, name.c_str());
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to write a C++0x wrapper around dlopen()/dlsym() to dynamically load functions from shared objects:

class DynamicLoader
{
  public:
    DynamicLoader(std::string const& filename);

    template<class Signature>
      std::function<Signature> load(std::string const& functionName);

  private:
    void *itsLibraryHandle;
};

DynamicLoader::DynamicLoader(std::string const& filename)
{
  itsLibraryHandle = dlopen(filename.c_str(), RTLD_LAZY);

  if(!itsLibraryHandle)
  { /* Throw Some Error */ }
}

  template<class Signature>
std::function<Signature> DynamicLoader::load(std::string const& functionName)
{
  return <insert magic here> dlsym(itsHandle, functionName.c_str());
}

Is there a way to convert the void* function pointer returned by dlsym into a std::function?

Body:
Based on what I see here: http://pubs.opengroup.org/onlinepubs/009695399/functions/dlsym.html

#include <boost/function_types/components.hpp>
#include <boost/function_types/function_pointer.hpp>

template< typename Signature >
std::function<Signature> DynamicLoader::load(std::string const& name)
{
  namespace ft = boost::function_types;
  typedef typename ft::function_pointer< typename ft::components<Signature>::type >::type fp_t;
  fp_t fun_ptr;

  *reinterpret_cast<void**>(&fun_ptr) = dlsym(itsHandle, name.c_str());

  return fun_ptr;
}

I've never used dlsym so I don't understand why the cast is being done that way and not simply casting dlsym's return like so:

fun_ptr = reinterpret_cast<fp_t>(dlsym(itsHandle, name.c_str());


问:
Sum aggregation for each columns in cassandra
I have a Data model like below,

```<code>CREATE TABLE appstat.nodedata (
    nodeip text,
    timestamp timestamp,
    flashmode text,
    physicalusage int,
    readbw int,
    readiops int,
    totalcapacity int,
    writebw int,
    writeiops int,
    writelatency int,
    PRIMARY KEY (nodeip, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)
</code>```

where, nodeip - primary key and timestamp - clustering key (Sorted by descinding oder to get the latest),

Sample data in this table,

```<code>SELECT * from nodedata WHERE nodeip = '172.30.56.60' LIMIT 2;

 nodeip       | timestamp                       | flashmode | physicalusage | readbw | readiops | totalcapacity | writebw | writeiops | writelatency
--------------+---------------------------------+-----------+---------------+--------+----------+---------------+---------+-----------+--------------
 172.30.56.60 | 2017-12-08 06:13:07.161000+0000 |       yes |            34 |     57 |       19 |            27 |       8 |        89 |           57
 172.30.56.60 | 2017-12-08 06:12:07.161000+0000 |       yes |            70 |      6 |       43 |            88 |      79 |        83 |           89
</code>```

This is properly available and whenever I need to get the statistics I am able to get the data using the partition key like below,

(The above logic seems similar to my previous question : Aggregation in Cassandra across partitions) but expectation is different,

I have value for each column (like readbw, latency etc.,) populated for every one minute in all the 4 nodes.

Now, If I need to get the max value for a column (Example : readbw), It is possible using the following query,

```<code>SELECT max(readbw) FROM nodedata WHERE nodeip IN ('172.30.56.60','172.30.56.61','172.30.56.60','172.30.56.63') AND timestamp < 1512652272989 AND timestamp > 1512537899000;
</code>```

1) First question : Is there a way to perform max aggregation on all nodes of a column (readbw) without using IN query?

2) Second question : Is there a way in Cassandra, whenever I insert the data in Node 1, Node 2, Node 3 and Node 4.
It needs to be aggregated and stored in another table. So that I will collect the aggregated value of each column from the aggregated table.

If any of my point is not clear, please let me know.

Thanks,

Harry

答:
Disclaimer. In your question you should define restrictions to query speed. Readers do not know whether you're trying to show this in real time, or is it more for analytical purposes. It's also not clear on how much data you're operating and the answers might depend on that.

Firstly decide whether you want to do aggregation on read or write. This largely depends on your read/write patterns.

1) First question: (aggregation on read)
The short answer is no - it's not possible. If you want to use Cassandra for this, the best approach would be doing aggregation in your application by reading each nodeip with timestamp restriction. That would be slow. But Cassandra aggregations are also potentially slow. This warning exists for a reason:

```<code>Warnings :
Aggregation query used without partition key
</code>```

I found C++ Cassandra driver to be the fastest option, if you're into that.

If your data size allows, I'd look into using other databases. Regular old MySQL or Postgres will do the job just fine, unless you have terabytes of data. There's also influx DB if you want a more exotic one. But I'm getting off-topic here.

2) Second question: (aggregation on write)
That's the approach I've been using for a while. Whenever I need some aggregations, I would do them in memory (redis) and then flush to Cassandra. Remember, Cassandra is super efficient at writing data, don't be afraid to create some extra tables for your aggregations. I can't say exactly how to do this for your data, as it all depends on your requirements. It doesn't seem feasible to provide results for arbitrary timestamp intervals when aggregating on write.

Just don't try to put large sets of data into a single partition. You're better of with traditional SQL databases then.

ContentLicense: CC BY-SA 3.0

Body:
I have a Data model like below,

CREATE TABLE appstat.nodedata (
    nodeip text,
    timestamp timestamp,
    flashmode text,
    physicalusage int,
    readbw int,
    readiops int,
    totalcapacity int,
    writebw int,
    writeiops int,
    writelatency int,
    PRIMARY KEY (nodeip, timestamp)
) WITH CLUSTERING ORDER BY (timestamp DESC)

where, nodeip - primary key and timestamp - clustering key (Sorted by descinding oder to get the latest),

Sample data in this table,

SELECT * from nodedata WHERE nodeip = '172.30.56.60' LIMIT 2;

 nodeip       | timestamp                       | flashmode | physicalusage | readbw | readiops | totalcapacity | writebw | writeiops | writelatency
--------------+---------------------------------+-----------+---------------+--------+----------+---------------+---------+-----------+--------------
 172.30.56.60 | 2017-12-08 06:13:07.161000+0000 |       yes |            34 |     57 |       19 |            27 |       8 |        89 |           57
 172.30.56.60 | 2017-12-08 06:12:07.161000+0000 |       yes |            70 |      6 |       43 |            88 |      79 |        83 |           89

This is properly available and whenever I need to get the statistics I am able to get the data using the partition key like below,

(The above logic seems similar to my previous question : Aggregation in Cassandra across partitions) but expectation is different,

I have value for each column (like readbw, latency etc.,) populated for every one minute in all the 4 nodes.

Now, If I need to get the max value for a column (Example : readbw), It is possible using the following query,

SELECT max(readbw) FROM nodedata WHERE nodeip IN ('172.30.56.60','172.30.56.61','172.30.56.60','172.30.56.63') AND timestamp < 1512652272989 AND timestamp > 1512537899000;

1) First question : Is there a way to perform max aggregation on all nodes of a column (readbw) without using IN query?

2) Second question : Is there a way in Cassandra, whenever I insert the data in Node 1, Node 2, Node 3 and Node 4.
It needs to be aggregated and stored in another table. So that I will collect the aggregated value of each column from the aggregated table.

If any of my point is not clear, please let me know.

Thanks,

Harry

Body:
Disclaimer. In your question you should define restrictions to query speed. Readers do not know whether you're trying to show this in real time, or is it more for analytical purposes. It's also not clear on how much data you're operating and the answers might depend on that.

Firstly decide whether you want to do aggregation on read or write. This largely depends on your read/write patterns.

1) First question: (aggregation on read)
The short answer is no - it's not possible. If you want to use Cassandra for this, the best approach would be doing aggregation in your application by reading each nodeip with timestamp restriction. That would be slow. But Cassandra aggregations are also potentially slow. This warning exists for a reason:

Warnings :
Aggregation query used without partition key

I found C++ Cassandra driver to be the fastest option, if you're into that.

If your data size allows, I'd look into using other databases. Regular old MySQL or Postgres will do the job just fine, unless you have terabytes of data. There's also influx DB if you want a more exotic one. But I'm getting off-topic here.

2) Second question: (aggregation on write)
That's the approach I've been using for a while. Whenever I need some aggregations, I would do them in memory (redis) and then flush to Cassandra. Remember, Cassandra is super efficient at writing data, don't be afraid to create some extra tables for your aggregations. I can't say exactly how to do this for your data, as it all depends on your requirements. It doesn't seem feasible to provide results for arbitrary timestamp intervals when aggregating on write.

Just don't try to put large sets of data into a single partition. You're better of with traditional SQL databases then.


问:
django UNIQUE constraint failed error
I have fallowing structure of database. I create ProductBidPrice class on view. Add all column has not have any problem but one column which is out_going_price and income_price. When I save the new ProductBidPrice django throw this error

"UNIQUE constraint failed: sales_productbidprice.price_income_id"

. I want use more than one to one realtionship.

I can add and save Django Web Interface. But I can't add in the view.

How can I fix this problem ?

Sorry about my English. I hope explain my problem.

models.py

```<code>    class ProductPriceHistory(BaseModel):
        currency = models.ForeignKey(PriceCurrency)
        price = models.FloatField()
        date = models.DateField()

        class Meta:
            abstract = True

    class ProductIncomePriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_income")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

    class ProductOutgoingPriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_outgoing")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

class AbstractBidDirectSales(BaseModel):
    name = models.CharField(max_length=45)
    sales_date = models.DateField()
    customer = models.ForeignKey(Customer)

    class Meta:
        abstract = True

    class Bid(AbstractBidDirectSales):
        products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice")

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class DirectSale(AbstractBidDirectSales):
        product = models.ManyToManyField(Product, related_name="directSales",  through="ProductDirectSalesPrice")

        class Meta:
            verbose_name_plural = "DirectSales"

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)
</code>```

views.py

```<code>@login_required(login_url="/login/")
def add_bid(request):
    if request.method == "POST":
        new_bid = Bid();
        new_bid.name = request.POST["name"];
        new_bid.sales_date = request.POST["date"];
        new_bid.customer_id = request.POST["customerSelection"];
        new_bid.save();
        price = request.POST;
        items = [];
        pieces = [];
        ubb_code = [];
        for q in price:
            if q.startswith("item"):
                items.append(q);
            if q.startswith("piece"):
                pieces.append(q);
            if q.startswith("productSelection"):
                ubb_code.append(q);
        items = sorted(items);
        pieces = sorted(pieces);
        ubb_code = sorted(ubb_code);

        for i in range(len(items)):
            new_bid_product = ProductBidPrice();
            new_bid_product.bid = new_bid;
            new_bid_product.product_id = request.POST[ubb_code[i]];
            new_bid_product.item_number = request.POST[items[i]];
            new_bid_product.piece = request.POST[pieces[i]];
            income_price = ProductIncomePriceHistory.objects.filter(product_id= request.POST[ubb_code[i]]);
            outgoing_price = ProductOutgoingPriceHistory.objects.filter(product_id=request.POST[ubb_code[i]]);
            new_bid_product.price_income_id = income_price[0].id;
            new_bid_product.price_outgoing_id = outgoing_price[0].id;
            new_bid_product.save();

    customers = Customer.objects.all();
    products = Product.objects.all();
    return render(request, "addBid.html", {"customers": customers, "products":products})
</code>```

答:
```<code>class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.ForeignKey(ProductIncomePriceHistory)
        price_outgoing = models.ForeignKey(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.ForeignKey(ProductIncomePriceHistory)
        price_outgoing = models.ForeignKey(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()
</code>```

use this model as OneToOneField will raise error if same number is tried to be inserted which exist in the database

Title: django UNIQUE constraint failed error

Body:
I have fallowing structure of database. I create ProductBidPrice class on view. Add all column has not have any problem but one column which is out_going_price and income_price. When I save the new ProductBidPrice django throw this error

"UNIQUE constraint failed: sales_productbidprice.price_income_id"

. I want use more than one to one realtionship.

I can add and save Django Web Interface. But I can't add in the view.

How can I fix this problem ?

Sorry about my English. I hope explain my problem.

models.py

    class ProductPriceHistory(BaseModel):
        currency = models.ForeignKey(PriceCurrency)
        price = models.FloatField()
        date = models.DateField()

        class Meta:
            abstract = True

    class ProductIncomePriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_income")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

    class ProductOutgoingPriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_outgoing")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)

class AbstractBidDirectSales(BaseModel):
    name = models.CharField(max_length=45)
    sales_date = models.DateField()
    customer = models.ForeignKey(Customer)

    class Meta:
        abstract = True

    class Bid(AbstractBidDirectSales):
        products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice")

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class DirectSale(AbstractBidDirectSales):
        product = models.ManyToManyField(Product, related_name="directSales",  through="ProductDirectSalesPrice")

        class Meta:
            verbose_name_plural = "DirectSales"

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)

    class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

views.py

@login_required(login_url="/login/")
def add_bid(request):
    if request.method == "POST":
        new_bid = Bid();
        new_bid.name = request.POST["name"];
        new_bid.sales_date = request.POST["date"];
        new_bid.customer_id = request.POST["customerSelection"];
        new_bid.save();
        price = request.POST;
        items = [];
        pieces = [];
        ubb_code = [];
        for q in price:
            if q.startswith("item"):
                items.append(q);
            if q.startswith("piece"):
                pieces.append(q);
            if q.startswith("productSelection"):
                ubb_code.append(q);
        items = sorted(items);
        pieces = sorted(pieces);
        ubb_code = sorted(ubb_code);

        for i in range(len(items)):
            new_bid_product = ProductBidPrice();
            new_bid_product.bid = new_bid;
            new_bid_product.product_id = request.POST[ubb_code[i]];
            new_bid_product.item_number = request.POST[items[i]];
            new_bid_product.piece = request.POST[pieces[i]];
            income_price = ProductIncomePriceHistory.objects.filter(product_id= request.POST[ubb_code[i]]);
            outgoing_price = ProductOutgoingPriceHistory.objects.filter(product_id=request.POST[ubb_code[i]]);
            new_bid_product.price_income_id = income_price[0].id;
            new_bid_product.price_outgoing_id = outgoing_price[0].id;
            new_bid_product.save();

    customers = Customer.objects.all();
    products = Product.objects.all();
    return render(request, "addBid.html", {"customers": customers, "products":products})

Body:
class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.ForeignKey(ProductIncomePriceHistory)
        price_outgoing = models.ForeignKey(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.ForeignKey(ProductIncomePriceHistory)
        price_outgoing = models.ForeignKey(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

use this model as OneToOneField will raise error if same number is tried to be inserted which exist in the database


问:
Implementing an interface through a subset of its methods
I have a C++ interface with two methods. Any class implementing this interface need to implement at least one of the two methods but may define both. It is however not necessary to define both. What is the best pattern to use in such situation ?</p>

答:
IMHO the question is already wrong and also the class it is based on.

Case A:
A class has a definition for a given method. The base implementation should provide an expectable behavior. In this case you are free to override it or not.

Case B:
The method is abstract so you have to overwrite it in an expectable manner, otherwise the compiler won't compile.

There is no way to declare a "please overwrite one or both" in C++. A class given, which expect that, is (very) bad design.

So the question does not exist. If it exists, it is not possible to answer it with more details, as it depends on the context.


问:
Change the one progress bar when its corresponding input filed is changed
Currently for both , when one of the input field's value change, two progress bar will change. Can i only change the one progress bar when its corresponding input filed is changed?

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>

<td></td>
<div class="form-group">
<input type="text" class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td></code>```

答:
With $('.progress-bar'), you select all .progress-bar element.

Instead, you need to go up one level to the parent, go to the next sibling, and find progress bar there:

Change

```<code>$('.progress-bar')
</code>```

To:

```<code>$(this).parent().next('.progress').find('.progress-bar')
</code>```

Al togehter:

```<code>$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $(this).parent().next('.progress').find('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();
</code>```

Body:
Currently for both , when one of the input field's value change, two progress bar will change. Can i only change the one progress bar when its corresponding input filed is changed?

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<input type="text" class="form-control"/>

        60% Complete

<input type="text" class="form-control"/>

        60% Complete

Body:
With $('.progress-bar'), you select all .progress-bar element.

Instead, you need to go up one level to the parent, go to the next sibling, and find progress bar there:

Change

$('.progress-bar')

To:

$(this).parent().next('.progress').find('.progress-bar')

Al togehter:

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $(this).parent().next('.progress').find('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();


问:
Why do I have to stage a file in order to make git realise that a conflict has been resolved?
Problem: I change multiple lines, and stage + commit all but one of them, then I want to push the commit. However, before I push them I want to merge from another branch to see if there's a conflict to be resolved as well.

Uh-oh, a conflict! I fix it, but in order to make git agree that it's fixed, I have to stage the entire file. Noooo, I want to keep that single line unstaged. Staging the entire file will bury that line among 1000 lines of conflict-resolved changes (so finding it and unstaging it will take days ;-).

Why can't I just tell git "listen, relax, forget it, it's not a problem anymore, I want to just leave things as they are now - when I'm done with the final fix to that single line I promise I'll stage everything (eventually;-) and commit it".

Am I missing something? Is there a simple workflow that'll get around this issue?

Cheers,
Stein

答: Staging can be done patch by patch rather than by whole files. Use a git client or git add -p and stage only the parts you want to be part of this commit (probably the parts around the merged areas).</p>


问:
Efficient string searching in Java
I am working with two big lists of data and I need to efficiently check for matches between the two. This is the scenario:

Reading from a file line by line (this file has 1 million lines)

For each line, check within an ArrayList of strings whether it has a match (this ArrayList also has a huge number of elements)

If a match is found, replace the line from the file with a new value

Any ideas what would be a good way to tackle this problem in terms of efficiency? Obviously looping through that number of records is hopelessly inefficient and process heavy.

Thanks for any help!

UPDATE
It's worth noting, I'm not specifically saying I need to use an ArrayList, that is just something I was using for testing. Any suggestions of more efficient Collections would be welcome.

答:
You may consider reading the file partially by different threads.
Similar issue is discussed here.

You may process the text in chunks (say x bytes or one line) , each chunk can be executed by different threads , ie one thread per chunk.

Title: Efficient string searching in Java


问:
How can I chain a list of Completable after executing another Completable
I am trying to save some data in a database. For adding methods I use Completable. After I save one entity - customer, I want to save a list of days, but only after customer is saved. This is my code now.

```<code>mDatabaseManager.addCustomer(customer)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(() -> {
                    for (Day day : days) {
                        mDatabaseManager.addDay(day)
                                .subscribeOn(Schedulers.io())
                                .subscribe(() -> {});
                    }
                });
</code>```

It works, but sometimes I get an error:

```<code>io.reactivex.exceptions.OnErrorNotImplementedException: FOREIGN KEY constraint failed (code 787)
</code>```

And I also learned that this is not a proper way how to do it and I should chain the completable. I found concatWith and andThen operators, but I still can not rewrite this code. Could anyone show me how?

答:
You could andThen the list of days wrapped into an Observable and use concatMapCompletable to insert them one after the other.

```<code>mDatabaseManager.addCustomer(customer)
            .subscribeOn(Schedulers.io())
            .andThen(
                 Observable.fromIterable(days)
                 .concatMapCompletable(day ->
                      mDatabaseManager.addDay(day)
                      .subscribeOn(Schedulers.io())
                 )
            )
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe();
</code>```

Body:
I am trying to save some data in a database. For adding methods I use Completable. After I save one entity - customer, I want to save a list of days, but only after customer is saved. This is my code now.

mDatabaseManager.addCustomer(customer)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(() -> {
                    for (Day day : days) {
                        mDatabaseManager.addDay(day)
                                .subscribeOn(Schedulers.io())
                                .subscribe(() -> {});
                    }
                });

It works, but sometimes I get an error:

io.reactivex.exceptions.OnErrorNotImplementedException: FOREIGN KEY constraint failed (code 787)

And I also learned that this is not a proper way how to do it and I should chain the completable. I found concatWith and andThen operators, but I still can not rewrite this code. Could anyone show me how?

Body:
You could andThen the list of days wrapped into an Observable and use concatMapCompletable to insert them one after the other.

mDatabaseManager.addCustomer(customer)
            .subscribeOn(Schedulers.io())
            .andThen(
                 Observable.fromIterable(days)
                 .concatMapCompletable(day ->
                      mDatabaseManager.addDay(day)
                      .subscribeOn(Schedulers.io())
                 )
            )
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe();


问:
Objective C: Having buttons work inside a mutable array
I'm making a game that involves have buttons move across the screen until the user taps them. What I have so far is buttons moving across being generated randomly. My problem is when a new button is created, the last one stops moving. I'm trying to stick them into an array, but I'm not sure that's really gonna keep them moving. </p>

```<code>-(void) generateStickFig:(NSTimer *)timer {

int x = random() % 100;
NSMutableArray *enemies = (NSMutableArray *)timer.userInfo;
if (x == 1) {
    stickFig = [[UIButton alloc] initWithFrame:CGRectMake(0, 650, 50, 50)];
    [stickFig setBackgroundColor:[UIColor blackColor]];
    [stickFig addTarget:self action:@selector(tapFig:) forControlEvents:UIControlEventTouchUpInside];
//  [enemies setObject:object forKey:[NSString stringWithFormat:@"object%i",i]];
    [enemies addObject:stickFig];
    int b = [enemies count];
    [self.view addSubview:stickFig];
    arrayNum++;
}

CGPoint oldPosition = stickFig.center;
stickFig.center = CGPointMake(oldPosition.x + 1 , oldPosition.y);

}
</code>```

答:
Where the buttons are stored is immaterial to moving them. You need to have a routine which animates them. You can do this by hand by moving them a small amount in response to a timer tick. The easiest method there would be fast enumeration over your array.

So you'd have the generation routine you have in your statement, a movement routine, and a touch IBAction handler which removes the button from the array. The generation routine, and the movement routine would both be called in your timer tick handler. (I tend to call that method "handleTick")

In high level psuedo-code it'd be something like this:

```<code>//tick handler
handleTick:
  one out a hundred times, make a new button
          give it a random starting location
          store it in the buttons array
  every time:
    for button in buttons:
      move button a few pixels

//button touch handler
buttonWasTouched:button :
  [buttons removeObject: button];
</code>```

I'm just getting into the system provided animation, so I don't know if your button can accept touches while being animated, but I wouldn't be surprised.

Body:
I'm making a game that involves have buttons move across the screen until the user taps them. What I have so far is buttons moving across being generated randomly. My problem is when a new button is created, the last one stops moving. I'm trying to stick them into an array, but I'm not sure that's really gonna keep them moving.

-(void) generateStickFig:(NSTimer *)timer {

int x = random() % 100;
NSMutableArray *enemies = (NSMutableArray *)timer.userInfo;
if (x == 1) {
    stickFig = [[UIButton alloc] initWithFrame:CGRectMake(0, 650, 50, 50)];
    [stickFig setBackgroundColor:[UIColor blackColor]];
    [stickFig addTarget:self action:@selector(tapFig:) forControlEvents:UIControlEventTouchUpInside];
//  [enemies setObject:object forKey:[NSString stringWithFormat:@"object%i",i]];
    [enemies addObject:stickFig];
    int b = [enemies count];
    [self.view addSubview:stickFig];
    arrayNum++;
}

CGPoint oldPosition = stickFig.center;
stickFig.center = CGPointMake(oldPosition.x + 1 , oldPosition.y);

}

Body:
Where the buttons are stored is immaterial to moving them. You need to have a routine which animates them. You can do this by hand by moving them a small amount in response to a timer tick. The easiest method there would be fast enumeration over your array.

So you'd have the generation routine you have in your statement, a movement routine, and a touch IBAction handler which removes the button from the array. The generation routine, and the movement routine would both be called in your timer tick handler. (I tend to call that method "handleTick")

In high level psuedo-code it'd be something like this:

//tick handler
handleTick:
  one out a hundred times, make a new button
          give it a random starting location
          store it in the buttons array
  every time:
    for button in buttons:
      move button a few pixels

//button touch handler
buttonWasTouched:button :
  [buttons removeObject: button];

I'm just getting into the system provided animation, so I don't know if your button can accept touches while being animated, but I wouldn't be surprised.


问:
Creating json file inside a specific directory using terminal
I'm trying to create my Starter Pack Setup and I need to install NPM dependencies. I should create a json file in: /Users/matteomattiussi/Documents/Udemy/Bootstrap/bs4projects/bs4starter
but I don't know how do it because I always getting the json file in:
/Users/matteomattiussi/package.json

Can someone help me, please?

答:
In order to create a package.json file in /Users/matteomattiussi/Documents/Udemy/Bootstrap/bs4projects/bs4starter (if the directory already exists and you have npm installed):

```<code>cd /Users/matteomattiussi/Documents/Udemy/Bootstrap/bs4projects/bs4starter
npm init
</code>```

In using package.json:

This will initiate a command line questionnaire that will conclude
  with the creation of a package.json in the directory you initiated the
  command.

Body:
In order to create a package.json file in /Users/matteomattiussi/Documents/Udemy/Bootstrap/bs4projects/bs4starter (if the directory already exists and you have npm installed):

cd /Users/matteomattiussi/Documents/Udemy/Bootstrap/bs4projects/bs4starter
npm init

In using package.json:

This will initiate a command line questionnaire that will conclude
  with the creation of a package.json in the directory you initiated the
  command.


问:
eBay Sell API: Aspects object returns 'Could not serialize field' error, when creating Inventory Item
I am using eBay's new REST Sell API to create an inventory item. I am having problems creating product aspects manually. I've tried creating a list of name value pairs but eBay is returning the following error:

```<code>Could not serialize field [product.aspects]
</code>```

Below is the request payload sample from eBay:

```<code>{
    "availability": {
        "shipToLocationAvailability": {
            "quantity": 50
        }
    },
    "condition": "NEW",
    "product": {
        "title": "GoPro Hero4 Helmet Cam",
        "description": "New GoPro Hero4 Helmet Cam. Unopened box.",
        "aspects": {
            "Brand": [
                "GoPro"
            ],
            "Type": [
                "Helmet/Action"
            ],
            "Storage Type": [
                "Removable"
            ],
            "Recording Definition": [
                "High Definition"
            ],
            "Media Format": [
                "Flash Drive (SSD)"
            ],
            "Optical Zoom": [
                "10x"
            ]
        },
        "imageUrls": [
            "http://i.ebayimg.com/images/i/182196556219-0-1/s-l1000.jpg",
            "http://i.ebayimg.com/images/i/182196556219-0-1/s-l1001.jpg",
            "http://i.ebayimg.com/images/i/182196556219-0-1/s-l1002.jpg"
        ]
    }
}
</code>```

As far as I know product aspects are not fixed and can be anything, because of this I cannot create a Class. I'm not sure how to handle this apart from manually creating the JSON and inserting it in the correct place in the request payload.

Is there a better way to do this? Maybe create a dynamic object on the fly (any examples would help)?

答:
I ended up creating a list of an Aspect object, using an extension method to manually convert the list into JSON which I deserialize into an object and pass into the request payload to eBay.</p>

```<code>Public Class Aspect
    Property Name As String
    Property Values As String()
End Class

Public Class RequestPayload
    <JsonProperty("aspects")>
    Public Property Aspects As Object
End Class

Sub Click()

    Dim Payload As New RequestPayload

    Payload.Aspects = (New List(Of Aspect) From {
                            New Aspect With {.Name = "Brand", .Values = {"GoPro"}},
                            New Aspect With {.Name = "Type", .Values = {"Helmet/Action"}}
                        }
                    ).ToAspectsObject()

End Sub

<Extension()>
Function ToAspectsObject(Source As List(Of Aspect)) As Object

    Dim Aspects As New List(Of String)

    For Each Aspect In Source
        Aspects.Add(String.Format("""{0}"": [{1}]", Aspect.Name, String.Join(", ", Aspect.Values.Select(Function(x) String.Format("""{0}""", x)))))
    Next

    Dim JsonObject = String.Format("{{{0}}}", String.Join(", ", Aspects))

    Return Json.DeserializeObject(JsonObject)

End Function
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using eBay's new REST Sell API to create an inventory item. I am having problems creating product aspects manually. I've tried creating a list of name value pairs but eBay is returning the following error:

Could not serialize field [product.aspects]

Below is the request payload sample from eBay:

{
    "availability": {
        "shipToLocationAvailability": {
            "quantity": 50
        }
    },
    "condition": "NEW",
    "product": {
        "title": "GoPro Hero4 Helmet Cam",
        "description": "New GoPro Hero4 Helmet Cam. Unopened box.",
        "aspects": {
            "Brand": [
                "GoPro"
            ],
            "Type": [
                "Helmet/Action"
            ],
            "Storage Type": [
                "Removable"
            ],
            "Recording Definition": [
                "High Definition"
            ],
            "Media Format": [
                "Flash Drive (SSD)"
            ],
            "Optical Zoom": [
                "10x"
            ]
        },
        "imageUrls": [
            "http://i.ebayimg.com/images/i/182196556219-0-1/s-l1000.jpg",
            "http://i.ebayimg.com/images/i/182196556219-0-1/s-l1001.jpg",
            "http://i.ebayimg.com/images/i/182196556219-0-1/s-l1002.jpg"
        ]
    }
}

As far as I know product aspects are not fixed and can be anything, because of this I cannot create a Class. I'm not sure how to handle this apart from manually creating the JSON and inserting it in the correct place in the request payload.

Is there a better way to do this? Maybe create a dynamic object on the fly (any examples would help)?

Body:
I ended up creating a list of an Aspect object, using an extension method to manually convert the list into JSON which I deserialize into an object and pass into the request payload to eBay.

Public Class Aspect
    Property Name As String
    Property Values As String()
End Class

Public Class RequestPayload
    <JsonProperty("aspects")>
    Public Property Aspects As Object
End Class

Sub Click()

    Dim Payload As New RequestPayload

    Payload.Aspects = (New List(Of Aspect) From {
                            New Aspect With {.Name = "Brand", .Values = {"GoPro"}},
                            New Aspect With {.Name = "Type", .Values = {"Helmet/Action"}}
                        }
                    ).ToAspectsObject()

End Sub

<Extension()>
Function ToAspectsObject(Source As List(Of Aspect)) As Object

    Dim Aspects As New List(Of String)

    For Each Aspect In Source
        Aspects.Add(String.Format("""{0}"": [{1}]", Aspect.Name, String.Join(", ", Aspect.Values.Select(Function(x) String.Format("""{0}""", x)))))
    Next

    Dim JsonObject = String.Format("{{{0}}}", String.Join(", ", Aspects))

    Return Json.DeserializeObject(JsonObject)

End Function


问:
Writing Unit Test for methods that use User.Identity.Name in ASP.NET Web API
I am writing test cases using the Unit Test for ASP.NET Web API.

Now I have an action which makes a call to some method I have defined in the service layer, where I have used the following line of code.

```<code>string username = User.Identity.Name;
// do something with username
// return something
</code>```

Now how to I create unit test method for this, I am getting null reference exceptions. I am kinda new to writing unit test and stuff.

I want to use Unit Test only for this. Please help me out on this.

答:
This is my solution.</p>

```<code>var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "Nikita"),
    new Claim(ClaimTypes.NameIdentifier, "1")
};

var identity = new ClaimsIdentity(claims);
IPrincipal user = new ClaimsPrincipal(identity);

controller.User = user;
</code>```

Body:
I am writing test cases using the Unit Test for ASP.NET Web API.

Now I have an action which makes a call to some method I have defined in the service layer, where I have used the following line of code.

string username = User.Identity.Name;
// do something with username
// return something

Now how to I create unit test method for this, I am getting null reference exceptions. I am kinda new to writing unit test and stuff.

I want to use Unit Test only for this. Please help me out on this.

Body:
This is my solution.

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "Nikita"),
    new Claim(ClaimTypes.NameIdentifier, "1")
};

var identity = new ClaimsIdentity(claims);
IPrincipal user = new ClaimsPrincipal(identity);

controller.User = user;


问:
How to define a user with SELECT privileges with puppet?
I want to create a user in postgres who can only made SELECT in all the tables of the current database.
How can specify ALL tables in puppet?

Here an extract of my puppet file:

```<code>...
postgresql::server::database_grant { 'PnBP':
  privilege => 'CREATE',
  db        => 'db',
  role      => 'role',
}

postgresql::server::table_grant { 'SELECT':
  privilege => 'SELECT',
  table     => 'ALL',
  db        => 'db',
  role      => 'role',
}
...
</code>```

But when I specify the word ALL it doesn't work.
Here the error:

Error: /Stage[main]/Main/Node[default]/Postgresql::Server::Table_grant[PnBP]/Postgresql::Server::Grant[table:PnBP]/Postgresql_psql[grant:table:PnBP]: Could not evaluate: Error evaluating 'unless' clause, returned pid 30443 exit 1: 'ERROR:  relation "all" does not exist
'

I check the doc, but it doesn't specify how to apply the privileges for all the tables.

table : Specifies the table to which you are granting access.

postgresql::server::table_grant

答:
The Puppet documentation for Postgresql describes a postgresql::server::grant option that looks more flexible than the table_grant which assumes a single table.

Looks to be something like:

```<code>postgresql::server::grant{ 'SELECT':
  object_type => 'ALL TABLES IN SCHEMA',
  object_name => 'public',
  privilege => 'SELECT',
  db        => 'db',
  role      => 'role',
}
</code>```

https://github.com/puppetlabs/puppetlabs-postgresql#postgresqlservergrant

Body:
I want to create a user in postgres who can only made SELECT in all the tables of the current database.
How can specify ALL tables in puppet?

Here an extract of my puppet file:

...
postgresql::server::database_grant { 'PnBP':
  privilege => 'CREATE',
  db        => 'db',
  role      => 'role',
}

postgresql::server::table_grant { 'SELECT':
  privilege => 'SELECT',
  table     => 'ALL',
  db        => 'db',
  role      => 'role',
}
...

But when I specify the word ALL it doesn't work.
Here the error:

Error: /Stage[main]/Main/Node[default]/Postgresql::Server::Table_grant[PnBP]/Postgresql::Server::Grant[table:PnBP]/Postgresql_psql[grant:table:PnBP]: Could not evaluate: Error evaluating 'unless' clause, returned pid 30443 exit 1: 'ERROR:  relation "all" does not exist
'

I check the doc, but it doesn't specify how to apply the privileges for all the tables.

table : Specifies the table to which you are granting access.

postgresql::server::table_grant

Body:
The Puppet documentation for Postgresql describes a postgresql::server::grant option that looks more flexible than the table_grant which assumes a single table.

Looks to be something like:

postgresql::server::grant{ 'SELECT':
  object_type => 'ALL TABLES IN SCHEMA',
  object_name => 'public',
  privilege => 'SELECT',
  db        => 'db',
  role      => 'role',
}

https://github.com/puppetlabs/puppetlabs-postgresql#postgresqlservergrant


问:
How can I make this css animation smooth
In the below example you can see the boxes jumping a little bit, How can I make that transition smooth?

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

答:
1: You have to start your animation from transform: translateY(0px) translateX(0px) for smooth transition and

2: transform value should be same at 0% and 100% of keyframes

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite;
  animation-timing-function: linear;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px) translateX(0px);
  }
  25% {
    transform: translateY(-10px) translateX(-10px);
  }
  50% {
    transform: translateY(0px) translateX(0px);
  }
  75% {
    transform: translateY(10px) translateX(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

Body:
1: You have to start your animation from transform: translateY(0px) translateX(0px) for smooth transition and

2: transform value should be same at 0% and 100% of keyframes

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite;
  animation-timing-function: linear;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px) translateX(0px);
  }
  25% {
    transform: translateY(-10px) translateX(-10px);
  }
  50% {
    transform: translateY(0px) translateX(0px);
  }
  75% {
    transform: translateY(10px) translateX(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


问:
how to access prototype functions in console
I created a javascript and added it to a page like this:

```<code>(function (window, google, List){
var myfunction = (function(){}
myfunction.prototype = {
hint: function(){alert('a good advise');}
})
}(window, google, List))
</code>```

I added the needed js files, and it works! it will show the result after loading when instatination id like

```<code>var myfancything = myfunction.create();
</code>```

I am getting the result after page load.
BUT! I would expect that if i then open the console and type

```<code>myfancything.hint();
</code>```

I would see the alert.
I know I was able to do that the other day, but I don't know how I achieved it!

so I would like to use the prototypes in the browser console, can you guys give me a hint how to do that?

答:
A function declared inside another function is not accessible from the outside by default :

f();

try {
  g("u");
} catch (e) {
  console.error(e);
}

function f () {
  g("f");
  function g (caller) {
    console.log(caller, "called g");
  }
}```
</div>
</div>
</p>

<p>If you want the inner function to be public, you have to declare it explicitely :</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>f();

try {
  g("u");
} catch (e) {
  console.error(e);
}

function f () {
  g("f");
  window.g = g;
  function g (caller) {
    console.log(caller, "called g");
  }
}</code>```

Body:
I created a javascript and added it to a page like this:

(function (window, google, List){
var myfunction = (function(){}
myfunction.prototype = {
hint: function(){alert('a good advise');}
})
}(window, google, List))

I added the needed js files, and it works! it will show the result after loading when instatination id like

var myfancything = myfunction.create();

I am getting the result after page load.
BUT! I would expect that if i then open the console and type

myfancything.hint();

I would see the alert.
I know I was able to do that the other day, but I don't know how I achieved it!

so I would like to use the prototypes in the browser console, can you guys give me a hint how to do that?

Body:
A function declared inside another function is not accessible from the outside by default :

f();

try {
  g("u");
} catch (e) {
  console.error(e);
}

function f () {
  g("f");
  function g (caller) {
    console.log(caller, "called g");
  }
}

If you want the inner function to be public, you have to declare it explicitely :

f();

try {
  g("u");
} catch (e) {
  console.error(e);
}

function f () {
  g("f");
  window.g = g;
  function g (caller) {
    console.log(caller, "called g");
  }
}


问:
Vertx thread blocked warnings
I am running a vert.x application on ubuntu server. It has an HTTPServer running on port 3000. Application is working fine but sometimes I am seeing following warnings:

```<code>Dec 08, 2017 1:23:43 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 138013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:44 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 139014 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:45 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 140013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:46 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 141013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:47 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 142013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:48 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 143013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:49 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 144013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:50 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 145013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

I am not able to understand what is causing these warnings to appear. At the time of warnings, the server was idle with 0 traffic on the application. Also, I am running a scheduler using vertx periodic, which makes query to mongo every 15 secs.

```<code>vertx.setPeriodic(15000, r -> someService.check()); // Every 15 seconds
</code>```

答: Are you executing blocking api calls using vertx.executeBlocking() ? It appears to me you might have a blocking API call somewhere in your someService.check() or anywhere else</p>

Title: Vertx thread blocked warnings

Body:
I am running a vert.x application on ubuntu server. It has an HTTPServer running on port 3000. Application is working fine but sometimes I am seeing following warnings:

Dec 08, 2017 1:23:43 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 138013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:44 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 139014 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:45 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 140013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:46 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 141013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:47 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 142013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:48 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 143013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:49 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 144013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Dec 08, 2017 1:23:50 AM io.vertx.core.impl.BlockedThreadChecker
WARNING: Thread Thread[vert.x-worker-thread-2,5,main] has been blocked for 145013 ms, time limit is 60000
io.vertx.core.VertxException: Thread blocked
    at java.io.FileInputStream.readBytes(Native Method)
    at java.io.FileInputStream.read(FileInputStream.java:255)
    at sun.security.provider.NativePRNG$RandomIO.readFully(NativePRNG.java:424)
    at sun.security.provider.NativePRNG$RandomIO.implGenerateSeed(NativePRNG.java:441)
    at sun.security.provider.NativePRNG$RandomIO.access$500(NativePRNG.java:331)
    at sun.security.provider.NativePRNG.engineGenerateSeed(NativePRNG.java:226)
    at java.security.SecureRandom.generateSeed(SecureRandom.java:533)
    at io.vertx.ext.auth.PRNG.lambda$null$0(PRNG.java:78)
    at io.vertx.ext.auth.PRNG$$Lambda$204/767088095.handle(Unknown Source)
    at io.vertx.core.impl.ContextImpl.lambda$executeBlocking$1(ContextImpl.java:271)
    at io.vertx.core.impl.ContextImpl$$Lambda$206/1202956360.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

I am not able to understand what is causing these warnings to appear. At the time of warnings, the server was idle with 0 traffic on the application. Also, I am running a scheduler using vertx periodic, which makes query to mongo every 15 secs.

vertx.setPeriodic(15000, r -> someService.check()); // Every 15 seconds


问:
Laravel deployment no display
i finishing doing my laravel apps on local xampp, i currently in process to up my apps on vps server. I got my own company VPS server.

The server department have help install debian jessie, php 7.0-fpm, nginx, mysql.

Now my part is to deploy the apps.

Already done with composer installing and database migration.
I also got 503 and 402 problem, already fix that.

The problem is, the favicon is showing, but the content is not showing.

I don't know where to start, i hope you guys can help me out, thanks.

P/S : Server department cannot help me out on this.

Here are the 2 important configuration...

Laravel .env

```<code>APP_NAME=eticket
APP_ENV=production
APP_KEY=secretLOL
APP_DEBUG=flase
APP_LOG_LEVEL=debug
APP_URL=http://sub.domain.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpass

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=587
MAIL_USERNAME=name@domain.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
</code>```

Nginx site-available for sub.domain.com

```<code>server {
    listen 80;
    server_name sub.domain.com;
    root /var/www/html/sub.domain.com/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
</code>```

答:
You need to give proper access to both storage and bootstrap/cache :

```<code>sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
</code>```

Also check that your web server has the right to read on your application folders

Title: Laravel deployment no display

Body:
i finishing doing my laravel apps on local xampp, i currently in process to up my apps on vps server. I got my own company VPS server.

The server department have help install debian jessie, php 7.0-fpm, nginx, mysql.

Now my part is to deploy the apps.

Already done with composer installing and database migration.
I also got 503 and 402 problem, already fix that.

The problem is, the favicon is showing, but the content is not showing.

I don't know where to start, i hope you guys can help me out, thanks.

P/S : Server department cannot help me out on this.

Here are the 2 important configuration...

Laravel .env

APP_NAME=eticket
APP_ENV=production
APP_KEY=secretLOL
APP_DEBUG=flase
APP_LOG_LEVEL=debug
APP_URL=http://sub.domain.com

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpass

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=587
MAIL_USERNAME=name@domain.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

Nginx site-available for sub.domain.com

server {
    listen 80;
    server_name sub.domain.com;
    root /var/www/html/sub.domain.com/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

Body:
You need to give proper access to both storage and bootstrap/cache :

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

Also check that your web server has the right to read on your application folders


问:
New tab in Javascript bookmarklet with POST
Hope everyone is having a great day! I was trying to create a bookmarklet that automatically opens links on the page with POST headers, yet only the last link is extended into a new page. Is there any reasons why to this?(If so, how could I look about fixing it?)

```<code>javascript: (function() {
        function openWindowWithPost(url, data) {
            var form = document.createElement("form");
            form.target = "_blank";
            form.method = "POST";
            form.action = url;
            form.style.display = "none";

            for (var key in data) {
                var input = document.createElement("input");
                input.type = "hidden";
                input.name = key;
                input.value = data[key];
                form.appendChild(input);
            }

            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
        var els = document.getElementsByTagName("a");
        for (var i = 0, l = els.length; i < l; i++) {
            var el = els[i];

            console.log(typeof el.href);
            console.log(el.href);
            if (el.href.startsWith('example.com')) {
                console.log(el.href.slice(39));
                openWindowWithPost("example.php", {
                    id: el.href.slice(39),
                    pdf: "-"
                });
            }
        }
    })();
</code>```

Thank you!

答:
Your JavaScript code runs as though it were code in the page (as you probably know), both with its privileges and its restrictions.

Browsers don't allow JavaScript code in pages to open an unlimited number of windows, because when they used to allow that, it was abused by nefarious sites. So when code on a page tries to do that, the browser prevents it. The specifics of how it prevents it and to what degreee it allows things to happen are browser-specific.

You'll probably need to have a user-event per window you want to open (e.g., trigger the bookmarklet repeatedly, and have the bookmarklet do one link at a time).

Body:
Hope everyone is having a great day! I was trying to create a bookmarklet that automatically opens links on the page with POST headers, yet only the last link is extended into a new page. Is there any reasons why to this?(If so, how could I look about fixing it?)

javascript: (function() {
        function openWindowWithPost(url, data) {
            var form = document.createElement("form");
            form.target = "_blank";
            form.method = "POST";
            form.action = url;
            form.style.display = "none";

            for (var key in data) {
                var input = document.createElement("input");
                input.type = "hidden";
                input.name = key;
                input.value = data[key];
                form.appendChild(input);
            }

            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
        var els = document.getElementsByTagName("a");
        for (var i = 0, l = els.length; i < l; i++) {
            var el = els[i];

            console.log(typeof el.href);
            console.log(el.href);
            if (el.href.startsWith('example.com')) {
                console.log(el.href.slice(39));
                openWindowWithPost("example.php", {
                    id: el.href.slice(39),
                    pdf: "-"
                });
            }
        }
    })();

Thank you!


答:
You can access the parent element that wraps both and set it as a "namespace" to look for progress bar. Just make sure your HTML markup is valid, as in your example you have missing code for
,
 and your 's are missplaced as well.

$('input').on('keyup', function(){
    var value = this.value;
    var wrappingTd = $(this).parent().parent();

    $(' .progress-bar',wrappingTd)
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}) ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.3/js/tether.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<table><tr>
<td>
<div class="form-group">
<input type="text"   class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>

<td>
<div class="form-group">
<input type="text"   class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>
</tr></table></code>```

Title: Change the one progress bar when its corresponding input filed is changed

Body:
Currently for both , when one of the input field's value change, two progress bar will change. Can i only change the one progress bar when its corresponding input filed is changed?

$('input').on('keyup', function(){
    var value = this.value;
   var bar =
    $('.progress-bar')
        .css('width', value+'%')
        .attr('aria-valuenow', value);
}).keyup();

 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<input type="text" class="form-control"/>

        60% Complete

<input type="text" class="form-control"/>

        60% Complete

Body:
You can access the parent element that wraps both and set it as a "namespace" to look for progress bar. Just make sure your HTML markup is valid, as in your example you have missing code for <table>,<tr> and your <td>'s are missplaced as well.

$('input').on('keyup', function(){
    var value = this.value;
    var wrappingTd = $(this).parent().parent();

    $(' .progress-bar',wrappingTd)
        .css('width', value+'%')
        .attr('aria-valuenow', value);
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.3/js/tether.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<table><tr>
<td>
<div class="form-group">
<input type="text"   class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>

<td>
<div class="form-group">
<input type="text"   class="form-control"/>
</div>

<div class="progress">
    <div class="progress-bar progress-bar-success"
         role="progressbar"
         aria-valuenow="0" aria-valuemin="0"
         aria-valuemax="100" style="width: 60%;">
        <span class="sr-only">60% Complete</span>
    </div>
</div>
</td>
</tr></table>


问:
Add pagination in a Wordpress Latest Posts widget
In a Wordpress Latest Posts widget I want to add pagination

 public function widget($args, $instance) {
  extract($args);
  $title    = apply_filters('widget_title', $instance['title'] );
  $count    = $instance['count'];
  $category   = $instance['category'];
  echo $before_widget;
  $output = '';
  if ( $title )
   echo $before_title . $title . $after_title;
  global $post;
  if ( isset( $category ) && $category != '' ) {
   $args = array(
    'category_name'  => $category,
    'posts_per_page' => $count,
   );
  } else {
   $args = array(
    'posts_per_page' => $count,
   );
  }
  $posts = get_posts( $args );
  if(count($posts)>0){
   $output .='
';
   foreach ($posts as $post): setup_postdata($post);
    $output .='
';

     if(has_post_thumbnail()):
      $output .='
';
      $output .=''.get_the_post_thumbnail($post->ID, 'xs-thumb', array('class' => 'img-responsive')).'';
      $output .='
';
     endif;

     $output .='
';
     $output .= '
'. get_the_title() .'
';
     $output .= '
'. get_the_time() . ' ' . get_the_date('d M Y') . '
';
     $output .='
';
    $output .='
';
   endforeach;
   wp_reset_query();
   $output .='
';
  }
  echo $output;
  echo $after_widget;
 }```

I tried with pagination_nav(); after adding code in functions.php and I used WP-PageNavi, but without success.
How to add numbered pagination in this case?
Thanks in advance!

答:
Use below code for numbered pagination,</p>

```<code><?php the_posts_pagination( array(
      'mid_size'  => 1,
      'prev_text' => __( 'Prev', 'textdomain' ),
      'next_text' => __( 'Next', 'textdomain' ),
      'screen_reader_text' => ' ',
    ) );

     } ?>
</code>```

Body:
In a Wordpress Latest Posts widget I want to add pagination

 public function widget($args, $instance) {
  extract($args);
  $title    = apply_filters('widget_title', $instance['title'] );
  $count    = $instance['count'];
  $category   = $instance['category'];
  echo $before_widget;
  $output = '';
  if ( $title )
   echo $before_title . $title . $after_title;
  global $post;
  if ( isset( $category ) && $category != '' ) {
   $args = array(
    'category_name'  => $category,
    'posts_per_page' => $count,
   );
  } else {
   $args = array(
    'posts_per_page' => $count,
   );
  }
  $posts = get_posts( $args );
  if(count($posts)>0){
   $output .='
';
   foreach ($posts as $post): setup_postdata($post);
    $output .='
';

     if(has_post_thumbnail()):
      $output .='
';
      $output .=''.get_the_post_thumbnail($post->ID, 'xs-thumb', array('class' => 'img-responsive')).'';
      $output .='
';
     endif;

     $output .='
';
     $output .= '
'. get_the_title() .'
';
     $output .= '
'. get_the_time() . ' ' . get_the_date('d M Y') . '
';
     $output .='
';
    $output .='
';
   endforeach;
   wp_reset_query();
   $output .='
';
  }
  echo $output;
  echo $after_widget;
 }

I tried with pagination_nav(); after adding code in functions.php and I used WP-PageNavi, but without success.
How to add numbered pagination in this case?
Thanks in advance!

Body:
Use below code for numbered pagination,

<?php the_posts_pagination( array(
      'mid_size'  => 1,
      'prev_text' => __( 'Prev', 'textdomain' ),
      'next_text' => __( 'Next', 'textdomain' ),
      'screen_reader_text' => ' ',
    ) );

     } ?>