问:
How to convert html blade that contains dynamic data from database to PDF in laravel?
I'm trying to write code that converts html blade to PDF using tcpdf in laravel.

This is the controller code which i use to convert:

```<code>public function htmlToPDF()
{
    $view=view('PdfDemo');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}
</code>```

When I put static data on my view(PdfDemo) everything runs successfully, but the problem is when I put dynamic data with some variables in the blade as the following:

```<code>                        <table>
                          <?php $i=0?>
                            @if(count($names))
                                @foreach($names as $n)
                                    <tr><td>
                                    <label>Name{{$i}}:</label>{{$n}}</td>
                                    <tr><td><hr></td></tr>
                                    <?php $index = $index+1; ?>
                                @endforeach
                            @endif
                        </table>
</code>```

Here $names is the result of select statement in other function of controller, then I pass it to the blade like this:

```<code> return view('PdfDemo',compact('names'));
</code>```

In this case the blade appear exactly as I want, but when I try to convert to PDF it shows error, $name not defined.

答:
You are not passing the data to the view in the htmlToPDF function.

try to change it to:

```<code>public function htmlToPDF($names)
{
    $view=view('PdfDemo', compact('names');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}
</code>```

Body:
I'm trying to write code that converts html blade to PDF using tcpdf in laravel.

This is the controller code which i use to convert:

public function htmlToPDF()
{
    $view=view('PdfDemo');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}

When I put static data on my view(PdfDemo) everything runs successfully, but the problem is when I put dynamic data with some variables in the blade as the following:

                          <?php $i=0?>
                            @if(count($names))
                                @foreach($names as $n)

                                    Name{{$i}}:{{$n}}

                                    <?php $index = $index+1; ?>
                                @endforeach
                            @endif

Here $names is the result of select statement in other function of controller, then I pass it to the blade like this:

 return view('PdfDemo',compact('names'));

In this case the blade appear exactly as I want, but when I try to convert to PDF it shows error, $name not defined.

Body:
You are not passing the data to the view in the htmlToPDF function.

try to change it to:

public function htmlToPDF($names)
{
    $view=view('PdfDemo', compact('names');
    $html_content =$view->render();
    PDF::SetTitle('Sample PDF');
    PDF::AddPage();
    PDF::writeHTML($html_content, true, false, true, false, '');
    PDF::Output('SamplePDF.pdf');
}


来源: stackexchange

问:
Osm2pgsql failed due to ERROR: PBF error: invalid BlobHeader size (> max_blob_header_size)
I am using a docker project in a rather strong server(120GB RAM and plenty of disc space).

When trying to run an import on postgres server I get the following error

```<code>Using projection SRS 4326 (Latlong)
NOTICE:  table "place" does not exist, skipping
Allocating memory for dense node cache
Allocating dense node cache in one big chunk
Allocating memory for sparse node cache
Sharing dense sparse
Node-cache: cache=1207MB, maxblocks=154496*8192, allocation method=11
Mid: pgsql, scale=10000000 cache=1207
Setting up table: planet_osm_nodes
Setting up table: planet_osm_ways
Setting up table: planet_osm_rels

Reading in file: /app/src/data.osm.pbf
Using PBF parser.
node cache: stored: 0(-nan%), storage efficiency: -nan% (dense blocks: 0, sparse nodes: 0), hit rate: -nan%
Osm2pgsql failed due to ERROR: PBF error: invalid BlobHeader size (> max_blob_header_size)
ERROR: Error executing external command: /app/src/osm2pgsql/osm2pgsql -lsc -O gazetteer --hstore --number-processes 1 -C 1207 -P 5432 -d nominatim /app/src/data.osm.pbf
</code>```

How could I increase the max_blob_header_size?

答:
I stumbled upon the same issue while feeding an S3 hosted PBF file into a  Nominatim docker container.

Unfortunately I failed to configure the access to the PBF file properly so the docker container saved the XML error response as /app/src/data.osm.pbf. That's why the file header check fails.

ContentLicense: CC BY-SA 3.0

Body:
I am using a docker project in a rather strong server(120GB RAM and plenty of disc space).

When trying to run an import on postgres server I get the following error

Using projection SRS 4326 (Latlong)
NOTICE:  table "place" does not exist, skipping
Allocating memory for dense node cache
Allocating dense node cache in one big chunk
Allocating memory for sparse node cache
Sharing dense sparse
Node-cache: cache=1207MB, maxblocks=154496*8192, allocation method=11
Mid: pgsql, scale=10000000 cache=1207
Setting up table: planet_osm_nodes
Setting up table: planet_osm_ways
Setting up table: planet_osm_rels

Reading in file: /app/src/data.osm.pbf
Using PBF parser.
node cache: stored: 0(-nan%), storage efficiency: -nan% (dense blocks: 0, sparse nodes: 0), hit rate: -nan%
Osm2pgsql failed due to ERROR: PBF error: invalid BlobHeader size (> max_blob_header_size)
ERROR: Error executing external command: /app/src/osm2pgsql/osm2pgsql -lsc -O gazetteer --hstore --number-processes 1 -C 1207 -P 5432 -d nominatim /app/src/data.osm.pbf

How could I increase the max_blob_header_size?


问:
Send both POST and GET in a form
I need to make a form send both POST and GET requests (due to some bugs in IE and iframes), how can you do so?

The data being sent is nothing mega secure so it doesn't matter if it can be set via GET, just need to make sure it is set both ways.

Thanks for the help!

答:
Not sure what bug you're trying to get around but you can use jQuery to easily modify the form's action to contain the posted values:

script:

```<code>function setAction() {
    $("#myform").attr("action", "/path/to/script/?" + $("#myform").serialize());
}
</code>```

html:

```<code><form id="myform" action="/path/to/script/" method="post" onsubmit="setAction()">
</code>```

ContentLicense: CC BY-SA 2.5

Title: Send both POST and GET in a form

Body:
Not sure what bug you're trying to get around but you can use jQuery to easily modify the form's action to contain the posted values:

script:

function setAction() {
    $("#myform").attr("action", "/path/to/script/?" + $("#myform").serialize());
}

html:

<form id="myform" action="/path/to/script/" method="post" onsubmit="setAction()">


问:
Classify a sentence into multiple categories
A beginner in NLTK and Scikit-learn here. I want to be able to classify a given sentence(or even a paragraph) into a group of categories. By categories, I don't mean only two categories like spam and not spam or good sentiment and bad sentiment, meaning its multiple(more than two) categories to choose from. Please help me in choosing the simplest algorithm for solving this problem. Thanks in advance.</p>

答:
If I'm right , you're trying to perform a topic modelling on your data set .
As far as I'm concerned , you can use LDA (Latent Dirichlet allocation ) , but you'll have the obligation to specify the number of topics , you can do several test to find the appropriate value of number of topics  .
This is an example of LDA performed using python and  demonstrates how to inspect a model of a subset of the Reuters news dataset . The input below, X, is a document-term matrix . </p>

```<code> >>> import numpy as np
>>> import lda
>>> X = lda.datasets.load_reuters()
>>> vocab = lda.datasets.load_reuters_vocab()
>>> titles = lda.datasets.load_reuters_titles()
>>> X.shape
(395, 4258)
>>> X.sum()
84010
>>> model = lda.LDA(n_topics=20, n_iter=1500, random_state=1)
>>> model.fit(X)  # model.fit_transform(X) is also available
>>> topic_word = model.topic_word_  # model.components_ also works
>>> n_top_words = 8
>>> for i, topic_dist in enumerate(topic_word):
...     topic_words = np.array(vocab)[np.argsort(topic_dist)][:-n_top_words:-1]
...     print('Topic {}: {}'.format(i, ' '.join(topic_words)))
Topic 0: british churchill sale million major letters west
Topic 1: church government political country state people party
Topic 2: elvis king fans presley life concert young
Topic 3: yeltsin russian russia president kremlin moscow michael
Topic 4: pope vatican paul john surgery hospital pontiff
Topic 5: family funeral police miami versace cunanan city
Topic 6: simpson former years court president wife south
Topic 7: order mother successor election nuns church nirmala
Topic 8: charles prince diana royal king queen parker
Topic 9: film french france against bardot paris poster
Topic 10: germany german war nazi letter christian book
Topic 11: east peace prize award timor quebec belo
Topic 12: n't life show told very love television
Topic 13: years year time last church world people
Topic 14: mother teresa heart calcutta charity nun hospital
Topic 15: city salonika capital buddhist cultural vietnam byzantine
Topic 16: music tour opera singer israel people film
Topic 17: church catholic bernardin cardinal bishop wright death
Topic 18: harriman clinton u.s ambassador paris president churchill
Topic 19: city museum art exhibition century million churches
</code>```

Body:
If I'm right , you're trying to perform a topic modelling on your data set .
As far as I'm concerned , you can use LDA (Latent Dirichlet allocation ) , but you'll have the obligation to specify the number of topics , you can do several test to find the appropriate value of number of topics  .
This is an example of LDA performed using python and  demonstrates how to inspect a model of a subset of the Reuters news dataset . The input below, X, is a document-term matrix .

 >>> import numpy as np
>>> import lda
>>> X = lda.datasets.load_reuters()
>>> vocab = lda.datasets.load_reuters_vocab()
>>> titles = lda.datasets.load_reuters_titles()
>>> X.shape
(395, 4258)
>>> X.sum()
84010
>>> model = lda.LDA(n_topics=20, n_iter=1500, random_state=1)
>>> model.fit(X)  # model.fit_transform(X) is also available
>>> topic_word = model.topic_word_  # model.components_ also works
>>> n_top_words = 8
>>> for i, topic_dist in enumerate(topic_word):
...     topic_words = np.array(vocab)[np.argsort(topic_dist)][:-n_top_words:-1]
...     print('Topic {}: {}'.format(i, ' '.join(topic_words)))
Topic 0: british churchill sale million major letters west
Topic 1: church government political country state people party
Topic 2: elvis king fans presley life concert young
Topic 3: yeltsin russian russia president kremlin moscow michael
Topic 4: pope vatican paul john surgery hospital pontiff
Topic 5: family funeral police miami versace cunanan city
Topic 6: simpson former years court president wife south
Topic 7: order mother successor election nuns church nirmala
Topic 8: charles prince diana royal king queen parker
Topic 9: film french france against bardot paris poster
Topic 10: germany german war nazi letter christian book
Topic 11: east peace prize award timor quebec belo
Topic 12: n't life show told very love television
Topic 13: years year time last church world people
Topic 14: mother teresa heart calcutta charity nun hospital
Topic 15: city salonika capital buddhist cultural vietnam byzantine
Topic 16: music tour opera singer israel people film
Topic 17: church catholic bernardin cardinal bishop wright death
Topic 18: harriman clinton u.s ambassador paris president churchill
Topic 19: city museum art exhibition century million churches


问:
Spark. Split RDD into batches
I have RDD, where each record is int:

```<code>[0,1,2,3,4,5,6,7,8]
</code>```

All I need to do is split this RDD into batches. I.e. make another RDD where each element is fixed size list of elements:

```<code>[[0,1,2], [3,4,5], [6,7,8]]
</code>```

This sounds trivial, however, I am puzzled last several days and cannot find anything except the following solution:

Use ZipWithIndex to enumerate records in RDD:

[0,1,2,3,4,5] -> [(0, 0),(1, 1),(2, 2),(3, 3),(4, 4),(5, 5)]

Iterate over this RDD using map() and calculate index like index = int(index / batchSize)

[1,2,3,4,5,6] -> [(0, 0),(0, 1),(0, 2),(1, 3),(1, 4),(1, 5)]

Then group by generated index.

[(0, [0,1,2]), (1, [3,4,5])]

This will get me what I need, however, I do not want to use group by here. It is trivial when you are using plain Map Reduce or some abstraction like Apache Crunch. But is there a way to produce similar result in Spark without using heavy group by?

答:
You did not clearly explained why you need fixed-size RDDs, depending on what you are trying to accomplish there could be better solution, but to answer the question as it has been asked, I see the following options:

1) implement filters based on the number of items and batch sizes. For example, if you have 1000 items in the original RDD and want to split them into 10 batches, you will end up applying 10 filters, the first one checks if index is [0, 99], the second one [100, 199] and so one. After apply each filter, you will have one RDD. Important to note that the original RDD might be cached to prior to filtering. Pros: each resulting RDD can be processed separately and does not have to be fully allocated on one node. Cons: this approach becomes slower with the number of batches.

