问:
Django rest framework, use different serializers in the same ModelViewSet
I would like to provide two different serializers and yet be able to benefit from all the facilities of ModelViewSet:

When viewing a list of objects, I would like each object to have an url which redirects to its details and every other relation appear using __unicode __ of the target model;

example:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "emilio",
  "accesso": "CHI",
  "membri": [
    "emilio",
    "michele",
    "luisa",
    "ivan",
    "saverio"
  ]
}
```

<ul>
<li>When viewing the details of an object, I would like to use the default <code>HyperlinkedModelSerializer</code></li>
</ul>

<p>example:</p>

<pre class="lang-json prettyprint-override"><code>{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "http://127.0.0.1:8000/database/utenti/3/",
  "accesso": "CHI",
  "membri": [
    "http://127.0.0.1:8000/database/utenti/3/",
    "http://127.0.0.1:8000/database/utenti/4/",
    "http://127.0.0.1:8000/database/utenti/5/",
    "http://127.0.0.1:8000/database/utenti/6/",
    "http://127.0.0.1:8000/database/utenti/7/"
  ]
}
</code>```

I managed to make all this work as I wish in the following way:

serializers.py

```<code># serializer to use when showing a list
class ListaGruppi(serializers.HyperlinkedModelSerializer):
    membri = serializers.RelatedField(many = True)
    creatore = serializers.RelatedField(many = False)

    class Meta:
        model = models.Gruppi

# serializer to use when showing the details
class DettaglioGruppi(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Gruppi
</code>```

views.py

```<code>class DualSerializerViewSet(viewsets.ModelViewSet):
    """
    ViewSet providing different serializers for list and detail views.

    Use list_serializer and detail_serializer to provide them
    """
    def list(self, *args, **kwargs):
        self.serializer_class = self.list_serializer
        return viewsets.ModelViewSet.list(self, *args, **kwargs)

    def retrieve(self, *args, **kwargs):
        self.serializer_class = self.detail_serializer
        return viewsets.ModelViewSet.retrieve(self, *args, **kwargs)

class GruppiViewSet(DualSerializerViewSet):
    model = models.Gruppi
    list_serializer = serializers.ListaGruppi
    detail_serializer = serializers.DettaglioGruppi

    # etc.
</code>```

Basically I detect when the user is requesting a list view or a detailed view and change serializer_class to suit my needs. I am not really satisfied with this code though, it looks like a dirty hack and, most importantly, what if two users request a list and a detail at the same moment?

Is there a better way to achieve this using ModelViewSets or do I have to fall back using GenericAPIView?

EDIT:

Here's how to do it using a custom base ModelViewSet:

```<code>class MultiSerializerViewSet(viewsets.ModelViewSet):
    serializers = {
        'default': None,
    }

    def get_serializer_class(self):
            return self.serializers.get(self.action,
                        self.serializers['default'])

class GruppiViewSet(MultiSerializerViewSet):
    model = models.Gruppi

    serializers = {
        'list':    serializers.ListaGruppi,
        'detail':  serializers.DettaglioGruppi,
        # etc.
    }
</code>```

答:
Regarding providing different serializers, why is nobody going for the approach that checks the HTTP method? It's clearer IMO and requires no extra checks.

```<code>def get_serializer_class(self):
    if self.request.method == 'POST':
        return NewRackItemSerializer
    return RackItemSerializer
</code>```

Credits/source: https://github.com/encode/django-rest-framework/issues/1563#issuecomment-42357718

Body:
I would like to provide two different serializers and yet be able to benefit from all the facilities of ModelViewSet:

When viewing a list of objects, I would like each object to have an url which redirects to its details and every other relation appear using __unicode __ of the target model;

example:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "emilio",
  "accesso": "CHI",
  "membri": [
    "emilio",
    "michele",
    "luisa",
    "ivan",
    "saverio"
  ]
}

When viewing the details of an object, I would like to use the default HyperlinkedModelSerializer

example:

{
  "url": "http://127.0.0.1:8000/database/gruppi/2/",
  "nome": "universitari",
  "descrizione": "unitn!",
  "creatore": "http://127.0.0.1:8000/database/utenti/3/",
  "accesso": "CHI",
  "membri": [
    "http://127.0.0.1:8000/database/utenti/3/",
    "http://127.0.0.1:8000/database/utenti/4/",
    "http://127.0.0.1:8000/database/utenti/5/",
    "http://127.0.0.1:8000/database/utenti/6/",
    "http://127.0.0.1:8000/database/utenti/7/"
  ]
}

I managed to make all this work as I wish in the following way:

serializers.py

# serializer to use when showing a list
class ListaGruppi(serializers.HyperlinkedModelSerializer):
    membri = serializers.RelatedField(many = True)
    creatore = serializers.RelatedField(many = False)

    class Meta:
        model = models.Gruppi

# serializer to use when showing the details
class DettaglioGruppi(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Gruppi

views.py

class DualSerializerViewSet(viewsets.ModelViewSet):
    """
    ViewSet providing different serializers for list and detail views.

    Use list_serializer and detail_serializer to provide them
    """
    def list(self, *args, **kwargs):
        self.serializer_class = self.list_serializer
        return viewsets.ModelViewSet.list(self, *args, **kwargs)

    def retrieve(self, *args, **kwargs):
        self.serializer_class = self.detail_serializer
        return viewsets.ModelViewSet.retrieve(self, *args, **kwargs)

class GruppiViewSet(DualSerializerViewSet):
    model = models.Gruppi
    list_serializer = serializers.ListaGruppi
    detail_serializer = serializers.DettaglioGruppi

    # etc.

Basically I detect when the user is requesting a list view or a detailed view and change serializer_class to suit my needs. I am not really satisfied with this code though, it looks like a dirty hack and, most importantly, what if two users request a list and a detail at the same moment?

Is there a better way to achieve this using ModelViewSets or do I have to fall back using GenericAPIView?

EDIT:

Here's how to do it using a custom base ModelViewSet:

class MultiSerializerViewSet(viewsets.ModelViewSet):
    serializers = {
        'default': None,
    }

    def get_serializer_class(self):
            return self.serializers.get(self.action,
                        self.serializers['default'])

class GruppiViewSet(MultiSerializerViewSet):
    model = models.Gruppi

    serializers = {
        'list':    serializers.ListaGruppi,
        'detail':  serializers.DettaglioGruppi,
        # etc.
    }

Body:
Regarding providing different serializers, why is nobody going for the approach that checks the HTTP method? It's clearer IMO and requires no extra checks.

def get_serializer_class(self):
    if self.request.method == 'POST':
        return NewRackItemSerializer
    return RackItemSerializer

Credits/source: https://github.com/encode/django-rest-framework/issues/1563#issuecomment-42357718


来源: stackexchange

问:
How to include html partials with webpack (version 2) with the html-loader?
I am working hard to include a simple footer.html, as an html partial) via html-loader. I am using webpack version 2.

I failed trying to use ${require('**./footer.html**')} and ${require('**../footer.html**')}.

I am not using ejs loader and I do not use the handlebar plugin.

Does somebody know how I can fix this problem and whether it possible to render partials with webpack.

Thanks for your advice!

答:
I tested with you webpack.config.js file. All you have to do is to remove the following from it:

