问:
Can I bind one element of class to another while initializing in one line?
I have a class (struct) like this:

```<code>type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}
</code>```

And I initialize it like this:

```<code>q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}
</code>```

While initilizing I want one of my values have similar value as another one. Is there any way to do that?

答:
Analog to setting the correctAnswer field after creating the Question value, you can store the correct answer in a variable prior, and use that twice in the composite literal:

```<code>answerA := "A"
q := Question{
    Question:      "What?",
    answerOne:     answerA,
    answerTwo:     "B",
    answerCorrect: answerA,
}
</code>```

Body:
I have a class (struct) like this:

type Question struct{
    Question string
    answerOne string
    answerTwo string
    answerCorrect string
}

And I initialize it like this:

q1:=Question{
    Question:"What?",
    answerOne:"A",
    answerTwo:"B",
    answerCorrect: ? //I want this have similar value as `answerOne`
}

While initilizing I want one of my values have similar value as another one. Is there any way to do that?

Body:
Analog to setting the correctAnswer field after creating the Question value, you can store the correct answer in a variable prior, and use that twice in the composite literal:

answerA := "A"
q := Question{
    Question:      "What?",
    answerOne:     answerA,
    answerTwo:     "B",
    answerCorrect: answerA,
}


来源: stackexchange

问:
.htaccess block all php files with the exepction of some files
Im trying to make a .htaccess file that blocks every folders and file with the exepction of the folder public, the file index.php, the file ajax.php, img, css and js. It should also redirect you to www.domain.com/index.php no matter what you type in the url. Almost everything is working but the ajax.php file is still blocked so my javascript files cant access it. Any suggestions?

My index.php is placed in the folder public, all other php files is placed in a folder named php, js, css and so on but they are not inside public. its like this /root/public and /root/php and so on. The .htaccess file is placed in /root/

```<code>RewriteEngine On

RewriteBase       /
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteRule       ^(.*)$    public/index.php?_url=$1    [QSA,L]

RewriteCond %{REQUEST_URI} !^/(?:public/|index\.php$|ajax\.php$|.+\.(?:jpe?g|gif|png|ico|tiff|css|js)$) [NC]
RewriteRule . - [F]
</code>```

答:
Have it this way:</p>

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^/(?:public/|(?:index|ajax)\.php$|.+\.(?:jpe?g|gif|png|ico|tiff|css|js)$) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ public/index.php?_url=$1 [QSA,L]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im trying to make a .htaccess file that blocks every folders and file with the exepction of the folder public, the file index.php, the file ajax.php, img, css and js. It should also redirect you to www.domain.com/index.php no matter what you type in the url. Almost everything is working but the ajax.php file is still blocked so my javascript files cant access it. Any suggestions?

My index.php is placed in the folder public, all other php files is placed in a folder named php, js, css and so on but they are not inside public. its like this /root/public and /root/php and so on. The .htaccess file is placed in /root/

RewriteEngine On

RewriteBase       /
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteRule       ^(.*)$    public/index.php?_url=$1    [QSA,L]

RewriteCond %{REQUEST_URI} !^/(?:public/|index\.php$|ajax\.php$|.+\.(?:jpe?g|gif|png|ico|tiff|css|js)$) [NC]
RewriteRule . - [F]

Body:
Have it this way:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !^/(?:public/|(?:index|ajax)\.php$|.+\.(?:jpe?g|gif|png|ico|tiff|css|js)$) [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ public/index.php?_url=$1 [QSA,L]


问:
how to remove href for "printing" html to PDF?
I build HTML pages and I would like to let the user "print" the HTML to a PDF, without embedding the HREF links (because they link to an internal server, and I do not want the readers of the PDF to see these links).

In Chromium, the resulting PDF file embeds the href links.

Is is possible to remove the hrefs via CSS of Javascript?

I tried this:

```<code><a class="no_print" href="javascript:printPreview()">Print Preview</a>

<script>
function printPreview() {
    var aTags = document.getElementsByTagName('a');
    var atl = aTags.length;
    var i;

    for (i = 0; i < atl; i++) {
        aTags[i].href = '';
    }
}
</script>
</code>```

but is does not work.

-- edit: after the solution was found, here is a complete example --

```<code><!DOCTYPE html>
<html><header>
    <title>x</title>
    <style>
        @media print { .no_print { display: none; }
    </style>
    <script>
function printPreview()
{
    var aTags = document.getElementsByTagName('a');
    var atl = aTags.length;
    var i;

    for (i = 0; i < atl; i++) {
        aTags[i].removeAttribute("href");
    }
}
    </script>

</head>
<body>
    <a class="no_print" href="javascript:printPreview()">Print Preview</a>
    <br>
    <a href="http://example.com">link to somewhere</a>
    <br>
    <a>anchor but no link</a>
    <br>
    other text...
</body>
</html>
</code>```

答:
Pure css solution:</p>

```<code>@media print {
    a:after {
        display: none !important;
    }
}
</code>```

Body:
I build HTML pages and I would like to let the user "print" the HTML to a PDF, without embedding the HREF links (because they link to an internal server, and I do not want the readers of the PDF to see these links).

In Chromium, the resulting PDF file embeds the href links.

Is is possible to remove the hrefs via CSS of Javascript?

I tried this:

Print Preview

but is does not work.

-- edit: after the solution was found, here is a complete example --

<!DOCTYPE html>

    <title>x</title>

    Print Preview

    link to somewhere

    anchor but no link

    other text...

Body:
Pure css solution:

@media print {
    a:after {
        display: none !important;
    }
}


问:
How to change value of current array/ object only using ngmodel angular2
I have an array and an object. In array I am getting a list from my service and in object I am assigning first element of that array.

```<code>feesEntries: Array<any> = [];
selectedFeesEntry: any;
clientList: Array<any> = [];

getData(data){
   this.feesEntries = JSON.parse(data['_body']);
   this.selectedFeesEntry = this.feesEntries[0];
}
</code>```

On UI A table is displayed from the feesEntries array. I have a dropdown to select clients and for options I have ClientList & ngModel is used to bind select to selectedFeesEntry.

Sample:

```<code><label class="control-label" for="select">Client Name</label>
    <div class="input-group">
        <select class="form-control" id="select" [(ngModel)]="selectedFeesEntry.client.name" name="selectedClientName" (change)="onClientNameChange(selectedFeesEntry.client.name)">
          <option *ngFor="let cl of clientList" [ngValue]="cl.name">{{cl.name}}</option>
        </select>
    </div>
</code>```

Now the issue is when i am selecting a client from the options then using ngmodel only selectedFeesEntry should be updated but in my case feesEntries are also updated. I have no idea why it is happening.

Any help would be appreciated.

Thanks

答:
As far as I understand, When an option is selected from the dropdown, selectedFeesEntry changes and since you have assigned selectedFeesEntry like this,

```<code>this.selectedFeesEntry = this.feesEntries[0];
</code>```

selectedFeesEntry is just a reference to this.feesEntries[0] or in other words, it's a shallow copy

To perform a deep copy,

```<code>this.selectedFeesEntry = JSON.parse(JSON.stringify(this.feesEntries[0]));
</code>```

Which will create a new object

Example: Shallow Copy

Example: Deep copy

Hope this helps

Body:
I have an array and an object. In array I am getting a list from my service and in object I am assigning first element of that array.

feesEntries: Array<any> = [];
selectedFeesEntry: any;
clientList: Array<any> = [];

getData(data){
   this.feesEntries = JSON.parse(data['_body']);
   this.selectedFeesEntry = this.feesEntries[0];
}

On UI A table is displayed from the feesEntries array. I have a dropdown to select clients and for options I have ClientList & ngModel is used to bind select to selectedFeesEntry.

Sample:

Client Name

        <select class="form-control" id="select" [(ngModel)]="selectedFeesEntry.client.name" name="selectedClientName" (change)="onClientNameChange(selectedFeesEntry.client.name)">
          <option *ngFor="let cl of clientList" [ngValue]="cl.name">{{cl.name}}</option>
        </select>

Now the issue is when i am selecting a client from the options then using ngmodel only selectedFeesEntry should be updated but in my case feesEntries are also updated. I have no idea why it is happening.

Any help would be appreciated.

Thanks

Body:
As far as I understand, When an option is selected from the dropdown, selectedFeesEntry changes and since you have assigned selectedFeesEntry like this,

this.selectedFeesEntry = this.feesEntries[0];

selectedFeesEntry is just a reference to this.feesEntries[0] or in other words, it's a shallow copy

To perform a deep copy,

this.selectedFeesEntry = JSON.parse(JSON.stringify(this.feesEntries[0]));

Which will create a new object

Example: Shallow Copy

Example: Deep copy

Hope this helps


问:
How can I communicate between related react components?
I just got started with ReactJS and am a little stuck on a problem that I have.

My application is essentially a list with filters and a button to change the layout.
At the moment I'm using three components: <list />, < Filters /> and <TopBar />, now obviously when I change settings in < Filters /> I want to trigger some method in <list /> to update my view.

How can I make those 3 components interact with each other, or do I need some sort of global data model where I can just make changes to?

答:
OK, there are few ways to do it, but I exclusively want focus on using store using Redux which makes your life much easier for these situations rather than give you a quick solution only for this case, using pure React will end up mess up in real big application and communicating between Components becomes harder and harder as the application grows...

So what Redux does for you?

Redux is like local storage in your application which can be used whenever you need data to be used in different places in your application...

Basically, Redux idea comes from flux originally, but with some fundamental changes including the concept of having one source of truth by creating only one store...

Look at the graph below to see some differences between Flux and Redux...

Consider applying Redux in your application from the start if your application needs communication between Components...

Also reading these words from Redux Documentation could be helpful to start with:

As the requirements for JavaScript single-page applications have
  become increasingly complicated, our code must manage more state than
  ever before. This state can include server responses and cached data,
  as well as locally created data that has not yet been persisted to the
  server. UI state is also increasing in complexity, as we need to
  manage active routes, selected tabs, spinners, pagination controls,
  and so on.

Managing this ever-changing state is hard. If a model can update
  another model, then a view can update a model, which updates another
  model, and this, in turn, might cause another view to update. At some
  point, you no longer understand what happens in your app as you have
  lost control over the when, why, and how of its state. When a system
  is opaque and non-deterministic, it's hard to reproduce bugs or add
  new features.

As if this wasn't bad enough, consider the new requirements becoming
  common in front-end product development. As developers, we are
  expected to handle optimistic updates, server-side rendering, fetching
  data before performing route transitions, and so on. We find ourselves
  trying to manage a complexity that we have never had to deal with
  before, and we inevitably ask the question: is it time to give up? The
  answer is no.

This complexity is difficult to handle as we're mixing two concepts
  that are very hard for the human mind to reason about: mutation and
  asynchronicity. I call them Mentos and Coke. Both can be great in
  separation, but together they create a mess. Libraries like React
  attempt to solve this problem in the view layer by removing both
  asynchrony and direct DOM manipulation. However, managing the state of
  your data is left up to you. This is where Redux enters.

Following in the steps of Flux, CQRS, and Event Sourcing, Redux
  attempts to make state mutations predictable by imposing certain
  restrictions on how and when updates can happen. These restrictions
  are reflected in the three principles of Redux.

ContentLicense: CC BY-SA 4.0


答:
you could proceed for example as:

```<code>print('*'*80)
print('{msg:^80s}'.format(msg = 'HELLO')) #^ centers the message
print('*'*80)
</code>```

or if you want to have the text-width dynamic:

```<code>def fn(msg, w = 80):
    delim = '*'*w
    fmt = '{msg:^%ds}'%w

    print(delim)
    print(fmt.format(msg=msg))
    print(delim)

fn('hello')
</code>```

or slightly generalized version should you need to write to a file:

```<code>import sys

def fn(msg, w = 80, F = sys.stdout):
    delim = '*'*w
    fmt = '{delim:s}\n{msg:^%ds}\n{delim:s}\n'%w
    F.write(fmt.format(delim = delim, msg = msg))

fn('hello')
</code>```

Title: multi line string formatting in python

Body:
To begin with, I am working to a get a desired output like this:

*********************************************************************
                                 hello
*********************************************************************

To achieve this I have assigned the desired output to a variable with multiline string and printing the same with format.

$ cat varibale.py
decorator = """ **********************************************************************
                               {}
            ********************************************************************** """
print(decorator.format("hello"))

Output:

**********************************************************************
                               hello
            **********************************************************************

The issue with above approach is the extra spaces in the third line of output which is looking odd.

I am able to achieve this in the following way:

$ cat varibale.py
decorator = """ **********************************************************************
                             {}
*********************************************************************
"""
print(decorator.format("hello"))

Output:

 **********************************************************************
                             hello
*********************************************************************

But this way my code doesn't look good, as it is not following the indentation.

Please suggest the right way to achieve the desired output.

Body:
you could proceed for example as:

print('*'*80)
print('{msg:^80s}'.format(msg = 'HELLO')) #^ centers the message
print('*'*80)

or if you want to have the text-width dynamic:

def fn(msg, w = 80):
    delim = '*'*w
    fmt = '{msg:^%ds}'%w

    print(delim)
    print(fmt.format(msg=msg))
    print(delim)

fn('hello')

or slightly generalized version should you need to write to a file:

import sys

def fn(msg, w = 80, F = sys.stdout):
    delim = '*'*w
    fmt = '{delim:s}\n{msg:^%ds}\n{delim:s}\n'%w
    F.write(fmt.format(delim = delim, msg = msg))

fn('hello')


问:
facets in elastic 5.5
I'm trying to build a feceted search with elastic 5.5 (With elastic 2.* I found information on how to do this but in 5.5 I can't)