2) Logically similar to this, but instead of filter, you just implement a custom partitioner that returns a partition id based on the index (key) as described here: Custom partitioner for equally sized partitions. Pros: faster than filters. Cons: each partition has to be fit into one node.

3) If the order in the original RDD is not important and just need it to be roughly equally chunked, you can coalesce/repartition in, explained here https://jaceklaskowski.gitbooks.io/mastering-apache-spark/spark-rdd-partitions.html

Title: Spark. Split RDD into batches

Body:
I have RDD, where each record is int:

[0,1,2,3,4,5,6,7,8]

All I need to do is split this RDD into batches. I.e. make another RDD where each element is fixed size list of elements:

[[0,1,2], [3,4,5], [6,7,8]]

This sounds trivial, however, I am puzzled last several days and cannot find anything except the following solution:

Use ZipWithIndex to enumerate records in RDD:

[0,1,2,3,4,5] -> [(0, 0),(1, 1),(2, 2),(3, 3),(4, 4),(5, 5)]

Iterate over this RDD using map() and calculate index like index = int(index / batchSize)

[1,2,3,4,5,6] -> [(0, 0),(0, 1),(0, 2),(1, 3),(1, 4),(1, 5)]

Then group by generated index.

[(0, [0,1,2]), (1, [3,4,5])]

This will get me what I need, however, I do not want to use group by here. It is trivial when you are using plain Map Reduce or some abstraction like Apache Crunch. But is there a way to produce similar result in Spark without using heavy group by?


问:
Adjusting vertical height of a character in an NSMutableAttributedString
I have an NSMutableAttributedString with a + in the first character that I want to lift 2 pts.

I can kern with this:
attributedAmountText.addAttribute(NSKernAttributeName, value: 2.0, range: NSRange(location: 0, length: 1))

Is there a way to lift that first character? Sort of like a vertical kern

Edit:

Trying attributedAmountText.addAttribute(NSBaselineOffsetAttributeName, value: 2.0, range: NSRange(location: 0, length: 1)) actually moves the baseline itself rather than the text vertically off the baseline which seems odd since the docs say otherwise:

The value of this attribute is an NSNumber object containing a floating point value indicating the character’s offset from the baseline, in points. The default value is 0.

答:
Hmmm... A quick test of this code:

```<code>class ScalingViewController: UIViewController {

    @IBOutlet weak var theLabel: UILabel!

    @IBOutlet weak var theOtherLabel: UILabel!

    let now = Date()

    let labelA: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.cyan
        return v
    }()

    let labelB: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.yellow
        return v
    }()

    let labelC: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.green
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(labelA)
        view.addSubview(labelB)
        view.addSubview(labelC)

        labelA.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0).isActive = true
        labelA.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0).isActive = true

        labelB.topAnchor.constraint(equalTo: labelA.topAnchor, constant: 0.0).isActive = true
        labelB.leadingAnchor.constraint(equalTo: labelA.trailingAnchor, constant: 8.0).isActive = true

        labelC.topAnchor.constraint(equalTo: labelA.topAnchor, constant: 0.0).isActive = true
        labelC.leadingAnchor.constraint(equalTo: labelB.trailingAnchor, constant: 8.0).isActive = true

        var aText = NSMutableAttributedString()
        let baseFont = UIFont.systemFont(ofSize: 30.0, weight: UIFontWeightLight)

        let testString = "Example"
        let tsLength = testString.characters.count

        // Font only
        aText = NSMutableAttributedString()
        aText.append(NSMutableAttributedString(string: testString, attributes: [NSFontAttributeName: baseFont]))

        labelA.attributedText = aText

        // Font + positive Baseline Offset of 1st character
        aText = NSMutableAttributedString()
        aText.append(NSMutableAttributedString(string: testString, attributes: [NSFontAttributeName: baseFont]))
        aText.addAttribute(NSBaselineOffsetAttributeName, value: 10.0, range: NSRange(location: 0, length: 1))

        labelB.attributedText = aText

        // Font + negative Baseline Offset of all but 1st character
        aText = NSMutableAttributedString()
        aText.append(NSMutableAttributedString(string: testString, attributes: [NSFontAttributeName: baseFont]))
        aText.addAttribute(NSBaselineOffsetAttributeName, value: -10.0, range: NSRange(location: 1, length: tsLength - 1))

        labelC.attributedText = aText

    }

}
</code>```

Gave me this result:

I suppose if I knew enough about all the typography aspects of String attributes this would make sense?

Body:
Hmmm... A quick test of this code:

class ScalingViewController: UIViewController {

    @IBOutlet weak var theLabel: UILabel!

    @IBOutlet weak var theOtherLabel: UILabel!

    let now = Date()

    let labelA: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.cyan
        return v
    }()

    let labelB: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.yellow
        return v
    }()

    let labelC: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = UIColor.green
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(labelA)
        view.addSubview(labelB)
        view.addSubview(labelC)

        labelA.topAnchor.constraint(equalTo: view.topAnchor, constant: 40.0).isActive = true
        labelA.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8.0).isActive = true

        labelB.topAnchor.constraint(equalTo: labelA.topAnchor, constant: 0.0).isActive = true
        labelB.leadingAnchor.constraint(equalTo: labelA.trailingAnchor, constant: 8.0).isActive = true

        labelC.topAnchor.constraint(equalTo: labelA.topAnchor, constant: 0.0).isActive = true
        labelC.leadingAnchor.constraint(equalTo: labelB.trailingAnchor, constant: 8.0).isActive = true

        var aText = NSMutableAttributedString()
        let baseFont = UIFont.systemFont(ofSize: 30.0, weight: UIFontWeightLight)

        let testString = "Example"
        let tsLength = testString.characters.count

        // Font only
        aText = NSMutableAttributedString()
        aText.append(NSMutableAttributedString(string: testString, attributes: [NSFontAttributeName: baseFont]))

        labelA.attributedText = aText

        // Font + positive Baseline Offset of 1st character
        aText = NSMutableAttributedString()
        aText.append(NSMutableAttributedString(string: testString, attributes: [NSFontAttributeName: baseFont]))
        aText.addAttribute(NSBaselineOffsetAttributeName, value: 10.0, range: NSRange(location: 0, length: 1))

        labelB.attributedText = aText

        // Font + negative Baseline Offset of all but 1st character
        aText = NSMutableAttributedString()
        aText.append(NSMutableAttributedString(string: testString, attributes: [NSFontAttributeName: baseFont]))
        aText.addAttribute(NSBaselineOffsetAttributeName, value: -10.0, range: NSRange(location: 1, length: tsLength - 1))

        labelC.attributedText = aText

    }

}

Gave me this result:

I suppose if I knew enough about all the typography aspects of String attributes this would make sense?


问:
How to change the image shown by a GtkImage?
in my program I would like to change an image by clicking a button but I can not find the function

```<code>class TestGdkPixbuf(Gtk.Window):
    Cover= "image.png"
    Cover2= "image2.png"

    def __init__(self):
        Gtk.Window.__init__(self, title="TestGdkPixbuf")

        mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250)
        image_renderer = Gtk.Image.new_from_pixbuf(self.image)

        button = Gtk.Button(label='Change')
        button.connect('clicked', self.editPixbuf)

        mainLayout.pack_start(image_renderer, True, True, 0)
        mainLayout.pack_start(button, True, True, 0)

        self.add(mainLayout)

    def editPixbuf(self, button):
        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250)
        print(self.Cover2)
</code>```

Thank you very much for your help

答:
When you've created the Gtk.Image, image_renderer, you supplied a pixbuf, self.image.

Then on your button callback, you did load an image into a pixbuf but did not update the image_renderer with the new pixbuf. You should use Gtk.Image set_from_pixbuf.

Try:

