问:
How to pass a textbox value from an ASP.NET MVC view to a SQL Server parameter
I'm new to this is it is possible to send a textbox value from an ASP.NET MVC view to a SQL Server parameter.

For example:

ASP.NET MVC view:  Name:mike

Html code: <input type="text" class="form-control" id="myinput4"  name="mike" />

SQL query:

```<code>DECLARE @value varchar(10)
SET @value = '@name'
</code>```

Is it possible?

答:
You could try below which could help you to achieve the above.

MVC View Page:

```<code><Script type="text/javascript">

var txtval = $('#myinput4').val();

function SaveTextValue(txtval) {
            window.location.href = '/ControllerName/ActionName?Name=' + txtval;
        }
</script>
</code>```

Controller Server Side:

Create Action in Controller with one string parameter.

Example:

```<code> public ActionResult SaveTextValue(string Name)
 {
// write logic for store Name(text) value into DB table using inline query or stored procedure.
 }
</code>```

Body:
I'm new to this is it is possible to send a textbox value from an ASP.NET MVC view to a SQL Server parameter.

For example:

ASP.NET MVC view:  Name:mike

Html code: <input type="text" class="form-control" id="myinput4"  name="mike" />

SQL query:

DECLARE @value varchar(10)
SET @value = '@name'

Is it possible?

Body:
You could try below which could help you to achieve the above.

MVC View Page:

<Script type="text/javascript">

var txtval = $('#myinput4').val();

function SaveTextValue(txtval) {
            window.location.href = '/ControllerName/ActionName?Name=' + txtval;
        }
</script>

Controller Server Side:

Create Action in Controller with one string parameter.

Example:

 public ActionResult SaveTextValue(string Name)
 {
// write logic for store Name(text) value into DB table using inline query or stored procedure.
 }


来源: stackexchange

问:
Object attribute's sharing same instance
I'm having a problem with one of my classes.

```<code>public class Sequence {

    private ArrayList<Spell> spells;

    public Sequence(ArrayList<Spell> spellsEnCours) {
    this.spellsEnCours = spellsEnCours;
    ...
    }

    public Sequence(Sequence pSequence) {
    this.spells = pSequence.spells;
    ...
    }
}
</code>```

There is no static field nowhere in my code.

My main treatment (for example) :

```<code>...
ArrayList<Spell> mySpells = new ArrayList<Spell>();
    Spell spell1 = new Spell(150, 0, 0, "Spell 1", null);
    Spell spell2 = new Spell(200, 2, 0, "Spell 2", new Buff(TypeBuff.ALLY_ATK, 2));
    Spell spell3 = new Spell(500, 3, 0, "Spell 3", null);
    mySpells.add(spell1);
    mySpells.add(spell2);
    mySpells.add(spell3);
    ArrayList<Sequence> mySequences = new ArrayList<Sequence>();
    Sequence initialSequence = new Sequence(mySpells);
    Sequence secondSequence = new Sequence(initialSequence);
    mySequences.add(initialSequence);
    // Let's just consider this call set a Spell's class attribute to true / false in the list Attribute of Spell
    secondSequence.choisirSpell(spell3);
    mySequences.add(secondSequence);
</code>```

And the state of spells attribute in my initialSequence will be the same as in my secondSequence after the call of my method choisirSpell. It's like it's the same instance, either the HashCode is different.

And i what i want is that the spells attribute for those two object are not related in anyway, independent.

答:
First thing, in your constructor for Sequence that accepts another sequence, you are just assigning the same spells list to your new sequence. Instead use:

```<code>this.spells = new ArrayList<>(pSequence.spells);
</code>```

Second, even if you do like above, only the list objects are different but still both lists have same Spell objects. So setting a property of spell will be reflecting on both lists.

To avoid that you must create a new spell object with same spell attributes if you intend the second list to ave completely its own new copy of spell. You may create a Copy constructor or clone method on Spell to do this.

This way, though the Spell objects are added from first list to second, it will still be a separate entity.

ContentLicense: CC BY-SA 3.0

Body:
I'm having a problem with one of my classes.

public class Sequence {

    private ArrayList<Spell> spells;

    public Sequence(ArrayList<Spell> spellsEnCours) {
    this.spellsEnCours = spellsEnCours;
    ...
    }

    public Sequence(Sequence pSequence) {
    this.spells = pSequence.spells;
    ...
    }
}

There is no static field nowhere in my code.

My main treatment (for example) :

...
ArrayList<Spell> mySpells = new ArrayList<Spell>();
    Spell spell1 = new Spell(150, 0, 0, "Spell 1", null);
    Spell spell2 = new Spell(200, 2, 0, "Spell 2", new Buff(TypeBuff.ALLY_ATK, 2));
    Spell spell3 = new Spell(500, 3, 0, "Spell 3", null);
    mySpells.add(spell1);
    mySpells.add(spell2);
    mySpells.add(spell3);
    ArrayList<Sequence> mySequences = new ArrayList<Sequence>();
    Sequence initialSequence = new Sequence(mySpells);
    Sequence secondSequence = new Sequence(initialSequence);
    mySequences.add(initialSequence);
    // Let's just consider this call set a Spell's class attribute to true / false in the list Attribute of Spell
    secondSequence.choisirSpell(spell3);
    mySequences.add(secondSequence);

And the state of spells attribute in my initialSequence will be the same as in my secondSequence after the call of my method choisirSpell. It's like it's the same instance, either the HashCode is different.

And i what i want is that the spells attribute for those two object are not related in anyway, independent.

Body:
First thing, in your constructor for Sequence that accepts another sequence, you are just assigning the same spells list to your new sequence. Instead use:

this.spells = new ArrayList<>(pSequence.spells);

Second, even if you do like above, only the list objects are different but still both lists have same Spell objects. So setting a property of spell will be reflecting on both lists.

To avoid that you must create a new spell object with same spell attributes if you intend the second list to ave completely its own new copy of spell. You may create a Copy constructor or clone method on Spell to do this.

This way, though the Spell objects are added from first list to second, it will still be a separate entity.


问:
Generate a simple 2nd level dropdown menu with php and mysql
I have a top_menu and a almenu named table. I want a simple dropdown menu by the menu id-s. The problem with this code, that it echo-s out the "Információk" menuitem 3 times, and puts into them the 3 menuitem from the almenu table.

The code does now: (It puts out 3 times the Információk menuitem from the top_menu table as new menuitems in the navbar)
Informáciok (Alapadatok),  Informáciok (Kollégium), Informáciok (Osztályok)

And not: Informáciok (Alapadatok, Kollégium, Osztályok) (This is what i want)

```<code><?php
                $menu_sql =
                "
                    SELECT

                        top_menu.top_menu_nev,
                        top_menu.top_menu_seo,
                        top_menu.top_menu_dropdown,
                        almenu.almenu_nev,
                        almenu.almenu_seo

                    FROM top_menu LEFT JOIN almenu ON top_menu.top_menu_id = almenu.almenu_parent

                    WHERE top_menu.menu_status = 1 AND top_menu.menu_position = 1

                    ORDER BY top_menu.top_menu_sorrend ASC

                ";
                $get_menu = mysqli_query($kapcs, $menu_sql) or die(mysqli_error($kapcs));
                while($top_menu = mysqli_fetch_assoc($get_menu))
                {
                    if($top_menu['top_menu_dropdown'] == 0 )
                    {
                        echo '<li><a href="'.$host.'/'.$top_menu['top_menu_seo'].'" title="'.$top_menu['top_menu_nev'].'" class="top_menu_to_link">'.$top_menu['top_menu_nev'].'</a></li>';
                    }
                    else
                    {
                        echo '<li class="dropdown">';
                            echo '<a href="#" title="" class="top_menu_to_link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">'.$top_menu['top_menu_nev'].'</a>';
                            echo '<ul class="dropdown-menu">';
                                echo '<li><a href="'.$host.'/'.$top_menu['almenu_seo'].'" title="'.$top_menu['almenu_nev'].'" class="top_menu_to_link">'.$top_menu['almenu_nev'].'</a></li>';
                            echo '</ul>';
                        echo '</li>';
                    }
                }
                ?>
</code>```

答:
The Problem is that you loop thru the whole nav over and over again.

The following code lets you generate new li items:

```<code>            echo '<li class="dropdown">';
            echo '<a href="#" title="" class="top_menu_to_link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">'.$top_menu['top_menu_nev'].'</a>';
            echo '<ul class="dropdown-menu">';

            $get_menu = mysqli_query($kapcs, $menu_sql) or die(mysqli_error($kapcs));
            while($top_menu = mysqli_fetch_assoc($get_menu))
            {
                if($top_menu['top_menu_dropdown'] == 0 )
                {
                    echo '<li><a href="'.$host.'/'.$top_menu['top_menu_seo'].'" title="'.$top_menu['top_menu_nev'].'" class="top_menu_to_link">'.$top_menu['top_menu_nev'].'</a></li>';
                }
                else
                {
                            echo '<li><a href="'.$host.'/'.$top_menu['almenu_seo'].'" title="'.$top_menu['almenu_nev'].'" class="top_menu_to_link">'.$top_menu['almenu_nev'].'</a></li>';

                }
            }
            echo '</ul>';
            echo '</li>';
</code>```

Body:
I have a top_menu and a almenu named table. I want a simple dropdown menu by the menu id-s. The problem with this code, that it echo-s out the "Információk" menuitem 3 times, and puts into them the 3 menuitem from the almenu table.

The code does now: (It puts out 3 times the Információk menuitem from the top_menu table as new menuitems in the navbar)
Informáciok (Alapadatok),  Informáciok (Kollégium), Informáciok (Osztályok)

And not: Informáciok (Alapadatok, Kollégium, Osztályok) (This is what i want)

<?php
                $menu_sql =
                "
                    SELECT

                        top_menu.top_menu_nev,
                        top_menu.top_menu_seo,
                        top_menu.top_menu_dropdown,
                        almenu.almenu_nev,
                        almenu.almenu_seo

                    FROM top_menu LEFT JOIN almenu ON top_menu.top_menu_id = almenu.almenu_parent

                    WHERE top_menu.menu_status = 1 AND top_menu.menu_position = 1

                    ORDER BY top_menu.top_menu_sorrend ASC

                ";
                $get_menu = mysqli_query($kapcs, $menu_sql) or die(mysqli_error($kapcs));
                while($top_menu = mysqli_fetch_assoc($get_menu))
                {
                    if($top_menu['top_menu_dropdown'] == 0 )
                    {
                        echo '
'.$top_menu['top_menu_nev'].'
';
                    }
                    else
                    {
                        echo '
';
                            echo ''.$top_menu['top_menu_nev'].'';
                            echo '
';
                                echo '
'.$top_menu['almenu_nev'].'
';
                            echo '
';
                        echo '
';
                    }
                }
                ?>