{
    test: /\.html$/,
    use: ['html-loader']
},
```

So that the fallback lodash loader comes into play.

ContentLicense: CC BY-SA 3.0

Body:
I tested with you webpack.config.js file. All you have to do is to remove the following from it:

{
    test: /\.html$/,
    use: ['html-loader']
},

So that the fallback lodash loader comes into play.


问:
parameter for shell scripts that is started with qsub
how can I parametrize a shell script that is executed on a grid (started with qsub) ? I have a shell script, where I use getopts to read the parameters.

When I start (qsub script.sh -r firstparam -s secondparam ..) this working script with qsub I receive error messages,

qsub: invalid option -- s

qsub: illegal -r value

as qsub thinks the parameter are for itself. Yet I have not found any solution.

Thanks

答:
Using the qsub -v option is the proper way:

```<code>qsub -v par_name=par_value[,par_name=par_value...] script.sh
</code>```

par_name can be used as variable in the shell script.

ContentLicense: CC BY-SA 2.5

Body:
Using the qsub -v option is the proper way:

qsub -v par_name=par_value[,par_name=par_value...] script.sh

par_name can be used as variable in the shell script.


问:
Regex get string after string and between white spaces
I'm parsing /var/log/secure looking to check for sudo commands in Linux and need a regex to pull out the user ID that did it.

I have a log entries that looks like this:

```<code>Nov 13 11:44:41 hostname sudo:     accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/
Nov 13 11:44:41 hostname sudo: accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/
</code>```

For whatever reason, I run across some log entries where there is a bunch of white space between sudo: and accountname.

Using a regex, how do I extract the text after sudo: followed by any number of blank spaces and before any number of blank spaces followed by :

I've been playing with online regex testers and this is as close as I've been able to get:

```<code>((sudo:)[ \t]+).*?([ \t]+)
</code>```

Note: regex needs to be a valid java regular expression.

答:
Just use sudo:\\s+([^\\s]+). This should match sudo: accountName, sudo:   accountName, sudo:account_name, and so on (if you want to match sudo:accountName change the first plus sign + for an asterisk *). It stops when it finds an space after the account name. Then, it's just a matter of getting the value of matcher.group(1) which would be the account name. Like this:

```<code>Pattern pattern = Pattern.compile("sudo:\\s+([^\\s]+)");
Matcher matcher = pattern.matcher("Nov 13 11:44:41 hostname sudo:     accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/");
matcher.find(); // Keep in mind this assumes all lines will match
System.out.println(matcher.group(1)); // accountName
</code>```

Here you have a working example

Side note: You can accomplish the same in a single line with this approach (without regular expressions):

```<code>"Nov 13 11:44:41 hostname sudo:     accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/".split("sudo:")[1].trim().split(" ")[0];
</code>```

Here you have a working example

Body:
I'm parsing /var/log/secure looking to check for sudo commands in Linux and need a regex to pull out the user ID that did it.

I have a log entries that looks like this:

Nov 13 11:44:41 hostname sudo:     accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/
Nov 13 11:44:41 hostname sudo: accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/

For whatever reason, I run across some log entries where there is a bunch of white space between sudo: and accountname.

Using a regex, how do I extract the text after sudo: followed by any number of blank spaces and before any number of blank spaces followed by :

I've been playing with online regex testers and this is as close as I've been able to get:

((sudo:)[ \t]+).*?([ \t]+)

Note: regex needs to be a valid java regular expression.

Body:
Just use sudo:\\s+([^\\s]+). This should match sudo: accountName, sudo:   accountName, sudo:account_name, and so on (if you want to match sudo:accountName change the first plus sign + for an asterisk *). It stops when it finds an space after the account name. Then, it's just a matter of getting the value of matcher.group(1) which would be the account name. Like this:

Pattern pattern = Pattern.compile("sudo:\\s+([^\\s]+)");
Matcher matcher = pattern.matcher("Nov 13 11:44:41 hostname sudo:     accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/");
matcher.find(); // Keep in mind this assumes all lines will match
System.out.println(matcher.group(1)); // accountName

Here you have a <a href="https://tio.run/##tVHLTsMwELznK1Y5JSo4jahUkZADAo4tFS1CqC2Sm7iJS2Jb9qYCoX57cPPghsSFgzXe2Vl7tHOgR3opFROH7P26aXilpEY4WJbUyEuiWc4@yIxiWjAdO7/0FxSRaRE7aUmNgRUz@OUAqHpX8hQMUrRwlDyDinLhLVFzkQPVuVlv/bMSoOdKLpglIYGOBnDn8gjhFYRhNJlEkxAKaVDQioGpMxm1GpqmshY4P7MRrFaviUITjCGGxct9EhhZsYxrWz4vH54SLSXa@93jbHY7t@0dF0FaVDKD6XQKAVZqmAjciz@6@D8HrYFT3EK/Z1A9JgNDUlkpXjLPbe1sNmbkrd8sbEe@63fDe6k9LhB4Mo6B37SbJiUTORa2Ho38YeN92jarDpPhP9IzXpcS3/YvwyAley4y74ddfhpkFZE1EmXTxVJ4gzDXslZe6Pfak3M@p6b5Bg" rel="nofollow noreferrer">working example

Side note: You can accomplish the same in a single line with this approach (without regular expressions):

"Nov 13 11:44:41 hostname sudo:     accountName : TTY=pts/0 ; PWD=/somedir ; USER=root ; COMMAND=/bin/chmod 777 /tmp/somedir/".split("sudo:")[1].trim().split(" ")[0];

Here you have a working example


问:
display message in button click during postback
Hai frnds , i want to show the message on button click....please help advance thanks</p>

答: use javascript, set an click event and change the text of the button....</p>


问:
How do I convert this csv data into a bar chart?
Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

```<code>ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30
</code>```

I have this so far

```<code>import pandas as pd

df = pd.read_csv("items4.csv",sep=",").set_index('ID')

d = dict(zip(df.index,df.values.tolist()))

print(d)
{12345: ['Italy', 100, 80], 13579: ['China', 50, 30], 24680: ['France', 50, 30]} #This is the output
</code>```

I want to make a bar chart that looks something like this with this given data.

答:
IIUC, call set_index and plot.bar:

```<code>df

      ID    Tour  Start  End
0  12345   Italy    100   80
1  13579   China     50   30
2  24680  France     50   30

df.set_index('Tour')[['Start', 'End']].plot.bar()
plt.show()
</code>```

If you're interested in annotating the bars too, take a look at Annotate bars with values on Pandas bar plots.

Body:
Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30

I have this so far

import pandas as pd

df = pd.read_csv("items4.csv",sep=",").set_index('ID')

d = dict(zip(df.index,df.values.tolist()))

print(d)
{12345: ['Italy', 100, 80], 13579: ['China', 50, 30], 24680: ['France', 50, 30]} #This is the output

I want to make a bar chart that looks something like this with this given data.

Body:
IIUC, call set_index and plot.bar:

df

      ID    Tour  Start  End
0  12345   Italy    100   80
1  13579   China     50   30
2  24680  France     50   30

df.set_index('Tour')[['Start', 'End']].plot.bar()
plt.show()

If you're interested in annotating the bars too, take a look at Annotate bars with values on Pandas bar plots.


问:
Ensure order of execution promise
I have two promises like the one below at my endpoint:

```<code>request.post({
          url: url,
          json: smsSTART,
          headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json'
          }
      },function(error, response, body){

      });
</code>```

I would like to ensure that "Request 1" is executed first than "Request 2"

Looking for I found the promise.race, but I saw some criticism about it.

How can I proceed?

答:
The example function looks like an async callback rather than a promise. The request-promise module wraps request in a promise.

```<code> const rp = require('request-promise')

 async function post(url, payload){
   return rp({
     method: 'POST',
     uri: url,
     json: true,
     body: payload,
   })
 }

 async function posts(){
   let post1 = await post('https://me.com/path1', { request: 1 })
   let post2 = await post('https://me.com/path2', { request: 2 })
 }

 posts()
</code>```

async/await are available in Node.js v7.6+ and via Babel.

Title: Ensure order of execution promise

Body:
I have two promises like the one below at my endpoint:

request.post({
          url: url,
          json: smsSTART,
          headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json'
          }
      },function(error, response, body){

      });

I would like to ensure that "Request 1" is executed first than "Request 2"

Looking for I found the promise.race, but I saw some criticism about it.

How can I proceed?

Body:
The example function looks like an async callback rather than a promise. The request-promise module wraps request in a promise.

 const rp = require('request-promise')

 async function post(url, payload){
   return rp({
     method: 'POST',
     uri: url,
     json: true,
     body: payload,
   })
 }

 async function posts(){
   let post1 = await post('https://me.com/path1', { request: 1 })
   let post2 = await post('https://me.com/path2', { request: 2 })
 }

 posts()

async/await are available in Node.js v7.6+ and via Babel.


问:
JavaScript Add function called as many times as you wanted
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that? </p>

```<code>function add () {

}
add(1)(2)(3)();  //6
add(5)(6)(7)(8)(9)()  //35
</code>```

答:
I would just use a Spread syntax like this:

function add(...values) {
  return values.reduce((sum, value) => sum + value, 0)
}

console.log(add(1, 4, 34, 45, 3, 4, 5))```

Body:
The simplest question for that is like to write a function that could return the sum of all the parameters. How I can do that?

function add () {

}
add(1)(2)(3)();  //6
add(5)(6)(7)(8)(9)()  //35


问:
How to pass symbol as parameter of post request in ruby?
This code work well

```<code>Geokit::default_units = :miles #:kms, :nms, :meters
</code>```

But this code make errors

```<code>puts params[:unit]     # miles
Geokit::default_units = params[:unit] #:miles, :kms, :nms, :meters
</code>```

What is wrong with this?

答:
have you confirmed that params[:unit] is actually a symbol, and not a string?

```<code> Geokit::default_units = params[:unit].to_sym
</code>```

If the above solves your problem, then you didn't have a symbol in there to start with (likely, if params has been read from an HTTP request)

Body:
This code work well

Geokit::default_units = :miles #:kms, :nms, :meters

But this code make errors

puts params[:unit]     # miles
Geokit::default_units = params[:unit] #:miles, :kms, :nms, :meters

What is wrong with this?

Body:
have you confirmed that params[:unit] is actually a symbol, and not a string?

 Geokit::default_units = params[:unit].to_sym

If the above solves your problem, then you didn't have a symbol in there to start with (likely, if params has been read from an HTTP request)


问:
Distribution function in ERC20 token which can be executed on a later stage?
I need to implement Distribute function in ERC20 token code which will send equal amount of the tokens on an array of addresses when executed. Below is the source code that I will use for that. Of course I will change the variables for my token:

https://pastebin.com/wAe9a1EV

Is the Distribute function that I add at the end of the contract suitable and does not interfere with the rest of the source code? Can I execute distributions on a later stage through Myetherwallet or Mist with that function if I deploy the contract with that function on the blockchain?

```<code> function distributeToken(address[] addresses, uint256 _value) onlyOwner{
 for (uint i = 0; i < addresses.length; i++) {
 balances[owner] -= _value;
 balances[addresses[i]] += _value;
 Transfer(owner, addresses[i], _value);
 }
}
</code>```

答:
Make sure you add some sanity checks to that function, you should do some basic checks to avoid user error.

e.g

```<code>require(_value > 0);
require(balances[owner] >= (_value * addresses.length));

// In your loop
require(addresses[i] != 0x0);
</code>```

Body:
I need to implement Distribute function in ERC20 token code which will send equal amount of the tokens on an array of addresses when executed. Below is the source code that I will use for that. Of course I will change the variables for my token:

https://pastebin.com/wAe9a1EV

Is the Distribute function that I add at the end of the contract suitable and does not interfere with the rest of the source code? Can I execute distributions on a later stage through Myetherwallet or Mist with that function if I deploy the contract with that function on the blockchain?

 function distributeToken(address[] addresses, uint256 _value) onlyOwner{
 for (uint i = 0; i < addresses.length; i++) {
 balances[owner] -= _value;
 balances[addresses[i]] += _value;
 Transfer(owner, addresses[i], _value);
 }
}

Body:
Make sure you add some sanity checks to that function, you should do some basic checks to avoid user error.

e.g

require(_value > 0);
require(balances[owner] >= (_value * addresses.length));

// In your loop
require(addresses[i] != 0x0);


问:
Default values in Haskell data types
When you define a class in a object-oriented language it usually sets the default values for the member variables. Is there any mechanism in Haskell to do the same thing in record types? And a follow up question: If we don't know from the very start all the values for a data constructor but we obtain them from IO interaction can we build the type using something like the builder pattern from OOP?

Thanks in advance

答:
Is there any mechanism in Haskell to do the same thing in record types?

What you can do is hide the constructor, and provide a function as constructor instead.

Say for instance we have a list we want to update, together with a revision number, then we can define it as:

```<code>data RevisionList a = RevisionList { theList :: [a],
                                     revision :: Int }
                          deriving Show
</code>```

Now we can define a function that initializes the BuildList with an initial list:

```<code>revisionList :: [a] -> RevisionList a
revisionList xs = RevisionList { theList = xs, revision=0 }
</code>```

and by hiding the constructor in the module export, we thus hide the possibility to initialize it with another revision than revision 0. So the module could look like:

```<code>module Foo(RevisionList(), revisionList)

data RevisionList a = RevisionList { theList :: [a],
                                     revision :: Int }

revisionList :: [a] -> RevisionList a
revisionList xs = RevisionList { theList = xs, revision=0 }
</code>```

something like the builder pattern from OOP?

We can for instance use a State monad for that. For instance:

```<code>module Foo(RevisionList(), revisionList,
           increvision, RevisionListBuilder, prefixList)

import Control.Monad.State.Lazy

type RevisionListBuilder a = State (RevisionList a)

increvision :: RevisionListBuilder a ()
increvision = do
    rl <- get
    put (rl { revision = 1 + revision rl})

prefixList :: a -> RevisionListBuilder a ()
prefixList x = do
    rl <- get
    put (rl { theList = x : theList rl })
    increvision
</code>```

So we get the RevisionList thus far, perform updates, put the new result back, and increment the revision number.

So now another module can import our Foo, and use the builder like:

```<code>some_building :: RevisionListBuilder Int ()
some_building = do
    prefixList 4
    prefixList 1
</code>```

and now we can "make" a RevisionList at revision 2 with as final list [1,4,2,5] with:

```<code>import Control.Monad.State.Lazy(execState)

some_rev_list :: RevisionList Int
some_rev_list = execState some_building (revisionList [2,5])
</code>```

So it would look approximately like:

Foo.hs:

```<code>module Foo(RevisionList(), revisionList,
           increvision, RevisionListBuilder, prefixList)

data RevisionList a = RevisionList { theList :: [a],
                                     revision :: Int }
                          deriving Show
type RevisionListBuilder a = State (RevisionList a)

revisionList :: [a] -> RevisionList a
revisionList xs = RevisionList { theList = xs, revision=0 }

increvision :: RevisionListBuilder a ()
increvision = do
    rl <- get
    put (rl { revision = 1 + revision rl})

prefixList :: a -> RevisionListBuilder a ()
prefixList x = do
    rl <- get
    put (rl { theList = x : theList rl })
    increvision
</code>```

Bar.hs:

```<code>import Foo
import Control.Monad.State.Lazy(execState)

some_building :: RevisionListBuilder Int ()
some_building = do
    prefixList 4
    prefixList 1

some_rev_list :: RevisionList Int
some_rev_list = execState some_building (revisionList [2,5])
</code>```

So now we have constructed a some_rev_list with the "building" of some_building:

```<code>Foo Bar> some_rev_list
RevisionList {theList = [1,4,2,5], revision = 2}
</code>```

Title: Default values in Haskell data types

Body:
Is there any mechanism in Haskell to do the same thing in record types?

What you can do is hide the constructor, and provide a function as constructor instead.

Say for instance we have a list we want to update, together with a revision number, then we can define it as:

data RevisionList a = RevisionList { theList :: [a],
                                     revision :: Int }
                          deriving Show

Now we can define a function that initializes the BuildList with an initial list:

revisionList :: [a] -> RevisionList a
revisionList xs = RevisionList { theList = xs, revision=0 }

and by hiding the constructor in the module export, we thus hide the possibility to initialize it with another revision than revision 0. So the module could look like:

module Foo(RevisionList(), revisionList)

data RevisionList a = RevisionList { theList :: [a],
                                     revision :: Int }

revisionList :: [a] -> RevisionList a
revisionList xs = RevisionList { theList = xs, revision=0 }

something like the builder pattern from OOP?

We can for instance use a State monad for that. For instance:

module Foo(RevisionList(), revisionList,
           increvision, RevisionListBuilder, prefixList)

import Control.Monad.State.Lazy

type RevisionListBuilder a = State (RevisionList a)

increvision :: RevisionListBuilder a ()
increvision = do
    rl <- get
    put (rl { revision = 1 + revision rl})

prefixList :: a -> RevisionListBuilder a ()
prefixList x = do
    rl <- get
    put (rl { theList = x : theList rl })
    increvision

So we get the RevisionList thus far, perform updates, put the new result back, and increment the revision number.

So now another module can import our Foo, and use the builder like:

some_building :: RevisionListBuilder Int ()
some_building = do
    prefixList 4
    prefixList 1

and now we can "make" a RevisionList at revision 2 with as final list [1,4,2,5] with:

import Control.Monad.State.Lazy(execState)

some_rev_list :: RevisionList Int
some_rev_list = execState some_building (revisionList [2,5])

So it would look approximately like:

Foo.hs:

module Foo(RevisionList(), revisionList,
           increvision, RevisionListBuilder, prefixList)

data RevisionList a = RevisionList { theList :: [a],
                                     revision :: Int }
                          deriving Show
type RevisionListBuilder a = State (RevisionList a)

revisionList :: [a] -> RevisionList a
revisionList xs = RevisionList { theList = xs, revision=0 }

increvision :: RevisionListBuilder a ()
increvision = do
    rl <- get
    put (rl { revision = 1 + revision rl})

prefixList :: a -> RevisionListBuilder a ()
prefixList x = do
    rl <- get
    put (rl { theList = x : theList rl })
    increvision

Bar.hs:

import Foo
import Control.Monad.State.Lazy(execState)

some_building :: RevisionListBuilder Int ()
some_building = do
    prefixList 4
    prefixList 1

some_rev_list :: RevisionList Int
some_rev_list = execState some_building (revisionList [2,5])

So now we have constructed a some_rev_list with the "building" of some_building:

Foo Bar> some_rev_list
RevisionList {theList = [1,4,2,5], revision = 2}

ContentLicense: CC BY-SA 4.0


问:
Populate email input on HTML form from email value within google sheets cell
I've created a pop-up email dialog box within google's html editor as follows with the input for email as follows:

```<code><input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">
</code>```

In my .gs file I'm storing the value of my cell containing the email address I want to use as follows:

```<code>function getEmail()
 {
   var s=SpreadsheetApp.getActive().getSheetByName("Template");
   var row=15;
   var column=3;
   var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
   Logger.log(contactAddress);
 }
</code>```

This works fine and is capturing the email address correctly and logging it. I now need to change the 'value' of my email input so that it populates with this address when the diolog opens. So I have the following in my HTML file:

```<code>window.onload = function (contactAddress)
{
   document.getElementById('mail').value=contactAddress;
}
</code>```

However, this is resulting in '[object Event]' being populated. I feel I'm close here but can't quite get it over the line!!!!

UPDATE:

So I added this to my .gs:

```<code>function showDialog() {
  var html = HtmlService.createHtmlOutputFromFile('emailTemplate')
  .setWidth(800)
  .setHeight(500);
  html.myvar = new getEmail();
  html.evaluate().getContent();
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
  .showModalDialog(html, ' ');
 }
</code>```

However, when I run the script I get an error stating Object does not allow properties to be added or changed.

答:
Edit: Original answer deleted.

So here is my answer to your problem. Tested it out, and it works.

My HTML page is set up like this just to test it:

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function onSuccess(contact) {
     //var contactAddress = google.script.run.getEmail();
        document.getElementById('mail').value=contact;
    }

    google.script.run.withSuccessHandler(onSuccess).getEmail();
    </script>
  </head>
  <body>
    <input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">

  </body>
</html>
</code>```

My .gs file contains

```<code>function getEmail()
 {
   var s=SpreadsheetApp.getActive().getSheetByName("Sheet1");
   var row=1;
   var column=3;
   var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
   Logger.log(contactAddress);
   return contactAddress;
 }
</code>```

The only real difference is that I added a return statement (and changed the row from 15 to 1 for my test).

Seems the main problem was how you were calling the function on the HTML page. It needed a google.script.run.withSuccessHandler() call instead of a window.onload = function() call.

Body:
I've created a pop-up email dialog box within google's html editor as follows with the input for email as follows:

<input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">

In my .gs file I'm storing the value of my cell containing the email address I want to use as follows:

function getEmail()
 {
   var s=SpreadsheetApp.getActive().getSheetByName("Template");
   var row=15;
   var column=3;
   var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
   Logger.log(contactAddress);
 }

This works fine and is capturing the email address correctly and logging it. I now need to change the 'value' of my email input so that it populates with this address when the diolog opens. So I have the following in my HTML file:

window.onload = function (contactAddress)
{
   document.getElementById('mail').value=contactAddress;
}

However, this is resulting in '[object Event]' being populated. I feel I'm close here but can't quite get it over the line!!!!

UPDATE:

So I added this to my .gs:

function showDialog() {
  var html = HtmlService.createHtmlOutputFromFile('emailTemplate')
  .setWidth(800)
  .setHeight(500);
  html.myvar = new getEmail();
  html.evaluate().getContent();
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
  .showModalDialog(html, ' ');
 }

However, when I run the script I get an error stating Object does not allow properties to be added or changed.

Body:
Edit: Original answer deleted.

So here is my answer to your problem. Tested it out, and it works.

My HTML page is set up like this just to test it:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
    function onSuccess(contact) {
     //var contactAddress = google.script.run.getEmail();
        document.getElementById('mail').value=contact;
    }

    google.script.run.withSuccessHandler(onSuccess).getEmail();
    </script>
  </head>
  <body>
    <input type="email" name="email" class="form-control" id="mail" aria-describedby="emailHelp" value="">

  </body>
</html>

My .gs file contains

function getEmail()
 {
   var s=SpreadsheetApp.getActive().getSheetByName("Sheet1");
   var row=1;
   var column=3;
   var contactAddress=Utilities.formatString('%s',s.getRange(row, column).getValue());
   Logger.log(contactAddress);
   return contactAddress;
 }

The only real difference is that I added a return statement (and changed the row from 15 to 1 for my test).

Seems the main problem was how you were calling the function on the HTML page. It needed a google.script.run.withSuccessHandler() call instead of a window.onload = function() call.


问:
error MSB3073: How do I fix this?
```<code>3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: The command "copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Release\EnergyLib.dll" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32\EnergyLib32.dll"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\EnergyDriver\objfre_win7_x86\i386\EnergyDriver.sys" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :VCEnd" exited with code 1.
</code>```

I was researching online, I think it has to do something with relative pathing; but I'm not sure. Can someone help explain what is wrong and how to fix this?

答:
Just add your user to permission for cmd.exe file in system32.
that will solve this problem.</p>

Title: error MSB3073: How do I fix this?

Body:
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: The command "copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Release\EnergyLib.dll" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32\EnergyLib32.dll"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: copy "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\EnergyDriver\objfre_win7_x86\i386\EnergyDriver.sys" "C:\Users\jlee\Desktop\10_IPG2.7_4\InitialPowerGadget\Bins32"
3>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppCommon.targets(113,5): error MSB3073: :VCEnd" exited with code 1.

I was researching online, I think it has to do something with relative pathing; but I'm not sure. Can someone help explain what is wrong and how to fix this?


问:
UI best practice question: Cancel button or Cancel link
I have a discussion with a colleague about what the "web standard" is for canceling in an form. In our discussion we have a "change password" page as example. We have a designed "send" button and "cancel" button. Both the same design.

He claims that in web standard a cancel button is no longer a button but a link transferring the user to another page. In my opinion, for those pages including a cancel button it actually is a cancel button which either resets the form and/or send the user to the prevision page.

Who is correct? Link or button... or both? And why? Any links to where this kind of standard is decided?

Br,

Paul Peelen

EDIT
I guess the answer with most votes will be the "correct answer"?

答: Buttons in a form setting indicate you're about to do something involving the form; submitting, clearing, add a file etc. Making the cancel button a link, indicates you can leave any time you want, without any consequences.</p>


问:
Load external JSON data with pure JavaScript
I am trying a JavaScript challenge but get stuck badly. The requirement is not to modify any other files except app.js and no library (i.e. no JQuery etc.)

Here is the file system:

```<code>css
  bootstrap.min.css