Not something unusual, store-like items that i want to show hint of the amount if the user will choose to filter using some property. Image for visualisation

Data set example:

```<code>[
  {
    "id" : "978-0641723445",
    "cat" : ["book","hardcover"],
    "name" : "The Lightning Thief",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 12.50,
    "pages_i" : 384
  }
,
  {
    "id" : "978-1423103349",
    "cat" : ["book","paperback"],
    "name" : "The Sea of Monsters",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 2,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 6.49,
    "pages_i" : 304
  }
,
  {
    "id" : "978-1857995879",
    "cat" : ["book","paperback"],
    "name" : "Sophie's World : The Greek Philosophers",
    "author" : "Jostein Gaarder",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 3.07,
    "pages_i" : 64
  }
,
  {
    "id" : "978-1933988177",
    "cat" : ["book","paperback"],
    "name" : "Lucene in Action, Second Edition",
    "author" : "Michael McCandless",
    "sequence_i" : 1,
    "genre_s" : "IT",
    "inStock" : true,
    "price" : 30.50,
    "pages_i" : 475
  }
]
</code>```

Thanks!

答:
if the column is text, you will need to use ".keyword" too to handle cases of country names where there are many words ("El Salvador", "United States of America", etc)</p>

```<code>GET index/_search
{
    "aggs" : {
        "countries" : {
            "terms" : { "field" : "country.keyword" }
        }
    }
}
</code>```

Title: facets in elastic 5.5

Body:
I'm trying to build a feceted search with elastic 5.5 (With elastic 2.* I found information on how to do this but in 5.5 I can't)

Not something unusual, store-like items that i want to show hint of the amount if the user will choose to filter using some property. Image for visualisation

Data set example:

[
  {
    "id" : "978-0641723445",
    "cat" : ["book","hardcover"],
    "name" : "The Lightning Thief",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 12.50,
    "pages_i" : 384
  }
,
  {
    "id" : "978-1423103349",
    "cat" : ["book","paperback"],
    "name" : "The Sea of Monsters",
    "author" : "Rick Riordan",
    "series_t" : "Percy Jackson and the Olympians",
    "sequence_i" : 2,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 6.49,
    "pages_i" : 304
  }
,
  {
    "id" : "978-1857995879",
    "cat" : ["book","paperback"],
    "name" : "Sophie's World : The Greek Philosophers",
    "author" : "Jostein Gaarder",
    "sequence_i" : 1,
    "genre_s" : "fantasy",
    "inStock" : true,
    "price" : 3.07,
    "pages_i" : 64
  }
,
  {
    "id" : "978-1933988177",
    "cat" : ["book","paperback"],
    "name" : "Lucene in Action, Second Edition",
    "author" : "Michael McCandless",
    "sequence_i" : 1,
    "genre_s" : "IT",
    "inStock" : true,
    "price" : 30.50,
    "pages_i" : 475
  }
]

Thanks!

Body:
if the column is text, you will need to use ".keyword" too to handle cases of country names where there are many words ("El Salvador", "United States of America", etc)

GET index/_search
{
    "aggs" : {
        "countries" : {
            "terms" : { "field" : "country.keyword" }
        }
    }
}


问:
SQL - Count records & update multiple columns depending on value
I have two tables ... accounts & tax. In table tax I would like to updated records (?) depending on column category available in table accounts like this:

table 'accounts'

```<code>id|cat2|cat3
1|A|Active
2|A|Active
3|A|Inactive
4|A|Active
5|B|Inactive
6|B|Active
</code>```

table 'tax'

```<code>id|category|count_total|count_active|count_inactive
1|A|?|?|?
2|B|?|?|?
</code>```

Desired result:

```<code>id|category|count_total|count_active|count_inactive
1|A|4|3|1
2|B|2|1|1
</code>```

For count_total I tried this:

```<code>UPDATE tax t2,
(   SELECT count(*)
    FROM accounts
) t1
SET t2.count_total = t1.count(*)
WHERE t1.cat2 = t2.category;
</code>```

答:
Another version without JOIN:

```<code>UPDATE tax
    SET
    count_total = (
        SELECT COUNT(*)
        FROM accounts
        WHERE accounts.cat2 = tax.category
    ),
    count_active = (
        SELECT COUNT(*)
        FROM accounts
        WHERE accounts.cat2 = tax.category AND accounts.cat3 = 'Active'
    ),
    count_inactive = (
        SELECT COUNT(*)
        FROM accounts
        WHERE accounts.cat2 = tax.category AND accounts.cat3 = 'Inactive'
    );
</code>```

Demo

Body:
I have two tables ... accounts & tax. In table tax I would like to updated records (?) depending on column category available in table accounts like this:

table 'accounts'

id|cat2|cat3
1|A|Active
2|A|Active
3|A|Inactive
4|A|Active
5|B|Inactive
6|B|Active

table 'tax'

id|category|count_total|count_active|count_inactive
1|A|?|?|?
2|B|?|?|?

Desired result:

id|category|count_total|count_active|count_inactive
1|A|4|3|1
2|B|2|1|1

For count_total I tried this:

UPDATE tax t2,
(   SELECT count(*)
    FROM accounts
) t1
SET t2.count_total = t1.count(*)
WHERE t1.cat2 = t2.category;

Body:
Another version without JOIN:

UPDATE tax
    SET
    count_total = (
        SELECT COUNT(*)
        FROM accounts
        WHERE accounts.cat2 = tax.category
    ),
    count_active = (
        SELECT COUNT(*)
        FROM accounts
        WHERE accounts.cat2 = tax.category AND accounts.cat3 = 'Active'
    ),
    count_inactive = (
        SELECT COUNT(*)
        FROM accounts
        WHERE accounts.cat2 = tax.category AND accounts.cat3 = 'Inactive'
    );

Demo


问:
Should I use a set to prevent items being added more than once to the collection by mistake?
Please see the code below:

```<code>public class Customer
{
    private readonly IHashSet<Order> _orders = new Set<Order>();

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public IEnumerable<Order> Orders
    {
        get { foreach (var order in _orders) yield return order; }
    }

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}
</code>```

I am trying to decide whether the _orders property should be a List (which I would normally use) or a Set.  The only reason a duplicate order would be added is if the client code added a duplicate by mistake.  Does that warrant the use of a Set? Is that a valid use case for a Set?

答:
Sure, this is a valid use case, if duplicate orders are not allowed.

Since you expose IEnumerable<Order> instead of IList<Order> you don't seem to be interested in keeping the insertion order, or let the caller use it like a list or array. So a HashSet<T> is perfect here. The database is the best place to ensure that no duplicates are added, but it's not wrong to check that also at client-side. On this way you can handle bugs early and report them in your logs.

```<code>public class Customer
{
    private readonly HashSet<Order> _orders = new HashSet<Order>();

    public IEnumerable<Order> Orders => _orders;

    // ...

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}
</code>```

Note that you should override Equals+GetHasCode in Order, implement IEquatable<Order> or pass a custom IEquatable<Comparer> to the HashSet constructor.

Body:
Please see the code below:

public class Customer
{
    private readonly IHashSet<Order> _orders = new Set<Order>();

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Province { get; set; }
    public IEnumerable<Order> Orders
    {
        get { foreach (var order in _orders) yield return order; }
    }

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}

I am trying to decide whether the _orders property should be a List (which I would normally use) or a Set.  The only reason a duplicate order would be added is if the client code added a duplicate by mistake.  Does that warrant the use of a Set? Is that a valid use case for a Set?

Body:
Sure, this is a valid use case, if duplicate orders are not allowed.

Since you expose IEnumerable<Order> instead of IList<Order> you don't seem to be interested in keeping the insertion order, or let the caller use it like a list or array. So a HashSet<T> is perfect here. The database is the best place to ensure that no duplicates are added, but it's not wrong to check that also at client-side. On this way you can handle bugs early and report them in your logs.

public class Customer
{
    private readonly HashSet<Order> _orders = new HashSet<Order>();