Body:
The Problem is that you loop thru the whole nav over and over again.

The following code lets you generate new li items:

            echo '<li class="dropdown">';
            echo '<a href="#" title="" class="top_menu_to_link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">'.$top_menu['top_menu_nev'].'</a>';
            echo '<ul class="dropdown-menu">';

            $get_menu = mysqli_query($kapcs, $menu_sql) or die(mysqli_error($kapcs));
            while($top_menu = mysqli_fetch_assoc($get_menu))
            {
                if($top_menu['top_menu_dropdown'] == 0 )
                {
                    echo '<li><a href="'.$host.'/'.$top_menu['top_menu_seo'].'" title="'.$top_menu['top_menu_nev'].'" class="top_menu_to_link">'.$top_menu['top_menu_nev'].'</a></li>';
                }
                else
                {
                            echo '<li><a href="'.$host.'/'.$top_menu['almenu_seo'].'" title="'.$top_menu['almenu_nev'].'" class="top_menu_to_link">'.$top_menu['almenu_nev'].'</a></li>';

                }
            }
            echo '</ul>';
            echo '</li>';


问:
Set Javascript variable in a class from outside
I have a library which has defined a class as this. I would like to call getMe() function outside class A with my own me.

```<code>var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(){
    me();
}
</code>```

I have class B where I call it like

A.prototype.getMe.call(this) but this would throw an error as me is not defined. How can I pass me into this ? I would like to make minimum changes to getMe function.

The only way to do this is, I guess to use an if .

```<code>A.prototype.getMe = function(){
  if(!me){
    me = this.myMe
  }
  me();
}
</code>```

So I did A.prototype.getMe.call({myMe: myMe}, args) but would it define the variable in global space ?

答:
You can't reasonably do this, not least because A is fundamentally broken (see below).

Whether you can do it at all depends entirely on where the A code is: If it's at global scope, you can do what you want but shouldn't. If it isn't at global scope, you can only do it from code within the scope where me is declared (or a scope within it).

If it's at global scope, you'd do it like this (but don't :-) ):

// The "A" Code
var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(){
  me();
}

// Your code using it
new A(); // Create `A.prototype.getMe`, because unless
         // `A` is called at least once, it doesn't exist
var myMe = function() {
  console.log("myMe called");
};
me = myMe; // Set the global `me`
A.prototype.getMe(); "myMe called"```
</div>
</div>
</p>

<blockquote>
  <p>The only way to do this is, I guess to use an if .</p>

```if(!me){
  me = this.myMe
}
```

  <p>So I did <code>A.prototype.getMe.call({myMe: myMe}, args)</code> but would it define the variable in global space ?</p>
</blockquote>

<p>Yes, it would. That's what <code>me = this.myMe</code> does.</p>

<p>From that observation, it sounds like you can modify <code>A</code>'s code. If so, fix it so that it doesn't define a prototype function in terms of a global variable. Perhaps isolate the code from the function into a function that doesn't expect to be called on an instance and pass in <code>me</code> as a parameter.</p>

<blockquote>
  <p>I am working on an existing library to make a small change. So I can only change inside getMe function definition. And I cant change var me definition.</p>
</blockquote>

<p>In that case, you can add a new optional parameter at the end, and use that if provided and <code>me</code> if not provide:</p>

```A.prototype.getMe = function(myMe){
    var meToCall = myMe || me;
    meToCall();
};
```

<p>Live Example:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// The "A" Code
var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(myMe){
  var meToCall = myMe || me;
  meToCall();
}

// Your code using it
A.prototype.getMe(function() {
  console.log("My me!");
});</code>```

And, separately, A is fundamentally broken if it's really as shown (barring an extremely specific use-case). Having constructor code set a global (global at least to A's code) that's then used by a prototype function is a huge design and maintenance red flag.

Consider the cross-talk horror:

// The "A" Code
var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(){
  me();
}

// Using it
var a1 = new A(function() {
  console.log("me1");
});
a1.getMe(); // "me1" -- so far so good
var a2 = new A(function() {
  console.log("me2");
});
a2.getMe(); // "me2" -- yup, still fine
a1.getMe(); // "me2" -- what the...?!?!?!!```

Body:
I have a library which has defined a class as this. I would like to call getMe() function outside class A with my own me.

var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(){
    me();
}

I have class B where I call it like

A.prototype.getMe.call(this) but this would throw an error as me is not defined. How can I pass me into this ? I would like to make minimum changes to getMe function.

The only way to do this is, I guess to use an if .

A.prototype.getMe = function(){
  if(!me){
    me = this.myMe
  }
  me();
}

So I did A.prototype.getMe.call({myMe: myMe}, args) but would it define the variable in global space ?

Body:
You can't reasonably do this, not least because A is fundamentally broken (see below).

Whether you can do it at all depends entirely on where the A code is: If it's at global scope, you can do what you want but shouldn't. If it isn't at global scope, you can only do it from code within the scope where me is declared (or a scope within it).

If it's at global scope, you'd do it like this (but don't :-) ):

// The "A" Code
var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(){
  me();
}

// Your code using it
new A(); // Create `A.prototype.getMe`, because unless
         // `A` is called at least once, it doesn't exist
var myMe = function() {
  console.log("myMe called");
};
me = myMe; // Set the global `me`
A.prototype.getMe(); "myMe called"

The only way to do this is, I guess to use an if .

if(!me){
  me = this.myMe
}

So I did A.prototype.getMe.call({myMe: myMe}, args) but would it define the variable in global space ?

Yes, it would. That's what me = this.myMe does.

From that observation, it sounds like you can modify A's code. If so, fix it so that it doesn't define a prototype function in terms of a global variable. Perhaps isolate the code from the function into a function that doesn't expect to be called on an instance and pass in me as a parameter.

I am working on an existing library to make a small change. So I can only change inside getMe function definition. And I cant change var me definition.

In that case, you can add a new optional parameter at the end, and use that if provided and me if not provide:

A.prototype.getMe = function(myMe){
    var meToCall = myMe || me;
    meToCall();
};

Live Example:

// The "A" Code
var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(myMe){
  var meToCall = myMe || me;
  meToCall();
}

// Your code using it
A.prototype.getMe(function() {
  console.log("My me!");
});

And, separately, A is fundamentally broken if it's really as shown (barring an extremely specific use-case). Having constructor code set a global (global at least to A's code) that's then used by a prototype function is a huge design and maintenance red flag.

Consider the cross-talk horror:

// The "A" Code
var me;
var A = function(_me){
  me = _me;
}
A.prototype.getMe = function(){
  me();
}

// Using it
var a1 = new A(function() {
  console.log("me1");
});
a1.getMe(); // "me1" -- so far so good
var a2 = new A(function() {
  console.log("me2");
});
a2.getMe(); // "me2" -- yup, still fine
a1.getMe(); // "me2" -- what the...?!?!?!!


问:
Easy way to excecute method after a given delay?
Is there a easy way to perform a method after a given delay like in iOS out of the box?

On iPhone I would do this:

[self performSelector:@selector(connectSensor) withObject:nil afterDelay:2.5];

It will then schedule the method connectSensor on the main thread (UI thread) to be executed after 2,5 seconds. And because it is automatically scheduled on the main thread, you don't have to worry about cross thread issues. (There is also a performSelectorOnBackground version)

So how would I do this properly in WP7?

Currently I'm accomplishing this with a timer, but I'm not sure if this is a good solution.

```<code>    private Timer timer;
    private void DoSomethingAfterDaly()
    {
        // ... do something here

        timer = new Timer( (o) => Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.GoBack()), null, 2500, Timeout.Infinite);
    }
</code>```

How could this be encapsulated into an extension method so I can just call this.Perform(MyMethod, null, 2500); ?

答:
You can use the Reactive Extensions for WP7 to observe on a timer:

```<code>Observable
  .Timer(TimeSpan.FromMilliseconds(2500))
  .SubscribeOnDispatcher()
  .Subscribe(_ =>
    {
      NavigationService.GoBack();
    });
```

Given the brevity of this code, I don't think you'd gain much by creating an extension method for it :) For more information about the Reactive Extensions for WP7, take a look at this MSDN page
.

ContentLicense: CC BY-SA 2.5

Body:
Is there a easy way to perform a method after a given delay like in iOS out of the box?

On iPhone I would do this:

[self performSelector:@selector(connectSensor) withObject:nil afterDelay:2.5];

It will then schedule the method connectSensor on the main thread (UI thread) to be executed after 2,5 seconds. And because it is automatically scheduled on the main thread, you don't have to worry about cross thread issues. (There is also a performSelectorOnBackground version)

So how would I do this properly in WP7?

Currently I'm accomplishing this with a timer, but I'm not sure if this is a good solution.

    private Timer timer;
    private void DoSomethingAfterDaly()
    {
        // ... do something here

        timer = new Timer( (o) => Deployment.Current.Dispatcher.BeginInvoke(() => NavigationService.GoBack()), null, 2500, Timeout.Infinite);
    }

How could this be encapsulated into an extension method so I can just call this.Perform(MyMethod, null, 2500); ?

Body:
You can use the Reactive Extensions for WP7 to observe on a timer:

Observable
  .Timer(TimeSpan.FromMilliseconds(2500))
  .SubscribeOnDispatcher()
  .Subscribe(_ =>
    {
      NavigationService.GoBack();
    });

Given the brevity of this code, I don't think you'd gain much by creating an extension method for it :) For more information about the Reactive Extensions for WP7, take a look at this MSDN page
.


问:
The condition `WHERE Id = 14317961` in my query is invalid
```<code>var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}
</code>```

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?

答:
In your query, no spaces are available between 'where' and 'ID', please add a space between those.</p>

```<code>'WHERE ' +
'Id = 14317961 ' +
</code>```

Body:
var report = AdWordsApp.report(
           'SELECT Id, Criteria, CpcBid, FirstPageCpc, FirstPositionCpc, TopOfPageCpc, Criteria ' +
           'FROM   KEYWORDS_PERFORMANCE_REPORT ' +
           'WHERE' +
           'Id = 14317961 ' +
           'DURING LAST_7_DAYS ');