```<code>class TestGdkPixbuf(Gtk.Window):
    Cover= "image.png"
    Cover2= "image2.png"

    def __init__(self):
        Gtk.Window.__init__(self, title="TestGdkPixbuf")

        mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250)
        self.image_renderer = Gtk.Image.new_from_pixbuf(self.image)

        button = Gtk.Button(label='Change')
        button.connect('clicked', self.editPixbuf)

        mainLayout.pack_start(image_renderer, True, True, 0)
        mainLayout.pack_start(button, True, True, 0)

        self.add(mainLayout)

    def editPixbuf(self, button):
        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250)
        self.image_renderer.set_from_pixbuf (self.image)
        print(self.Cover2)
</code>```

Body:
in my program I would like to change an image by clicking a button but I can not find the function

class TestGdkPixbuf(Gtk.Window):
    Cover= "image.png"
    Cover2= "image2.png"

    def __init__(self):
        Gtk.Window.__init__(self, title="TestGdkPixbuf")

        mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250)
        image_renderer = Gtk.Image.new_from_pixbuf(self.image)

        button = Gtk.Button(label='Change')
        button.connect('clicked', self.editPixbuf)

        mainLayout.pack_start(image_renderer, True, True, 0)
        mainLayout.pack_start(button, True, True, 0)

        self.add(mainLayout)

    def editPixbuf(self, button):
        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250)
        print(self.Cover2)

Thank you very much for your help

Body:
When you've created the Gtk.Image, image_renderer, you supplied a pixbuf, self.image.

Then on your button callback, you did load an image into a pixbuf but did not update the image_renderer with the new pixbuf. You should use Gtk.Image set_from_pixbuf.

Try:

class TestGdkPixbuf(Gtk.Window):
    Cover= "image.png"
    Cover2= "image2.png"

    def __init__(self):
        Gtk.Window.__init__(self, title="TestGdkPixbuf")

        mainLayout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover, 250, 250)
        self.image_renderer = Gtk.Image.new_from_pixbuf(self.image)

        button = Gtk.Button(label='Change')
        button.connect('clicked', self.editPixbuf)

        mainLayout.pack_start(image_renderer, True, True, 0)
        mainLayout.pack_start(button, True, True, 0)

        self.add(mainLayout)

    def editPixbuf(self, button):
        self.image = GdkPixbuf.Pixbuf.new_from_file_at_size(self.Cover2, 250, 250)
        self.image_renderer.set_from_pixbuf (self.image)
        print(self.Cover2)


问:
How do i bind two radiobuttons to a data model?
I have an account update form. In that form I can set whether the account is enabled or disabled. When the update form gets loaded I would like the radiobutton group to be checked according to the database value (enabled = true or false) retrieved from the database for that particular account. I have tried to accomplish it via this code:

```<code><label>Status</label>
<div class = "control-group">
<div class="controls radio-group" id="status" name = "status">
<label class="radio-inline">
  <input type="radio" [checked] = "account.enabled === true" name="optradio1" formControlName="status" [value] = "true">Actief
</label>
<label class="radio-inline">
  <input type="radio" [checked] = "account.enabled === false" name="optradio1" formControlName="status" [value] = "false">Inactief
</label>
</div>
</div>
</code>```

But it doesen't automatically check the radiobutton corresponding to the last saved radiobutton value.

Does anyone know how I can accomplish this?

答:
don't use the event listener, it would break rule ,elegant and it pretty rude.

In addition,bad performance and slowly when you spy(listen) every single event.

Fortunately, angular supported the native event trigger to complete the radio button to deal ngModel

html

```<code><label class="radio-inline">
  <input type="radio" [checked] = "account.enabled" name="optradio1" formControlName="status" [value] = "true" (change)="account.enabled=!account.enabled" />Actief
</label>
<label class="radio-inline">
  <input type="radio" [checked] = "!account.enabled" name="optradio1" formControlName="status" [value] = "false" (change)="account.enabled=!account.enabled" />Inactief
</label>
</code>```

Despite use the (change) , there is more simple way to deal it, make a component yourself or build a Directive(really tough if you want to use CDK).

Body:
I have an account update form. In that form I can set whether the account is enabled or disabled. When the update form gets loaded I would like the radiobutton group to be checked according to the database value (enabled = true or false) retrieved from the database for that particular account. I have tried to accomplish it via this code:

Status

  <input type="radio" [checked] = "account.enabled === true" name="optradio1" formControlName="status" [value] = "true">Actief

  <input type="radio" [checked] = "account.enabled === false" name="optradio1" formControlName="status" [value] = "false">Inactief

But it doesen't automatically check the radiobutton corresponding to the last saved radiobutton value.

Does anyone know how I can accomplish this?

Body:
don't use the event listener, it would break rule ,elegant and it pretty rude.

In addition,bad performance and slowly when you spy(listen) every single event.

Fortunately, angular supported the native event trigger to complete the radio button to deal ngModel

html

<label class="radio-inline">
  <input type="radio" [checked] = "account.enabled" name="optradio1" formControlName="status" [value] = "true" (change)="account.enabled=!account.enabled" />Actief
</label>
<label class="radio-inline">
  <input type="radio" [checked] = "!account.enabled" name="optradio1" formControlName="status" [value] = "false" (change)="account.enabled=!account.enabled" />Inactief
</label>

Despite use the (change) , there is more simple way to deal it, make a component yourself or build a Directive(really tough if you want to use CDK).


问:
React - refetch child component data when the props change
I have a Parent component with state 'form_type'.  That parent has a child like

```<code><Child
    url='myroot.com?formtype=' + this.state.form_type
/>
</code>```

When I change the form_type state, I need the child to reload, getting the new url endpoint.

Any thoughts?  I can see that the parent is rendering when the state changes.

答:
When your parent gets re-rendered, then your child component's componentWillReceiveProps function will be executed and unless you return false from shouldComponentUpdate of Child, it also will re-render. Now if you wan't to receive the updated value of url in the Child component you could probably implement the componentWillReceiveProps function of Child like

```<code>componentWillReceiveProps(nextProps) {
    if(nextProps.url !== this.props.url) {
        //do something with the nextProps.url
    }

}
</code>```

Body:
I have a Parent component with state 'form_type'.  That parent has a child like

<Child
    url='myroot.com?formtype=' + this.state.form_type
/>

When I change the form_type state, I need the child to reload, getting the new url endpoint.

Any thoughts?  I can see that the parent is rendering when the state changes.

Body:
When your parent gets re-rendered, then your child component's componentWillReceiveProps function will be executed and unless you return false from shouldComponentUpdate of Child, it also will re-render. Now if you wan't to receive the updated value of url in the Child component you could probably implement the componentWillReceiveProps function of Child like

componentWillReceiveProps(nextProps) {
    if(nextProps.url !== this.props.url) {
        //do something with the nextProps.url
    }

}


问:
Write a method to print out a string "Name" multiple times
I am answering a question for an Intro to Programming class and cannot - after reading through my notes, Big Java book, and looking online - find out where to begin.

It seems as though it should be very simple, but I just need to get started.  All of this is for Java and is being worked on in Eclipse.

The task is to take in a name ("Name") and a number (int x) and display the "Name" x number of times on one line, x-1 times on another line, and so on and so on until you display the name only once.  It seems like it should be a reverse accumulator, but I'm having trouble starting my method.  How do I begin?  I know I can't multiply strings in Java like you can in python or other languages, but how can I print the "Name" x number of times without building an Array or inputing

```<code>System.out.println("name" + " " + "name" + " "...).
</code>```

Any suggestions are appreciated.  I am a novice at this.  Thank you!

答:
```<code>public class WithoutLoop
{
      static int count;
   public static void repeat(String s)
   {
       while(count <= 10)
       {
           System.out.println(s);
           count++;
       }
   }
   public static void main(String[] args)
   {
        repeat("hello");
   }
}
</code>```

Body:
I am answering a question for an Intro to Programming class and cannot - after reading through my notes, Big Java book, and looking online - find out where to begin.

It seems as though it should be very simple, but I just need to get started.  All of this is for Java and is being worked on in Eclipse.

The task is to take in a name ("Name") and a number (int x) and display the "Name" x number of times on one line, x-1 times on another line, and so on and so on until you display the name only once.  It seems like it should be a reverse accumulator, but I'm having trouble starting my method.  How do I begin?  I know I can't multiply strings in Java like you can in python or other languages, but how can I print the "Name" x number of times without building an Array or inputing

System.out.println("name" + " " + "name" + " "...).

Any suggestions are appreciated.  I am a novice at this.  Thank you!


问:
Upload file to directory on server using Java and JSP - can't get path right
On my vps, I want to upload a file to the Logos directory.
The directory structure is as follows on my vps -

/home/webadmin/domain.com/html/Logos

When a file is uploaded through my jsp page, that file is renamed, and then I want to put it into the Logos directory.... but I can't seem to get the path right in my servlet code.

Snippet of servlet code -

```<code>String upload_directory="/Logos/"; // path to the upload folder

File savedFile = new File(upload_directory,BusinessName+"_Logo."+fileExtension);

//.....
//file saved to directory
//.....
</code>```

I've tried many variations, but still fail. What is the proper way to specify the path?

Edited

The problem with using getServletContext() is that it returns the path to the directory where Tomcat and my webapp is...whereas I want to reach the directory where my html and image files are - under the root directory of the vps. How do I specify that path?

```<code>    String server_path = getServletContext().getRealPath("/"); // get server path.

    //server_path = /opt/tomcat6/webapps/domain.com/

    String upload_directory = "Logos/"; // get path to the upload folder.

    String complete_path = server_path + upload_directory; // get the complete path to the upload folder.

    //complete_path = /opt/tomcat6/webapps/domain.com/Logos/

    File savedFile = new File(complete_path,"NewLogo.jpg");

    //savedFile = /opt/tomcat6/webapps/domain.com/Logos/NewLogo.jpg
</code>```

答: The path "/Logos/" will attempt to create the file in the root of your system, which is not what you want. Look at the ServletContext.getRealPath() method.</p>

Body:
On my vps, I want to upload a file to the Logos directory.
The directory structure is as follows on my vps -

/home/webadmin/domain.com/html/Logos

When a file is uploaded through my jsp page, that file is renamed, and then I want to put it into the Logos directory.... but I can't seem to get the path right in my servlet code.

Snippet of servlet code -

String upload_directory="/Logos/"; // path to the upload folder

File savedFile = new File(upload_directory,BusinessName+"_Logo."+fileExtension);

//.....
//file saved to directory
//.....

I've tried many variations, but still fail. What is the proper way to specify the path?