    public IEnumerable<Order> Orders => _orders;

    // ...

    internal void AddOrder(Order order)
    {
        _orders.Add(order);
    }
}

Note that you should override Equals+GetHasCode in Order, implement IEquatable<Order> or pass a custom IEquatable<Comparer> to the HashSet constructor.


问:
Custom code for wp product page
I'm trying to make a text field option on product page of wp website. The scenario is when the customer clicks on how quantity he requires, what I need is to show the corresponding text fields for it. Like 2 text fields for 2 quantity. How can I do that?   </p>

答:
You may try the following -

Have a text field that takes that number as input.

Have a button which when clicked triggers a javascript function create_fields

Insert logic for creating text fields according to the number input.

Use the docs - https://api.jquery.com/ to learn how you would accomplish the above in code.

Title: Custom code for wp product page


问:
Align SVG element in Bootstrap 4 row
I want to align both icon (<svg>) and text to the center of a container. I want a small spacing between icon and text:

```<code>|      ICON TEXT      |
</code>```

https://jsbin.com/tatomas/edit?html,css,output

I have Bootstrap 4 (Flexbox) available. But I can not find out how to do it. Especially the <svg> is hard to align - I can't move it anywhere. I tried putting them in a .row with a .col each, but the SVG stays in center of the col...

How can I achieve this (with or without BS grid) ??

答:
With the existing markup, two main things need to be done:

col has predefined paddings, which needs to be reset

e.g. use text-align: right to align the SVG to the right

Additionally, SVG elements w/o a width set can cause trouble on some browsers, so I gave it one here (added width="80" to its markup)

With this you can now either add a margin or a padding of your choice to the col elements (in the alternative below, to the section-* elements), and in these samples I used margin.

Stack snippet

.container {
  max-width: 300px;
}
.row .col {
  padding: 0;                   /*  added  */
}

.section-icon {
  max-height: 30px;
  text-align: right;            /*  added  */
  margin-right: 5px;
}

.section-title {
  text-align: left;
  margin-left: 5px;
}