var rows = report.rows();

while(rows.hasNext()) {
    var row = rows.next();
    var keywordIdReport = row['Id'];
    var keywordNameReport = row['Criteria'];
    var cpcBid = row['CpcBid'];
    var firstPageCpc = row['FirstPageCpc'];
    var firstPositionCpc = row['FirstPositionCpc'];
    var topOfPageCpc = row['TopOfPageCpc'];

    Logger.log('KeywordIdReport :' + keywordIdReport)
    Logger.log('CPCbid :' + cpcBid)
    Logger.log('firstPositionCpc : ' + firstPositionCpc)
    Logger.log('topOfPageCpc : ' + topOfPageCpc)
    Logger.log('firstPageCpc : ' + firstPageCpc)
}

I don't understand why, but the Adwords IDE tell me that the condition WHERE Id = 14317961 in my query is invalid, but I can't explain it is wrong. Assume here that the current Id exists. The purpose of that query is to access the three fields firstPositionCpc, topOfPageCpc and firstPageCpc for the specific keyword id. How could I fix my problem?

Body:
In your query, no spaces are available between 'where' and 'ID', please add a space between those.

'WHERE ' +
'Id = 14317961 ' +


问:
Java: Instantiate a generic type by returning a Supplier vs returning a new instance
I was reading how to instantiate a generic and after reading and applying this answer; I would like to know what would be the differences between expecting a Supplier<T> vs. expecting a new instance of T.

Example:

```<code>abstract class AbstractService<T extends AbstractEntity> {
    protected Supplier<T> makeNewThing();  // supplier is expected

    public T myMethod(){
        T object = makeNewThing().get(); // local object by calling supplier
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Supplier<Car> makeNewThing(){
        return Car::new;
    }
}
</code>```

vs.

```<code>abstract class AbstractService<T extends SomeAbstractEntity> {
    protected T makeNewThing();  // object is expected, newness is assumed

    public T myMethod(){
        T object = makeNewThing(); // local object by calling constructor
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Car makeNewThing(){
        return new Car();
    }
}
</code>```

The only thing I can think of is that expecting a supplier ensures that a new object will be created, but when expecting an object we can only assume that the implementing classes are calling the constructor and not re-using an existing instance.

I'd like to know of other objective differences and possible use cases, if any. Thanks in advance.

答:
The only thing I can think of is that expecting a supplier ensures
  that a new object will be created,

Not necessarily.

You implement the Supplier in this way :

```<code> return SomeEntityImplementation::new;
</code>```

But you could have implemented it in this other way :

```<code> if (myCachedObject != null){
    return (()-> myCachedObject);
 }
 return SomeEntityImplementation::new;
</code>```

Both ways may be used to return a cached object or create a new one.

One of Supplier advantages is the case of Supplier creating an object : this one is actually created only as the Supplier.get() method is invoked.

Note that in your example, using Supplier doesn't bring any advantage as in both cases (with or without Supplier) the object creation is already performed in a lazy way : as the factory method is invoked.

To take advantage of it, you should have a method that provides a Supplier<T>  as parameter as in the Eran and Dasblinkenlight examples.

Another Supplier advantage is its ability to implement factory that may return multiple of things.

Using Supplier allows to have a shorter and more readable code and besides that doesn't rely on Java Reflection.

Supposing that you want to create the object from an Enum value, you could so write :

```<code>public enum MyBaseClassFactory {

  ENUM_A (A::new),
  ENUM_B (B::new),
  ENUM_C (C::new),
  ENUM_D (D::new);

  private Supplier<BaseClass> supplier;

  MyBaseClassFactory (Supplier<BaseClass> supplier){
    this.supplier = supplier;
  }

  public BaseClass createObject(){
       return supplier.get();
  }
}
</code>```

You could so use it :

```<code>BaseClass base = MyBaseClassFactory.ENUM_A.createObject();
</code>```

Without Supplier, you will have to use Reflection (that may fail at runtime) or write a verbose and unmaintainable code.

For example with Reflection :

```<code>public enum MyEnumFactoryClass {

    ENUM_A(A.class), ENUM_B(B.class), ENUM_C(C.class), ENUM_D(D.class);

    private Class<BaseClass> clazz;

    MyEnumFactoryClass(Class<BaseClass> clazz) {
       this.clazz = clazz;
    }

    public BaseClass createObject() {
       return clazz.newInstance();
    }

}
</code>```

For example without reflection but with more verbose code :

```<code>public enum MyEnumFactoryClass {

  ENUM_A {
     @Override
     public BaseClass createObject() {
        return new A();
     }
    },
    ENUM_B {
     @Override
     public BaseClass createObject() {
        return new B();
     }
    },
    ENUM_C {
    @Override
     public BaseClass createObject() {
        return new C();
     }
    },
    ENUM_D {
    @Override
     public BaseClass createObject() {
        return new D();
     }
    };
    public abstract BaseClass createObject();

}
</code>```

You could of course take advantage in a close way of Supplier by using it with a Map<String, Supplier<BaseClass>>.

Body:
I was reading how to instantiate a generic and after reading and applying this answer; I would like to know what would be the differences between expecting a Supplier<T> vs. expecting a new instance of T.

Example:

abstract class AbstractService<T extends AbstractEntity> {
    protected Supplier<T> makeNewThing();  // supplier is expected

    public T myMethod(){
        T object = makeNewThing().get(); // local object by calling supplier
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Supplier<Car> makeNewThing(){
        return Car::new;
    }
}

vs.

abstract class AbstractService<T extends SomeAbstractEntity> {
    protected T makeNewThing();  // object is expected, newness is assumed

    public T myMethod(){
        T object = makeNewThing(); // local object by calling constructor
        object.doStuff();
        return object;
    }
}

class CarService extends AbstractService<Car> {
    public Car makeNewThing(){
        return new Car();
    }
}

The only thing I can think of is that expecting a supplier ensures that a new object will be created, but when expecting an object we can only assume that the implementing classes are calling the constructor and not re-using an existing instance.

I'd like to know of other objective differences and possible use cases, if any. Thanks in advance.

Body:
The only thing I can think of is that expecting a supplier ensures
  that a new object will be created,

Not necessarily.

You implement the Supplier in this way :

 return SomeEntityImplementation::new;

But you could have implemented it in this other way :

 if (myCachedObject != null){
    return (()-> myCachedObject);
 }
 return SomeEntityImplementation::new;

Both ways may be used to return a cached object or create a new one.

One of Supplier advantages is the case of Supplier creating an object : this one is actually created only as the Supplier.get() method is invoked.

Note that in your example, using Supplier doesn't bring any advantage as in both cases (with or without Supplier) the object creation is already performed in a lazy way : as the factory method is invoked.

To take advantage of it, you should have a method that provides a Supplier<T>  as parameter as in the Eran and Dasblinkenlight examples.

Another Supplier advantage is its ability to implement factory that may return multiple of things.

Using Supplier allows to have a shorter and more readable code and besides that doesn't rely on Java Reflection.

Supposing that you want to create the object from an Enum value, you could so write :

public enum MyBaseClassFactory {

  ENUM_A (A::new),
  ENUM_B (B::new),
  ENUM_C (C::new),
  ENUM_D (D::new);

  private Supplier<BaseClass> supplier;

  MyBaseClassFactory (Supplier<BaseClass> supplier){
    this.supplier = supplier;
  }

  public BaseClass createObject(){
       return supplier.get();
  }
}

You could so use it :

BaseClass base = MyBaseClassFactory.ENUM_A.createObject();

Without Supplier, you will have to use Reflection (that may fail at runtime) or write a verbose and unmaintainable code.

For example with Reflection :

public enum MyEnumFactoryClass {

    ENUM_A(A.class), ENUM_B(B.class), ENUM_C(C.class), ENUM_D(D.class);

    private Class<BaseClass> clazz;

    MyEnumFactoryClass(Class<BaseClass> clazz) {
       this.clazz = clazz;
    }

    public BaseClass createObject() {
       return clazz.newInstance();
    }

}

For example without reflection but with more verbose code :

public enum MyEnumFactoryClass {