Edited

The problem with using getServletContext() is that it returns the path to the directory where Tomcat and my webapp is...whereas I want to reach the directory where my html and image files are - under the root directory of the vps. How do I specify that path?

    String server_path = getServletContext().getRealPath("/"); // get server path.

    //server_path = /opt/tomcat6/webapps/domain.com/

    String upload_directory = "Logos/"; // get path to the upload folder.

    String complete_path = server_path + upload_directory; // get the complete path to the upload folder.

    //complete_path = /opt/tomcat6/webapps/domain.com/Logos/

    File savedFile = new File(complete_path,"NewLogo.jpg");

    //savedFile = /opt/tomcat6/webapps/domain.com/Logos/NewLogo.jpg


问:
Using self join/inner join to get the data by adding all the above rows data, in SQL Server
I am working with SQL server, the query details are as below:

Need to get the calculative column whose result will be the addition of all the above rows. And I can't use correlated queries, Lag and Lead as it is not supported.

I tried using self-join/inner join/left outer join, the only problem I am facing is due to group by clause of other columns the result is not coming as expected.

For example, data is like

Expected Output

But the output I am getting due to group by clause applied on Column4.
Output getting is like below

Is there some alternative of GROUP BY clause or other alternatives?

答:
using subquery for earlier version of 2012

```<code>SELECT  Column1,Column2,Column3,
        ( SELECT    SUM(y.Column3)
          FROM      Data y
          WHERE     y.Column1 = x.Column1
                    AND y.Column2 <= x.Column2
        ) AS [Column5(Summation of Column3)]
FROM    Data x
ORDER BY 1 ,2 ,3;
</code>```

Query result

Body:
using subquery for earlier version of 2012

SELECT  Column1,Column2,Column3,
        ( SELECT    SUM(y.Column3)
          FROM      Data y
          WHERE     y.Column1 = x.Column1
                    AND y.Column2 <= x.Column2
        ) AS [Column5(Summation of Column3)]
FROM    Data x
ORDER BY 1 ,2 ,3;

Query result


问:
How to make messages not stretch before they scroll
We are creating a messenger with Google's Material and have the trouble that if you enter messages to a grid, the first message will fill the entire area, when adding a second one, both will take up half the page, this goes on until the messages can't get smaller until finally it starts to scroll. Then the scroll automation to scroll down works, but it looks stupid at the beginning.

not so good looking

This is what it looks like once the messages can't get smaller

```<code> <div class="mdl-tabs__panel is-active chatbox" id="newest-panel">

       <section class="mdl-grid chatdiv">

          <div class=" chat mdl-cell mdl-cell--3-col mdl-cell--7-col-tablet mdl-cell--11-col-desktop">
            <div class="NameOfSender">Anton</div>
            <div class="ChatMessage">Inwiefern beeinflusst das autonome Fahren meinen Alltag?</div>
            <div class="Timestamp">- vor 3 min</div>
          </div>

    .chatbox{

  position: fixed;
  width: 100%;
  height: 81vh;
  padding-bottom: 1px;
  overflow-y: scroll;
}

.chatdiv{

  position: fixed;
  width: 100%;
  height: 50vh;
  overflow-y: scroll;
}

$("#messagefield").stop().animate({ scrollTop: $("#messagefield")[0].scrollHeight}, 1000);
</code>```

How can I fix this?
IMPORTANT NOTE: The new messages are dynamically added via javascript!

Thanks in advance!

答:
You should try using the max-height attribute on .chatbox

```<code>.chatbox {
  position: fixed;
  width: 100%;
  height: 81vh;
  max-height: /*whatever suits*/; /* <-- Here is the fix*/
  padding-bottom: 1px;
  overflow-y: scroll;
}

.chatdiv {
  position: fixed;
  width: 100%;
  height: 50vh;
  overflow-y: scroll;
}
</code>```

Body:
We are creating a messenger with Google's Material and have the trouble that if you enter messages to a grid, the first message will fill the entire area, when adding a second one, both will take up half the page, this goes on until the messages can't get smaller until finally it starts to scroll. Then the scroll automation to scroll down works, but it looks stupid at the beginning.

not so good looking

This is what it looks like once the messages can't get smaller

Anton

Inwiefern beeinflusst das autonome Fahren meinen Alltag?

- vor 3 min

    .chatbox{

  position: fixed;
  width: 100%;
  height: 81vh;
  padding-bottom: 1px;
  overflow-y: scroll;
}

.chatdiv{

  position: fixed;
  width: 100%;
  height: 50vh;
  overflow-y: scroll;
}

$("#messagefield").stop().animate({ scrollTop: $("#messagefield")[0].scrollHeight}, 1000);

How can I fix this?
IMPORTANT NOTE: The new messages are dynamically added via javascript!

Thanks in advance!

Body:
You should try using the max-height attribute on .chatbox

.chatbox {
  position: fixed;
  width: 100%;
  height: 81vh;
  max-height: /*whatever suits*/; /* <-- Here is the fix*/
  padding-bottom: 1px;
  overflow-y: scroll;
}

.chatdiv {
  position: fixed;
  width: 100%;
  height: 50vh;
  overflow-y: scroll;
}


问:
Can't re-instantiate/respawn object I've destroyed in Unity3D
I've 2 scripts. 1 makes objects and the other destroys them.

I first press OnSave button which runs script #1 and creates my objects. (there's more than one, although here in the script just shows one, I shortened for the sake of question)

then I press OnReset button which destroys created objects/prefabs. But when I press OnSave again, it doesn't recreated objects.

These 2 scripts are attached to 2 different gameObjects

here's what I have:

script #1:

```<code>public GameObject go;
public static volatile List<GameObject> prefab = new List<GameObject>();

public class OnSave : MonoBehaviour
{
public void Start2()
{
                var newObj = Instantiate(go);
                newObj.transform.parent = GameObject.Find("MOOSE").transform;
                newObj.GetComponent<Renderer>().material.color = Color.green;
                newObj.transform.localPosition = new Vector3(1.0,1.0,1.0)
                prefab.Add(newObj);

}
}
</code>```

script #2

```<code>public class OnReset: MonoBehaviour
{
foreach (GameObject obj in prefab)
{
Destroy(obj);
}
}
</code>```

I'm using the latest version of Unity. I have to destroy these objects and recreate them

答:
You need a prefab to be able to reinstantiate the object, but the operation of destroying and reinstantiating is heavy, so normally you use a pooling manager of sort like https://www.assetstore.unity3d.com/en/#!/content/47242 (disclaimer: I'm the author of this one) or https://www.assetstore.unity3d.com/en/#!/content/23931.

Here's the official Unity totorial about pooling objects: https://unity3d.com/learn/tutorials/topics/scripting/object-pooling

Body:
I've 2 scripts. 1 makes objects and the other destroys them.

I first press OnSave button which runs script #1 and creates my objects. (there's more than one, although here in the script just shows one, I shortened for the sake of question)

then I press OnReset button which destroys created objects/prefabs. But when I press OnSave again, it doesn't recreated objects.

These 2 scripts are attached to 2 different gameObjects

here's what I have:

script #1:

public GameObject go;
public static volatile List<GameObject> prefab = new List<GameObject>();

public class OnSave : MonoBehaviour
{
public void Start2()
{
                var newObj = Instantiate(go);
                newObj.transform.parent = GameObject.Find("MOOSE").transform;
                newObj.GetComponent<Renderer>().material.color = Color.green;
                newObj.transform.localPosition = new Vector3(1.0,1.0,1.0)
                prefab.Add(newObj);

}
}

script #2

public class OnReset: MonoBehaviour
{
foreach (GameObject obj in prefab)
{
Destroy(obj);
}
}

I'm using the latest version of Unity. I have to destroy these objects and recreate them


问:
What is the difference between min SDK version/target SDK version vs. compile SDK version?
What are the differences between "min sdk version/target sdk version" and "compile sdk version"? I know what min and target sdk means, but what does compile sdk version mean?

In Eclipse, I have min/max and target sdk, but in android studio there are these three settings.

答:
minSdkVersion, targetSdkVersion, compileSdkVersion

The formula is

```<code>minSdkVersion <= targetSdkVersion <= compileSdkVersion
</code>```

minSdkVersion - is a marker that defines a minimum Android version on which the application will be able to install. Also, it is used by Lint to prevent calling API that doesn’t exist. Also, it has an impact on Build Time. So you can use build flavors to override minSdkVersion to the maximum during the development. It will help to make the build faster using all improvements that the Android team provides for us. For example, some features of Java 8 are available only when you are using specific versions of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of these new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read the official documentation.

For example:

Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is the SDK Platform version and tells Gradle which Android SDK uses to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here.
Also, I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]

ContentLicense: CC BY-SA 4.0

Body:
minSdkVersion, targetSdkVersion, compileSdkVersion

The formula is

minSdkVersion <= targetSdkVersion <= compileSdkVersion

minSdkVersion - is a marker that defines a minimum Android version on which the application will be able to install. Also, it is used by Lint to prevent calling API that doesn’t exist. Also, it has an impact on Build Time. So you can use build flavors to override minSdkVersion to the maximum during the development. It will help to make the build faster using all improvements that the Android team provides for us. For example, some features of Java 8 are available only when you are using specific versions of minSdkVersion.

targetSdkVersion - If AndroidOS version is >= targetSdkVersion it says Android system to turn on specific(new) behavior changes. *Please note that some of these new behaviors will be turned on by default even if thought targetSdkVersion is <, you should read the official documentation.

For example:

Starting in Android 6.0 (API level 23) Runtime Permissions were introduced. If you set targetSdkVersion to 22 or lower your application does not ask a user for some permission in run time.

Starting in Android 8.0 (API level 26), all notifications must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).

Starting in Android 9 (API level 28), Web-based data directories separated by process. If targetSdkVersion is 28+ and you create several WebView in different processes you will get java.lang.RuntimeException

compileSdkVersion - actually it is the SDK Platform version and tells Gradle which Android SDK uses to compile. When you want to use new features or debug .java files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion - level 28. compileSdkVersion is not included in your APK: it is purely used at compile time. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version

You can read more about it here.
Also, I would recommend you to take a look at the example of migration to Android 8.0.

[buildToolsVersion]