image
  1.gif
  2.gif
  3.gif
  4.gif
  5.gif
js
  app.js
json
  data.js
sample.html
</code>```

Here is the sample.html:

```<code><!doctype>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
  <h2>Only Pure JavaScript</h2>
  <div class="contents">
    <table class="table">
      <thead>
        <tr>
          <th>Id</th>
          <th>Image</th>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>
  </div>
</div>
<script src="json/data.js"></script>
<script src="js/app.js"></script>
</body>
</html>
</code>```

Here is the data.js:

```<code>var sample_data = [
  {
    "id": "5",
    "name": "name #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "name #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "name #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "name #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "name #10",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
]
</code>```

And this is what I have in app.js currently:

```<code>var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "<br>");

var table = document.createElement('table');
var body = document.createElement('tbody');

for (var i = 0; i < len; i++) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var s = sample_data[i];

    document.write('id: ' + s.id + "<br>");

    td.innerHTML = s.id;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('name: ' + s.name + "<br>");
    td.innerHTML = s.name;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('thumbnailUrl: ' + s.thumbnailUrl + "<br>");
    td.innerHTML = s.thumbnailUrl;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('price: ' + s.price + "<br>");
    td.innerHTML = s.price;
    tr.appendChild(td);

    body.appendChild(tr);
}

table.appendChild(body);
</code>```

I've spent so much time and tried 4 different ways and this one attached is the closest I can get (it shows correctly with document.write). Seriously, without any library or changes in the html page, it is hard for me. Any help or direction of where to look for information will be greatly appreciated. Remember, only app.js can be changed for this.

答:
data.js is Javascript, not JSON. To load it, create a ');
```

Body:
I am trying a JavaScript challenge but get stuck badly. The requirement is not to modify any other files except app.js and no library (i.e. no JQuery etc.)

Here is the file system:

css
  bootstrap.min.css
image
  1.gif
  2.gif
  3.gif
  4.gif
  5.gif
js
  app.js
json
  data.js
sample.html

Here is the sample.html:

<!doctype>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<title>Sample</title>
<link rel="stylesheet" href="css/bootstrap.min.css">

Only Pure JavaScript

          Id
          Image
          Name
          Price

Here is the data.js:

var sample_data = [
  {
    "id": "5",
    "name": "name #5",
    "thumbnailUrl": "image/5.gif",
    "price": 170
  },
  {
    "id": "1",
    "name": "name #1",
    "thumbnailUrl": "image/1.gif",
    "price": 170
  },
  {
    "id": "2",
    "name": "name #2",
    "thumbnailUrl": "image/2.gif",
    "price": 270
  },
  {
    "id": "8",
    "name": "name #8",
    "thumbnailUrl": "image/8.gif",
    "price": 70
  },
  {
    "id": "10",
    "name": "name #10",
    "thumbnailUrl": "image/10.gif",
    "price": 170
  },
]

And this is what I have in app.js currently:

var jsonFile = "json/data.js";
var len = sample_data.length;
// document.write('len: ' + len + "
");

var table = document.createElement('table');
var body = document.createElement('tbody');