  ENUM_A {
     @Override
     public BaseClass createObject() {
        return new A();
     }
    },
    ENUM_B {
     @Override
     public BaseClass createObject() {
        return new B();
     }
    },
    ENUM_C {
    @Override
     public BaseClass createObject() {
        return new C();
     }
    },
    ENUM_D {
    @Override
     public BaseClass createObject() {
        return new D();
     }
    };
    public abstract BaseClass createObject();

}

You could of course take advantage in a close way of Supplier by using it with a Map<String, Supplier<BaseClass>>.


问:
Sitecore Custom role permissions for experience editor
We need to add a custom role which should have edit permissions on the page but should be able to add components\create new content. The user shouldn't be able to publish content or add new pages. He can edit page and add\create relevant components\content on the page. Currently, we've added below roles to the custom role and denied 'create' permission to the role on the entire content tree except for relevant page templates and placeholder settings.

Sitecore Designer

Sitecore client authoring

But while adding content in experience editor user is getting 'you don't have access to add content' error. What should be the exact set of permissions to be able to add content to pages but not create pages.

答:
By default items are denied access and you need grant the specific access on the items in question. To be able to edit an item a user will need the Write permission.

Resources:

The different Access Rights explained

Assigning Access Rights


问:
Error MEDIA_ERROR_SERVER_DIED while trying to write with MediaRecord
For most versions, this works fine, but for Api 24-25, the MEDIA_ERROR_SERVER_AD error occurs immediately when the recording starts and you must finish the recording.
If there are any specific reasons, can this be handled in order not to interrupt the recording?

if this helps, then I attach the code. Thaks!

```<code>import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

public class MainCameraFragment extends BaseFragment implements SurfaceHolder.Callback,
    MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener {

  private static final String TAG = "MainCameraFragment";

  private static final float MIN_BATTERY_CHARGE = 0.1f;

  private Camera camera = null;
  private int cameraId = -1;
  private MediaRecorder recorder = null;
  private boolean inPreview = false;
  private Action<RecordingError> recordingErrorAction = null;

  /** Surface view container. */
  private FrameLayout container;
  /** Surface view instance. */
  private SurfaceView surfaceView;
  /** Orientation listener. */
  private OrientationEventListener orientationEventListener;
  /** Start recording time. */
  private long startRecordingTime = 0;
  /** Last video path. */
  private File lastVideoPath;

  /** Recording manager instance. */
  @Inject
  RecordingManager recordingManager;
  /** Settings manager instance. */
  @Inject
  SettingsManager settingsManager;

  /** Do on resume. */
  private Runnable doOnResume;

  public enum RecordingError {
    ILLEGAL_MEDIA_RECORDER_STATE,
    NOT_ENOUGH_MEMORY,
    NOT_ENOUGH_BATTERY,
  }

  /** Start preview from camera. */
  private void startPreview() {
    if (camera != null && !inPreview) {
      try {

        camera.setPreviewDisplay(surfaceView.getHolder());

        Camera.Parameters parameters = camera.getParameters();
        final List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();

        Camera.Size bestFitSize = camera.new Size(0, 0);

        for( Camera.Size size : supportedSizes ) {
          if( size.width <= surfaceView.getWidth() && size.height <= surfaceView.getHeight() ) {
            bestFitSize = size;
            break;
          }
        }

        if( bestFitSize.width == 0 && bestFitSize.height == 0 ) {
          bestFitSize = supportedSizes.get(0);
        }

        parameters.setPreviewSize(bestFitSize.width, bestFitSize.height);
        camera.setParameters(parameters);
        camera.startPreview();

        inPreview = true;
      } catch (IOException e) {
        Log.e(TAG, "Error setting camera preview: " + e.getMessage());
      }
    }
  }

  /** Stop camera preview. */
  private void stopPreview() {
    if (camera != null && inPreview) {
      try {
        camera.stopPreview();
      } catch (Exception e) {
        Log.i(TAG, "Error setting camera preview: " + e.getMessage());
      }

      inPreview = false;
    }

  }

  /** Init camera. */
  private void initCamera() {
    if (camera == null) {
      cameraId = recordingManager.getCameraId();

      if (cameraId >= 0) {
        try {
          camera = Camera.open(cameraId);

          setupCameraDisplayOrientation();

          lockAutoFocus(camera, settingsManager.isLockAutoFocus());
          lockAutoExposure(camera, settingsManager.isLockAutoExposure());
        }
        catch (Exception e) {
          Log.e(TAG, e.getMessage(), e);
        }
      } else {
        Log.e(TAG, "Can't find camera id");
      }
    }
  }

  /** Release camera. */
  private void releaseCamera() {
    if (camera != null) {
      camera.release();
      camera = null;
      cameraId = -1;
    }
  }

  /** @return recording state. */
  public boolean isRecording() {
    return recorder != null;
  }

  /** Start recording. */
  public void startRecording(final Action<RecordingError> recordingErrorAction, boolean micUsage) {
    if (camera != null && !isRecording()) {
      camera.stopPreview();
      final RecordingError recordingError = checkEnoughs();
      if (recordingError != null) {
        if (recordingErrorAction != null) {
          recordingErrorAction.act(recordingError);
        }
        return;
      }

      startRecordingTime = System.currentTimeMillis();

      final CamcorderProfile profile = recordingManager.getCamcorderProfile(cameraId, camera.getParameters());

      stopPreview();
      camera.unlock();

      MediaRecorder recorder = null;
      try {
        recorder = new MediaRecorder();
        recorder.setCamera(camera);

        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);

        recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        recorder.setProfile(profile);

        final String ts = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        lastVideoPath = new File(recordingManager.getRecordsDirPath(), "Video_" + ts + ".mp4");
        recorder.setOutputFile(lastVideoPath.getAbsolutePath());
        final int orientationHint = getRecorderOrientationHint();
        if (orientationHint != -1) {
          recorder.setOrientationHint(orientationHint);
        }
        recorder.setMaxFileSize(Long.MAX_VALUE);
        recorder.setMaxDuration(Integer.MAX_VALUE);

        stopPreview();
        recorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
        recorder.setOnErrorListener(this);
        recorder.setOnInfoListener(this);
        recorder.prepare();
        recorder.start();

        this.recordingErrorAction = recordingErrorAction;
      } catch (IOException e) {
        Log.d(TAG, "Error " + e.getMessage(), e);
        if (recorder != null) {
          recorder.release();
          recorder = null;
        }
      } finally {
        this.recorder = recorder;
      }
    }
  }

  /** Stop recording. */
  public void stopRecording() {
    if (isRecording()) {
      final MediaRecorder recorder = this.recorder;
      this.recorder = null;

      recorder.stop();
      recorder.reset();
      recorder.release();

      this.recordingErrorAction = null;
      try {
        camera.reconnect();
        startPreview();
      } catch (IOException e) {
        Log.w(TAG, e.getMessage(), e);
      }
    }
  }

  @Override
  public void onError(final MediaRecorder mr, final int what, final int extra) {
    Log.e(TAG, "Media recorder error: " + what + " extra: " + extra);

    if (recordingErrorAction != null) {
      recordingErrorAction.act(RecordingError.ILLEGAL_MEDIA_RECORDER_STATE);
    }
  }
}
</code>```

答:
You can catch the MEDIA_ERROR_SERVER_DIED message inside the onError method and try to re instantiate your recorder.

```<code>public void onError(final MediaRecorder mr, final int what, final int extra) {
    Log.e(TAG, "Media recorder error: " + what + " extra: " + extra);

    if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
        Log.i(LOGTAG, "MediaPlayer died, restarting");
        recorder.release();

        recorder = new MediaRecorder();
    }

    if (recordingErrorAction != null) {
      recordingErrorAction.act(RecordingError.ILLEGAL_MEDIA_RECORDER_STATE);
    }
}
</code>```

In my sample code above I just re instantiate the recorder via the line:  recorder = new MediaRecorder();. Perhaps it might need more settings applied on it afterwards.

Body:
For most versions, this works fine, but for Api 24-25, the MEDIA_ERROR_SERVER_AD error occurs immediately when the recording starts and you must finish the recording.
If there are any specific reasons, can this be handled in order not to interrupt the recording?

if this helps, then I attach the code. Thaks!

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

public class MainCameraFragment extends BaseFragment implements SurfaceHolder.Callback,
    MediaRecorder.OnErrorListener, MediaRecorder.OnInfoListener {

  private static final String TAG = "MainCameraFragment";

  private static final float MIN_BATTERY_CHARGE = 0.1f;

  private Camera camera = null;
  private int cameraId = -1;
  private MediaRecorder recorder = null;
  private boolean inPreview = false;
  private Action<RecordingError> recordingErrorAction = null;

  /** Surface view container. */
  private FrameLayout container;
  /** Surface view instance. */
  private SurfaceView surfaceView;
  /** Orientation listener. */
  private OrientationEventListener orientationEventListener;
  /** Start recording time. */
  private long startRecordingTime = 0;
  /** Last video path. */
  private File lastVideoPath;

  /** Recording manager instance. */
  @Inject
  RecordingManager recordingManager;
  /** Settings manager instance. */
  @Inject
  SettingsManager settingsManager;

  /** Do on resume. */
  private Runnable doOnResume;

  public enum RecordingError {
    ILLEGAL_MEDIA_RECORDER_STATE,
    NOT_ENOUGH_MEMORY,
    NOT_ENOUGH_BATTERY,
  }

  /** Start preview from camera. */
  private void startPreview() {
    if (camera != null && !inPreview) {
      try {

        camera.setPreviewDisplay(surfaceView.getHolder());

        Camera.Parameters parameters = camera.getParameters();
        final List<Camera.Size> supportedSizes = parameters.getSupportedPreviewSizes();

        Camera.Size bestFitSize = camera.new Size(0, 0);

        for( Camera.Size size : supportedSizes ) {
          if( size.width <= surfaceView.getWidth() && size.height <= surfaceView.getHeight() ) {
            bestFitSize = size;
            break;
          }
        }

        if( bestFitSize.width == 0 && bestFitSize.height == 0 ) {
          bestFitSize = supportedSizes.get(0);
        }

        parameters.setPreviewSize(bestFitSize.width, bestFitSize.height);
        camera.setParameters(parameters);
        camera.startPreview();

        inPreview = true;
      } catch (IOException e) {
        Log.e(TAG, "Error setting camera preview: " + e.getMessage());
      }
    }
  }

  /** Stop camera preview. */
  private void stopPreview() {
    if (camera != null && inPreview) {
      try {
        camera.stopPreview();
      } catch (Exception e) {
        Log.i(TAG, "Error setting camera preview: " + e.getMessage());
      }

      inPreview = false;
    }

  }

  /** Init camera. */
  private void initCamera() {
    if (camera == null) {
      cameraId = recordingManager.getCameraId();

      if (cameraId >= 0) {
        try {
          camera = Camera.open(cameraId);

          setupCameraDisplayOrientation();

          lockAutoFocus(camera, settingsManager.isLockAutoFocus());
          lockAutoExposure(camera, settingsManager.isLockAutoExposure());
        }
        catch (Exception e) {
          Log.e(TAG, e.getMessage(), e);
        }
      } else {
        Log.e(TAG, "Can't find camera id");
      }
    }
  }

  /** Release camera. */
  private void releaseCamera() {
    if (camera != null) {
      camera.release();
      camera = null;
      cameraId = -1;
    }
  }

  /** @return recording state. */
  public boolean isRecording() {
    return recorder != null;
  }

  /** Start recording. */
  public void startRecording(final Action<RecordingError> recordingErrorAction, boolean micUsage) {
    if (camera != null && !isRecording()) {
      camera.stopPreview();
      final RecordingError recordingError = checkEnoughs();
      if (recordingError != null) {
        if (recordingErrorAction != null) {
          recordingErrorAction.act(recordingError);
        }
        return;
      }

      startRecordingTime = System.currentTimeMillis();

      final CamcorderProfile profile = recordingManager.getCamcorderProfile(cameraId, camera.getParameters());

      stopPreview();
      camera.unlock();

      MediaRecorder recorder = null;
      try {
        recorder = new MediaRecorder();
        recorder.setCamera(camera);

        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);

        recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        recorder.setProfile(profile);

        final String ts = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        lastVideoPath = new File(recordingManager.getRecordsDirPath(), "Video_" + ts + ".mp4");
        recorder.setOutputFile(lastVideoPath.getAbsolutePath());
        final int orientationHint = getRecorderOrientationHint();
        if (orientationHint != -1) {
          recorder.setOrientationHint(orientationHint);
        }
        recorder.setMaxFileSize(Long.MAX_VALUE);
        recorder.setMaxDuration(Integer.MAX_VALUE);

        stopPreview();
        recorder.setPreviewDisplay(surfaceView.getHolder().getSurface());
        recorder.setOnErrorListener(this);
        recorder.setOnInfoListener(this);
        recorder.prepare();
        recorder.start();

        this.recordingErrorAction = recordingErrorAction;
      } catch (IOException e) {
        Log.d(TAG, "Error " + e.getMessage(), e);
        if (recorder != null) {
          recorder.release();
          recorder = null;
        }
      } finally {
        this.recorder = recorder;
      }
    }
  }