问:
Headless build in Eclipse: how to retrieve result value
I'm trying to use Eclipse CDT's headlessbuild feature for integrating Eclipse with TeamCity. I use a command line call to build my projects as descriped in this question. If there is a compilation error, a message box pops up saying "Java was started but returned exit code=1". I'd rather not have this message but get the return code so I can process it further in my script. Is there any way to do this?

Thanks!

答:
You can suppress the popup and redirect output to be included with your script:

Add "--launcher.suppressErrors" to your command line arguments for eclipse

The error needs to be tracked down in the GUI from what I can tell, because the headless mode doesn't support very good error reporting from sub-tasks yet.

From there I used output from the GUI-based build to narrow down why my project failed to build.

Sources:

http://dev.eclipse.org/mhonarc/lists/cdt-dev/msg15343.html

http://www.eclipse.org/forums/index.php?t=msg&goto=481938&S=c88d71260a7d130eebdccb8f2e5537f2

http://www.eclipse.org/forums/index.php?t=msg&goto=481938&S=c88d71260a7d130eebdccb8f2e5537f2

https://bugs.eclipse.org/bugs/show_bug.cgi?id=209080#c21


问:
Eclipse no longer makes import suggestions in quickfixes
eclipse isn't making import suggestions anymore. I don't know why it stopped. Here is an example.

答: It can happen when you have some brackets missing in your source code, and the suggestion system just cannot figure out how to do suggestions anymore.</p>


问:
Want data added to the Query via Left Outer Joint to NOT repeat
I have a database structure (ER diagram below) that has three level of hierarchical data and the fourth level of optional data.

If I write a query to get de-normalized data of three levels - level 1 to level 3 with sample data across three tables shown as below:

When queried, this layout of the data is very straight forward and as expected as below:

Upon running the below query, I get the following output (And I have tried various combinations by clubbing the set of L1 to L4 and moving one L4 out as a another query and then joining the set L1 - L4 etc.) - again this is on the expected lines.

```<code>SELECT        [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId,
                         ManagementResponse.ManagementResponseTest
FROM            Category INNER JOIN
                         [Group] ON Category.GroupId = [Group].GroupId INNER JOIN
                         RLI ON Category.CategoryId = RLI.CategoryId LEFT OUTER JOIN
                         ManagementResponse ON RLI.RLIId = ManagementResponse.RLIId LEFT OUTER JOIN
                         Comment ON RLI.RLIId = Comment.RLIId
</code>```

However, I need data in the following format - and this is what I am unable to figure out how to get (I don't want the level 4 data to repeat as I add additional level 4 data via left outer joins):

答:
You need to specify that Comment.CommentId is equal to ManagementResponse.ManagementResponseId or either is null. That can be part of a JOIN or a separate WHERE

```<code>SELECT          [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId,
                         ManagementResponse.ManagementResponseTest
FROM            [Category]
INNER JOIN      [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN      [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [ManagementResponse] ON RLI.RLIId = ManagementResponse.RLIId
LEFT OUTER JOIN [Comment] ON RLI.RLIId = Comment.RLIId
WHERE           ManagementResponse.ManagementResponseId = Comment.CommentId OR ManagementResponse.ManagementResponseId IS NULL OR Comment.CommentId IS NULL
</code>```

This assumes that those IDs begin equal is the relationship you want to model. The example data seems to show this, but it could be a coincidence of how you assembled the example. Alternatively, if there is no relationship between Comment and ManagementResponse besides RLIId, something like

```<code>WITH CommentAndResponse AS (
    SELECT Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId, ManagementResponse.ManagementResponseTest,
        COALESCE(Comment.RLIId, ManagementResponse.RLIId) AS RLIId,
        ROW_NUMBER() OVER (ORDER BY Comment.CommentId, ManagementResponse.ManagementResponseId, PARTITION BY Comment.RLIId, ManagementResponse.RLIId) AS rn
    FROM Comment
    FULL JOIN ManagementResponse ON Comment.RLIId = ManagementResponse.RLIId)
SELECT          [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, CommentAndResponse.CommentId, CommentAndResponse.CommentText, CommentAndResponse.ManagementResponseId, CommentAndResponse.ManagementResponseTest
FROM            [Category]
INNER JOIN      [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN      [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [CommentAndResponse] ON RLI.RLIId = CommentAndResponse.RLIId AND CommentAndResponse.rn = 1
</code>```

Body:
I have a database structure (ER diagram below) that has three level of hierarchical data and the fourth level of optional data.

If I write a query to get de-normalized data of three levels - level 1 to level 3 with sample data across three tables shown as below:

When queried, this layout of the data is very straight forward and as expected as below:

Upon running the below query, I get the following output (And I have tried various combinations by clubbing the set of L1 to L4 and moving one L4 out as a another query and then joining the set L1 - L4 etc.) - again this is on the expected lines.

SELECT        [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId,
                         ManagementResponse.ManagementResponseTest
FROM            Category INNER JOIN
                         [Group] ON Category.GroupId = [Group].GroupId INNER JOIN
                         RLI ON Category.CategoryId = RLI.CategoryId LEFT OUTER JOIN
                         ManagementResponse ON RLI.RLIId = ManagementResponse.RLIId LEFT OUTER JOIN
                         Comment ON RLI.RLIId = Comment.RLIId

However, I need data in the following format - and this is what I am unable to figure out how to get (I don't want the level 4 data to repeat as I add additional level 4 data via left outer joins):

Body:
You need to specify that Comment.CommentId is equal to ManagementResponse.ManagementResponseId or either is null. That can be part of a JOIN or a separate WHERE

SELECT          [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId,
                         ManagementResponse.ManagementResponseTest
FROM            [Category]
INNER JOIN      [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN      [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [ManagementResponse] ON RLI.RLIId = ManagementResponse.RLIId
LEFT OUTER JOIN [Comment] ON RLI.RLIId = Comment.RLIId
WHERE           ManagementResponse.ManagementResponseId = Comment.CommentId OR ManagementResponse.ManagementResponseId IS NULL OR Comment.CommentId IS NULL

This assumes that those IDs begin equal is the relationship you want to model. The example data seems to show this, but it could be a coincidence of how you assembled the example. Alternatively, if there is no relationship between Comment and ManagementResponse besides RLIId, something like

WITH CommentAndResponse AS (
    SELECT Comment.CommentId, Comment.CommentText, ManagementResponse.ManagementResponseId, ManagementResponse.ManagementResponseTest,
        COALESCE(Comment.RLIId, ManagementResponse.RLIId) AS RLIId,
        ROW_NUMBER() OVER (ORDER BY Comment.CommentId, ManagementResponse.ManagementResponseId, PARTITION BY Comment.RLIId, ManagementResponse.RLIId) AS rn
    FROM Comment
    FULL JOIN ManagementResponse ON Comment.RLIId = ManagementResponse.RLIId)
SELECT          [Group].GroupId, [Group].GroupName, Category.CategoryId, Category.CategoryName, RLI.RLIId, RLI.RLIText, CommentAndResponse.CommentId, CommentAndResponse.CommentText, CommentAndResponse.ManagementResponseId, CommentAndResponse.ManagementResponseTest
FROM            [Category]
INNER JOIN      [Group] ON Category.GroupId = [Group].GroupId
INNER JOIN      [RLI] ON Category.CategoryId = RLI.CategoryId
LEFT OUTER JOIN [CommentAndResponse] ON RLI.RLIId = CommentAndResponse.RLIId AND CommentAndResponse.rn = 1


问:
Garbled text when printing website
I'm working on a website where the users will be printing pages from the site fairly frequently, in order to give them to people without internet access. Some of the text comes out garbled when printed on our users' office printers:

That's supposed to say Reduced Fare and Free Ride Programs, Chicago Transit Authority.

My first thought was that this has something to do with the font we're using, so I changed that text to have font-family: 'Times New Roman', serif. Some google research made me think those font settings were widely supported and shouldn't cause problems, but our users are still having the issue.

Even if you don't know exactly how to fix this problem, I would appreciate suggestions about

What other than the font selection could be causing it?

If you do think it has something to do with the font, what is a good font to use? Or how could I figure that out, is it printer-specific?

Update

The page is being printed from the browser, which for this particular group of users is IE8. I'm not sure what version of Windows they're on. I've tested this on a Windows machine with IE8 in our office, and was not able to reproduce the issue. So while the browser might be a factor, I don't believe it's the only factor.

Second Update

The font we're using is Libre Baskerville, which we're loading through the Google Fonts API. It renders fine on screen, and actually prints with no issue from some of the printers at our client's office. The text only comes out garbled when printed on a Lexmark MS410dn.

答: For the record (and anyone reading this with a similar issue), I had exactly the same issue trying to print a document written in Libre Baskerville on my laptop, in LibreOffice.  The font is embedded in both RTF and PDF formats and the text is garbled in the same way.  I also worked around the issue by changing to a different font.  It's a pity as LibreBaskerville is a nice font.</p>

Title: Garbled text when printing website


问:
How to add a set on numbers on a two dimensional array based on the results of first row in javascript
I have a two dimensional array:

```<code>var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];
</code>```

How can I make a new array where in the result would be something like this.

```<code>newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];
</code>```

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

答:
You can use array#reduce and associate each array to the name in it. In case of repeated name, add its numeric value. After that, get the result using Object.values()

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];

var result = array.reduce((res,[name,val]) => {
  if(name in res)
    res[name][1] += val;
  else
    res[name] = [name,val];
  return res;
},Object.create(null));

console.log(Object.values(result));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have a two dimensional array:

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];

How can I make a new array where in the result would be something like this.

newArray = [["Alex", 30], ["Sam", 25], ["Rob", 20]];

So basically what I want is to get the sum of the numbers for a particular individual.

Any help would be appreciated. I don't know if I have been able to explain the problem properly.

Body:
You can use array#reduce and associate each array to the name in it. In case of repeated name, add its numeric value. After that, get the result using Object.values()

var array = [["Alex", 10], ["Sam", 15], ["Alex", 20], ["Rob", 20], ["Sam", 10]];

var result = array.reduce((res,[name,val]) => {
  if(name in res)
    res[name][1] += val;
  else
    res[name] = [name,val];
  return res;
},Object.create(null));

console.log(Object.values(result));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Stop BeautifulSoup from removing whitespace
BeautifulSoup is removing whitespace between before newlines tags:

```<code>print BeautifulSoup("<?xml version='1.0' encoding='UTF-8'?><section>    \n</section>")
</code>```

The code above prints:

```<code><?xml version="1.0" encoding="utf-8"?>
<section>
</section>
</code>```

Notice that the four spaces after the section tag are missing! Interestingly, if I do:

```<code>print BeautifulSoup("<?xml version='1.0' encoding='UTF-8'?><section>a    \n</section>")
</code>```

I get:

```<code><?xml version="1.0" encoding="utf-8"?>
<section>a
</section>
</code>```

The four spaces after 'a' are now present! How can I get the four spaces to show in the original print statement?

答:
As a workaround, you could try replacing all
...
 with ```...</section></code> before parsing. BeautifulSoup would then fully preserve the spaces. For example:</p>

```from bs4 import BeautifulSoup
import re

html = "<?xml version='1.0' encoding='UTF-8'?>
    \n
"
html = re.sub(r'(\</?)(section)(\>)', r'\1pre\3', html)
soup = BeautifulSoup(html, "lxml")

print repr(soup.pre.text)    # repr used to show where the spaces are
```

<p>Giving you:</p>

```u'    \n'
```

Body:
BeautifulSoup is removing whitespace between before newlines tags:

print BeautifulSoup("<?xml version='1.0' encoding='UTF-8'?>
    \n
")

The code above prints:

<?xml version="1.0" encoding="utf-8"?>

Notice that the four spaces after the section tag are missing! Interestingly, if I do:

print BeautifulSoup("<?xml version='1.0' encoding='UTF-8'?>
a    \n
")

I get:

<?xml version="1.0" encoding="utf-8"?>

a

The four spaces after 'a' are now present! How can I get the four spaces to show in the original print statement?

Body:
As a workaround, you could try replacing all <section>...</section> with <pre>...</section> before parsing. BeautifulSoup would then fully preserve the spaces. For example:

from bs4 import BeautifulSoup
import re

html = "<?xml version='1.0' encoding='UTF-8'?><section>    \n</section>"
html = re.sub(r'(\</?)(section)(\>)', r'\1pre\3', html)
soup = BeautifulSoup(html, "lxml")

print repr(soup.pre.text)    # repr used to show where the spaces are

Giving you:

u'    \n'


问:
Passing Data Between Controllers via a Service in AngularJS Does Not Work
I have two controllers like so:

```<code>myApp.controller('Ctrl1', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){
    DataService.set('HelloWorld', 'TheValue')
    alert(DataService.value.TheValue + 'in Ctrl1');
}]);

myApp.controller('Ctrl2', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){
    alert(DataService.value.TheValue + ' in Ctrl2');
}]);
</code>```

And my service is defined like so:

```<code>myApp.service("DataService", function () {

    var data = {
        TheValue: null
    };

    function set(value, field) {
        data[field] = value;
    }

    return {
        set: set,
        value: data
    };
});
</code>```

In Ctrl1, the alert shows that the value of TheValue is correctly HelloWorld. But when I navigate to Ctrl2, TheValue becomes null.

How do I get the TheValue value in DataService to persist between controllers?

Edit:

Here is how I navigate between controllers:

My application is a Asp.Net MVC app. Ctrl1 is the AngularJS controller for the Dashboard page, while Ctrl2 is the controller for the next page via a button click and the routing to the new Asp.Net controller.

Dashboard Page snippet:

```<code><body>
<div class="row" ng-controller="Ctrl1">

    <div class="col-sm-4">
            <ul class="dashboard-list">
                <li>
                    <div class="tile">
                        <a href="/NextPage" title="The Next Page">
                            <h2>Schedule New Visit</h2>
                        </a>
                    </div>
                </li>
            </ul>
    </div>
    </body>