/*  for styling of this demo  */
div.section-icon, .section-title {
  border: 1px dotted;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  <div class="container p-4 border">
    <div class="row">
      <div class="col">
        <div class="section-icon">
          <svg width="80" class="section-icon active" viewBox="0 0 512 234.34"><path d="M110.93,287.83A42.67,42.67,0,1,0,153.6,330.5,42.71,42.71,0,0,0,110.93,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.63,25.63,0,0,1,110.93,356.1Z" transform="translate(0 -138.83)"></path><path d="M503.47,287.83v-51.2a8.53,8.53,0,0,0-5.84-8.09l-48.14-16c-18.14-30.72-43.06-59.94-98.15-69.59l-.3-.05c-101.73-14.07-178.1,8.88-227.14,68.22-36.49.53-73.75,8.16-95.66,22.19-11.35,7.27-18.08,19.92-18.72,33.39l-1,21.19A8.53,8.53,0,0,0,0,296.37V330.5A8.53,8.53,0,0,0,8.53,339H42.67a8.59,8.59,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53H332.8a8.58,8.58,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53h34.13A8.54,8.54,0,0,0,512,330.5V296.37A8.54,8.54,0,0,0,503.47,287.83Zm-230.4-81.06A4.27,4.27,0,0,1,268.8,211H157.52a4.3,4.3,0,0,1-2.83-7.51c29.61-27,67.27-42.42,113.67-46.53a4.36,4.36,0,0,1,4.71,4.3Zm102.52,0a4.27,4.27,0,0,1-4.27,4.22H294.4a4.27,4.27,0,0,1-4.27-4.26V160.18a4.28,4.28,0,0,1,4.24-4.31,393,393,0,0,1,54.17,3.86,144.79,144.79,0,0,1,24.62,6.51,4.29,4.29,0,0,1,2.77,4.08ZM420.12,211h-23.2a4.27,4.27,0,0,1-4.27-4.31l.23-23.12a4.29,4.29,0,0,1,6.89-3.35,112.87,112.87,0,0,1,23.73,23.88A4.29,4.29,0,0,1,420.12,211Z" transform="translate(0 -138.83)"></path><path d="M401.07,287.83a42.67,42.67,0,1,0,42.66,42.67A42.72,42.72,0,0,0,401.07,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.62,25.62,0,0,1,401.07,356.1Z" transform="translate(0 -138.83)"></path></svg>
        </div>
      </div>
      <div class="col">
        <div class="section-title">
          Car
        </div>
      </div>
    </div>
  </div></code>```

As an alternative you could drop the col elements and add the built-in class justify-content-center to the row element (
)

Stack snippet

.container {
  max-width: 300px;
}

.section-icon {
  max-height: 30px;
  margin-right: 5px;
}

.section-title {
  margin-left: 5px;
}

/*  for styling of this demo  */
div.section-icon, .section-title {
  border: 1px dotted;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  <div class="container p-4 border">
    <div class="row justify-content-center">
        <div class="section-icon">
          <svg width="80" class="section-icon active" viewBox="0 0 512 234.34"><path d="M110.93,287.83A42.67,42.67,0,1,0,153.6,330.5,42.71,42.71,0,0,0,110.93,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.63,25.63,0,0,1,110.93,356.1Z" transform="translate(0 -138.83)"></path><path d="M503.47,287.83v-51.2a8.53,8.53,0,0,0-5.84-8.09l-48.14-16c-18.14-30.72-43.06-59.94-98.15-69.59l-.3-.05c-101.73-14.07-178.1,8.88-227.14,68.22-36.49.53-73.75,8.16-95.66,22.19-11.35,7.27-18.08,19.92-18.72,33.39l-1,21.19A8.53,8.53,0,0,0,0,296.37V330.5A8.53,8.53,0,0,0,8.53,339H42.67a8.59,8.59,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53H332.8a8.58,8.58,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53h34.13A8.54,8.54,0,0,0,512,330.5V296.37A8.54,8.54,0,0,0,503.47,287.83Zm-230.4-81.06A4.27,4.27,0,0,1,268.8,211H157.52a4.3,4.3,0,0,1-2.83-7.51c29.61-27,67.27-42.42,113.67-46.53a4.36,4.36,0,0,1,4.71,4.3Zm102.52,0a4.27,4.27,0,0,1-4.27,4.22H294.4a4.27,4.27,0,0,1-4.27-4.26V160.18a4.28,4.28,0,0,1,4.24-4.31,393,393,0,0,1,54.17,3.86,144.79,144.79,0,0,1,24.62,6.51,4.29,4.29,0,0,1,2.77,4.08ZM420.12,211h-23.2a4.27,4.27,0,0,1-4.27-4.31l.23-23.12a4.29,4.29,0,0,1,6.89-3.35,112.87,112.87,0,0,1,23.73,23.88A4.29,4.29,0,0,1,420.12,211Z" transform="translate(0 -138.83)"></path><path d="M401.07,287.83a42.67,42.67,0,1,0,42.66,42.67A42.72,42.72,0,0,0,401.07,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.62,25.62,0,0,1,401.07,356.1Z" transform="translate(0 -138.83)"></path></svg>
        </div>

        <div class="section-title">
          Car
        </div>
      </div>
  </div></code>```

The main difference between the two, besides their markup, is that the small gap/margin between the icon/title are in the first sample in their parents center, and in the alternative it is not, there the icon/title center as a group.

Title: Align SVG element in Bootstrap 4 row

Body:
I want to align both icon (<svg>) and text to the center of a container. I want a small spacing between icon and text:

|      ICON TEXT      |

https://jsbin.com/tatomas/edit?html,css,output

I have Bootstrap 4 (Flexbox) available. But I can not find out how to do it. Especially the <svg> is hard to align - I can't move it anywhere. I tried putting them in a .row with a .col each, but the SVG stays in center of the col...

How can I achieve this (with or without BS grid) ??

Body:
With the existing markup, two main things need to be done:

col has predefined paddings, which needs to be reset

e.g. use text-align: right to align the SVG to the right

Additionally, SVG elements w/o a width set can cause trouble on some browsers, so I gave it one here (added width="80" to its markup)

With this you can now either add a margin or a padding of your choice to the col elements (in the alternative below, to the section-* elements), and in these samples I used margin.

Stack snippet

.container {
  max-width: 300px;
}
.row .col {
  padding: 0;                   /*  added  */
}

.section-icon {
  max-height: 30px;
  text-align: right;            /*  added  */
  margin-right: 5px;
}

.section-title {
  text-align: left;
  margin-left: 5px;
}

/*  for styling of this demo  */
div.section-icon, .section-title {
  border: 1px dotted;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  <div class="container p-4 border">
    <div class="row">
      <div class="col">
        <div class="section-icon">
          <svg width="80" class="section-icon active" viewBox="0 0 512 234.34"><path d="M110.93,287.83A42.67,42.67,0,1,0,153.6,330.5,42.71,42.71,0,0,0,110.93,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.63,25.63,0,0,1,110.93,356.1Z" transform="translate(0 -138.83)"></path><path d="M503.47,287.83v-51.2a8.53,8.53,0,0,0-5.84-8.09l-48.14-16c-18.14-30.72-43.06-59.94-98.15-69.59l-.3-.05c-101.73-14.07-178.1,8.88-227.14,68.22-36.49.53-73.75,8.16-95.66,22.19-11.35,7.27-18.08,19.92-18.72,33.39l-1,21.19A8.53,8.53,0,0,0,0,296.37V330.5A8.53,8.53,0,0,0,8.53,339H42.67a8.59,8.59,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53H332.8a8.58,8.58,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53h34.13A8.54,8.54,0,0,0,512,330.5V296.37A8.54,8.54,0,0,0,503.47,287.83Zm-230.4-81.06A4.27,4.27,0,0,1,268.8,211H157.52a4.3,4.3,0,0,1-2.83-7.51c29.61-27,67.27-42.42,113.67-46.53a4.36,4.36,0,0,1,4.71,4.3Zm102.52,0a4.27,4.27,0,0,1-4.27,4.22H294.4a4.27,4.27,0,0,1-4.27-4.26V160.18a4.28,4.28,0,0,1,4.24-4.31,393,393,0,0,1,54.17,3.86,144.79,144.79,0,0,1,24.62,6.51,4.29,4.29,0,0,1,2.77,4.08ZM420.12,211h-23.2a4.27,4.27,0,0,1-4.27-4.31l.23-23.12a4.29,4.29,0,0,1,6.89-3.35,112.87,112.87,0,0,1,23.73,23.88A4.29,4.29,0,0,1,420.12,211Z" transform="translate(0 -138.83)"></path><path d="M401.07,287.83a42.67,42.67,0,1,0,42.66,42.67A42.72,42.72,0,0,0,401.07,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.62,25.62,0,0,1,401.07,356.1Z" transform="translate(0 -138.83)"></path></svg>
        </div>
      </div>
      <div class="col">
        <div class="section-title">
          Car
        </div>
      </div>
    </div>
  </div>

As an alternative you could drop the col elements and add the built-in class justify-content-center to the row element (<div class="row justify-content-center">)

Stack snippet

.container {
  max-width: 300px;
}

.section-icon {
  max-height: 30px;
  margin-right: 5px;
}

.section-title {
  margin-left: 5px;
}

/*  for styling of this demo  */
div.section-icon, .section-title {
  border: 1px dotted;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

  <div class="container p-4 border">
    <div class="row justify-content-center">
        <div class="section-icon">
          <svg width="80" class="section-icon active" viewBox="0 0 512 234.34"><path d="M110.93,287.83A42.67,42.67,0,1,0,153.6,330.5,42.71,42.71,0,0,0,110.93,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.63,25.63,0,0,1,110.93,356.1Z" transform="translate(0 -138.83)"></path><path d="M503.47,287.83v-51.2a8.53,8.53,0,0,0-5.84-8.09l-48.14-16c-18.14-30.72-43.06-59.94-98.15-69.59l-.3-.05c-101.73-14.07-178.1,8.88-227.14,68.22-36.49.53-73.75,8.16-95.66,22.19-11.35,7.27-18.08,19.92-18.72,33.39l-1,21.19A8.53,8.53,0,0,0,0,296.37V330.5A8.53,8.53,0,0,0,8.53,339H42.67a8.59,8.59,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53H332.8a8.58,8.58,0,0,0,8.53-8.62c0-.05,0-.09,0-.14a59.73,59.73,0,0,1,119.46.23c-.62,5.18,3.47,8.53,8.53,8.53h34.13A8.54,8.54,0,0,0,512,330.5V296.37A8.54,8.54,0,0,0,503.47,287.83Zm-230.4-81.06A4.27,4.27,0,0,1,268.8,211H157.52a4.3,4.3,0,0,1-2.83-7.51c29.61-27,67.27-42.42,113.67-46.53a4.36,4.36,0,0,1,4.71,4.3Zm102.52,0a4.27,4.27,0,0,1-4.27,4.22H294.4a4.27,4.27,0,0,1-4.27-4.26V160.18a4.28,4.28,0,0,1,4.24-4.31,393,393,0,0,1,54.17,3.86,144.79,144.79,0,0,1,24.62,6.51,4.29,4.29,0,0,1,2.77,4.08ZM420.12,211h-23.2a4.27,4.27,0,0,1-4.27-4.31l.23-23.12a4.29,4.29,0,0,1,6.89-3.35,112.87,112.87,0,0,1,23.73,23.88A4.29,4.29,0,0,1,420.12,211Z" transform="translate(0 -138.83)"></path><path d="M401.07,287.83a42.67,42.67,0,1,0,42.66,42.67A42.72,42.72,0,0,0,401.07,287.83Zm0,68.27a25.6,25.6,0,1,1,25.6-25.6A25.62,25.62,0,0,1,401.07,356.1Z" transform="translate(0 -138.83)"></path></svg>
        </div>

        <div class="section-title">
          Car
        </div>
      </div>
  </div>

The main difference between the two, besides their markup, is that the small gap/margin between the icon/title are in the first sample in their parents center, and in the alternative it is not, there the icon/title center as a group.


问:
How to access the methods and html zones of one component from another in Angular 4+?
Here is the scenario:

app.component.html got the main layout;
say you got a RED-STICKY-HEADER at the top,
and then you got a TOGGLING-ORANGE-SIDENAV on the left, and a STEADY- GREEN-SIDENAV on the right. ( the colors are only for reference purposes and make my question easier to follow. )

And to conclude, the app.component.html also has the <router-outlet></router-outlet> and that is to house the other components' html. Duh!

OK... I'm done with the scenario. So far, it's just an ordinary set up.

Here comes the complication in my mind and my question:

Say, you click on a link at the RED-STICKY-HEADER and this brings the component X's HTML in the middle.

Is it possible that you click on something on the component X's html, and this does an update on the GREEN SIDENAV contents? Please note that here, the URL does not change, no reloads takes place, and the only thing that happens is the fact that green sidenav content changes to something else. ( which could be an HTTP get request results being dumped in there, but this does not matter. )The jest of the question is is it possible to make a change in the areas that belong to app.component.html from another component?

If this is possible, then I will also ask whether it is also possible that I can trigger a component X method by clicking on a link at the RED STICKY HEADER.

In other words, is it possible to access and trigger the method of component X while you are on the app.component.html URL?

答:
Yes it is possible.
You can write a common service for RED-STICKY-HEADER 's component and middle component then make the updating variable as observable one in your common service.
please refer the code to create a object / list as observable in service.

```<code> @Injectable()
 export class CommonService {
     aListWhichIsSubscribedByRedStickyHeader: Array<YourObject>;
     private subject = new Subject<Array<YourObject>>();

     // this is the method used to get the observable property
     getSubscribedVariables() {
         return this.subject.asObservable();
     }

     aMethodCalledByAnotherComponent(){
       /*modyfying the aListWhichIsSubscribedByRedStickyHeader
       property . Just assume that your middle component is calling this
       method to save the object received from hhtp get request*/
     }

   this.subject.next(this.aListWhichIsSubscribedByRedStickyHeader); // so it will reflect in RedStickyHeader component's constructor.
 }
</code>```

How you are going to subscribe it ? refer below code

```<code>  export class RedStickyComponent implements OnInit{

     aObjectList : Array<YourObject>;
     constructor(serviceCommon : CommonService){
        this.serviceCommon.getSubscribedVariables().subscribe(e => {
        let list = e;
        this.aObjectList = JSON.parse(JSON.stringify(list));
        })
     }

  }
</code>```

so in this RedStickyHeader component wherever you are using the aObjectList there you will get changes. or by analyzing the object you can change anything inside this component or you can call another service from it.

Body:
Yes it is possible.
You can write a common service for RED-STICKY-HEADER 's component and middle component then make the updating variable as observable one in your common service.
please refer the code to create a object / list as observable in service.

 @Injectable()
 export class CommonService {
     aListWhichIsSubscribedByRedStickyHeader: Array<YourObject>;
     private subject = new Subject<Array<YourObject>>();

     // this is the method used to get the observable property
     getSubscribedVariables() {
         return this.subject.asObservable();
     }

     aMethodCalledByAnotherComponent(){
       /*modyfying the aListWhichIsSubscribedByRedStickyHeader
       property . Just assume that your middle component is calling this
       method to save the object received from hhtp get request*/
     }

   this.subject.next(this.aListWhichIsSubscribedByRedStickyHeader); // so it will reflect in RedStickyHeader component's constructor.
 }

How you are going to subscribe it ? refer below code

  export class RedStickyComponent implements OnInit{

     aObjectList : Array<YourObject>;
     constructor(serviceCommon : CommonService){
        this.serviceCommon.getSubscribedVariables().subscribe(e => {
        let list = e;
        this.aObjectList = JSON.parse(JSON.stringify(list));
        })
     }

  }

so in this RedStickyHeader component wherever you are using the aObjectList there you will get changes. or by analyzing the object you can change anything inside this component or you can call another service from it.


问:
HttpClient is sending NULL in web Api in mvc5
HttpClient is sending null values to controller while post and my code is here please help me
....................

```<code>using (HttpClient client=new HttpClient())
                    {

                            var parameters = ConvertToDictionary(tc);

                        client.BaseAddress = new Uri($"http://localhost:9797/");

                        var json = JsonConvert.SerializeObject(tc);
                        var data = new StringContent(content: json,encoding: Encoding.UTF8,mediaType: "application/json");
                        var response = client.PostAsync(api_url, data).GetAwaiter().GetResult();
                        var k = JsonConvert.DeserializeObject<Api>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
</code>```

Thanks in advance

答:
Try to use @ insted of $ in client.BaseAddress. And check if tc object is not null.
I used Your code like this:

```<code>class Program
{
    static void Main(string[] args)
    {
        using (HttpClient client=new HttpClient())
        {
            client.BaseAddress = new Uri(@"http://localhost:61737/api/presidents");

            var json = JsonConvert.SerializeObject(new { name = "name", value = "value" });
            var data = new StringContent(content: json,encoding: Encoding.UTF8,mediaType: "application/json");
            var response = client.PostAsync(@"http://localhost:61737/api/presidents/post", data).GetAwaiter().GetResult();
            var k = (response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
        }
    }
}
</code>```

And controller looks like this:

```<code>[RoutePrefix("api/presidents")]
public class PresidentsController : ApiController
{
    public class oooo
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
    [Route("post")]
    public IHttpActionResult Post(oooo o)
    {
        return Ok(o);
    }
}
</code>```

and everything is working.

Body:
HttpClient is sending null values to controller while post and my code is here please help me
....................

using (HttpClient client=new HttpClient())
                    {

                            var parameters = ConvertToDictionary(tc);

                        client.BaseAddress = new Uri($"http://localhost:9797/");

                        var json = JsonConvert.SerializeObject(tc);
                        var data = new StringContent(content: json,encoding: Encoding.UTF8,mediaType: "application/json");
                        var response = client.PostAsync(api_url, data).GetAwaiter().GetResult();
                        var k = JsonConvert.DeserializeObject<Api>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}

Thanks in advance

Body:
Try to use @ insted of $ in client.BaseAddress. And check if tc object is not null.
I used Your code like this:

class Program
{
    static void Main(string[] args)
    {
        using (HttpClient client=new HttpClient())
        {
            client.BaseAddress = new Uri(@"http://localhost:61737/api/presidents");

            var json = JsonConvert.SerializeObject(new { name = "name", value = "value" });
            var data = new StringContent(content: json,encoding: Encoding.UTF8,mediaType: "application/json");
            var response = client.PostAsync(@"http://localhost:61737/api/presidents/post", data).GetAwaiter().GetResult();
            var k = (response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
        }
    }
}

And controller looks like this:

[RoutePrefix("api/presidents")]
public class PresidentsController : ApiController
{
    public class oooo
    {
        public string Name { get; set; }
        public string Value { get; set; }
    }
    [Route("post")]
    public IHttpActionResult Post(oooo o)
    {
        return Ok(o);
    }
}

and everything is working.


问:
How to synchronize consumers with rabbitmq
I have the following problem:
I have a RabbitMQ cluster, a messages producer and a cluster of consumers (for high availability).
Whenever a consumer is receiving the message it is spawning another process based on the message content and running it. This process is pretty long, takes like 30 min.

I must ensure that messages are processed one at a time. However, there are more consumers then one, so if there are 2 messages in a queue, one consumer gets one message, a second consumer another message, and they are processed in parallel.

For reference: each consumer resides in a different machine.

Is there any mechanism on the level of RabbitMQ that would allow me to wait with consuming next message until the previous one was ACKed? Or do I have to develop some locking mechanism between the servers?

答:
I am just referring a couple of points from rabbitmq docs that I thinks would able be able to satisfy your requirements.

First ref - https://www.rabbitmq.com/consumer-priority.html

Normally, active consumers connected to a queue receive messages from
  it in a round-robin fashion. When consumer priorities are in use,
  messages are delivered round-robin if multiple active consumers exist
  with the same high priority.

I assume all of your consumers have same priority, therefore the messages will be evenly distributed to all active consumers.

Second ref - https://www.rabbitmq.com/consumer-prefetch.html

the basic.qos method to allow you to limit the number of
  unacknowledged messages on a channel (or connection) when consuming

As you have mentioned you will have single consumer on one machine, its even easier.

Just set consumer prefetch limit 1 per consumer. So the server will deliver only one message to consumers before requiring acknowledgements. And send the basic ack once your message is fully processed.

```<code>Channel channel = ...;
Consumer consumer = ...;
channel.basicQos(1); // Per consumer limit

Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                System.out.println("received message");
                // process the message .. time consuming

                // after processing send the basic ack so that next message can be received from queue
                channel.basicAck(envelope.getDeliveryTag(), false);
        };

 channel.basicConsume("my-queue", false, consumer);
</code>```

I hope this helps.

Update -

Just to add a bit more description -
When you use

```<code>channel.basicQos(x);
</code>```

Rabbitmq will push (if available in the queue, of course after complying with priority and round robin etc.) at the max x number of unacked messages to each consumer on the channel. That means each consumer on the channel will not have more than x unacked messages at it, that is consumer can process at the max x messages simultaneously at any given moment. As soon as the consumer sends an ack back, the next message can be pushed to it. A consumer can also send a nack if it feels it is not able to process the message. In such case the message will be re-queued, and the re-queued message may go to any of the consumers on the queue depending on priority, round robin etc.

Each channel can have multiple consumers. So, when you use

```<code>channel.basicQos(x, true);
</code>```

The limit x applies to the whole channel rather than a single/each consumer on the channel.

In your case you have only one consumer on each channel. So channel limit actually does not have any impact on your case.

More Update -

A machine connects to RabbitMQ by a connection. A connection can have multiple channels. And a channel can have multiple Consumers. So logically there can be different machines connected to RabbitMQ and having multiple channels and consumers listening on the same Queue. You can set QOS limit to both channel (using channel.basicQos(x, true)) as well as consumers within the channel (using channel.basicQos(x, false)) simultaneously. Limit 0 means unlimited.  Apparently these limits are applied to channel instance. All the consumers residing on different channel instances (on same machine or different machine) will have their own limit (either default or if set explicitly by QOS method).

Body:
I am just referring a couple of points from rabbitmq docs that I thinks would able be able to satisfy your requirements.

First ref - https://www.rabbitmq.com/consumer-priority.html

Normally, active consumers connected to a queue receive messages from
  it in a round-robin fashion. When consumer priorities are in use,
  messages are delivered round-robin if multiple active consumers exist
  with the same high priority.

I assume all of your consumers have same priority, therefore the messages will be evenly distributed to all active consumers.

Second ref - https://www.rabbitmq.com/consumer-prefetch.html

the basic.qos method to allow you to limit the number of
  unacknowledged messages on a channel (or connection) when consuming

As you have mentioned you will have single consumer on one machine, its even easier.

Just set consumer prefetch limit 1 per consumer. So the server will deliver only one message to consumers before requiring acknowledgements. And send the basic ack once your message is fully processed.

Channel channel = ...;
Consumer consumer = ...;
channel.basicQos(1); // Per consumer limit

Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {

                System.out.println("received message");
                // process the message .. time consuming

                // after processing send the basic ack so that next message can be received from queue
                channel.basicAck(envelope.getDeliveryTag(), false);
        };

 channel.basicConsume("my-queue", false, consumer);

I hope this helps.

Update -

Just to add a bit more description -
When you use

channel.basicQos(x);

Rabbitmq will push (if available in the queue, of course after complying with priority and round robin etc.) at the max x number of unacked messages to each consumer on the channel. That means each consumer on the channel will not have more than x unacked messages at it, that is consumer can process at the max x messages simultaneously at any given moment. As soon as the consumer sends an ack back, the next message can be pushed to it. A consumer can also send a nack if it feels it is not able to process the message. In such case the message will be re-queued, and the re-queued message may go to any of the consumers on the queue depending on priority, round robin etc.

Each channel can have multiple consumers. So, when you use

channel.basicQos(x, true);

The limit x applies to the whole channel rather than a single/each consumer on the channel.

In your case you have only one consumer on each channel. So channel limit actually does not have any impact on your case.

More Update -

A machine connects to RabbitMQ by a connection. A connection can have multiple channels. And a channel can have multiple Consumers. So logically there can be different machines connected to RabbitMQ and having multiple channels and consumers listening on the same Queue. You can set QOS limit to both channel (using channel.basicQos(x, true)) as well as consumers within the channel (using channel.basicQos(x, false)) simultaneously. Limit 0 means unlimited.  Apparently these limits are applied to channel instance. All the consumers residing on different channel instances (on same machine or different machine) will have their own limit (either default or if set explicitly by QOS method).


问:
How can I style an ASP.NET Radio List so that the label appears before the input?
I want to style an ASP.NET RadioList so that the list is horizontally oriented, with two rows, the first of labels, and the second of inputs, for example:

A    B    C    D

o    o    o    o

答:
Use two lists and style them horizontally in your CSS

The CSS:
.answerL
{
    list-style-type: none;

}
.answerL
{
    display: block;
}

ContentLicense: CC BY-SA 2.5


问:
Custom Method Sorting Spring Data JPA
is there possibility to use Java method to sort JPA result?

I have entity:

```<code>+--------+----------+-----------+
| Name   | Latitude | Longitude |
+--------+----------+-----------+
| A      | x1       | y1        |
| B      | x2       | y2        |
| C      | x3       | y3        |
+--------+----------+-----------+
</code>```

I mean instead of writing SQL:

```<code>    "  ORDER BY (acos(sin(latitude * $RADIAN) * sin(:latitude * $RADIAN)" +
    "       + cos(latitude * $RADIAN) * cos(:latitude * $RADIAN)" +
    "         * cos((:longitude * $RADIAN) - (longitude * $RADIAN))" +
    "  ) * $EARTH_RADIUS)")
fun findDoctorDepartmentsInRange(@Param("latitude") latitude: Double,
                                 @Param("longitude") longitude: Double)
</code>```

I've tried with Specification but how to inject custom java method into EXPRESSION used below:

```<code>query.orderBy(cb.asc(EXPRESSION))
</code>```

答:
If you are using Spring JPA, you could use Sort object, and you append it not in your specification but to your query

as far as i remember sntax will be something like that

```<code>repository.findAll(specification,  new Sort(Sort.Direction.ASC, "field"));
</code>```

Edit

I'm not sure is Sort supports expressions, so if you want to do this in java code, you need to create Criteria API query, which will be something like that

```<code>CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SomeClass> query = cb.createQuery(SomeClass.class);
Root<SomeClass> root = query.from(SomeClass.class);
Expression EXPRESSION = <<TypeYourExpression>>;
query.orderBy(cb.asc(EXPRESSION))
query.where(specification.toPredicate(root,query,cb))
List<SomeClass> result = em.createQuery(query).getResultList();
</code>```

Title: Custom Method Sorting Spring Data JPA

Body:
is there possibility to use Java method to sort JPA result?

I have entity:

+--------+----------+-----------+
| Name   | Latitude | Longitude |
+--------+----------+-----------+
| A      | x1       | y1        |
| B      | x2       | y2        |
| C      | x3       | y3        |
+--------+----------+-----------+

I mean instead of writing SQL:

    "  ORDER BY (acos(sin(latitude * $RADIAN) * sin(:latitude * $RADIAN)" +
    "       + cos(latitude * $RADIAN) * cos(:latitude * $RADIAN)" +
    "         * cos((:longitude * $RADIAN) - (longitude * $RADIAN))" +
    "  ) * $EARTH_RADIUS)")
fun findDoctorDepartmentsInRange(@Param("latitude") latitude: Double,
                                 @Param("longitude") longitude: Double)

I've tried with Specification but how to inject custom java method into EXPRESSION used below:

query.orderBy(cb.asc(EXPRESSION))

Body:
If you are using Spring JPA, you could use Sort object, and you append it not in your specification but to your query

as far as i remember sntax will be something like that

repository.findAll(specification,  new Sort(Sort.Direction.ASC, "field"));

Edit

I'm not sure is Sort supports expressions, so if you want to do this in java code, you need to create Criteria API query, which will be something like that

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SomeClass> query = cb.createQuery(SomeClass.class);
Root<SomeClass> root = query.from(SomeClass.class);
Expression EXPRESSION = <<TypeYourExpression>>;
query.orderBy(cb.asc(EXPRESSION))
query.where(specification.toPredicate(root,query,cb))
List<SomeClass> result = em.createQuery(query).getResultList();


问:
Planning Large Projects?
How do you start planning a fairly large project?  Do you immediately start writing up the major classes and break it down further and further? Do you sit down and draw out some UML?

I'm designing my first large project (well, large compared to the other ones) and I'm looking for ideas.

答:
Large Projects would be beneficial when used Agile scrum methodology.

Agile methods divides your projects into smaller sprints giving one the time to prioritize the main features to be concentrated & completed.

Continuous interaction with client means less ambiguity, more real value. The client would see live ideas before final. So more improvising at very early stage with ample of time to make it better.

Bug fixing process gets speedy. Less the bugs, more efficient the Project!

By using time-boxed, fixed schedule Sprints of 1-4 weeks, new features are delivered quickly and frequently, with a high level of predictability. This also provides the opportunity to release or beta test the software earlier than planned if there is sufficient business value.

Improves Quality. By breaking down the project into manageable units, the project team can focus on high-quality development, testing, and collaboration. Also, by producing frequent builds and conducting testing and reviews during each iteration, quality is improved by finding and fixing defects quickly and identifying expectation mismatches early.

Title: Planning Large Projects?


问:
Why does SQLite not realize this is a covering index?
I have a SQLite database that looks something like this:

```<code>CREATE TABLE image
(
    capture_time,
    capture_number,

    part_located,

    other_data,
    some_more_data,

    PRIMARY KEY (capture_time, capture_number)
) WITHOUT ROWID;

CREATE INDEX image_ix_no_part
    ON image (capture_time, capture_number)
    WHERE NOT part_located;
</code>```

The partial index was specifically created for queries like this one:

```<code>SELECT capture_time, capture_number FROM image
    WHERE NOT part_located
    ORDER BY capture_time, capture_number;
</code>```

Unfortunately, EXPLAIN QUERY PLAN doesn't mention anything about a covering index, even though this partial index contains all the necessary information. Shouldn't this work?

答:
Here's a workaround I ended up using:

```<code>CREATE INDEX image_ix_no_part
    ON image (
        capture_time, capture_number,
        part_located -- Needed for a covering index search.
    )
    WHERE NOT part_located;
</code>```

It needlessly adds a zero to the end of every index entry, but it only takes one byte so it's an acceptable loss.

Body:
I have a SQLite database that looks something like this:

CREATE TABLE image
(
    capture_time,
    capture_number,

    part_located,

    other_data,
    some_more_data,

    PRIMARY KEY (capture_time, capture_number)
) WITHOUT ROWID;

CREATE INDEX image_ix_no_part
    ON image (capture_time, capture_number)
    WHERE NOT part_located;

The partial index was specifically created for queries like this one:

SELECT capture_time, capture_number FROM image
    WHERE NOT part_located
    ORDER BY capture_time, capture_number;

Unfortunately, EXPLAIN QUERY PLAN doesn't mention anything about a covering index, even though this partial index contains all the necessary information. Shouldn't this work?

Body:
Here's a workaround I ended up using:

CREATE INDEX image_ix_no_part
    ON image (
        capture_time, capture_number,
        part_located -- Needed for a covering index search.
    )
    WHERE NOT part_located;

It needlessly adds a zero to the end of every index entry, but it only takes one byte so it's an acceptable loss.


问:
Django admin site: how to compute field from multiple fields value?
I am wondering if is there a way to compute a field in the admin site based on a concatenation of multiple fields.

Basically I have a Product model with different fields associated to various attributes
(colour, size, length etc).

I would like to compute the code value to be a concatenation of the values of the various attribute fields like:

```<code>code = colour + "_" + size + "_" + length
</code>```

Body:
I am wondering if is there a way to compute a field in the admin site based on a concatenation of multiple fields.

Basically I have a Product model with different fields associated to various attributes
(colour, size, length etc).

I would like to compute the code value to be a concatenation of the values of the various attribute fields like:

code = colour + "_" + size + "_" + length

Body: look at ModelAdmin.prepopulated_fields


问:
What does "too generic" type system mean?
Referring to the following tutorial https://twitter.github.io/scala_school/type-basics.html, foo[A,B] will not compile because it is 'too generic'. I do not understand what 'too generic' implies. Why does foo doesn't compile but foo1 does?

```<code>scala> def foo[A,B](f: A=>List[A], b:B) = f(b)
<console>:11: error: type mismatch;
 found   : b.type (with underlying type B)
 required: A
       def foo[A,B](f: A=>List[A], b:B) = f(b)
                                            ^

scala> def foo1[A](f: A=>List[A], b:A) = f(b)
foo1: [A](f: A => List[A], b: A)List[A]
</code>```

答:
The type of f is A => List[A]. This means that f can only be called with an argument of type A. Therefore b must be of type A for f(b). b: B is too generic in the sense that you allow b to be of any type, not just A.

Consider for example the following function:

```<code>def wrapInt(i: Int): List[Int] = List(i)
</code>```

Now the following call is legal:

```<code>wrapInt(42)
</code>```

But this one is not

```<code>wrapInt("hello")
</code>```

because "hello" is not an Int. Therefore this should be allowed:

```<code>foo(wrapInt, 42)
</code>```

, but this should not:

```<code>foo(wrapInt, "hello")
</code>```

According to the signature def foo[A,B](f: A=>List[A], b:B), both would be allowed even though the the latter would lead to wrapInt("hello"), which is ill-typed. Therefore that signature is illegal for that body.

Body:
Referring to the following tutorial https://twitter.github.io/scala_school/type-basics.html, foo[A,B] will not compile because it is 'too generic'. I do not understand what 'too generic' implies. Why does foo doesn't compile but foo1 does?

scala> def foo[A,B](f: A=>List[A], b:B) = f(b)
<console>:11: error: type mismatch;
 found   : b.type (with underlying type B)
 required: A
       def foo[A,B](f: A=>List[A], b:B) = f(b)
                                            ^

scala> def foo1[A](f: A=>List[A], b:A) = f(b)
foo1: [A](f: A => List[A], b: A)List[A]

Body:
The type of f is A => List[A]. This means that f can only be called with an argument of type A. Therefore b must be of type A for f(b). b: B is too generic in the sense that you allow b to be of any type, not just A.

Consider for example the following function:

def wrapInt(i: Int): List[Int] = List(i)

Now the following call is legal:

wrapInt(42)

But this one is not

wrapInt("hello")

because "hello" is not an Int. Therefore this should be allowed:

foo(wrapInt, 42)

, but this should not:

foo(wrapInt, "hello")

According to the signature def foo[A,B](f: A=>List[A], b:B), both would be allowed even though the the latter would lead to wrapInt("hello"), which is ill-typed. Therefore that signature is illegal for that body.


问:
Clearing RDD data that is persisted on Spark node
In case of task failures,does spark clear the persisted RDD (StorageLevel.MEMORY_ONLY_SER) and recompute them again when the task is attempted to start from beginning. Or will the cached RDD be appended.

I am seeing duplicate records in case of any task failures for a persisted RDD. Any help would be appreciated.

答:
You can call

```<code>rdd.unpersist()
</code>```

to clear the cached rdd.

Body:
You can call

rdd.unpersist()

to clear the cached rdd.


问:
Populate GridLayout with Repeater
I try to add cells to my GridLayout by using a Repeater. My data is stored in a model and containing two properties per element:

Title

Value

My goal is to get a GridLayout containing the Title in first cell and the Value in the second cell of each row.

```<code>GridLayout {
    id: someId
    columns: 2
    rowSpacing: 5
    columnSpacing: 5
    anchors.margins: 5
    anchors.left: parent.left
    anchors.right: parent.right

    Repeater {
        model: myModel
        Label {
            text: modelData.title
        }
        TextArea {
            text: modelData.value
        }
    }
}
</code>```

But QML Repeater allows only one element. Any ideas how I could get the layout I want?

```<code>+------------+---------------------------------------+
|            |                                       |
|  title0    |         value0                        |
|            |                                       |
|            |                                       |
+------------+---------------------------------------+
|            |                                       |
|            |                                       |
|  title1    |         value1                        |
|            |                                       |
|            |                                       |
+------------+---------------------------------------+
|            |                                       |
|  title2    |         value2                        |
|            |                                       |
|            |                                       |
+------------+---------------------------------------+
</code>```

答:
You can use GridLayout.flow to specify in which order the cells should be filled, i.e. row- (GridLayout.LeftToRight) or column-wise (GridLayout.TopToBottom). Note that you should specify the number of rows when using GridLayout.TopToBottom.

Using this solution, the (simplified) example of skypjack would become:

```<code>import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4

Window {
    width: 600; height: 400; visible: true

    GridLayout {
        anchors.fill: parent

        // specify the flow and number of rows
        flow: GridLayout.TopToBottom
        rows: repeater.count

        Repeater {
            id: repeater
            model: [ "title1", "title2", "title3", "title4", "title5", "title6" ] // example model
            Label {
                Layout.fillWidth: true
                Layout.fillHeight: true
                text: modelData
            }
        }

        Repeater {
            model: [ "value1", "value2", "value3", "value4", "value5", "value6" ]  // example model
            TextArea {
                Layout.fillWidth: true
                Layout.fillHeight: true
                text: modelData
            }
        }
    }
}
</code>```

Title: Populate GridLayout with Repeater

Body:
I try to add cells to my GridLayout by using a Repeater. My data is stored in a model and containing two properties per element:

Title

Value

My goal is to get a GridLayout containing the Title in first cell and the Value in the second cell of each row.

GridLayout {
    id: someId
    columns: 2
    rowSpacing: 5
    columnSpacing: 5
    anchors.margins: 5
    anchors.left: parent.left
    anchors.right: parent.right

    Repeater {
        model: myModel
        Label {
            text: modelData.title
        }
        TextArea {
            text: modelData.value
        }
    }
}

But QML Repeater allows only one element. Any ideas how I could get the layout I want?

+------------+---------------------------------------+
|            |                                       |
|  title0    |         value0                        |
|            |                                       |
|            |                                       |
+------------+---------------------------------------+
|            |                                       |
|            |                                       |
|  title1    |         value1                        |
|            |                                       |
|            |                                       |
+------------+---------------------------------------+
|            |                                       |
|  title2    |         value2                        |
|            |                                       |
|            |                                       |
+------------+---------------------------------------+

Body:
You can use GridLayout.flow to specify in which order the cells should be filled, i.e. row- (GridLayout.LeftToRight) or column-wise (GridLayout.TopToBottom). Note that you should specify the number of rows when using GridLayout.TopToBottom.

Using this solution, the (simplified) example of skypjack would become:

import QtQuick 2.5
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4

Window {
    width: 600; height: 400; visible: true

    GridLayout {
        anchors.fill: parent

        // specify the flow and number of rows
        flow: GridLayout.TopToBottom
        rows: repeater.count

        Repeater {
            id: repeater
            model: [ "title1", "title2", "title3", "title4", "title5", "title6" ] // example model
            Label {
                Layout.fillWidth: true
                Layout.fillHeight: true
                text: modelData
            }
        }

        Repeater {
            model: [ "value1", "value2", "value3", "value4", "value5", "value6" ]  // example model
            TextArea {
                Layout.fillWidth: true
                Layout.fillHeight: true
                text: modelData
            }
        }
    }
}


问:
Is there are way to get rowIDs of first occurrences of value from codechunks?
Is there a way to get that realized?

example:(distribution is random)

```<code>ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x
</code>```

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

答:
Use data.table::lag() to create a new column which lags one row behind ID. If d is your data.frame:

```<code>d <- d %>% dplyr::mutate(prevID = lag(ID))

   ID size prevID
1   1   44     NA
2   2   55      1
3   3   66      2
4   4   77      3
5   5   88      4
6   0    2      5
7   0   33      0
8   0   44      0
9   0   55      0
10  4   66      0
11  5   77      4
12  0    4      5
13  0   11      0
14  0   22      0
15  0   33      0
16  4   44      0
17  5   55      4
18  0    3      5
19  0   44      0
20  0   55      0
21  0   66      0
22  4   77      0
23  5   88      4
</code>```

Then get the rows where ID is 0 and not equal to prevID - these are the first 0 rows:

```<code>> which(d$ID == 0 & d$prevID != 0)
[1]  6 12 18
</code>```

Or use this to filter the original data.frame:

```<code>> d[which(d$ID == 0 & d$prevID != 0), ]
# A tibble: 3 x 3
     ID  size prevID
  <int> <int>  <int>
1     0     2      5
2     0     4      5
3     0     3      5
</code>```

Body:
Is there a way to get that realized?

example:(distribution is random)

ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

Body:
Use data.table::lag() to create a new column which lags one row behind ID. If d is your data.frame:

d <- d %>% dplyr::mutate(prevID = lag(ID))

   ID size prevID
1   1   44     NA
2   2   55      1
3   3   66      2
4   4   77      3
5   5   88      4
6   0    2      5
7   0   33      0
8   0   44      0
9   0   55      0
10  4   66      0
11  5   77      4
12  0    4      5
13  0   11      0
14  0   22      0
15  0   33      0
16  4   44      0
17  5   55      4
18  0    3      5
19  0   44      0
20  0   55      0
21  0   66      0
22  4   77      0
23  5   88      4

Then get the rows where ID is 0 and not equal to prevID - these are the first 0 rows:

> which(d$ID == 0 & d$prevID != 0)
[1]  6 12 18

Or use this to filter the original data.frame:

> d[which(d$ID == 0 & d$prevID != 0), ]
# A tibble: 3 x 3
     ID  size prevID
  <int> <int>  <int>
1     0     2      5
2     0     4      5
3     0     3      5


问:
sql fine tuning

In a Table, I need to combine 2 records into one record, based on columns
    (in this case column 1.WORK_ORDER_NUM, 2.ESN 3.PLANT 4. REMD_PART_NUM
    5. REMD_PART_SERIAL).  If these 5 columns are equal then I have to use Aggregate function in other column to make it into one record.[In
    this case the columns are LLP_TRACKD_PART_IND,REMD_PART_TSN and
    REMD_PART_CSN].

This is what I've tried:

```<code>SELECT decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)PLANT,
 COUNT(*) RECORD_COUNT,
 COUNT(DISTINCT OFF.REMD_PART_NUM) REMD_PART_NUM_COUNT,
 COUNT(DISTINCT OFF.REMD_PART_SERIAL) REMD_PART_SER_NUM_COUNT,
  COUNT(DECODE(LLP_TRACKD_PART_IND,'LL',LLP_TRACKD_PART_IND,NULL)) LL_COUNT,
 COUNT(DECODE(LLP_TRACKD_PART_IND,'LR',LLP_TRACKD_PART_IND,NULL)) LR_COUNT,
 COUNT(DECODE(LLP_TRACKD_PART_IND,'TR',LLP_TRACKD_PART_IND,NULL)) TR_COUNT,
 SUM(OFF.REMD_PART_QTY) TOTAL_REMD_PART_QTY,
  SUM(decode(LLP_TRACKD_PART_IND,null,0,
     CASE
       WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_TSN AS NUMBER)
        ELSE 0
    END
  )) TOTAL_TSN,
 SUM(decode(LLP_TRACKD_PART_IND,null,0,
    CASE
        WHEN REGEXP_LIKE(REMD_PART_CSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_CSN AS NUMBER)
        ELSE 0
    END
 )) TOTAL_CSN
FROM (with t as ( SELECT distinct PLANT,
WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,REMD_PART_IIN,
LLP_TRACKD_PART_IND,
REMD_PART_QTY,REMD_PART_TSN,REMD_PART_CSN,REMD_PART_TSO,REMD_PART_CSO
,REMD_PART_TSC,REMD_PART_CSC,REMD_CYCLE_REMAIN
FROM <TABLE1>
WHERE
REMD_PART_NUM is not null
)
select DISTINCT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL
,REMD_PART_IIN
 ,(select max(LLP_TRACKD_PART_IND) from t bb  where aa.PLANT=bb.PLANT and
aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
 and aa.ESN=bb.ESN
  and aa.REMD_PART_NUM=bb.REMD_PART_NUM
  and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL) LLP_TRACKD_PART_IND
 ,REMD_PART_QTY
 ,(select max(REMD_PART_TSN) from t bb  where aa.PLANT=bb.PLANT and
aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
 and aa.ESN=bb.ESN
 and aa.REMD_PART_NUM=bb.REMD_PART_NUM
 and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL) REMD_PART_TSN
 ,
(select max(REMD_PART_CSN) from t bb  where aa.PLANT=bb.PLANT and
aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
  and aa.ESN=bb.ESN
  and aa.REMD_PART_NUM=bb.REMD_PART_NUM
  and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL) REMD_PART_CSN
  from t aa) OFF
WHERE
REMD_PART_NUM is not null
GROUP BY decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)
</code>```

And it takes around 8 hours to complete. Is there any other way to complete it faster.
It took 8 hours to complete

答:
Start with a better formatting of the query, it will allow you to easily understand the code and notice repeated patterns:

```<code>SELECT decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)PLANT,
    COUNT(*) RECORD_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_NUM) REMD_PART_NUM_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_SERIAL) REMD_PART_SER_NUM_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LL',LLP_TRACKD_PART_IND,NULL)) LL_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LR',LLP_TRACKD_PART_IND,NULL)) LR_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'TR',LLP_TRACKD_PART_IND,NULL)) TR_COUNT,
    SUM(OFF.REMD_PART_QTY) TOTAL_REMD_PART_QTY,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_TSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_TSN,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_CSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_CSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_CSN
FROM (
    with t as (
        SELECT distinct PLANT, WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,REMD_PART_IIN,
                LLP_TRACKD_PART_IND,
                REMD_PART_QTY,REMD_PART_TSN,REMD_PART_CSN,REMD_PART_TSO,REMD_PART_CSO
                ,REMD_PART_TSC,REMD_PART_CSC,REMD_CYCLE_REMAIN
        FROM <TABLE1>
        WHERE REMD_PART_NUM is not null
    )
    select DISTINCT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL
            ,REMD_PART_IIN
            ,(  select max(LLP_TRACKD_PART_IND)
                from t bb
                where aa.PLANT=bb.PLANT
                    and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
                    and aa.ESN=bb.ESN
                    and aa.REMD_PART_NUM=bb.REMD_PART_NUM
                    and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
            ) LLP_TRACKD_PART_IND
            ,REMD_PART_QTY
            ,(  select max(REMD_PART_TSN) from t bb
                where aa.PLANT=bb.PLANT
                    and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
                    and aa.ESN=bb.ESN
                    and aa.REMD_PART_NUM=bb.REMD_PART_NUM
                    and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
            ) REMD_PART_TSN
            ,
            (   select max(REMD_PART_CSN) from t bb
                where aa.PLANT=bb.PLANT
                    and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
                    and aa.ESN=bb.ESN
                    and aa.REMD_PART_NUM=bb.REMD_PART_NUM
                    and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
            ) REMD_PART_CSN
    from t aa
) OFF
WHERE REMD_PART_NUM is not null
GROUP BY decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)
;
</code>```

You will see that the below pattern is repeated 3 times (3 almost identical subqueries):

```<code>select max( some_field )
from t bb
where aa.PLANT=bb.PLANT
  and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
  and aa.ESN=bb.ESN
  and aa.REMD_PART_NUM=bb.REMD_PART_NUM
  and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
</code>```

You will also easily see that there are 3 very expensive sort operations in this query - one DISTINCT in the innermost subquery, then another DISTINCT in another subquery, then finally GROUP BY operation (a kind of DISTINCT) in the top level query.

Looking only on your query one can easily eliminate one sort (DISTINCT) using analytic functions in this way:

```<code>SELECT * FROM (
    SELECT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,
           REMD_PART_IIN, REMD_PART_QTY,
           max( LLP_TRACKD_PART_IND ) over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL)
           as LLP_TRACKD_PART_IND,
           max( REMD_PART_TSN )       over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL)
           as REMD_PART_TSN,
           max( REMD_PART_CSN )       over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL)
           as REMD_PART_CSN,
           row_number() over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL, REMD_PART_IIN, REMD_PART_QTY
                   order by PLANT) as Rn
    FROM TABLE1
    WHERE REMD_PART_NUM is not null
)
WHERE rn = 1
</code>```

so the final query migh be:

```<code>SELECT decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)PLANT,
    COUNT(*) RECORD_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_NUM) REMD_PART_NUM_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_SERIAL) REMD_PART_SER_NUM_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LL',LLP_TRACKD_PART_IND,NULL)) LL_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LR',LLP_TRACKD_PART_IND,NULL)) LR_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'TR',LLP_TRACKD_PART_IND,NULL)) TR_COUNT,
    SUM(OFF.REMD_PART_QTY) TOTAL_REMD_PART_QTY,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_TSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_TSN,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_CSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_CSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_CSN
FROM (
    SELECT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,REMD_PART_IIN, REMD_PART_QTY,
           max( LLP_TRACKD_PART_IND ) over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL) as LLP_TRACKD_PART_IND,
           max( REMD_PART_TSN )       over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL) as REMD_PART_TSN,
           max( REMD_PART_CSN )       over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL) as REMD_PART_CSN,
           row_number()               over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL, REMD_PART_IIN, REMD_PART_QTY
                                            order by PLANT) as Rn
    FROM TABLE1
    WHERE REMD_PART_NUM is not null
)
WHERE rn = 1
GROUP BY decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)
</code>```

I feel that this query could be further optimized, but it would require insight into the structure of the tables and a knowledge of business requirements.

There are still some microoptimalizations possible, though.

This pattern:

```<code>SUM(decode(LLP_TRACKD_PART_IND,null,0,
        CASE
            WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_TSN AS NUMBER)
            ELSE 0
        END
    )) TOTAL_TSN,
</code>```

can be replaced with this one:

```<code>coalesce(
    SUM(
        CASE
            WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_TSN AS NUMBER)
            ELSE 0
        END
    ), 0
)
</code>```

since SUM ignores nulls, then checking for NULL value for each record is a waste. For a small number of records ( < 1 million) it does not matter, but for hundreds of millions of records you can achieve the effect of scale - say 0.05 ms for checking each record multiplied by 10.000.000 records can give 500 seconds.

Title: sql fine tuning

Body:
In a Table, I need to combine 2 records into one record, based on columns
    (in this case column 1.WORK_ORDER_NUM, 2.ESN 3.PLANT 4. REMD_PART_NUM
    5. REMD_PART_SERIAL).  If these 5 columns are equal then I have to use Aggregate function in other column to make it into one record.[In
    this case the columns are LLP_TRACKD_PART_IND,REMD_PART_TSN and
    REMD_PART_CSN].

This is what I've tried:

SELECT decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)PLANT,
 COUNT(*) RECORD_COUNT,
 COUNT(DISTINCT OFF.REMD_PART_NUM) REMD_PART_NUM_COUNT,
 COUNT(DISTINCT OFF.REMD_PART_SERIAL) REMD_PART_SER_NUM_COUNT,
  COUNT(DECODE(LLP_TRACKD_PART_IND,'LL',LLP_TRACKD_PART_IND,NULL)) LL_COUNT,
 COUNT(DECODE(LLP_TRACKD_PART_IND,'LR',LLP_TRACKD_PART_IND,NULL)) LR_COUNT,
 COUNT(DECODE(LLP_TRACKD_PART_IND,'TR',LLP_TRACKD_PART_IND,NULL)) TR_COUNT,
 SUM(OFF.REMD_PART_QTY) TOTAL_REMD_PART_QTY,
  SUM(decode(LLP_TRACKD_PART_IND,null,0,
     CASE
       WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_TSN AS NUMBER)
        ELSE 0
    END
  )) TOTAL_TSN,
 SUM(decode(LLP_TRACKD_PART_IND,null,0,
    CASE
        WHEN REGEXP_LIKE(REMD_PART_CSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_CSN AS NUMBER)
        ELSE 0
    END
 )) TOTAL_CSN
FROM (with t as ( SELECT distinct PLANT,
WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,REMD_PART_IIN,
LLP_TRACKD_PART_IND,
REMD_PART_QTY,REMD_PART_TSN,REMD_PART_CSN,REMD_PART_TSO,REMD_PART_CSO
,REMD_PART_TSC,REMD_PART_CSC,REMD_CYCLE_REMAIN
FROM <TABLE1>
WHERE
REMD_PART_NUM is not null
)
select DISTINCT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL
,REMD_PART_IIN
 ,(select max(LLP_TRACKD_PART_IND) from t bb  where aa.PLANT=bb.PLANT and
aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
 and aa.ESN=bb.ESN
  and aa.REMD_PART_NUM=bb.REMD_PART_NUM
  and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL) LLP_TRACKD_PART_IND
 ,REMD_PART_QTY
 ,(select max(REMD_PART_TSN) from t bb  where aa.PLANT=bb.PLANT and
aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
 and aa.ESN=bb.ESN
 and aa.REMD_PART_NUM=bb.REMD_PART_NUM
 and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL) REMD_PART_TSN
 ,
(select max(REMD_PART_CSN) from t bb  where aa.PLANT=bb.PLANT and
aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
  and aa.ESN=bb.ESN
  and aa.REMD_PART_NUM=bb.REMD_PART_NUM
  and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL) REMD_PART_CSN
  from t aa) OFF
WHERE
REMD_PART_NUM is not null
GROUP BY decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)