  /** Stop recording. */
  public void stopRecording() {
    if (isRecording()) {
      final MediaRecorder recorder = this.recorder;
      this.recorder = null;

      recorder.stop();
      recorder.reset();
      recorder.release();

      this.recordingErrorAction = null;
      try {
        camera.reconnect();
        startPreview();
      } catch (IOException e) {
        Log.w(TAG, e.getMessage(), e);
      }
    }
  }

  @Override
  public void onError(final MediaRecorder mr, final int what, final int extra) {
    Log.e(TAG, "Media recorder error: " + what + " extra: " + extra);

    if (recordingErrorAction != null) {
      recordingErrorAction.act(RecordingError.ILLEGAL_MEDIA_RECORDER_STATE);
    }
  }
}

Body:
You can catch the MEDIA_ERROR_SERVER_DIED message inside the onError method and try to re instantiate your recorder.

public void onError(final MediaRecorder mr, final int what, final int extra) {
    Log.e(TAG, "Media recorder error: " + what + " extra: " + extra);

    if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
        Log.i(LOGTAG, "MediaPlayer died, restarting");
        recorder.release();

        recorder = new MediaRecorder();
    }

    if (recordingErrorAction != null) {
      recordingErrorAction.act(RecordingError.ILLEGAL_MEDIA_RECORDER_STATE);
    }
}

In my sample code above I just re instantiate the recorder via the line:  recorder = new MediaRecorder();. Perhaps it might need more settings applied on it afterwards.


问:
Tkinter Scrollbar
If I call text_area.pack() before scrollbar.pack() (i.e switch them), the scrollbar doesn't show. Why is that? If I am going to create a larger program, I would have absolutely no chance to find out where the problem is.

```<code>from tkinter import *
import tkinter.filedialog

root = Tk()
root.geometry("200x100")
frame = Frame(root,width=150, height=90)
frame.pack()
scrollbar = Scrollbar(frame)
text_area = Text(frame, width=200, height=50,yscrollcommand=scrollbar.set)
scrollbar.config(command=text_area.yview)
scrollbar.pack(side="right", fill="y")
text_area.pack()
root.mainloop()
</code>```