</code>```

Then, NextPage is just like so:

```<code><body>
    <div ng-controller="Ctrl2"  class="ng-cloak">
          @*Page stuffz here...*@
    </div>
</body>
</code>```

答:
It works fie with the following code. Make sure you have the controller set.

DEMO

var myApp = angular.module('testApp',[]);

myApp.controller('Ctrl1', ['$scope', 'DataService', function ($scope, DataService){
$scope.setData = function(){
    DataService.set('HelloWorld', 'TheValue')
    alert(DataService.value.TheValue + 'in Ctrl1');
  };
}]);

myApp.controller('Ctrl2', ['$scope', 'DataService', function ($scope, DataService){
$scope.getData = function(){
    alert(DataService.value.TheValue + ' in Ctrl2');
   };
}]);

myApp.service("DataService", function () {

    var data = {
        TheValue: null
    };

    function set(value, field) {
        data[field] = value;
    }

    return {
        set: set,
        value: data
    };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" >
<div ng-controller="Ctrl1">
<button ng-click="setData()">SET
</button>
</div>
<div ng-controller="Ctrl2">
<button ng-click="getData()"> GET
</button>
</div>

</body></code>```

Body:
I have two controllers like so:

myApp.controller('Ctrl1', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){
    DataService.set('HelloWorld', 'TheValue')
    alert(DataService.value.TheValue + 'in Ctrl1');
}]);

myApp.controller('Ctrl2', ['$scope', '$filter', '$http', 'DataService', function ($scope, $filter, $http, DataService){
    alert(DataService.value.TheValue + ' in Ctrl2');
}]);

And my service is defined like so:

myApp.service("DataService", function () {

    var data = {
        TheValue: null
    };

    function set(value, field) {
        data[field] = value;
    }

    return {
        set: set,
        value: data
    };
});

In Ctrl1, the alert shows that the value of TheValue is correctly HelloWorld. But when I navigate to Ctrl2, TheValue becomes null.

How do I get the TheValue value in DataService to persist between controllers?

Edit:

Here is how I navigate between controllers:

My application is a Asp.Net MVC app. Ctrl1 is the AngularJS controller for the Dashboard page, while Ctrl2 is the controller for the next page via a button click and the routing to the new Asp.Net controller.

Dashboard Page snippet:

Schedule New Visit

Then, NextPage is just like so:

          @*Page stuffz here...*@

Body:
It works fie with the following code. Make sure you have the controller set.

DEMO

var myApp = angular.module('testApp',[]);

myApp.controller('Ctrl1', ['$scope', 'DataService', function ($scope, DataService){
$scope.setData = function(){
    DataService.set('HelloWorld', 'TheValue')
    alert(DataService.value.TheValue + 'in Ctrl1');
  };
}]);

myApp.controller('Ctrl2', ['$scope', 'DataService', function ($scope, DataService){
$scope.getData = function(){
    alert(DataService.value.TheValue + ' in Ctrl2');
   };
}]);