And it takes around 8 hours to complete. Is there any other way to complete it faster.
It took 8 hours to complete

Body:
Start with a better formatting of the query, it will allow you to easily understand the code and notice repeated patterns:

SELECT decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)PLANT,
    COUNT(*) RECORD_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_NUM) REMD_PART_NUM_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_SERIAL) REMD_PART_SER_NUM_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LL',LLP_TRACKD_PART_IND,NULL)) LL_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LR',LLP_TRACKD_PART_IND,NULL)) LR_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'TR',LLP_TRACKD_PART_IND,NULL)) TR_COUNT,
    SUM(OFF.REMD_PART_QTY) TOTAL_REMD_PART_QTY,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_TSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_TSN,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_CSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_CSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_CSN
FROM (
    with t as (
        SELECT distinct PLANT, WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,REMD_PART_IIN,
                LLP_TRACKD_PART_IND,
                REMD_PART_QTY,REMD_PART_TSN,REMD_PART_CSN,REMD_PART_TSO,REMD_PART_CSO
                ,REMD_PART_TSC,REMD_PART_CSC,REMD_CYCLE_REMAIN
        FROM <TABLE1>
        WHERE REMD_PART_NUM is not null
    )
    select DISTINCT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL
            ,REMD_PART_IIN
            ,(  select max(LLP_TRACKD_PART_IND)
                from t bb
                where aa.PLANT=bb.PLANT
                    and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
                    and aa.ESN=bb.ESN
                    and aa.REMD_PART_NUM=bb.REMD_PART_NUM
                    and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
            ) LLP_TRACKD_PART_IND
            ,REMD_PART_QTY
            ,(  select max(REMD_PART_TSN) from t bb
                where aa.PLANT=bb.PLANT
                    and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
                    and aa.ESN=bb.ESN
                    and aa.REMD_PART_NUM=bb.REMD_PART_NUM
                    and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
            ) REMD_PART_TSN
            ,
            (   select max(REMD_PART_CSN) from t bb
                where aa.PLANT=bb.PLANT
                    and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
                    and aa.ESN=bb.ESN
                    and aa.REMD_PART_NUM=bb.REMD_PART_NUM
                    and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL
            ) REMD_PART_CSN
    from t aa
) OFF
WHERE REMD_PART_NUM is not null
GROUP BY decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)
;