答:
The reason the scrollbar doesn't show is because there's simply no room for it. You're specifying a window size of 200x100 pixels and an inner frame size of 150x90 pixels, but you are trying to put a much larger text widget in that space. You're specifying a size of 200x50 characters (roughly 1400x750, depending on the fonts you're using) which is much too wide for the available space.

The way pack works is that it looks at the available space, puts the widget in that space, and subtracts the spaced needed for that widget from the space available for the next widget. Because you put the text widget first, and it requested more than the available space, it used up all of the available space. Then, when you call pack on the scrollbar, there's simply nowhere to put it.

When you reverse the order, the scrollbar takes up only a fraction of the available space, so there's room to fit the text widget in.

The best solution is to change the order in which you call pack. In general, it's best to call pack so that the last widget you call pack on is the "hero" -- the one that takes up all remaining space and grows or shrinks as the window grows and shrinks. Usually that's a text widget or a canvas widget, or a frame that itself contains many widgets.

The key to success with tkinter is to not try to force a tkinter widget or window to be a particular size in pixels (except, perhaps, for the canvas). Instead, either let a widget use it's default size (particularly with buttons and scrollbars), or pick a sensible default (number of rows and/or columns). Tkinter will then compute the right size to fit everything in based on the font, the screen resolution, and other factors.

Title: Tkinter Scrollbar

Body:
If I call text_area.pack() before scrollbar.pack() (i.e switch them), the scrollbar doesn't show. Why is that? If I am going to create a larger program, I would have absolutely no chance to find out where the problem is.

from tkinter import *
import tkinter.filedialog

root = Tk()
root.geometry("200x100")
frame = Frame(root,width=150, height=90)
frame.pack()
scrollbar = Scrollbar(frame)
text_area = Text(frame, width=200, height=50,yscrollcommand=scrollbar.set)
scrollbar.config(command=text_area.yview)
scrollbar.pack(side="right", fill="y")
text_area.pack()
root.mainloop()


问:
Django-Filter | Looping over form fields
I am using django-filter which works as intended. I am however trying to loop over the form fields but the standard django attributes aren't working. The only one that does is {{ form.id_for_label }}. Am I missing something?

My template code:

```<code><form action="" method="get">
    {% for form in forms.form.product_colours %}
    <div class="form-group">
        <input type="checkbox"  name="product_colours" id="{{ form.id_for_label }}" value="{{ form.value }}">
        <label for="{{ form.id_for_label }}">{{ form.label }}</label>
    </div>
    {% endfor %}
    <input type="submit" />
</form>
</code>```

The reason I don't want to simply use {{ form }} is because it loads the  before the <input> whereas I'd need it to work viceversa to fit into my styling. I would prefer not to have to change the styling.

In case they are needed, here are my (simplified) models, FilterSet and my view:

Model:

```<code>class ProductColour(models.Model):
    name = models.CharField(max_length=255)
    colour_hex = models.CharField(max_length=16, default="#FFF")

    def __str__(self):
        return self.name

class Product(Page):
    # My product fields
    product_colours = ParentalManyToManyField('products.ProductColour', blank=True)
</code>```

FilterSet:

```<code>class ProductFilter(django_filters.FilterSet):
    product_colours = django_filters.ModelMultipleChoiceFilter(name="product_colours",
        label="Product Colour",
        widget=forms.CheckboxSelectMultiple,
        queryset=ProductColour.objects.all(),
        conjoined=False)

    class Meta:
        model = Product
        fields = ['product_colours']
</code>```

View:

```<code>def get_context(self, request):
    context = super(Page, self).get_context(request)

    all_products = ProductFilter(request.GET, queryset=Product.objects.live()).qs
    forms = ProductFilter(request.GET, queryset=Product.objects.live())

    paginator = Paginator(all_products, 9) # Show 9 resources per page

    page = request.GET.get('page')

    try:
        products = paginator.page(page)
    except PageNotAnInteger:
        products = paginator.page(1)
    except EmptyPage:
        products = paginator.page(paginator.num_pages)

    context['forms'] = forms
    context['products'] = products

    return context
</code>```

In case you are wondering what the ParentalManyToManyField is, it's a Wagtail CMS class.

答:
OK so I have found the solution - as user @Vicmathur suggested in the comments above I tried adding {% for check in form %}{% endfor %} and it threw up a 'BoundWidget' object is not iterable error.

So I googled BoundWidget and found the related Django documentation.

Instead of trying to access the data through, for example, {{ form.value }}, I need to specify{{ form.data.value }}

Body:
I am using django-filter which works as intended. I am however trying to loop over the form fields but the standard django attributes aren't working. The only one that does is {{ form.id_for_label }}. Am I missing something?

My template code:

<form action="" method="get">
    {% for form in forms.form.product_colours %}

        <input type="checkbox"  name="product_colours" id="{{ form.id_for_label }}" value="{{ form.value }}">
        {{ form.label }}

    {% endfor %}
    <input type="submit" />
</form>

The reason I don't want to simply use {{ form }} is because it loads the  before the <input> whereas I'd need it to work viceversa to fit into my styling. I would prefer not to have to change the styling.

In case they are needed, here are my (simplified) models, FilterSet and my view:

Model:

class ProductColour(models.Model):
    name = models.CharField(max_length=255)
    colour_hex = models.CharField(max_length=16, default="#FFF")

    def __str__(self):
        return self.name

class Product(Page):
    # My product fields
    product_colours = ParentalManyToManyField('products.ProductColour', blank=True)

FilterSet:

class ProductFilter(django_filters.FilterSet):
    product_colours = django_filters.ModelMultipleChoiceFilter(name="product_colours",
        label="Product Colour",
        widget=forms.CheckboxSelectMultiple,
        queryset=ProductColour.objects.all(),
        conjoined=False)

    class Meta:
        model = Product
        fields = ['product_colours']

View:

def get_context(self, request):
    context = super(Page, self).get_context(request)

    all_products = ProductFilter(request.GET, queryset=Product.objects.live()).qs
    forms = ProductFilter(request.GET, queryset=Product.objects.live())

    paginator = Paginator(all_products, 9) # Show 9 resources per page

    page = request.GET.get('page')

    try:
        products = paginator.page(page)
    except PageNotAnInteger:
        products = paginator.page(1)
    except EmptyPage:
        products = paginator.page(paginator.num_pages)

    context['forms'] = forms
    context['products'] = products

    return context

In case you are wondering what the ParentalManyToManyField is, it's a Wagtail CMS class.


问:
can someone explain what this code is doing
I am having two problems here:

The following block of codes has got me confused. Primarily, I do not know what exactly the code is doing from the basics; I just copied it from a tutorial, and it seems to do what i want it to do. If anyone can explain in bits what it does, it will be really helpful.

The second problem is that I do not know why it throws an ArrayIndexOutOfBounds error, maybe because I do not understand it or otherwise. I really need clarification.

```<code>   try {
        Document searchLink = Jsoup.connect("https://www.google.com.ng/search?dcr=0&source=hp&ei=5-cIWuZ30cCwB7aUhrAN&q=" + URLEncoder.encode(searchValue, encoding))
                .userAgent("Mozilla/5.0").get();
        String websiteLink = searchLink.getElementsByTag("cite").get(0).text();

        //we are setting the value for the action "titles" in the wikipedia API with our own article title
        //we use the string method replaceAll() to remove the title of the article from the wikipedia URL that we generated from google
        //
        String wikiAPItoSearch = "https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles="
                                + URLEncoder.encode(websiteLink.replaceAll("https://en.wikipedia.org/wiki/", ""),encoding);
        System.out.println(wikiAPItoSearch);

        //extraction of textfiles
        //from this point till down i cant really grab what is happening
        HttpURLConnection httpconn = (HttpURLConnection) new URL(wikiAPItoSearch).openConnection();
        httpconn.addRequestProperty("userAgent", "Mozilla/5.0");

        BufferedReader bf = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));

        //read line by line
        String response = bf.lines().collect(Collectors.joining());
        bf.close();
        ///it returns ArrayIndexOutOfBounds here
        String result = response.split("\"extract\":\"")[1];
        System.out.println(result);
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
</code>```

答:
OPPS... i realized it was the API that i was using that caused the error, the API i got from wikimedia does not use /extract /as a delimetre , so i checked other stack overflow articles for a more cleaner API especially a one that uses /extract/ as a delimetre for the API response.

this is the new API i got :

```<code>https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=
</code>```

this was the former one that causes the error:

```<code>https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=
</code>```

i think the error was caused by my inability to understand the process in-dept.. thanks for the responses.

Body:
I am having two problems here:

The following block of codes has got me confused. Primarily, I do not know what exactly the code is doing from the basics; I just copied it from a tutorial, and it seems to do what i want it to do. If anyone can explain in bits what it does, it will be really helpful.

The second problem is that I do not know why it throws an ArrayIndexOutOfBounds error, maybe because I do not understand it or otherwise. I really need clarification.

   try {
        Document searchLink = Jsoup.connect("https://www.google.com.ng/search?dcr=0&source=hp&ei=5-cIWuZ30cCwB7aUhrAN&q=" + URLEncoder.encode(searchValue, encoding))
                .userAgent("Mozilla/5.0").get();
        String websiteLink = searchLink.getElementsByTag("cite").get(0).text();

        //we are setting the value for the action "titles" in the wikipedia API with our own article title
        //we use the string method replaceAll() to remove the title of the article from the wikipedia URL that we generated from google
        //
        String wikiAPItoSearch = "https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles="
                                + URLEncoder.encode(websiteLink.replaceAll("https://en.wikipedia.org/wiki/", ""),encoding);
        System.out.println(wikiAPItoSearch);

        //extraction of textfiles
        //from this point till down i cant really grab what is happening
        HttpURLConnection httpconn = (HttpURLConnection) new URL(wikiAPItoSearch).openConnection();
        httpconn.addRequestProperty("userAgent", "Mozilla/5.0");

        BufferedReader bf = new BufferedReader(new InputStreamReader(httpconn.getInputStream()));

        //read line by line
        String response = bf.lines().collect(Collectors.joining());
        bf.close();
        ///it returns ArrayIndexOutOfBounds here
        String result = response.split("\"extract\":\"")[1];
        System.out.println(result);
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }

Body:
OPPS... i realized it was the API that i was using that caused the error, the API i got from wikimedia does not use /extract /as a delimetre , so i checked other stack overflow articles for a more cleaner API especially a one that uses /extract/ as a delimetre for the API response.

this is the new API i got :

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=

this was the former one that causes the error:

https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=

i think the error was caused by my inability to understand the process in-dept.. thanks for the responses.


问:
How to fetch children of node via webroot path in Gentics Mesh?
I have a webroot path of a parent node and would like to return the children of this node.
Using https://demo.getmesh.io/api/v1/demo/webroot/images/ for example just yields the node itself.</p>

答:
There is currently no way to load the children of a node via REST using a single request. You can however load the node of the path. Use the uuid of that node and load the children via /api/v1/:projectName/nodes/:nodeUuid/children

A much more elegant approach however would be to use the following graphql query. I highly recommend this option since it is more efficient when handling large datasets.

Background: Computing the totalCount / totalPage size is costly and you can avoid this by using hasPreviousPage and hasNextPage.

You can use the following graphql query:

```<code>query ($path: String) {
  node(path: $path) {
    children(perPage: 5) {
      hasNextPage
      hasPreviousPage
      currentPage
      elements {
        uuid
        fields {
          ... on vehicleImage {
            name
          }
        }
      }
    }
  }
}
</code>```

Query variables:

```<code>{
  "path": "/images"
}
</code>```

Body:
There is currently no way to load the children of a node via REST using a single request. You can however load the node of the path. Use the uuid of that node and load the children via /api/v1/:projectName/nodes/:nodeUuid/children

A much more elegant approach however would be to use the following graphql query. I highly recommend this option since it is more efficient when handling large datasets.

Background: Computing the totalCount / totalPage size is costly and you can avoid this by using hasPreviousPage and hasNextPage.

You can use the following <a href="https://demo.getmesh.io/api/v1/demo/graphql/browser/#query=query%20(%24path%3A%20String)%20%7B%0A%20%20node(path%3A%20%24path)%20%7B%0A%20%20%20%20children(perPage%3A%205)%20%7B%0A%20%20%20%20%20%20hasNextPage%0A%20%20%20%20%20%20hasPreviousPage%0A%20%20%20%20%20%20currentPage%0A%20%20%20%20%20%20elements%20%7B%0A%20%20%20%20%20%20%20%20uuid%0A%20%20%20%20%20%20%20%20fields%20%7B%0A%20%20%20%20%20%20%20%20%20%20...%20on%20vehicleImage%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20name%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%7D%0A%20%20%7D%0A%7D%0A&variables=%7B%0A%20%20%22path%22%3A%20%22%2Fimages%22%0A%7D%0A" rel="nofollow noreferrer">graphql query:

query ($path: String) {
  node(path: $path) {
    children(perPage: 5) {
      hasNextPage
      hasPreviousPage
      currentPage
      elements {
        uuid
        fields {
          ... on vehicleImage {
            name
          }
        }
      }
    }
  }
}

Query variables:

{
  "path": "/images"
}


问:
WPF DataGrid: Selecting CellTemplate by DataType of ItemsSoure
I am Building a DataGrid where i want to switch the images inside a cell based on the underlying datatype of the current item.

Question:
Is it possible to apply this type of template switching?
Preferably in xaml-only?

ItemsSource is

```<code>ObservableCollection<BaseModel>
</code>```

which contains Items of type

```<code>IncidentModel : BaseModel
ServiceModel : BaseModel
</code>```

This is where i currently am:

```<code><DataGrid
    ItemsSource="{Binding TicketCollection,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}"
    IsReadOnly="True"
    AutoGenerateColumns="False"
    DockPanel.Dock="Top">

    <DataGrid.Resources>
        <DataTemplate DataType="{x:Type models:IncidentModel}">
            <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/Active_16.png" />

        </DataTemplate>
        <DataTemplate DataType="{x:Type models:ServiceModel}">
            <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/IncidentMgmt_AllIncidents_16.png" />

        </DataTemplate>
    </DataGrid.Resources>

    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Typ">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>

                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTextColumn Header="Id" Binding="{Binding Id,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
        <DataGridTextColumn Header="Titel" Binding="{Binding Title,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
        <DataGridTextColumn Header="Status" Binding="{Binding Status,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
        <DataGridTextColumn Header="Erstellung" Binding="{Binding CreatedDate,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
    </DataGrid.Columns>
</DataGrid>
</code>```

Thanks for every possible help!

答:
Doing it all in XAML with an additional ContentPresenter seems to work:

```<code><DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Typ">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ContentPresenter Content="{Binding}">
                        <ContentPresenter.Resources>
                            <DataTemplate DataType="{x:Type models:IncidentModel}">
                                <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/Active_16.png" />
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type models:ServiceModel}">
                                <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/IncidentMgmt_AllIncidents_16.png" />
                            </DataTemplate>
                        </ContentPresenter.Resources>
                    </ContentPresenter>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
</code>```

Body:
I am Building a DataGrid where i want to switch the images inside a cell based on the underlying datatype of the current item.

Question:
Is it possible to apply this type of template switching?
Preferably in xaml-only?

ItemsSource is

ObservableCollection<BaseModel>

which contains Items of type

IncidentModel : BaseModel
ServiceModel : BaseModel

This is where i currently am:

<DataGrid
    ItemsSource="{Binding TicketCollection,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}"
    IsReadOnly="True"
    AutoGenerateColumns="False"
    DockPanel.Dock="Top">

    <DataGrid.Resources>
        <DataTemplate DataType="{x:Type models:IncidentModel}">
            <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/Active_16.png" />

        </DataTemplate>
        <DataTemplate DataType="{x:Type models:ServiceModel}">
            <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/IncidentMgmt_AllIncidents_16.png" />

        </DataTemplate>
    </DataGrid.Resources>

    <DataGrid.Columns>

        <DataGridTemplateColumn Header="Typ">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>

                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>

        <DataGridTextColumn Header="Id" Binding="{Binding Id,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
        <DataGridTextColumn Header="Titel" Binding="{Binding Title,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
        <DataGridTextColumn Header="Status" Binding="{Binding Status,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
        <DataGridTextColumn Header="Erstellung" Binding="{Binding CreatedDate,UpdateSourceTrigger=PropertyChanged,Mode=OneWay}" />
    </DataGrid.Columns>
</DataGrid>

Thanks for every possible help!

Body:
Doing it all in XAML with an additional ContentPresenter seems to work:

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Typ">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ContentPresenter Content="{Binding}">
                        <ContentPresenter.Resources>
                            <DataTemplate DataType="{x:Type models:IncidentModel}">
                                <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/Active_16.png" />
                            </DataTemplate>
                            <DataTemplate DataType="{x:Type models:ServiceModel}">
                                <Image Source="pack://application:,,,/SMLib;component/Files/Images/16x16/IncidentMgmt_AllIncidents_16.png" />
                            </DataTemplate>
                        </ContentPresenter.Resources>
                    </ContentPresenter>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>


问:
RxSwift best practice: Shall I use a Subject for my internal data source?
I am still fairly new to the Rx world and I was wondering if I am doing it right or if I have a misconception and are violating the best practices. If so, I'd be happy if you could point me to the right direction.

In my iOS app I need to call a web service to retrieve my data. There are basically two calls I can make:

A call to a collection resource (/devices)

A call to a single resource (/devices/{id})

To reduce the amount of calls I need to do I thought it would be a good idea to store the data locally in memory so that when I go from the list view (which displays all devices) to the detail view (which displays a single device), I don't have to make a call to the single resource.

Instead, I would only make this call when the user uses pull to refresh inside the detail screen and then write back the data to the collection which is used as the datasource for the list screen.

Now due to the fact that the app is running on a mobile device, there can be multiple errors while making a call to the web service and if an error occurs I would like to show a message to the user to inform about the problem.

I was thinking about using a Subject inside a Singleton class as my data source to which my UI subscribes. Whenever I need to refresh the list, I would create a new observable with my web service call which, as a side effect, populates new data to the Subject but does not populate onError or onComplete events to the Subject.

I hope this piece of pseudo code explains better what I mean:

```<code>//Pull-to-refresh function
Observable.create { observable in
  let hud = HUD("loading devices")
  self.hud = hud
  observable.next()
  return Disposable.create { hud.dismiss() }
}
.flatMap {
  return DeviceService.getList() //The web service
}
.flatMap { devices in
  DeviceSingleton.devicesSubject.next(devices) //The singleton
  return Observable.just()
}
.subscribe(
  onNext: { self.hud.dismiss() }
  onError: { error in
      self.hud.dismiss()
      self.displayError(error)
  }
)
.disposed(by: disposeBag)
</code>```

The pull-to-refresh in the detail screen would look similar but it would involve getting the current data from the subject, then replacing the updated device and re-publishing the data like so:

```<code>//Pull-to-refresh function in detail screen
let id = ...
Observable.create { observable in
  let hud = HUD("loading devices")
  self.hud = hud
  observable.next()
  return Disposable.create { hud.dismiss() }
}
.flatMap {
  return DeviceService.getDevice(id: id) //The web service
}
.flatMap { device in
  let devices = try! DeviceSingleton.devicesSubject.value()
  let updatedDevices = self.updateDevice(device, in: devices) //removing old device, adding new one, sorting, etc.
  DeviceSingleton.devicesSubject.next(devices)
  return Observable.just()
}
.subscribe(
  onNext: { self.hud.dismiss() }
  onError: { error in
      self.hud.dismiss()
      self.displayError(error)
  }
)
.disposed(by: disposeBag)
</code>```

Is this correct? Is this valid? What could be a better approach? I think one problem might be that reloading a single device can not only happen when the user pulls-to-refresh but also when a remote notification comes in.

I hope you can tell me if I am using Rx correctly or if I am doing something wrong here.

答:
Have a look at .materialize() and .switchLatest() operators, they come in handy in such scenarios.

I personally prefer to keep latest state by using this small library - https://github.com/maxvol/RaspSwift

Body:
I am still fairly new to the Rx world and I was wondering if I am doing it right or if I have a misconception and are violating the best practices. If so, I'd be happy if you could point me to the right direction.

In my iOS app I need to call a web service to retrieve my data. There are basically two calls I can make:

A call to a collection resource (/devices)

A call to a single resource (/devices/{id})

To reduce the amount of calls I need to do I thought it would be a good idea to store the data locally in memory so that when I go from the list view (which displays all devices) to the detail view (which displays a single device), I don't have to make a call to the single resource.

Instead, I would only make this call when the user uses pull to refresh inside the detail screen and then write back the data to the collection which is used as the datasource for the list screen.

Now due to the fact that the app is running on a mobile device, there can be multiple errors while making a call to the web service and if an error occurs I would like to show a message to the user to inform about the problem.

I was thinking about using a Subject inside a Singleton class as my data source to which my UI subscribes. Whenever I need to refresh the list, I would create a new observable with my web service call which, as a side effect, populates new data to the Subject but does not populate onError or onComplete events to the Subject.

I hope this piece of pseudo code explains better what I mean:

//Pull-to-refresh function
Observable.create { observable in
  let hud = HUD("loading devices")
  self.hud = hud
  observable.next()
  return Disposable.create { hud.dismiss() }
}
.flatMap {
  return DeviceService.getList() //The web service
}
.flatMap { devices in
  DeviceSingleton.devicesSubject.next(devices) //The singleton
  return Observable.just()
}
.subscribe(
  onNext: { self.hud.dismiss() }
  onError: { error in
      self.hud.dismiss()
      self.displayError(error)
  }
)
.disposed(by: disposeBag)

The pull-to-refresh in the detail screen would look similar but it would involve getting the current data from the subject, then replacing the updated device and re-publishing the data like so:

//Pull-to-refresh function in detail screen
let id = ...
Observable.create { observable in
  let hud = HUD("loading devices")
  self.hud = hud
  observable.next()
  return Disposable.create { hud.dismiss() }
}
.flatMap {
  return DeviceService.getDevice(id: id) //The web service
}
.flatMap { device in
  let devices = try! DeviceSingleton.devicesSubject.value()
  let updatedDevices = self.updateDevice(device, in: devices) //removing old device, adding new one, sorting, etc.
  DeviceSingleton.devicesSubject.next(devices)
  return Observable.just()
}
.subscribe(
  onNext: { self.hud.dismiss() }
  onError: { error in
      self.hud.dismiss()
      self.displayError(error)
  }
)
.disposed(by: disposeBag)

Is this correct? Is this valid? What could be a better approach? I think one problem might be that reloading a single device can not only happen when the user pulls-to-refresh but also when a remote notification comes in.

I hope you can tell me if I am using Rx correctly or if I am doing something wrong here.


问:
MySQL count value by ID
Not sure if the title explains what I am trying to do correctly however I was unable to word it.

I am trying to create an output for a some graphs. The output I am aiming for is just the total value of some rows in a mySQL table grouped by a category ID. My tables are as follows:

```<code>Transactions:

TransactiondID | TransactionName |TransactionCategory| Value
*************************************************************
       1       |  GenericText1   |      1            | 30
       2       |  GenericText2   |      1            | 38
       3       |  GenericText2   |      2            | 38
</code>```

And my Reference Data for TransactionCategory

```<code>TranCatID | TransCatName
*************************
    1     | Tranportation
    2     | Petrol
</code>```

So what I want to do is do is a SUM of the value field by each category. So I would get an output of.

```<code>Category       | Value
****************************
Transportation | 68
Petrol         | 30
</code>```

I got this but it does not work. I think it is completely incorrect but wanted to show my attempt.

```<code>SELECT SUM( `TransactionValue`) AS Value,
transaction_category.transaction_category
FROM Transactions
JOIN transaction_category on Transactions.TransactionID = transaction_category_id
</code>```

答:
Grouping by either "TransactionCategory" or "TranCatID" will give you the desired result shown as follows:</p>

```<code>SELECT TransactionCategory.TransCatName, SUM( `Value`) AS Value FROM Transactions  JOIN TransactionCategory on Transactions.TransactionCategory = TransactionCategory.TranCatID GROUP BY TransactionCategory.TransactionCategory;

or

SELECT TransactionCategory.TransCatName, SUM( `Value`) AS Value FROM Transactions  JOIN TransactionCategory on Transactions.TransactionCategory = TransactionCategory.TranCatID GROUP BY TransactionCategory.TranCatID;
</code>```

Title: MySQL count value by ID

Body:
Not sure if the title explains what I am trying to do correctly however I was unable to word it.

I am trying to create an output for a some graphs. The output I am aiming for is just the total value of some rows in a mySQL table grouped by a category ID. My tables are as follows:

Transactions:

TransactiondID | TransactionName |TransactionCategory| Value
*************************************************************
       1       |  GenericText1   |      1            | 30
       2       |  GenericText2   |      1            | 38
       3       |  GenericText2   |      2            | 38

And my Reference Data for TransactionCategory

TranCatID | TransCatName
*************************
    1     | Tranportation
    2     | Petrol

So what I want to do is do is a SUM of the value field by each category. So I would get an output of.

Category       | Value
****************************
Transportation | 68
Petrol         | 30

I got this but it does not work. I think it is completely incorrect but wanted to show my attempt.

SELECT SUM( `TransactionValue`) AS Value,
transaction_category.transaction_category
FROM Transactions
JOIN transaction_category on Transactions.TransactionID = transaction_category_id

Body:
Grouping by either "TransactionCategory" or "TranCatID" will give you the desired result shown as follows:

SELECT TransactionCategory.TransCatName, SUM( `Value`) AS Value FROM Transactions  JOIN TransactionCategory on Transactions.TransactionCategory = TransactionCategory.TranCatID GROUP BY TransactionCategory.TransactionCategory;

or

SELECT TransactionCategory.TransCatName, SUM( `Value`) AS Value FROM Transactions  JOIN TransactionCategory on Transactions.TransactionCategory = TransactionCategory.TranCatID GROUP BY TransactionCategory.TranCatID;


问:
When might Application_EndRequest not be called?
We have an ASMX web service hosted in IIS 6, and are seeing some strange behaviour with one of our WebMethods. After an iisreset, the first call to a particular method fails to return to the client, which times out after 60 seconds.

I've introduced logging into Application_BeginRequest and Application_EndRequest in the Global.asax.cs file. The logging shows that for that one call, EndRequest is not called. A try-finally block in the method itself shows that it is running to completion.

There are other requests to different methods before, during and after this one that show no problems. TcpTrace shows that no reply is ever returned for that first request to the method.

The logs also show that the thread that serviced the request starts serving other requests after the finally block has completed.

I'm wondering what might cause such behaviour, and how I might debug this further.

答:
some recommendations:
put your logging under:
        Application_AuthenticateRequest
        Application_Error
and see if you are getting any error.

If this cannot help, check your Application Domain's and IIS's event logs


问:
How is a vptr initialized at compile time?
The above was an interview question.

I understand that as part of the virtual dispatch mechanism, the compiler creates a vTable for each class and inserts an extra pointer (vptr) during compilation. But when exactly does it assign the class' virtual table to this vptr?

How is the vptr initialized at compile time?

Whatever I read over the internet says that the compiler initializes the vptr at compile time, but initialization is a run-time mechanism. Am I wrong?

I don't understand how a compiler would initialize it.

答:
Strictly speaking, this is not covered by the C++ standard. But enough implementations go for this to consider it common wisdom. I'm going to address only single inheritance, since multiple inheritance is way more complicated.

The compiler knows in advance where a type's virtual function table is located (it's the compiler that allocates it). It also knows all of that class type's constructors. So what it has to do is fairly simple, at the beginning of each constructor, add the following (illustrative):