myApp.service("DataService", function () {

    var data = {
        TheValue: null
    };

    function set(value, field) {
        data[field] = value;
    }

    return {
        set: set,
        value: data
    };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp" >
<div ng-controller="Ctrl1">
<button ng-click="setData()">SET
</button>
</div>
<div ng-controller="Ctrl2">
<button ng-click="getData()"> GET
</button>
</div>

</body>


问:
How to change register link in laravel 5.5?
I want to change my register link to  domain.com/register?ref=abc
how to do it in laravel 5.5?</p>

```<code><a style="margin-bottom: 5px;font-size: 17px;font-weight: 600;" href="{{ route('login') }}" class=""><i class="fa fa-sign-in"></i> Log In</a>
                           <a style="margin-bottom: 5px;font-size: 17px;font-weight: 600;" href="{{ route('register') }}" class=""><i class="fa fa-user-plus"></i> Registration</a>
</code>```

答:
1. Overrating the default authroutes :

You can overrite the default auth routes by putting on your routes/web.php and changing them to your needs :

```<code>{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout')->name('logout');

    // Registration Routes...
    $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
    $this->post('register', 'Auth\RegisterController@register');

    // Password Reset Routes...
    $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
    $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
    $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
    $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}
</code>```

2. Changing it directly on the html anchor tag :

You can omit the named routes and use a direct link :

```<code><a style="margin-bottom: 5px;font-size: 17px;font-weight: 600;" href="http://example.com/register?ref=abc" class=""><i class="fa fa-user-plus"></i> Registration</a>
</code>```

OR

```<code><a style="margin-bottom: 5px;font-size: 17px;font-weight: 600;" href="{{ route('register') }}/?ref=abc" class=""><i class="fa fa-user-plus"></i> Registration</a>
</code>```

Hope that helps

Body:
I want to change my register link to  domain.com/register?ref=abc
how to do it in laravel 5.5?

 Log In
                            Registration

Body:
1. Overrating the default authroutes :

You can overrite the default auth routes by putting on your routes/web.php and changing them to your needs :

{
    // Authentication Routes...
    $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
    $this->post('login', 'Auth\LoginController@login');
    $this->post('logout', 'Auth\LoginController@logout')->name('logout');

    // Registration Routes...
    $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
    $this->post('register', 'Auth\RegisterController@register');

    // Password Reset Routes...
    $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm');
    $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
    $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm');
    $this->post('password/reset', 'Auth\ResetPasswordController@reset');
}

2. Changing it directly on the html anchor tag :

You can omit the named routes and use a direct link :

<a style="margin-bottom: 5px;font-size: 17px;font-weight: 600;" href="http://example.com/register?ref=abc" class=""><i class="fa fa-user-plus"></i> Registration</a>

OR

<a style="margin-bottom: 5px;font-size: 17px;font-weight: 600;" href="{{ route('register') }}/?ref=abc" class=""><i class="fa fa-user-plus"></i> Registration</a>

Hope that helps


问:
python boto3 connection error with no apparent cause
I'm hitting an error with code that connects to AWS using boto3. The error just started yesterday afternoon, and between the last time I didn't get the error and the first time I got the error I don't see anything that changed.

The error is:

```<code>botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL:
</code>```

In .aws/config I have:

```<code>$ cat ~/.aws/config
[default]
region=us-east-1
</code>```

Here's what I know:

Using the same AWS credentials and config on another machine, I don't see the error.

Using different AWS credentials and config on the same machine, I do see the error.

I'm the only one in our group that has this issue for any credentials on any machine.

I don't think I changed anything that would affect this between the last time this worked and the first time it didn't. It seems like I'd have had to change some AWS specific configuration on my side or some low level libraries, and I didn't make any such change. I was talking with a colleague for 30-45 minutes and when I returned and picked up where I left off the issue first appeared.

Any thoughts or ideas on troubleshooting this?

Full exception dump follows.

```<code>$ python
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> boto3.client('ec2').describe_regions()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/botocore/client.py", line 200, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Library/Python/2.7/site-packages/botocore/client.py", line 244, in _make_api_call
    operation_model, request_dict)
  File "/Library/Python/2.7/site-packages/botocore/endpoint.py", line 173, in make_request
    return self._send_request(request_dict, operation_model)
  File "/Library/Python/2.7/site-packages/botocore/endpoint.py", line 203, in _send_request
    success_response, exception):
  File "/Library/Python/2.7/site-packages/botocore/endpoint.py", line 267, in _needs_retry
    caught_exception=caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/hooks.py", line 226, in emit
    return self._emit(event_name, kwargs)
  File "/Library/Python/2.7/site-packages/botocore/hooks.py", line 209, in _emit
    response = handler(**kwargs)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 183, in __call__
    if self._checker(attempts, response, caught_exception):
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 250, in __call__
    caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 273, in _should_retry
    return self._checker(attempt_number, response, caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 313, in __call__
    caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 222, in __call__
    return self._check_caught_exception(attempt_number, caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 355, in _check_caught_exception
    raise caught_exception
botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://ec2.us-east-1.amazonaws.com/"
</code>```

答:
I just had a similar issue. All of a sudden, no connection possible anymore to my s3 through boto3 on django while I had still the possibility to do the actions on my Heroku environment.

Appeared I recently installed the amazon CLI where my configuration was different and the CLI overrules the environment variables... Damn. took me 3 hours to find.

through aws configure I now set

AWS Access Key ID [****************MPIA]: "your true key here without quotes"
AWS Secret Access Key [****************7DWm]: "your true secret access key here without quotes"
Default region name [eu-west-1]: "your true region here without quotes"
Default output format [None]: [here i did just an enter in order not to change this]

Just posting this for the sake of anyone having this issue.

Body:
I'm hitting an error with code that connects to AWS using boto3. The error just started yesterday afternoon, and between the last time I didn't get the error and the first time I got the error I don't see anything that changed.

The error is:

botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL:

In .aws/config I have:

$ cat ~/.aws/config
[default]
region=us-east-1

Here's what I know:

Using the same AWS credentials and config on another machine, I don't see the error.

Using different AWS credentials and config on the same machine, I do see the error.

I'm the only one in our group that has this issue for any credentials on any machine.

I don't think I changed anything that would affect this between the last time this worked and the first time it didn't. It seems like I'd have had to change some AWS specific configuration on my side or some low level libraries, and I didn't make any such change. I was talking with a colleague for 30-45 minutes and when I returned and picked up where I left off the issue first appeared.

Any thoughts or ideas on troubleshooting this?

Full exception dump follows.

$ python
Python 2.7.10 (default, Jul 14 2015, 19:46:27)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto3
>>> boto3.client('ec2').describe_regions()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/botocore/client.py", line 200, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/Library/Python/2.7/site-packages/botocore/client.py", line 244, in _make_api_call
    operation_model, request_dict)
  File "/Library/Python/2.7/site-packages/botocore/endpoint.py", line 173, in make_request
    return self._send_request(request_dict, operation_model)
  File "/Library/Python/2.7/site-packages/botocore/endpoint.py", line 203, in _send_request
    success_response, exception):
  File "/Library/Python/2.7/site-packages/botocore/endpoint.py", line 267, in _needs_retry
    caught_exception=caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/hooks.py", line 226, in emit
    return self._emit(event_name, kwargs)
  File "/Library/Python/2.7/site-packages/botocore/hooks.py", line 209, in _emit
    response = handler(**kwargs)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 183, in __call__
    if self._checker(attempts, response, caught_exception):
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 250, in __call__
    caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 273, in _should_retry
    return self._checker(attempt_number, response, caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 313, in __call__
    caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 222, in __call__
    return self._check_caught_exception(attempt_number, caught_exception)
  File "/Library/Python/2.7/site-packages/botocore/retryhandler.py", line 355, in _check_caught_exception
    raise caught_exception
botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://ec2.us-east-1.amazonaws.com/"


问:
Optimising asyncronus HttpClient requests
I have made a class to handle multiple HTTP GET requests.  It looks something like this:

```<code>public partial class MyHttpClass : IDisposable
{
    private HttpClient theClient;
    private string ApiBaseUrl = "https://example.com/";

    public MyHttpClass()
    {

        this.theClient = new HttpClient();
        this.theClient.BaseAddress = new Uri(ApiBaseUrl);
        this.theClient.DefaultRequestHeaders.Accept.Clear();
        this.theClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<JObject> GetAsync(string reqUrl)
    {

        var returnObj = new JObject();
        var response = await this.theClient.GetAsync(reqUrl);

        if (response.IsSuccessStatusCode)
        {
            returnObj = await response.Content.ReadAsAsync<JObject>();
            Console.WriteLine("GET successful");

        }
        else
        {
            Console.WriteLine("GET failed");
        }

        return returnObj;
    }
    public void Dispose()
    {
        theClient.Dispose();
    }
}
</code>```

I am then queueing multiple requets by using a loop over Task.Run() and then after Task.WaitAll() in the manner of:

```<code>public async Task Start()
{
    foreach(var item in list)
    {
        taskList.Add(Task.Run(() => this.GetThing(item)));
    }
    Task.WaitAll(taskList.ToArray());
}

public async Task GetThing(string url)
{
    var response = await this.theClient.GetAsync(url);

    // some code to process and save response

}
</code>```

It definitiely works faster than synchonus operation but it is not as fast as I expected.  Based on other advice I think the local threadpool is slowing me down.  MSDN suggest I should specify it as a long running task but I can't see a way to do that calling it like this.

Right now I haven't got into limiting threads, I am just doing batches and testing speed to discover the right approach.

Can anyone suggest some areas for me to look at to increase the speed?

答:
You are probably hitting some overhead in creating multiple instance-based HttpClient vs using a static instance.  Your implementation will not scale. Using a shared HttpClient is actually recommended.

See my answer why - What is the overhead of creating a new HttpClient per call in a WebAPI client?

Body:
I have made a class to handle multiple HTTP GET requests.  It looks something like this:

public partial class MyHttpClass : IDisposable
{
    private HttpClient theClient;
    private string ApiBaseUrl = "https://example.com/";

    public MyHttpClass()
    {

        this.theClient = new HttpClient();
        this.theClient.BaseAddress = new Uri(ApiBaseUrl);
        this.theClient.DefaultRequestHeaders.Accept.Clear();
        this.theClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<JObject> GetAsync(string reqUrl)
    {

        var returnObj = new JObject();
        var response = await this.theClient.GetAsync(reqUrl);

        if (response.IsSuccessStatusCode)
        {
            returnObj = await response.Content.ReadAsAsync<JObject>();
            Console.WriteLine("GET successful");

        }
        else
        {
            Console.WriteLine("GET failed");
        }

        return returnObj;
    }
    public void Dispose()
    {
        theClient.Dispose();
    }
}

I am then queueing multiple requets by using a loop over Task.Run() and then after Task.WaitAll() in the manner of:

public async Task Start()
{
    foreach(var item in list)
    {
        taskList.Add(Task.Run(() => this.GetThing(item)));
    }
    Task.WaitAll(taskList.ToArray());
}

public async Task GetThing(string url)
{
    var response = await this.theClient.GetAsync(url);

    // some code to process and save response

}

It definitiely works faster than synchonus operation but it is not as fast as I expected.  Based on other advice I think the local threadpool is slowing me down.  MSDN suggest I should specify it as a long running task but I can't see a way to do that calling it like this.

Right now I haven't got into limiting threads, I am just doing batches and testing speed to discover the right approach.

Can anyone suggest some areas for me to look at to increase the speed?


问:
Collection? Dictionary? List?
Neo4j's manual does a very good job at explaining the meaning of the terms Node, Relationship, Label and a few others.

However, the real vocabulary of Cypher seems to include quite a few elusive terms, as well.

For instance, clause 3.3.15.1 of the manual says "Lists and paths are key concepts in Cypher". Fine, but what is a List in Cypher? I have all but given up trying to find a definition of that "key concept".

Similarly, the Cypher Reference Card mentions that "Cypher also supports maps and collections". Elsewhere, one can find that Cypher also "works with dictionaries".

Needless to say, I am in the dark as to how to spot and/or use those in Cypher.

Would really appreciate some illustrations.

Thanks.

答:
According to wikipedia :

https://en.wikipedia.org/wiki/List_(abstract_data_type) : a list (or sequence, collection) is a data type that represents a countable number of ordered values.

https://en.wikipedia.org/wiki/List_(abstract_data_type) : a map (or dictionnary) is a data type composed of a collection of (key, value) pairs.

And in Cypher :

this is a list : RETURN ['Benoit', 'Simard'] AS list

this is a map : RETURN { firstname:'Benoit', lastname:'Simard'} AS map

Cheers

Title: Collection? Dictionary? List?


问:
Do list except with two list of different classes instances
I want to compare two list with objects of two different classes. These are the classes:

```<code>namespace AngularWebApplication.Models
{
    public class AggregationLevelConfigurationPresentation
    {
        public byte AggregationLevelConfigurationId { get; set; }
        public int ProductionOrderId { get; set; }
        public string Name { get; set; }
        [ ... ]
    }
}

public class AggregationLevelConfiguration : IEquatable<AggregationLevelConfiguration>
{
    public byte AggregationLevelConfigurationId { get; set; }
    public int ProductionOrderId { get; set; }
    public string Name { get; set; }
    [ ... ]
}
</code>```

I want to get the elements in presentations list that are not in currentLevels:

List presentations;
List currentLevels;

```<code>List<Models.AggregationLevelConfigurationPresentation> newLevels =
    presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .ToList();
</code>```

But I get the following error when I do the Except:

```<code>Error   CS0029  Cannot implicitly convert type
'System.Collections.Generic.List<<anonymous type: byte AggregationLevelConfigurationId, int ProductionOrderId>>' to
'System.Collections.Generic.List<AngularWebApplication.Models.AggregationLevelConfigurationPresentation>'
</code>```

I think the problem is in the new { l.AggregationLevelConfigurationId, l.ProductionOrderId } but I don't know how to do the Except with list of objects from different classes.

I need the objects in presentations list that they aren't in currentLevels using AggregationLevelConfigurationId and ProductionOrderId as primary key.

答:
Following Evk comment, this is how I have solved this problem:</p>

```<code>List<Models.AggregationLevelConfigurationPresentation> newLevels =
     presentations.Where(p => !currentLevels.Any(l => p.AggregationLevelConfigurationId == l.AggregationLevelConfigurationId && p.ProductionOrderId == l.ProductionOrderId));
</code>```

Body:
I want to compare two list with objects of two different classes. These are the classes:

namespace AngularWebApplication.Models
{
    public class AggregationLevelConfigurationPresentation
    {
        public byte AggregationLevelConfigurationId { get; set; }
        public int ProductionOrderId { get; set; }
        public string Name { get; set; }
        [ ... ]
    }
}

public class AggregationLevelConfiguration : IEquatable<AggregationLevelConfiguration>
{
    public byte AggregationLevelConfigurationId { get; set; }
    public int ProductionOrderId { get; set; }
    public string Name { get; set; }
    [ ... ]
}

I want to get the elements in presentations list that are not in currentLevels:

List presentations;
List currentLevels;

List<Models.AggregationLevelConfigurationPresentation> newLevels =
    presentations
        .Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId })
        .Except(currentLevels.Select(l => new { l.AggregationLevelConfigurationId, l.ProductionOrderId }))
        .ToList();