for (var i = 0; i < len; i++) {
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    var s = sample_data[i];

    document.write('id: ' + s.id + "
");

    td.innerHTML = s.id;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('name: ' + s.name + "
");
    td.innerHTML = s.name;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('thumbnailUrl: ' + s.thumbnailUrl + "
");
    td.innerHTML = s.thumbnailUrl;
    tr.appendChild(td);

    td = document.createElement('td');
    document.write('price: ' + s.price + "
");
    td.innerHTML = s.price;
    tr.appendChild(td);

    body.appendChild(tr);
}

table.appendChild(body);

I've spent so much time and tried 4 different ways and this one attached is the closest I can get (it shows correctly with document.write). Seriously, without any library or changes in the html page, it is hard for me. Any help or direction of where to look for information will be greatly appreciated. Remember, only app.js can be changed for this.

Body:
data.js is Javascript, not JSON. To load it, create a <script> element that points to it.

After the line:

var jsonFile = "json/data.js";

Put the line:

document.write('<scr' + 'ipt src="' + jsonFile + '"></script>');


问:
mask in FlannBasedMatcher::match doesn't work normally
Cross post here

I note the function FlannBasedMatcher::match have a parameter mask, so I give a try with following code:

```<code>#include<opencv.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
using namespace std;

int main() {
    Mat rightImg = imread("right.jpg", 0);
    Mat leanImg = imread("lean.jpg", 0);
    if (!rightImg.data || !leanImg.data) {
        cout << "Fail to read your image. Please check your path.\n";
        return -1;
    }
    resize(leanImg, leanImg, rightImg.size());
    int minHessian = 400;
    SurfFeatureDetector detector(minHessian);
    vector<KeyPoint> keypoints_right, keypoints_lean;

    detector.detect(rightImg, keypoints_right);
    detector.detect(leanImg, keypoints_lean);

    Mat med_right, med_lean;
    drawKeypoints(rightImg, keypoints_right, med_right);
    drawKeypoints(leanImg, keypoints_lean, med_lean);

    SurfDescriptorExtractor extractor;
    Mat descriptors_right, descriptors_lean;
    extractor.compute(rightImg, keypoints_right, descriptors_right);
    extractor.compute(leanImg, keypoints_lean, descriptors_lean);

    FlannBasedMatcher matcher;
    vector< DMatch > matches;

    Mat mask(descriptors_right.rows, descriptors_lean.rows, CV_8UC1, Scalar(0));

    Mat target(rightImg.size(), CV_8UC1, Scalar(255));
    ellipse(target, Point(rightImg.cols / 2, rightImg.rows / 2), Size(rightImg.cols / 2, rightImg.rows / 2), 0, 0, 360, Scalar(0), CV_FILLED);

    for (int i = 0; i < mask.rows; i++) {
        uchar* pixrow = mask.ptr<uchar>(i);
        for (int j = 0; j < mask.cols; j++) {
            if (target.at<uchar>(keypoints_right[i].pt) == 255)
                pixrow[j] = 255;
        }
    }

    matcher.match(descriptors_right, descriptors_lean, matches/*, mask*/);//use it or not to test

    Mat img_matches;
    drawMatches(rightImg, keypoints_right, leanImg, keypoints_lean,
        matches, img_matches, Scalar::all(-1), Scalar::all(-1),
        vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
    return 0;
    }
</code>```

And this is my right.jpg and lean.jpg. I don't care those points in the center of right.jpg. So I make a mask for it. But I note I will get a same result totally whether I use the mask in the function FlannBasedMatcher::match. You can use the mask or not to reproduce it. Do I have missed something or the OpenCV have a bug in my 2.4.13? Can anyone tell me how to use the mask in the FlannBasedMatcher::match? I think it is a usefull parameter..

答: From the docs: "FlannBasedMatcher does not support masking permissible matches of descriptor sets because flann::Index does not support this." See the DescriptorMatcher::isMaskSupported method for a way to test if the matcher supports masking.

Body:
Cross post here

I note the function FlannBasedMatcher::match have a parameter mask, so I give a try with following code:

#include<opencv.hpp>
#include "opencv2/core/core.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/nonfree/nonfree.hpp"
using namespace cv;
using namespace std;

int main() {
    Mat rightImg = imread("right.jpg", 0);
    Mat leanImg = imread("lean.jpg", 0);
    if (!rightImg.data || !leanImg.data) {
        cout << "Fail to read your image. Please check your path.\n";
        return -1;
    }
    resize(leanImg, leanImg, rightImg.size());
    int minHessian = 400;
    SurfFeatureDetector detector(minHessian);
    vector<KeyPoint> keypoints_right, keypoints_lean;

    detector.detect(rightImg, keypoints_right);
    detector.detect(leanImg, keypoints_lean);

    Mat med_right, med_lean;
    drawKeypoints(rightImg, keypoints_right, med_right);
    drawKeypoints(leanImg, keypoints_lean, med_lean);

    SurfDescriptorExtractor extractor;
    Mat descriptors_right, descriptors_lean;
    extractor.compute(rightImg, keypoints_right, descriptors_right);
    extractor.compute(leanImg, keypoints_lean, descriptors_lean);

    FlannBasedMatcher matcher;
    vector< DMatch > matches;

    Mat mask(descriptors_right.rows, descriptors_lean.rows, CV_8UC1, Scalar(0));

    Mat target(rightImg.size(), CV_8UC1, Scalar(255));
    ellipse(target, Point(rightImg.cols / 2, rightImg.rows / 2), Size(rightImg.cols / 2, rightImg.rows / 2), 0, 0, 360, Scalar(0), CV_FILLED);

    for (int i = 0; i < mask.rows; i++) {
        uchar* pixrow = mask.ptr<uchar>(i);
        for (int j = 0; j < mask.cols; j++) {
            if (target.at<uchar>(keypoints_right[i].pt) == 255)
                pixrow[j] = 255;
        }
    }

    matcher.match(descriptors_right, descriptors_lean, matches/*, mask*/);//use it or not to test

    Mat img_matches;
    drawMatches(rightImg, keypoints_right, leanImg, keypoints_lean,
        matches, img_matches, Scalar::all(-1), Scalar::all(-1),
        vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS);
    return 0;
    }

And this is my right.jpg and lean.jpg. I don't care those points in the center of right.jpg. So I make a mask for it. But I note I will get a same result totally whether I use the mask in the function FlannBasedMatcher::match. You can use the mask or not to reproduce it. Do I have missed something or the OpenCV have a bug in my 2.4.13? Can anyone tell me how to use the mask in the FlannBasedMatcher::match? I think it is a usefull parameter..


问:
Vue2 Router link from server data
I have a Vue2 SPA page which is loading content from the server.
It is editable by client in a CMS.

When user is adding relative link (lets say /about-us), this should be picked by Vue and treated as the menu link (which already has /about-us link).

However link to /about-us added in the content is reloading the whole page, so it is not picked as vue route.

How is it possible to attach router to such links?

What I did so far is changing the content in the backend response.

So I am essentially changing

```<code><a href="/about-us">Text</a>
</code>```

into

```<code><router-link :to="{ path: '/about-us'}">Text</router-link>
</code>```

Using:

```<code>function parseVueLinks($value)
{
    $pattern = "/<a([^>]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}
</code>```

Still no luck.

How is this possible?

答:
If I understand you correctly your issue is not with the link parsing, this looks fine. You want to compile the resulting HTML so Vue router can kick in. There is a function Vue.compile which can help you:

```<code>Vue.component('my-component', {
  template: '<div></div>',
  props: {
    html: String
  },
  mounted() {
    let { render, staticRenderFns } = Vue.compile(this.html);
    new Vue({ el: this.$el, render, staticRenderFns, router })
  }
});
</code>```

With this component you can specify any HTML using the prop html, which will then get compiled in the mounted event and will replace the component template. Please note the router being passed to new Vue(), this is a reference to your Vue router, which is needed so all the <router-link> tags in your HTML can be resolved.

Now you can use this component to compile your HTML like this:

```<code><my-component :html="content"></my-component>
</code>```

where var content = parseVueLinks('Text').

You can see a working example over here https://codepen.io/anon/pen/BmmjwV

Title: Vue2 Router link from server data

Body:
I have a Vue2 SPA page which is loading content from the server.
It is editable by client in a CMS.

When user is adding relative link (lets say /about-us), this should be picked by Vue and treated as the menu link (which already has /about-us link).

However link to /about-us added in the content is reloading the whole page, so it is not picked as vue route.

How is it possible to attach router to such links?

What I did so far is changing the content in the backend response.

So I am essentially changing

Text

into

<router-link :to="{ path: '/about-us'}">Text</router-link>

Using:

function parseVueLinks($value)
{
    $pattern = "/]*) href=\\\"[^http|https|mailto|tel]([^\\\"]*)\"([^>]*)>(.*?)<(\\/a>)/";
    $replace = "<router-link$1 :to=\"{ path: '$2'}\">$4</router-link>";

    return preg_replace($pattern, $replace, $value);
}

Still no luck.

How is this possible?

Body:
If I understand you correctly your issue is not with the link parsing, this looks fine. You want to compile the resulting HTML so Vue router can kick in. There is a function Vue.compile which can help you:

Vue.component('my-component', {
  template: '<div></div>',
  props: {
    html: String
  },
  mounted() {
    let { render, staticRenderFns } = Vue.compile(this.html);
    new Vue({ el: this.$el, render, staticRenderFns, router })
  }
});

With this component you can specify any HTML using the prop html, which will then get compiled in the mounted event and will replace the component template. Please note the router being passed to new Vue(), this is a reference to your Vue router, which is needed so all the <router-link> tags in your HTML can be resolved.

Now you can use this component to compile your HTML like this:

<my-component :html="content"></my-component>

where var content = parseVueLinks('<a href="/about-us">Text</a>').

You can see a working example over here https://codepen.io/anon/pen/BmmjwV


问:
How to select a cell in the Tktable without editing state?
I'm using the Tktable package to draw the table, below example:

```<code>package require Tktable
global TableValue
array set TableValue {
    0,1 Col1 0,2 Col2 1,0 Row1 2,0 Row2 1,1 a 1,2 b 2,1 c 2,2 d
}
table .t -rows 3 -cols 3 -titlerows 1 -titlecols 1 -variable TableValue
pack .t
</code>```

When i click the cell, how to just show the cell selected state not editing state that I can use "Delete" to clear the cell content and if I double click the cell then show editing state. How to realize that? Thanks!

答:
Probably the greatest visual control you can achieve with a table widget is done by embedding widgets in the table. This is because the table has default bindings that are difficult to override to your specifications. But you can insert widgets as illustrated below, and completely control their appearance. Play around with attributes and bindings as you like. But this should be a fair start.

```<code>package require Tktable

array set TableTitles {
    0,1 Col1 0,2 Col2 1,0 Row1 2,0 Row2, 1,1 a 1,2 b 2,1 c 2,2 d
}

table .t -rows 3 -cols 3 -titlerows 1 -titlecols 1 -variable TableTitles
pack .t

proc EnableEntry { entry } {
    $entry configure -state normal -cursor ibeam
    $entry selection range 0 end
}

foreach row [list 1 2] {
    foreach col [list 1 2] {
        set cell [set row],[set col]
        # Use the array already created for the entry variable
        set entry [entry .t.e$row$col -justify center -textvariable TableTitles($cell) \
            -highlightthickness 1 -highlightcolor blue -state disabled \
            -disabledbackground white -disabledforeground black -cursor arrow]

        bind $entry <Double-Button-1> "EnableEntry $entry"
        bind $entry <Button-1> "focus $entry"
        bind $entry <FocusOut> "$entry configure -state disabled -cursor arrow"
        .t window configure $cell -window $entry
    }
}
</code>```

Body:
I'm using the Tktable package to draw the table, below example:

package require Tktable
global TableValue
array set TableValue {
    0,1 Col1 0,2 Col2 1,0 Row1 2,0 Row2 1,1 a 1,2 b 2,1 c 2,2 d
}
table .t -rows 3 -cols 3 -titlerows 1 -titlecols 1 -variable TableValue
pack .t

When i click the cell, how to just show the cell selected state not editing state that I can use "Delete" to clear the cell content and if I double click the cell then show editing state. How to realize that? Thanks!

Body:
Probably the greatest visual control you can achieve with a table widget is done by embedding widgets in the table. This is because the table has default bindings that are difficult to override to your specifications. But you can insert widgets as illustrated below, and completely control their appearance. Play around with attributes and bindings as you like. But this should be a fair start.

package require Tktable

array set TableTitles {
    0,1 Col1 0,2 Col2 1,0 Row1 2,0 Row2, 1,1 a 1,2 b 2,1 c 2,2 d
}

table .t -rows 3 -cols 3 -titlerows 1 -titlecols 1 -variable TableTitles
pack .t

proc EnableEntry { entry } {
    $entry configure -state normal -cursor ibeam
    $entry selection range 0 end
}

foreach row [list 1 2] {
    foreach col [list 1 2] {
        set cell [set row],[set col]
        # Use the array already created for the entry variable
        set entry [entry .t.e$row$col -justify center -textvariable TableTitles($cell) \
            -highlightthickness 1 -highlightcolor blue -state disabled \
            -disabledbackground white -disabledforeground black -cursor arrow]

        bind $entry <Double-Button-1> "EnableEntry $entry"
        bind $entry <Button-1> "focus $entry"
        bind $entry <FocusOut> "$entry configure -state disabled -cursor arrow"
        .t window configure $cell -window $entry
    }
}


问:
find the "rebase -m" starting point
Recently I am using

```<code>git checkout dev_branch -b merge_branch
git rebase -m merge_branch master
git checkout master
git rebase merge_branch
</code>```

to do a merge rebase. As the help document indicates, merge_branch is first reset to HEAD of master and then the new commits in original dev_branch is played back one by one to the new branch.

Several days later I want to find where is the "starting point" of this rebase merge. I can find the first delta commit in dev_branch using

```<code>git merge-base master dev_branch // Get an SHA_root of the common ancestor
git log --reverse -1 <SHA_root>..dev_branch  // Get an SHA_delta of the first delta commit
</code>```

But I don't find a way to locate where is the merged version of

```<code>git branch --contains <SHA_delta>
</code>```

But find it is only in "dev_branch", not in "master_branch", though actually it has been merged.

In another word, the same commit with different parent (like the situation using cherry-pick) are with different SHA. Is there a way that git can recognize them as actually identical?

答:
This is what git cherry does.

In a situation where topic consisted of three commits, and the maintainer applied two of them, the situation might look like:

```<code>$ git log --graph --oneline --decorate --boundary origin/master...topic
* 7654321 (origin/master) upstream tip commit
[... snip some other commits ...]
* cccc111 cherry-pick of C
* aaaa111 cherry-pick of A
</code>```

[… snip a lot more that has happened …]

```<code>| * cccc000 (topic) commit C
| * bbbb000 commit B
| * aaaa000 commit A
|/
* 1234567 branch point
</code>```

In such cases, git cherry shows a concise summary of what has yet to be applied:

```<code>$ git cherry origin/master topic
- cccc000... commit C
+ bbbb000... commit B
- aaaa000... commit A
</code>```

Here, we see that the commits A and C (marked with -) can be dropped from your topic branch when you rebase it on top of origin/master, while the commit B (marked with +) still needs to be kept so that it will be sent to be applied to origin/master.

Title: find the "rebase -m" starting point

Body:
Recently I am using

git checkout dev_branch -b merge_branch
git rebase -m merge_branch master
git checkout master
git rebase merge_branch

to do a merge rebase. As the help document indicates, merge_branch is first reset to HEAD of master and then the new commits in original dev_branch is played back one by one to the new branch.

Several days later I want to find where is the "starting point" of this rebase merge. I can find the first delta commit in dev_branch using

git merge-base master dev_branch // Get an SHA_root of the common ancestor
git log --reverse -1 <SHA_root>..dev_branch  // Get an SHA_delta of the first delta commit

But I don't find a way to locate where is the merged version of

git branch --contains <SHA_delta>

But find it is only in "dev_branch", not in "master_branch", though actually it has been merged.

In another word, the same commit with different parent (like the situation using cherry-pick) are with different SHA. Is there a way that git can recognize them as actually identical?

Body:
This is what git cherry does.

In a situation where topic consisted of three commits, and the maintainer applied two of them, the situation might look like:

$ git log --graph --oneline --decorate --boundary origin/master...topic
* 7654321 (origin/master) upstream tip commit
[... snip some other commits ...]
* cccc111 cherry-pick of C
* aaaa111 cherry-pick of A

[… snip a lot more that has happened …]

| * cccc000 (topic) commit C
| * bbbb000 commit B
| * aaaa000 commit A
|/
* 1234567 branch point

In such cases, git cherry shows a concise summary of what has yet to be applied:

$ git cherry origin/master topic
- cccc000... commit C
+ bbbb000... commit B
- aaaa000... commit A

Here, we see that the commits A and C (marked with -) can be dropped from your topic branch when you rebase it on top of origin/master, while the commit B (marked with +) still needs to be kept so that it will be sent to be applied to origin/master.


问:
Sharepoint discussion board, replicate the settings and rules to a webpart
I am currently developing a sharepoint webpart to display a private discussion board. The discussion can only be viewed by limitted users. The following allowed users as of now could be: Site Collection Owner, Discussion Board Members, Discussion Board Owner.

The way I setup the security of the webpart is by getting all the users and check if they belong to the said allowed persons in the discussion board.

My logic seems to be working right now but, the concern here of my client is:
What if in the future they will change the settings or security of the discussion board and I might no longer be around to fix the code of the webpart such that the settings and security of the webpart will sync to the discussion board?
My idea as of now is, instead of developing a code that will copy the settings and security of the discussion board and apply it to the webpart, I will point the settings and security of the webpart right directly to the discussion board. My question right now is, would this be possible?

Please see the attached pic to have a better view of what I wanted to happen.

答:
The web part should use the CheckPermissions method

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist.checkpermissions.aspx

```<code>SPContext.List.CheckPermissions(SPBasePermissions.EditListItems);
</code>```

This way you can set the permissions only on the list.

If a user doesn't have permissions, either display nothing, or a message that says "you have no permissions"

Body:
The web part should use the CheckPermissions method

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist.checkpermissions.aspx

SPContext.List.CheckPermissions(SPBasePermissions.EditListItems);

This way you can set the permissions only on the list.

If a user doesn't have permissions, either display nothing, or a message that says "you have no permissions"


问:
return a zero for month with zero rows using case extract sql
Trying to list last 12 months counting records in each month and want to include months where no record was found to display 0 next to that month name. I tried including another table that would always have at least one record for all 12 months and case extract the month from their but I know I'm doing this wrong. All the research I did, didn't use case extract and I'm looking to keep it if I can.. open to if i cannot.

Current query works and is:

```<code>select count(RMA.id) "Number of RMAs", case extract(month from
RMA.RMA_DATE)when 1 then 'January'
when 2 then 'February'
when 3 then 'March'
when 4 then 'April'
when 5 then 'May'
when 6 then 'June'
when 7 then 'July'
when 8 then 'August'
when 9 then 'September'
when 10 then 'October'
when 11 then 'November'
when 12 then 'December'
else 'error'
end, extract(year from RMA.rma_date)
from RMA,
    RMA_DETAIL
where RMA.ID = RMA_DETAIL.RMA_ID And
       RMA.rma_date >= sysdate - 365 And
       RMA_DETAIL.ID <> 3
group by extract(month from RMA.rma_date), extract(year from RMA.rma_date)
order by extract(year from RMA.rma_date), extract(month from RMA.rma_date)
</code>```

results

答:
SUM Cases

If you're already fine with identifying the months in the query, it might be worth just summing these up. A count can only count what's in the table. If you sum up the instances of appearance, you'll get a sum of 0 where your months don't appear. Consider something like this:

```<code>SELECT
    SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '1' THEN 1 ELSE 0) AS January
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '2' THEN 1 ELSE 0) AS February
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '3' THEN 1 ELSE 0) AS March
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '4' THEN 1 ELSE 0) AS April
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '5' THEN 1 ELSE 0) AS May
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '6' THEN 1 ELSE 0) AS June
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '7' THEN 1 ELSE 0) AS July
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '8' THEN 1 ELSE 0) AS August
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '9' THEN 1 ELSE 0) AS September
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '10' THEN 1 ELSE 0) AS October
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '11' THEN 1 ELSE 0) AS November
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '12' THEN 1 ELSE 0) AS December
...
</code>```

Body:
Trying to list last 12 months counting records in each month and want to include months where no record was found to display 0 next to that month name. I tried including another table that would always have at least one record for all 12 months and case extract the month from their but I know I'm doing this wrong. All the research I did, didn't use case extract and I'm looking to keep it if I can.. open to if i cannot.

Current query works and is:

select count(RMA.id) "Number of RMAs", case extract(month from
RMA.RMA_DATE)when 1 then 'January'
when 2 then 'February'
when 3 then 'March'
when 4 then 'April'
when 5 then 'May'
when 6 then 'June'
when 7 then 'July'
when 8 then 'August'
when 9 then 'September'
when 10 then 'October'
when 11 then 'November'
when 12 then 'December'
else 'error'
end, extract(year from RMA.rma_date)
from RMA,
    RMA_DETAIL
where RMA.ID = RMA_DETAIL.RMA_ID And
       RMA.rma_date >= sysdate - 365 And
       RMA_DETAIL.ID <> 3
group by extract(month from RMA.rma_date), extract(year from RMA.rma_date)
order by extract(year from RMA.rma_date), extract(month from RMA.rma_date)

results

Body:
SUM Cases

If you're already fine with identifying the months in the query, it might be worth just summing these up. A count can only count what's in the table. If you sum up the instances of appearance, you'll get a sum of 0 where your months don't appear. Consider something like this:

SELECT
    SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '1' THEN 1 ELSE 0) AS January
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '2' THEN 1 ELSE 0) AS February
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '3' THEN 1 ELSE 0) AS March
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '4' THEN 1 ELSE 0) AS April
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '5' THEN 1 ELSE 0) AS May
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '6' THEN 1 ELSE 0) AS June
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '7' THEN 1 ELSE 0) AS July
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '8' THEN 1 ELSE 0) AS August
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '9' THEN 1 ELSE 0) AS September
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '10' THEN 1 ELSE 0) AS October
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '11' THEN 1 ELSE 0) AS November
    ,SUM(CASE WHEN EXTRACT(month from RMA.RMA_DATE) = '12' THEN 1 ELSE 0) AS December