```<code>this->_vptr = /*VTable's Address*/;
</code>```

That's it. This is exceptionally simple, and even works intuitively when overriding. Because a derived class's constructor will just overwrite the pointer value.

And yes, that assignment, naturally, happens at run-time. Even though the table itself may be populated beforehand.

Body:
Strictly speaking, this is not covered by the C++ standard. But enough implementations go for this to consider it common wisdom. I'm going to address only single inheritance, since multiple inheritance is way more complicated.

The compiler knows in advance where a type's virtual function table is located (it's the compiler that allocates it). It also knows all of that class type's constructors. So what it has to do is fairly simple, at the beginning of each constructor, add the following (illustrative):

this->_vptr = /*VTable's Address*/;

That's it. This is exceptionally simple, and even works intuitively when overriding. Because a derived class's constructor will just overwrite the pointer value.

And yes, that assignment, naturally, happens at run-time. Even though the table itself may be populated beforehand.


问:
Get the element with the highest occurrence in an array
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

```<code>['pear', 'apple', 'orange', 'apple']
</code>```

the 'apple' element is the most frequent one.

答:
Try it too, this does not take in account browser version.

```<code>function mode(arr){
var a = [],b = 0,occurrence;
    for(var i = 0; i < arr.length;i++){
    if(a[arr[i]] != undefined){
        a[arr[i]]++;
    }else{
        a[arr[i]] = 1;
    }
    }
    for(var key in a){
    if(a[key] > b){
        b = a[key];
        occurrence = key;
    }
    }
return occurrence;
}
alert(mode(['segunda','terça','terca','segunda','terça','segunda']));
</code>```