You will see that the below pattern is repeated 3 times (3 almost identical subqueries):

select max( some_field )
from t bb
where aa.PLANT=bb.PLANT
  and aa.WORK_ORDER_NUM=bb.WORK_ORDER_NUM
  and aa.ESN=bb.ESN
  and aa.REMD_PART_NUM=bb.REMD_PART_NUM
  and aa.REMD_PART_SERIAL=bb.REMD_PART_SERIAL

You will also easily see that there are 3 very expensive sort operations in this query - one DISTINCT in the innermost subquery, then another DISTINCT in another subquery, then finally GROUP BY operation (a kind of DISTINCT) in the top level query.

Looking only on your query one can easily eliminate one sort (DISTINCT) using analytic functions in this way:

SELECT * FROM (
    SELECT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,
           REMD_PART_IIN, REMD_PART_QTY,
           max( LLP_TRACKD_PART_IND ) over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL)
           as LLP_TRACKD_PART_IND,
           max( REMD_PART_TSN )       over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL)
           as REMD_PART_TSN,
           max( REMD_PART_CSN )       over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL)
           as REMD_PART_CSN,
           row_number() over
              (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL, REMD_PART_IIN, REMD_PART_QTY
                   order by PLANT) as Rn
    FROM TABLE1
    WHERE REMD_PART_NUM is not null
)
WHERE rn = 1