...


问:
Break code line with Console.WriteLine
I can't find how to split a Console.WriteLine text without creating a new line in the program. I mean, my code line is too long and it's uncomforable to scroll horizontally in order to check it

```<code>Console.WriteLine("BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla")
</code>```

the result is only a line of text in the console (Might be split because of its length, but keeps being the same line)

into the same, but in different lines in the code, giving the same result. I've tried just splitting them with a new code of line as if it was common code like this:

```<code>Console.WriteLine("BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla
BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla
BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla
BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla")
</code>```

and the result keeps being a line of text in the console

But looks like it's not the right way.

Sorry if it's stupid. Thanks

答:
If you only are going to write Bla then do</p>

```<code>for(int i = 0; i < /*Amount of Bla's here*/; i++){
Console.Write("Bla");
}
</code>```

Title: Break code line with Console.WriteLine

Body:
I can't find how to split a Console.WriteLine text without creating a new line in the program. I mean, my code line is too long and it's uncomforable to scroll horizontally in order to check it

Console.WriteLine("BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla")

the result is only a line of text in the console (Might be split because of its length, but keeps being the same line)

into the same, but in different lines in the code, giving the same result. I've tried just splitting them with a new code of line as if it was common code like this:

Console.WriteLine("BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla
BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla
BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla
BlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBlaBla")

and the result keeps being a line of text in the console

But looks like it's not the right way.

Sorry if it's stupid. Thanks

Body:
If you only are going to write Bla then do

for(int i = 0; i < /*Amount of Bla's here*/; i++){
Console.Write("Bla");
}


问:
Table with Fixed header in Elm - how to sync the header with the body both horizontally and vertically
I have a table where I don't know in advance the number of columns and number of rows. I need:

fixed header

horizontal scroll

vertical scroll

The main issue I am having is that the table header is not moving in sync horizontally. In JavaScript, I could do that, for example in How to make fixed table header scroll horizontally in sync with tbody data?.
How can I make it work in Elm?

I also have some other issues:

the header cell not being the same width as the body cells.

In this example https://ellie-app.com/hS8kFyKRza1/0, I want only the first 3 columns to be displayed and the rest to show when scrolling horizontally, and the table to move in sync with the header when scrolling both ways.

If I can't do without JavaScript, I would appreciate some pointers on how I should set my ports and what the JS code should be.

答: If your browser support requirements allow for it, the way we've done this is to use CSS position: sticky on the th elements in the header row. Older browsers (including IE 11) don't support this, but as a progressive enhancement it works well, since unsupported browsers just don't get the sticky header effect.


问:
How to call default method from interface with TestNG tests and Selenium?
I want to know if it is possible to use default methods from interface with  TestNG @BeforeMethod annotation?

Here is sample, which I tried:

```<code>@Listeners(TestListener.class)
public interface ITestBase {
    String baseUrl = Config.getProperty(Config.TEST_HOST);
    String driverName = Config.getProperty(Config.BROWSER);
    DriversEnum driverInstance = DriversEnum.valueOf(driverName.toUpperCase());

    @BeforeMethod(alwaysRun = true)
    default public void start() {
        try {
            driver.init();
            DriverUnit.preconfigureDriver(Driver.driver.get());
            driver.get().manage().deleteAllCookies();
            driver.get().get(baseUrl);
        } catch (TimeoutException e) {
            Logger.logEnvironment("QT application is not available");
        }
    }

    @AfterMethod(alwaysRun = true)
    default public void end() {
        if (driver.get() != null) {
            try {
                driver.get().quit();
            } catch (UnreachableBrowserException e) {
                Logger.logDebug("UnreachableBrowser on close");
            } finally {
                driver.remove();
            }
        }
    }
</code>```

When I run typical TestNG test method, like:

```<code>public class AppUiDemo implements ITestBase {
    @Test(enabled = true)
    public void checkWebDriverCreation() {
      ...
    }
</code>```

start() and end() methods aren't called. Driver instance isn't created for test execution.

Is it possible to make something like it with default method and TestNG methods?

If I change the interface to a regular class, before and after methods are called (driver instance is created fine):

```<code>public class TestBase {
    protected final String baseUrl = Config.getProperty(Config.TEST_HOST);
    protected final String driverName = Config.getProperty(Config.BROWSER);
    protected final DriversEnum driverInstance = DriversEnum.valueOf(driverName.toUpperCase());

    @BeforeMethod(alwaysRun = true)
    public void start() {
    ....
</code>```

The problem is that my test class is already extending another class:

```<code>public class MainTest extends ExecutionContext
</code>```

Thus I can't extend TestBase.

Is it possible to use interface with any implementation for execution code before and after test methods?

答:
Yes, it is possible but the version of TestNG that allow using interface methods in tests is not released yet. You need to download it from this repository.

If you use Maven you can specify additional repository in your pom.xml:

```<code><repository>
    <id>testng</id>
    <name>testng</name>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>
</code>```

And then add TestNG dependency:

```<code><dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.11.1-SNAPSHOT</version>
</dependency>
</code>```

Example:

```<code>package test;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class DummyTest implements ITest {

    @BeforeMethod
    public void beforeTest() {
        System.out.println("before from class");
    }

    @Test
    public void test1() {
        System.out.println("I am test1");
    }
}
</code>```

and ITest interface

```<code>package test;

import org.testng.annotations.BeforeMethod;

public interface ITest {

    @BeforeMethod
    default void beforeDefaultInterface() {
        System.out.println("before from default interface method");
    }
    @BeforeMethod
    static void beforeStaticInterface() {
        System.out.println("before from static interface method");
    }
}
</code>```

The output of the test above will be:

```
    before from default interface method
    before from static interface method
    before from class
    I am test1
```

Body:
I want to know if it is possible to use default methods from interface with  TestNG @BeforeMethod annotation?

Here is sample, which I tried:

@Listeners(TestListener.class)
public interface ITestBase {
    String baseUrl = Config.getProperty(Config.TEST_HOST);
    String driverName = Config.getProperty(Config.BROWSER);
    DriversEnum driverInstance = DriversEnum.valueOf(driverName.toUpperCase());

    @BeforeMethod(alwaysRun = true)
    default public void start() {
        try {
            driver.init();
            DriverUnit.preconfigureDriver(Driver.driver.get());
            driver.get().manage().deleteAllCookies();
            driver.get().get(baseUrl);
        } catch (TimeoutException e) {
            Logger.logEnvironment("QT application is not available");
        }
    }

    @AfterMethod(alwaysRun = true)
    default public void end() {
        if (driver.get() != null) {
            try {
                driver.get().quit();
            } catch (UnreachableBrowserException e) {
                Logger.logDebug("UnreachableBrowser on close");
            } finally {
                driver.remove();
            }
        }
    }

When I run typical TestNG test method, like:

public class AppUiDemo implements ITestBase {
    @Test(enabled = true)
    public void checkWebDriverCreation() {
      ...
    }

start() and end() methods aren't called. Driver instance isn't created for test execution.

Is it possible to make something like it with default method and TestNG methods?

If I change the interface to a regular class, before and after methods are called (driver instance is created fine):

public class TestBase {
    protected final String baseUrl = Config.getProperty(Config.TEST_HOST);
    protected final String driverName = Config.getProperty(Config.BROWSER);
    protected final DriversEnum driverInstance = DriversEnum.valueOf(driverName.toUpperCase());

    @BeforeMethod(alwaysRun = true)
    public void start() {
    ....

The problem is that my test class is already extending another class:

public class MainTest extends ExecutionContext

Thus I can't extend TestBase.

Is it possible to use interface with any implementation for execution code before and after test methods?

Body:
Yes, it is possible but the version of TestNG that allow using interface methods in tests is not released yet. You need to download it from this repository.

If you use Maven you can specify additional repository in your pom.xml:

<repository>
    <id>testng</id>
    <name>testng</name>
    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
</repository>

And then add TestNG dependency:

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.11.1-SNAPSHOT</version>
</dependency>

Example:

package test;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class DummyTest implements ITest {

    @BeforeMethod
    public void beforeTest() {
        System.out.println("before from class");
    }

    @Test
    public void test1() {
        System.out.println("I am test1");
    }
}

and ITest interface

package test;

import org.testng.annotations.BeforeMethod;

public interface ITest {

    @BeforeMethod
    default void beforeDefaultInterface() {
        System.out.println("before from default interface method");
    }
    @BeforeMethod
    static void beforeStaticInterface() {
        System.out.println("before from static interface method");
    }
}

The output of the test above will be:

    before from default interface method
    before from static interface method
    before from class
    I am test1


问:
The "XamlCTask" task failed unexpectedly. What to do?
I am getting this error:

The "XamlCTask" task failed unexpectedly.
  System.ArgumentException: An item with the same key has already been added.

```<code>Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()
</code>```

I know that it is saying that the item is duplicated but I scanned whole project with Total Commander and I didn't find any duplicated file.

答: You might just have an error in your XAML page. "An item with the same key has already been added." might be some duplicate property.</p>

Body:
I am getting this error:

The "XamlCTask" task failed unexpectedly.
  System.ArgumentException: An item with the same key has already been added.

Server stack trace:
   at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
   at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ReadNode(XmlReader reader, Boolean nested)
   at Xamarin.Forms.Xaml.XamlParser.ParseXamlElementFor(IElementNode node, XmlReader reader)
   at Xamarin.Forms.Xaml.XamlParser.ParseXaml(RootNode rootNode, XmlReader reader)
   at Xamarin.Forms.Build.Tasks.XamlTask.ParseXaml(Stream stream, TypeReference typeReference)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute(IList`1& thrownExceptions)
   at Xamarin.Forms.Build.Tasks.XamlTask.Execute()
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

I know that it is saying that the item is duplicated but I scanned whole project with Total Commander and I didn't find any duplicated file.


问:
Testing array elements vs multiple criteria
I am trying to create a method complex_check(n), which will do the following:

Create an array of integers ascending from 0 to n

Check each element of that array against complex criteria.

For example, I have an array from 0..n, and I want to know which elements of the array are both evenly divisible by 3 and not divisible by 4. I can index through to check for single criteria like odd?, etc., but is there a compact way to check each integer against multiple criteria?

答:
This is the best I could come up with, I think this is sort of what you're trying to do:

```<code>def complex_check(n)
  check_array = (0..n).to_a
  check_array.select { |num|
    num % 3 == 0 &&
    num % 4 != 0
  }
end
</code>```

Then using it:

```<code>complex_check(15)
=> [3, 6, 9, 15]
</code>```

Body:
This is the best I could come up with, I think this is sort of what you're trying to do:

def complex_check(n)
  check_array = (0..n).to_a
  check_array.select { |num|
    num % 3 == 0 &&
    num % 4 != 0
  }
end

Then using it:

complex_check(15)
=> [3, 6, 9, 15]


问:
Reverse construction of Custom Routes from inside a Controller using Pimcore 5.x
As per the Pimcore 5 Documentation:

URLs are generated using the default URL helper of Symfony $this->path() and $this->url(). Additionally to the standard helpers for generating URLs, Pimcore offers a special templating helper ($this->pimcoreUrl()) to generate URLs like you did with Pimcore 4. You can define a placeholder in the reverse pattern with %NAME and it is also possible to define an optional part, to do so just embrace the part with curly brackets { } (see example below).

https://pimcore.com/docs/5.0.x/Development_Documentation/MVC/Routing_and_URLs/Custom_Routes.html

I should be able to reverse construct a route using the path method like so:

```<code>$this->path( 'MyRouteName', [
  'route_param_a' => 'A',
  'route_param_b' => 'B',
  'route_param_c' => 'C'
] );
</code>```

Unfortunately, when I call this from inside a Controller, I get the following error:

Attempted to call an undefined method named "path" of class "AppBundle\Controller\MyController".

Is there a similar function or method available in the Controller scope that I can use to generate my paths when I respond with my JSON object directly from the controller (without using a view)?

答:
Looks like the answer for this is not covered in the Pimcore 5 documentation, rather the Symfony 3 documentation!

https://symfony.com/doc/current/routing.html#generating-urls

```<code>$url = $this->generateUrl( 'MyRouteName', [
  'route_param_a' => 'A',
  'route_param_b' => 'B',
  'route_param_c' => 'C'
] );
</code>```

Body:
As per the Pimcore 5 Documentation:

URLs are generated using the default URL helper of Symfony $this->path() and $this->url(). Additionally to the standard helpers for generating URLs, Pimcore offers a special templating helper ($this->pimcoreUrl()) to generate URLs like you did with Pimcore 4. You can define a placeholder in the reverse pattern with %NAME and it is also possible to define an optional part, to do so just embrace the part with curly brackets { } (see example below).

https://pimcore.com/docs/5.0.x/Development_Documentation/MVC/Routing_and_URLs/Custom_Routes.html

I should be able to reverse construct a route using the path method like so:

$this->path( 'MyRouteName', [
  'route_param_a' => 'A',
  'route_param_b' => 'B',
  'route_param_c' => 'C'
] );

Unfortunately, when I call this from inside a Controller, I get the following error:

Attempted to call an undefined method named "path" of class "AppBundle\Controller\MyController".

Is there a similar function or method available in the Controller scope that I can use to generate my paths when I respond with my JSON object directly from the controller (without using a view)?

Body:
Looks like the answer for this is not covered in the Pimcore 5 documentation, rather the Symfony 3 documentation!

https://symfony.com/doc/current/routing.html#generating-urls

$url = $this->generateUrl( 'MyRouteName', [
  'route_param_a' => 'A',
  'route_param_b' => 'B',
  'route_param_c' => 'C'
] );


问:
Fixed size div which sits to the right of a main div that fills up remainder of screen
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

```<code>+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+
</code>```

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

```<code>#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}
</code>```

答:
This should work</p>

```<code><div id="container">
    <div id="left" style="background: #ff00ff; ">
        Left
        <div id="right" style="width: 210px; float: right; background: #ff0000;">
            Right
        </div>
    </div>
</div>
</code>```

Body:
I have seen lots of questions but none that seem to quite solve my problem.

I have two divs: mainbody and rightpanel. I would like the rightpanel to be a fixed size (210px), and to sit to the right of the mainbody div which fills up all the remaining space of the window.

So it would resize like this:

+----------------------------------------+
|                             |          |
|                             |          |
|                             |          |
|       mainbody              |rightpanel|
|                             |          |
|                             |          |
|                             |          |
+----------------------------------------+

+-------------------------------+
|                    |          |
|                    |          |
|                    |          |
|  mainbody          |rightpanel|
|                    |          |
|                    |          |
|                    |          |
+-------------------------------+

My current solution below sort of works, but if the window is resized to below about 900px the right bar gets pushed to the bottom as the 25% remaining space gets too small for it to fit into, so I force the window to horizontally scroll at this width.

#wrap {
    width:97%;
    margin:0 auto;
}

#mainbody {
    float:left;
    width: 75%;
    margin-right: 10px;
    margin-left: 10px;
}

#rightpanel  {
    float:right;
    width: 22%;
    min-width: 210px;
    max-width: 210px;
}

Body:
This should work

<div id="container">
    <div id="left" style="background: #ff00ff; ">
        Left
        <div id="right" style="width: 210px; float: right; background: #ff0000;">
            Right
        </div>
    </div>
</div>


问:
Handling function pointer with covariant types uniformly (how to call callbacks with derived types?)
Suppose that I have a Task class:

```<code>class Task;

using FinishedCallback = void (Task &);

class Task {
    public:
        // this function is implemented by derived classes
        // there are other virtual functions too
        virtual bool isFinished() = 0;

    private:
        std::vector<FinishedCallback> m_callbacks;

    protected:
        // these functions are called by derived classes
        void addFinishedCallback(FinishedCallback callback) {
            m_callbacks.push_back(callback);
        }

        void callFinishedCallbacks();
};
</code>```

This class is the base class. I'd like to put as much implementation as possible into it. It has a m_callbacks vector, which stores the callbacks which are needed to be called when the task is finished (callFinishedCallbacks() does this).

Now, derive from this class:

```<code>class MyTask;

using MyFinishedCallback = void (MyTask &);

class MyTask: public Task {
    public:
        void addFinishedCallback(MyFinishedCallback callback) {
            Task::addFinishedCallback(reinterpret_cast<FinishedCallback &>(callback));
        }

        // when MyTask finishes, it calls callFinishedCallbacks
};
</code>```

Here, the finished callback has MyTask & parameter, so I have to reinterpret_cast it. So my program has UB. (The reason of the MyTask & type is that I don't have to cast Task & to MyTask & in the callback - it is for convenience).

But, even my program has UB, it works (the only real problem I could have if MyTask had multiple inheritance). Is it possible to modify this program to remove UB, while retaining its main attributes:

(compiled) code is small

small amount of coding work needed, if one derives from Task

no wrappers needed for callbacks

答:
One idea would be to make a slight change to how you write your callbacks.

Use Task * rather than Task & as the callback parameter type.

At the beginning of the callback, use dynamic_cast to turn the Task * into a pointer to the derived type (MyType *).

```<code>void MyCallback(Task *task) {
  auto *mytask = dynamic_cast<MyTask *>(task);
  assert(mytask != nullptr);
  // use mytask from here on
}
</code>```

Another idea would be to use the Curiously Recurring Template Pattern (CRTP).

```<code>class BasicTask {
    public:
        virtual ~BasicTask() = default;
        virtual bool isFinished() = 0;
};

template <typename Self>
class Task : public BasicTask {
    private:
        typedef void FinishedCallback(Self &task);
        std::vector<FinishedCallback> m_callbacks;

    protected:
        void addFinishedCallback(FinishedCallback callback) {
            m_callbacks.push_back(callback);
        }

        void callFinishedCallbacks();
};
</code>```

Then you'd derive your specific task types from Task like this:

```<code>class MyTask : public Task<MyTask> { ... };
</code>```

This reduced the amount of code you have to write (because there's only one source code implementation of addFinishedCallback), but it runs the risk of generating more object code.  The optimizer and linker might be able to reign in that possibility.

Body:
Suppose that I have a Task class:

class Task;

using FinishedCallback = void (Task &);

class Task {
    public:
        // this function is implemented by derived classes
        // there are other virtual functions too
        virtual bool isFinished() = 0;

    private:
        std::vector<FinishedCallback> m_callbacks;

    protected:
        // these functions are called by derived classes
        void addFinishedCallback(FinishedCallback callback) {
            m_callbacks.push_back(callback);
        }

        void callFinishedCallbacks();
};

This class is the base class. I'd like to put as much implementation as possible into it. It has a m_callbacks vector, which stores the callbacks which are needed to be called when the task is finished (callFinishedCallbacks() does this).

Now, derive from this class:

class MyTask;

using MyFinishedCallback = void (MyTask &);

class MyTask: public Task {
    public:
        void addFinishedCallback(MyFinishedCallback callback) {
            Task::addFinishedCallback(reinterpret_cast<FinishedCallback &>(callback));
        }

        // when MyTask finishes, it calls callFinishedCallbacks
};

Here, the finished callback has MyTask & parameter, so I have to reinterpret_cast it. So my program has UB. (The reason of the MyTask & type is that I don't have to cast Task & to MyTask & in the callback - it is for convenience).

But, even my program has UB, it works (the only real problem I could have if MyTask had multiple inheritance). Is it possible to modify this program to remove UB, while retaining its main attributes:

(compiled) code is small

small amount of coding work needed, if one derives from Task

no wrappers needed for callbacks

Body:
One idea would be to make a slight change to how you write your callbacks.

Use Task * rather than Task & as the callback parameter type.

At the beginning of the callback, use dynamic_cast to turn the Task * into a pointer to the derived type (MyType *).

void MyCallback(Task *task) {
  auto *mytask = dynamic_cast<MyTask *>(task);
  assert(mytask != nullptr);
  // use mytask from here on
}

Another idea would be to use the Curiously Recurring Template Pattern (CRTP).

class BasicTask {
    public:
        virtual ~BasicTask() = default;
        virtual bool isFinished() = 0;
};

template <typename Self>
class Task : public BasicTask {
    private:
        typedef void FinishedCallback(Self &task);
        std::vector<FinishedCallback> m_callbacks;

    protected:
        void addFinishedCallback(FinishedCallback callback) {
            m_callbacks.push_back(callback);
        }

        void callFinishedCallbacks();
};

Then you'd derive your specific task types from Task like this:

class MyTask : public Task<MyTask> { ... };

This reduced the amount of code you have to write (because there's only one source code implementation of addFinishedCallback), but it runs the risk of generating more object code.  The optimizer and linker might be able to reign in that possibility.


问:
How to Pass a String or Variable with HTTP Redirect in Laravel
I'm developing a quiz and want to check if a question is answered already. Then I'd like to print something and/or disable the form after submitting. The page will be redirected back to show the new option if the user has any observation or reservation. If the form redirects back how can I check or disable the form so a user can't submit the form again? I am using the following method to redirect back.

```<code><?php

return redirect()->back();
</code>```

If I pass a variable using the with() method I get no success. The system doesn't recognize my variable. I also tried...

```<code><?php

return redirect()->back()->withDisable('disable');
</code>```

答:
Just with should do it.  For example:

```<code>return redirect()->back()->with('status', 'disable');
</code>```

This is saved in the session data, so you could check for it with:

```<code>@if (session('status'))
...
</code>```

From: https://laravel.com/docs/5.5/redirects#redirecting-with-flashed-session-data

Body:
I'm developing a quiz and want to check if a question is answered already. Then I'd like to print something and/or disable the form after submitting. The page will be redirected back to show the new option if the user has any observation or reservation. If the form redirects back how can I check or disable the form so a user can't submit the form again? I am using the following method to redirect back.

<?php

return redirect()->back();

If I pass a variable using the with() method I get no success. The system doesn't recognize my variable. I also tried...

<?php

return redirect()->back()->withDisable('disable');

Body:
Just with should do it.  For example:

return redirect()->back()->with('status', 'disable');

This is saved in the session data, so you could check for it with:

@if (session('status'))
...

From: https://laravel.com/docs/5.5/redirects#redirecting-with-flashed-session-data