Please note that this function returns latest occurence in the array
  when 2 or more entries appear same number of times!

Body:
I'm looking for an elegant way of determining which element has the highest occurrence (mode) in a JavaScript array.

For example, in

['pear', 'apple', 'orange', 'apple']

the 'apple' element is the most frequent one.

Body:
Try it too, this does not take in account browser version.

function mode(arr){
var a = [],b = 0,occurrence;
    for(var i = 0; i < arr.length;i++){
    if(a[arr[i]] != undefined){
        a[arr[i]]++;
    }else{
        a[arr[i]] = 1;
    }
    }
    for(var key in a){
    if(a[key] > b){
        b = a[key];
        occurrence = key;
    }
    }
return occurrence;
}
alert(mode(['segunda','terça','terca','segunda','terça','segunda']));

Please note that this function returns latest occurence in the array
  when 2 or more entries appear same number of times!


问:
fast/right way to create Domain-Objects out of database
i have in the database typical tables like user, usergroup, and they have relations.

in my domain-model i want that if you request users, you will get the users and each user has the property belongsto, which means these are the groups he belongs to. in the property i want to have the list of groups (typesafe as groups)

the same should be done on the other hand, that means each group should know which users belong to the group.

i have this classes (example):

```<code>public class User
{
    int Id { get; set; }
    string Name { get; set; }
    List<Usergroup> BelongsTo { get; set; }

    User()
    {
        BelongsTo = new List<Usergroup>();
    }
}

public class Usergroup
{
    int Id { get; set; }
    string Name { get; set; }
    List<User> Users { get; set; }

    Usergroup()
    {
        Users = new List<User>();
    }
}

internal class Relation
{
    int userId;
    int groupId;
}
</code>```

now, whats the best way to implement it, and whats the fastest way to get all objects filled.

btw: i'm using subsonic to get all the database-records (for each table one select). and there are at least 1500 user and 30 groups.

my current code is based on foreach over the groups, relations.where for the groups, and then users.singleordefault to find the user and then add the user to the group and the group to the user. but it takes appx 30secs to do this.

my client-app is a webapp, so i store the results after all in a cached repository, thats why i'm doing it in this way!!

答:
my current code is based on foreach over the groups, relations.where for the groups, and then users.singleordefault to find the user and then add the user to the group and the group to the user.

I don't understand what you're saying here.

it takes appx 30secs to do this

Whatever it is you're doing seems too slow, given there's only 1500 users and 30 groups.

now, whats the best way to implement it, and whats the fastest way to get all objects filled.

If you wanted ...

Either, all users, with the groups for each user

Or, all groups, with the users for each group

... then I might suggest selecting joined records from the database.

However, because ...

You want all data (joined in both directions)

You only have 1500 records

... then I suggest that you select everything as simply as you can, and join in it your application.

```<code>//select users
Dictionary<int, User> users = new Dictionary<int, User>();
foreach (User user in selectUsersFromDatabase())
{
  users.Add(user.Id, user);
}
//select groups
Dictionary<int, Group> groups = new Dictionary<int, Group>();
foreach (Group group in selectGroupsFromDatabase())
{
  groups.Add(group.Id, group);
}
//select relations
//and join groups to users
//and join users to groups
foreach (Relation relation in selectRelationsFromDatabase())
{
  //find user in dictionary
  User user = users[relation.userId];
  //find group in dictionary
  Group group = groups[relation.groupId];
  //add group to user and add user to group
  user.BelongsTo.Add(group);
  group.Users.Add(user);
}
</code>```

Body:
i have in the database typical tables like user, usergroup, and they have relations.

in my domain-model i want that if you request users, you will get the users and each user has the property belongsto, which means these are the groups he belongs to. in the property i want to have the list of groups (typesafe as groups)

the same should be done on the other hand, that means each group should know which users belong to the group.

i have this classes (example):

public class User
{
    int Id { get; set; }
    string Name { get; set; }
    List<Usergroup> BelongsTo { get; set; }

    User()
    {
        BelongsTo = new List<Usergroup>();
    }
}

public class Usergroup
{
    int Id { get; set; }
    string Name { get; set; }
    List<User> Users { get; set; }

    Usergroup()
    {
        Users = new List<User>();
    }
}

internal class Relation
{
    int userId;
    int groupId;
}

now, whats the best way to implement it, and whats the fastest way to get all objects filled.

btw: i'm using subsonic to get all the database-records (for each table one select). and there are at least 1500 user and 30 groups.

my current code is based on foreach over the groups, relations.where for the groups, and then users.singleordefault to find the user and then add the user to the group and the group to the user. but it takes appx 30secs to do this.

my client-app is a webapp, so i store the results after all in a cached repository, thats why i'm doing it in this way!!

Body:
my current code is based on foreach over the groups, relations.where for the groups, and then users.singleordefault to find the user and then add the user to the group and the group to the user.

I don't understand what you're saying here.

it takes appx 30secs to do this

Whatever it is you're doing seems too slow, given there's only 1500 users and 30 groups.

now, whats the best way to implement it, and whats the fastest way to get all objects filled.

If you wanted ...

Either, all users, with the groups for each user

Or, all groups, with the users for each group

... then I might suggest selecting joined records from the database.

However, because ...

You want all data (joined in both directions)

You only have 1500 records

... then I suggest that you select everything as simply as you can, and join in it your application.

//select users
Dictionary<int, User> users = new Dictionary<int, User>();
foreach (User user in selectUsersFromDatabase())
{
  users.Add(user.Id, user);
}
//select groups
Dictionary<int, Group> groups = new Dictionary<int, Group>();
foreach (Group group in selectGroupsFromDatabase())
{
  groups.Add(group.Id, group);
}
//select relations
//and join groups to users
//and join users to groups
foreach (Relation relation in selectRelationsFromDatabase())
{
  //find user in dictionary
  User user = users[relation.userId];
  //find group in dictionary
  Group group = groups[relation.groupId];
  //add group to user and add user to group
  user.BelongsTo.Add(group);
  group.Users.Add(user);
}

OwnerDisplayName: ChrisW

LastEditorDisplayName: ChrisW


问:
How to perform division operation in dataFrame Spark using Scala?
I have a dataFrame something like below.

```<code>+---+---+-----+
|uId| Id| sum |
+---+---+-----+
|  3|  1|  1.0|
|  7|  1|  1.0|
|  1|  2|  3.0|
|  1|  1|  1.0|
|  6|  5|  1.0|
</code>```

using above DataFrame, I want to generate new DataFrame mention below
Sum column should be :-

For example:

```<code>For uid=3 and id=1, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
1.0*1/3=0.333

For uid=7 and id=1, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
1.0*1/3=0.333

For uid=1 and id=2, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
3.0*1/1=3.0

For uid=6 and id=5, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
1.0*1/1=1.0
</code>```

My final output should be:

```<code>+---+---+---------+
|uId| Id|  sum    |
+---+---+---------+
|  3|  1|  0.33333|
|  7|  1|  0.33333|
|  1|  2|  3.0    |
|  1|  1|  0.3333 |
|  6|  5|  1.0    |
</code>```

答:
You can use Window function to get the count of each group of id column and finally use that count to divide the original sum

```<code>import org.apache.spark.sql.expressions.Window
val windowSpec = Window.partitionBy("id")

import org.apache.spark.sql.functions._
df.withColumn("sum", $"sum"/count("id").over(windowSpec))
</code>```

you should have the final dataframe as

```<code>+---+---+------------------+
|uId|Id |sum               |
+---+---+------------------+
|3  |1  |0.3333333333333333|
|7  |1  |0.3333333333333333|
|1  |1  |0.3333333333333333|
|6  |5  |1.0               |
|1  |2  |3.0               |
+---+---+------------------+
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dataFrame something like below.

+---+---+-----+
|uId| Id| sum |
+---+---+-----+
|  3|  1|  1.0|
|  7|  1|  1.0|
|  1|  2|  3.0|
|  1|  1|  1.0|
|  6|  5|  1.0|

using above DataFrame, I want to generate new DataFrame mention below
Sum column should be :-

For example:

For uid=3 and id=1, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
1.0*1/3=0.333

For uid=7 and id=1, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
1.0*1/3=0.333

For uid=1 and id=2, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
3.0*1/1=3.0

For uid=6 and id=5, my sum column value should be  (old sum value  * 1 / count of ID(1)) I.e.
1.0*1/1=1.0

My final output should be:

+---+---+---------+
|uId| Id|  sum    |
+---+---+---------+
|  3|  1|  0.33333|
|  7|  1|  0.33333|
|  1|  2|  3.0    |
|  1|  1|  0.3333 |
|  6|  5|  1.0    |

Body:
You can use Window function to get the count of each group of id column and finally use that count to divide the original sum

import org.apache.spark.sql.expressions.Window
val windowSpec = Window.partitionBy("id")

import org.apache.spark.sql.functions._
df.withColumn("sum", $"sum"/count("id").over(windowSpec))

you should have the final dataframe as

+---+---+------------------+
|uId|Id |sum               |
+---+---+------------------+
|3  |1  |0.3333333333333333|
|7  |1  |0.3333333333333333|
|1  |1  |0.3333333333333333|
|6  |5  |1.0               |
|1  |2  |3.0               |
+---+---+------------------+