so the final query migh be:

SELECT decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)PLANT,
    COUNT(*) RECORD_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_NUM) REMD_PART_NUM_COUNT,
    COUNT(DISTINCT OFF.REMD_PART_SERIAL) REMD_PART_SER_NUM_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LL',LLP_TRACKD_PART_IND,NULL)) LL_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'LR',LLP_TRACKD_PART_IND,NULL)) LR_COUNT,
    COUNT(DECODE(LLP_TRACKD_PART_IND,'TR',LLP_TRACKD_PART_IND,NULL)) TR_COUNT,
    SUM(OFF.REMD_PART_QTY) TOTAL_REMD_PART_QTY,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_TSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_TSN,
    SUM(decode(LLP_TRACKD_PART_IND,null,0,
            CASE
                WHEN REGEXP_LIKE(REMD_PART_CSN, '^-?\d+(\.\d+)?$')
                THEN CAST(REMD_PART_CSN AS NUMBER)
                ELSE 0
            END
        )) TOTAL_CSN
FROM (
    SELECT PLANT,WORK_ORDER_NUM,ESN,REMD_PART_NUM,REMD_PART_SERIAL,REMD_PART_IIN, REMD_PART_QTY,
           max( LLP_TRACKD_PART_IND ) over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL) as LLP_TRACKD_PART_IND,
           max( REMD_PART_TSN )       over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL) as REMD_PART_TSN,
           max( REMD_PART_CSN )       over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL) as REMD_PART_CSN,
           row_number()               over (partition by PLANT, WORK_ORDER_NUM, ESN, REMD_PART_NUM, REMD_PART_SERIAL, REMD_PART_IIN, REMD_PART_QTY
                                            order by PLANT) as Rn
    FROM TABLE1
    WHERE REMD_PART_NUM is not null
)
WHERE rn = 1
GROUP BY decode (PLANT ,'ECL','CELMA','EDS','CELMA',PLANT)