But I get the following error when I do the Except:

Error   CS0029  Cannot implicitly convert type
'System.Collections.Generic.List<<anonymous type: byte AggregationLevelConfigurationId, int ProductionOrderId>>' to
'System.Collections.Generic.List<AngularWebApplication.Models.AggregationLevelConfigurationPresentation>'

I think the problem is in the new { l.AggregationLevelConfigurationId, l.ProductionOrderId } but I don't know how to do the Except with list of objects from different classes.

I need the objects in presentations list that they aren't in currentLevels using AggregationLevelConfigurationId and ProductionOrderId as primary key.

Body:
Following Evk comment, this is how I have solved this problem:

List<Models.AggregationLevelConfigurationPresentation> newLevels =
     presentations.Where(p => !currentLevels.Any(l => p.AggregationLevelConfigurationId == l.AggregationLevelConfigurationId && p.ProductionOrderId == l.ProductionOrderId));


问:
What does '-Olimit 2000' mean for cc
I try to compile an old program (which was compiled by cc) using gcc. In the makefile there is one line like this:

```<code>CFLAGS = -O2 -Olimit 2000 -w
</code>```

There is no '-Olimit 2000' in gcc. I am wondering what does it really mean. Whether it is safe to just delete this option when using gcc.

答:
As far as I can tell, this was only supported by IRIX's C compiler.  I can't even find a solid reference as to what it was used for.  Since it doesn't do anything with GCC, its definitely safe to remove it.

A little more detail, it was used to disable optimization on routines that were larger than the "Olimit".  This limit is to make it so the amount of time doing optimization is limited.  If you specify 0 for the Olimit, it means an "infinite Olimit" and will optimization every routine.  Here's a man page for MIPSpro: http://cimss.ssec.wisc.edu/~gumley/modis/old/mips_64.pdf

Title: What does '-Olimit 2000' mean for cc

Body:
I try to compile an old program (which was compiled by cc) using gcc. In the makefile there is one line like this:

CFLAGS = -O2 -Olimit 2000 -w

There is no '-Olimit 2000' in gcc. I am wondering what does it really mean. Whether it is safe to just delete this option when using gcc.


问:
Ruby/RoR, ActiveRecord - "arrange" method and use "super" in model
System

```<code>[2017-11-13 18:34:46] INFO  WEBrick 1.3.1
[2017-11-13 18:34:46] INFO  ruby 1.9.3 (2012-02-16) [x86_64-linux]
</code>```

Model in Ror, that working (currenct version)

```<code>class Expenditure < ActiveRecord::Base
...
  class << self
    def arrange
      super(:order => :name)
    end
...
</code>```

I tried to add one more field for change order way. "sort_order".
I cannot find method arrange in ActiveRecord, which was redifyned
I have tried unsuccesfully

```<code>super(:order => :sort_order, :name)
</code>```

...

```<code>super.order(:sort_order, :name)
</code>```

答:
arrange method from ancestry gem. It's https://github.com/stefankroes/ancestry/blob/8482196e32ac46a9d89c5e3b2d7080e4b830b1d0/lib/ancestry/class_methods.rb#L31

```<code>    # Arrangement
    def arrange options = {}
      # Get all nodes ordered by ancestry and start sorting them into an empty hash
      arrange_nodes self.ancestry_base_class.reorder(options.delete(:order)).where(options)
    end
</code>```

Body:
System

[2017-11-13 18:34:46] INFO  WEBrick 1.3.1
[2017-11-13 18:34:46] INFO  ruby 1.9.3 (2012-02-16) [x86_64-linux]

Model in Ror, that working (currenct version)

class Expenditure < ActiveRecord::Base
...
  class << self
    def arrange
      super(:order => :name)
    end
...

I tried to add one more field for change order way. "sort_order".
I cannot find method arrange in ActiveRecord, which was redifyned
I have tried unsuccesfully

super(:order => :sort_order, :name)

...

super.order(:sort_order, :name)

Body:
arrange method from ancestry gem. It's https://github.com/stefankroes/ancestry/blob/8482196e32ac46a9d89c5e3b2d7080e4b830b1d0/lib/ancestry/class_methods.rb#L31

    # Arrangement
    def arrange options = {}
      # Get all nodes ordered by ancestry and start sorting them into an empty hash
      arrange_nodes self.ancestry_base_class.reorder(options.delete(:order)).where(options)
    end


问:
Log4j2 one file per user session
In my vaadin application, I'd like to create one log file per user session. I started to create a customer file appender but then decided to investigate on ThreadContexts a bit more. I now store the user's uid inside the ThreadContext, which works fine within my PatternLayout (%X{uid}), but unfortunately not inside the FileAppender (maybe I was a bit naive).

Which way would you go for something like this? Simply put, I'd like to get this result for the time being:

User not logged in -> filename=debug.log

User logged in -> filename=[username]_debug.log

Any ideas or pointers highly appreciated!

答:
Problem solved and lessons learned:

To write to different log files, I needed Routers, as described in the FAQ. No clue why I didn't come across this while googling.

There's no need for a custom appender to solve this problem.

Log4j2 is very, very picky about directories not being writable. If this occurs, scroll up in the stacktrace: ERROR Unable to invoke factory method in class org.apache.logging.log4j.core.appender.RollingFileAppender. You'll find the culprit, google won't.

As well, Log4j2 cares in which order the appenders appear. It's stated multiple times in the FAQ and in the appender docs, still I overread it multiple times.

Title: Log4j2 one file per user session


答:
The docs has a section on Composite types:

3.2.1.3. Composite types

✓ Can be returned from Cypher queries

✓ Can be used as parameters

❏ Cannot be stored as properties

✓ Can be constructed with Cypher literals

Composite types comprise:

Lists are heterogeneous, ordered collections of values, each of which has any property, structural or composite type.

Maps are heterogeneous, unordered collections of (key, value) pairs, where:

the key is a String

the value has any property, structural or composite type

You might also be interested in the development of openCypher. One of the goals of the openCypher project is to define the concepts of the Cypher language. As stated on its homepage:

The openCypher project aims to deliver a full and open specification of the industry’s most widely adopted graph database query language: Cypher.

Currently, openCypher is a work-in-progress. It has a draft document on the Property Graph Model, which itself does not discuss lists/maps in detail, but refers the CIP2015-06-16 - Public Type System and Type Annotations document, which is an accepted Cypher Improvement Proposal. It has a section on "Container Types", which defines how lists and maps work in Cypher.

I have not seen the term "dictionary" in the core Neo4j docs. It could be mentioned around drivers though, as some languages, e.g. Python, use this term for maps.

(Disclaimer: I am a regular participant at the openCypher Implementers Group meetings.)

Title: Collection? Dictionary? List?

Body:
Neo4j's manual does a very good job at explaining the meaning of the terms Node, Relationship, Label and a few others.

However, the real vocabulary of Cypher seems to include quite a few elusive terms, as well.

For instance, clause 3.3.15.1 of the manual says "Lists and paths are key concepts in Cypher". Fine, but what is a List in Cypher? I have all but given up trying to find a definition of that "key concept".

Similarly, the Cypher Reference Card mentions that "Cypher also supports maps and collections". Elsewhere, one can find that Cypher also "works with dictionaries".

Needless to say, I am in the dark as to how to spot and/or use those in Cypher.

Would really appreciate some illustrations.

Thanks.


问:
Graph Algorithm in Python
I have this example graph

```<code>graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }
</code>```

And I have this two algorithm for generating edges and finding isolated nodes:

```<code>def edges(g):
    edges = []
    for node in g[node]:
        edges.append((node, g[node]))
    return edges

def isolated(g):
    result = []
    for node in g[node]:
        if not g[node]:
            result += node
    return result
</code>```

What am I doing wrong?

答:
What you are trying to do is this:

```<code>graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

res = [k for k, v in graph.items() if not v]

print(res)
</code>```

you'll get ['v6'] because it is the only with no nodes assoc

Title: Graph Algorithm in Python

Body:
I have this example graph

graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

And I have this two algorithm for generating edges and finding isolated nodes:

def edges(g):
    edges = []
    for node in g[node]:
        edges.append((node, g[node]))
    return edges

def isolated(g):
    result = []
    for node in g[node]:
        if not g[node]:
            result += node
    return result

What am I doing wrong?

Body:
What you are trying to do is this:

graph = { "v1" : ["v3"],
          "v2" : ["v3", "v5"],
          "v3" : ["v1", "v2", "v4", "v5"],
          "v4" : ["v3"],
          "v5" : ["v3", "v2"],
          "v6" : []
        }

res = [k for k, v in graph.items() if not v]

print(res)

you'll get ['v6'] because it is the only with no nodes assoc