I feel that this query could be further optimized, but it would require insight into the structure of the tables and a knowledge of business requirements.

There are still some microoptimalizations possible, though.

This pattern:

SUM(decode(LLP_TRACKD_PART_IND,null,0,
        CASE
            WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_TSN AS NUMBER)
            ELSE 0
        END
    )) TOTAL_TSN,

can be replaced with this one:

coalesce(
    SUM(
        CASE
            WHEN REGEXP_LIKE(REMD_PART_TSN, '^-?\d+(\.\d+)?$')
            THEN CAST(REMD_PART_TSN AS NUMBER)
            ELSE 0
        END
    ), 0
)

since SUM ignores nulls, then checking for NULL value for each record is a waste. For a small number of records ( < 1 million) it does not matter, but for hundreds of millions of records you can achieve the effect of scale - say 0.05 ms for checking each record multiplied by 10.000.000 records can give 500 seconds.


问:
Recommendations for a "Getting started with Greasemonkey" tutorial
I'm interested in writing some Chrome compatible Greasemonkey scripts, but I'm finding that there are few updated tutorials on how to really get started properly with writing userscripts. Dive Into Greasemonkey by Mark Pilgrim is five years old now and hasn't been updated. Searches for tutorials are rife with garbage hits, affiliate blog links and general nonsense. The wiki for Greasemonkey is nearly all reference, not really a "this is a good place to start" kind of article.

Can you recommend a good, updated tutorial for getting started writing userscripts?

I define "good" as:

How to setup an environment

Basic skills required to know

Common use examples

Best practices

I define "updated" as:

Written or updated in the last 18 months

答: http://wiki.greasespot.net/Main_Page <-- the page which is opened the first time you install Greasemonkey</p>


答:
Maybe :

```<code>print '*' * 80 + '\n' + ' ' * 38 + 'hello' + '\n' + '*' *80
</code>```

OR
If it is python3

```<code>a = lambda x,c,mess: print(c*x + ('\n' if not mess else mess))
a(80, '*', None)
a(38, ' ', 'Hello')
a(80, '*', None)
</code>```

Title: multi line string formatting in python

Body:
To begin with, I am working to a get a desired output like this:

*********************************************************************
                                 hello
*********************************************************************

To achieve this I have assigned the desired output to a variable with multiline string and printing the same with format.

$ cat varibale.py
decorator = """ **********************************************************************
                               {}
            ********************************************************************** """
print(decorator.format("hello"))

Output:

**********************************************************************
                               hello
            **********************************************************************

The issue with above approach is the extra spaces in the third line of output which is looking odd.

I am able to achieve this in the following way:

$ cat varibale.py
decorator = """ **********************************************************************
                             {}
*********************************************************************
"""
print(decorator.format("hello"))

Output:

 **********************************************************************
                             hello
*********************************************************************

But this way my code doesn't look good, as it is not following the indentation.

Please suggest the right way to achieve the desired output.

Body:
Maybe :

print '*' * 80 + '\n' + ' ' * 38 + 'hello' + '\n' + '*' *80

OR
If it is python3

a = lambda x,c,mess: print(c*x + ('\n' if not mess else mess))
a(80, '*', None)
a(38, ' ', 'Hello')
a(80, '*', None)