问:
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

```<code>int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}
</code>```

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

```<code>int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}
</code>```

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

答:
I would usually prefer what your teacher suggested, simply because it's easier to read and understand what are the conditions to stop the loop.

If you have an infinite loop with a return statement it's a little bit more difficult for someone who didn't write the code to go through the code and figure out when the program will hit a return statement.

Also I usually don't like early returns in general because it's easy for someone maintaining the code to introduce bugs, for example:

```<code>int main()
{
    // code added by some other programmer:
    importantInitialization();

    while (true)
    {
        OutputMenu();

        // code added by some other programmer:
        Something *st = new Something();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "a") runA();
        else if (UserChoice == "b") runB();
        else if (UserChoice == "c") runC();
        else if (UserChoice == "d") runD();
        else if (UserChoice == "exit") return 0;
        else if (UserChoice == "help") showHelp();

        // code added by some other programmer:
        delete st; // this would not run on the last loop
    }

    // code added by some other programmer:
    importantCleanUp(); // this would never run
}
</code>```

of course that in this particular case it's easy to see the problems, but when maintaining a more complicated function you can see how an early return statement might make it even more prone to lack-of-attention bugs like this.

Body:
I have a simple console application that outputs a menu and waits for user input.  After performing the appropriate action, the entire process repeats.  The program exits when a specific string is entered.  This is implemented with an infinite loop and an early return statement:

int main()
{
    while (true)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") return 0;
    }
}

According to my teacher, it's bad practice to use an infinite loop and hack my way out of it with a return statement.  He suggests something like the following:

int main()
{
    bool ShouldExit = false;
    while (!ShouldExit)
    {
        OutputMenu();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "exit") ShouldExit = true;
    }

    return 0;
}

Is it really a bad idea to use an infinite loop and an early return statement?

If so, is there a technical reason or is it just bad practice?

Body:
I would usually prefer what your teacher suggested, simply because it's easier to read and understand what are the conditions to stop the loop.

If you have an infinite loop with a return statement it's a little bit more difficult for someone who didn't write the code to go through the code and figure out when the program will hit a return statement.

Also I usually don't like early returns in general because it's easy for someone maintaining the code to introduce bugs, for example:

int main()
{
    // code added by some other programmer:
    importantInitialization();

    while (true)
    {
        OutputMenu();

        // code added by some other programmer:
        Something *st = new Something();

        string UserChoice;
        cin >> UserChoice;

        // ...

        if (UserChoice == "a") runA();
        else if (UserChoice == "b") runB();
        else if (UserChoice == "c") runC();
        else if (UserChoice == "d") runD();
        else if (UserChoice == "exit") return 0;
        else if (UserChoice == "help") showHelp();

        // code added by some other programmer:
        delete st; // this would not run on the last loop
    }

    // code added by some other programmer:
    importantCleanUp(); // this would never run
}

of course that in this particular case it's easy to see the problems, but when maintaining a more complicated function you can see how an early return statement might make it even more prone to lack-of-attention bugs like this.


来源: stackexchange

问:
How to rollback a transaction if the POST response could not be delivered
Using Spring MVC, assume I have implemented a controller that handles a POST request, performs a database operation inside a transaction, and returns a result in the response body.

Here is the controller and service layer:

```<code>@RestController
@RequiredArgsConstructor
public class SomeController {

  private final SomeService someService;

  @PostMapping("/something")
  public SomeResult postSomething(Something something) {
    return someService.handle(something);
  }

}

@Service
@RequiredArgsConstructor
public class SomeService {

  private final SomeRepository someRepository;

  @Transactional
  public SomeResult handle(Something something){
    // changes to the database
  }

}
</code>```

Questions:

Assuming someone pulls the network cable right after the service call, so the transaction is comitted.

1) Will Spring throw an exception if the response cannot be delivered?

2) Is it possible to rollback the transaction if the response cannot be delivered?

3) How can I make sure the database stays consistent when the client retries? (the POST is not idempotent).

Thanks!

答:
I'll try to answer you questions:

1) Maybe. It depends on size of answer and exact moment when connection is lost.

Exception will be thrown if when spring try to write response to socket OS detect that TCP/IP connection is closed. TCP protocol do not contain internal procedure of detection such situation so OS use heuristics like timeouts.

So I see only one option here. Spring try to write response to socket, but response too big to fit in buffer. In this situation write operation will be blocked. Then after some time it will be interrupted because of timeout and exception is raised.

I'm not 100% sure that my answer accurate, so you better check it yourself.
I suggest you not rely on this mechanics because it depend on many different factors like buffer size, timeout and Spring implementation.

2) With Spring answer will be NO.

3) It is up to you. There is no universal answer. For example Hibernate can be configured to use versioning on your objects.

ContentLicense: CC BY-SA 3.0

Body:
Using Spring MVC, assume I have implemented a controller that handles a POST request, performs a database operation inside a transaction, and returns a result in the response body.

Here is the controller and service layer:

@RestController
@RequiredArgsConstructor
public class SomeController {

  private final SomeService someService;

  @PostMapping("/something")
  public SomeResult postSomething(Something something) {
    return someService.handle(something);
  }

}

@Service
@RequiredArgsConstructor
public class SomeService {

  private final SomeRepository someRepository;

  @Transactional
  public SomeResult handle(Something something){
    // changes to the database
  }

}

Questions:

Assuming someone pulls the network cable right after the service call, so the transaction is comitted.

1) Will Spring throw an exception if the response cannot be delivered?

2) Is it possible to rollback the transaction if the response cannot be delivered?

3) How can I make sure the database stays consistent when the client retries? (the POST is not idempotent).

Thanks!


问:
Get button click from reusable cell in collection view (xib file)
I have created reusable cell with include a button in a XIB for a collection.

I can change the text of labels and buttons in the collection view but i can't get on click event.

I have tried below options:

a.   This in UICollectionViewCell :  Not working

```<code>class cellVC: UICollectionViewCell {
    @IBOutlet weak var sampleLabel: UILabel!
    @IBOutlet weak var buttonClicked: UIButton!

    @IBAction func buttonTest(_ sender: Any) {
        print("dsfsdf   111111")
    }
}
</code>```

b. I have also tried : Not working

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
    cell.sampleLabel. = "sample text"
    cell.buttonClicked.tag = indexPath.row
    cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

    cell.buttonClicked.backgroundColor = UIColor.cyan
    return cell
}

func masterAction(_ sender: UIButton) {
    print ("button click")
}
</code>```

As both solutions are not working, how do i achieve this.

Thanks

答:
instead of

```<code> cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)
</code>```

write

```<code> cell.buttonClicked.addTarget(self, action: #selector(masterAction(_:)), for: .touchUpInside)
</code>```

Body:
I have created reusable cell with include a button in a XIB for a collection.

I can change the text of labels and buttons in the collection view but i can't get on click event.

I have tried below options:

a.   This in UICollectionViewCell :  Not working

class cellVC: UICollectionViewCell {
    @IBOutlet weak var sampleLabel: UILabel!
    @IBOutlet weak var buttonClicked: UIButton!

    @IBAction func buttonTest(_ sender: Any) {
        print("dsfsdf   111111")
    }
}

b. I have also tried : Not working

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{

    let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
    cell.sampleLabel. = "sample text"
    cell.buttonClicked.tag = indexPath.row
    cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

    cell.buttonClicked.backgroundColor = UIColor.cyan
    return cell
}

func masterAction(_ sender: UIButton) {
    print ("button click")
}

As both solutions are not working, how do i achieve this.

Thanks

Body:
instead of

 cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)

write

 cell.buttonClicked.addTarget(self, action: #selector(masterAction(_:)), for: .touchUpInside)


问:
trouble making an "if" statment with time.now on ruby on rails
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

```<code><% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>! <br>
<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

答:
I'd use a helper:

```<code>def morning?(t = Time.current)
  t.between? t.change(hour: 7), t.change(hour: 14)
end
</code>```

t is a time instance, defaulting to the current time, for example:

```<code>t = Time.current
#=> Tue, 04 Jul 2017 16:30:09 CEST +02:00
</code>```

change sets one or more of the time's elements. If only :hour is specified, the "smaller" units like minutes and seconds are set to 0:

```<code>t.change(hour: 7)  #=> Tue, 04 Jul 2017 07:00:00 CEST +02:00
t.change(hour: 14) #=> Tue, 04 Jul 2017 14:00:00 CEST +02:00
</code>```

between? finally checks if t is between these values.

Passing the current time as an argument makes it easier to test the method:

```<code>morning? Time.parse('06:59') #=> false
morning? Time.parse('07:00') #=> true
morning? Time.parse('14:00') #=> true
morning? Time.parse('14:01') #=> false
</code>```

Usage:

```<code><% if morning? %>
  Good Morning <%= current_user.nome %>!
<% else %>
  Good Afternoon <%= current_user.nome %>!
<% end %>
</code>```

Body:
I'm trying to display a message depending on the time of the day and I currently have this piece of code:

<% if Time.now >= "7:00" and Time.now <= "14:00" %>
Good Morning <%= current_user.nome %>!

<% else %>
Good Afternoon <%= current_user.nome %>!
<% end %>

It's currently 14:30 and the page still displays Good Morning (username), when it should display Good Evening (username)

Is my code wrong?

How do I fix this?

Body:
I'd use a helper:

def morning?(t = Time.current)
  t.between? t.change(hour: 7), t.change(hour: 14)
end

t is a time instance, defaulting to the current time, for example:

t = Time.current
#=> Tue, 04 Jul 2017 16:30:09 CEST +02:00

change sets one or more of the time's elements. If only :hour is specified, the "smaller" units like minutes and seconds are set to 0:

t.change(hour: 7)  #=> Tue, 04 Jul 2017 07:00:00 CEST +02:00
t.change(hour: 14) #=> Tue, 04 Jul 2017 14:00:00 CEST +02:00

between? finally checks if t is between these values.

Passing the current time as an argument makes it easier to test the method:

morning? Time.parse('06:59') #=> false
morning? Time.parse('07:00') #=> true
morning? Time.parse('14:00') #=> true
morning? Time.parse('14:01') #=> false

Usage:

<% if morning? %>
  Good Morning <%= current_user.nome %>!
<% else %>
  Good Afternoon <%= current_user.nome %>!
<% end %>


问:
Partial class spanning assemblies
In my framework project I have a class that represents tabs in a content management system. In some framewrok implementations it is desirable to extend this class with defintions of tabs that are specific to that implementation. I had though to do this by changing the CmsTabs class to be partial, like this:

```<code>namespace Framework
{
/// <summary>
/// Class containing common CMS Tab names
/// </summary>
public static partial class CmsTab
{
    /// <summary>
    /// Information Tab
    /// </summary>
    public const string Information = "Information";
</code>```

And then creating a class with the same name and namespace in the assembly that implements the framework.

However, when I build the framework assembly, the CmsTabs class appears no longer to be partial - it's members are hidden in the implementing assembly when I add the partial class to that. When disassembled in Reflector, I get this:

```<code>public class CmsTab
{...
</code>```

Is there something I need to do to make it retain its partial status, assuming that it is possible to do what I am trying to do.

Thanks.

答:
Partial classes are a purely compile-time feature.

It is not possible to create a class definition that spans multiple assemblies.

Instead, you can make the class a non-static singleton, and allow implementations to inherit the class, add properties to it, and set the inherited version as the singleton instance.

If it's purely a collection of const strings, you can make it a private partial class, but add a link to the file in every project.

ContentLicense: CC BY-SA 2.5

Title: Partial class spanning assemblies

Body:
In my framework project I have a class that represents tabs in a content management system. In some framewrok implementations it is desirable to extend this class with defintions of tabs that are specific to that implementation. I had though to do this by changing the CmsTabs class to be partial, like this:

namespace Framework
{
///
/// Class containing common CMS Tab names
///
public static partial class CmsTab
{
    ///
    /// Information Tab
    ///
    public const string Information = "Information";

And then creating a class with the same name and namespace in the assembly that implements the framework.

However, when I build the framework assembly, the CmsTabs class appears no longer to be partial - it's members are hidden in the implementing assembly when I add the partial class to that. When disassembled in Reflector, I get this:

public class CmsTab
{...

Is there something I need to do to make it retain its partial status, assuming that it is possible to do what I am trying to do.

Thanks.


问:
ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
I want to simplify my configuration in my ASP.NET Core Web Application (.NET Framework) application using VS 2017.

I already know that my website will be running under Windows/IIS in x64 environment and .NET 4.6.2. There is no chance in the foreseen and unforeseen future for this application to use any other environment from the dev to production.

So, I only need Debug x64 and Release x64 modes only. (AnyCPU and x86 are not needed!), so I went ahead and removed all other configuration from the project.

Now, upon compilation, I am getting the following error:

'C:\Projects\MyProject\My.Website\obj\project.assets.json' doesn't
  have a target for '.NETFramework,Version=v4.6.2/win7-x64'.

Ensure you
  have restored this project for TargetFramework='net462' and
  RuntimeIdentifier='win7-x64'. MD.Website  C:\Program Files
  (x86)\Microsoft Visual
  Studio\2017\Enterprise\MSBuild\Sdks\Microsoft.NET.Sdk\build\Microsoft.NET.Sdk.targets

I am developing on Windows 7, I am not sure how to fix this one. Any idea?

答:
I had manually changed mine from x86 to x64. In this case, just restoring the packages from Visual Studio would not work but closing Visual Studio, deleting the project.assets.json, re-starting Visual Studio and re-building the project worked for me. I left <TargetFramework> singular.

Command line nuget restore ... may also have worked.


问:
Sed remove NULL but only when the NULL means empty or no value
Exporting a table from MySQL where fields that have no value will have the keyword NULL within.

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
</code>```

I have written a script to automatically remove all occurrences of NULL using a one-liner sed, which will remove the NULL in date column correctly:

```<code>sed -i 's/NULL//g'
</code>```

However, how do we handle IF we have the following?

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Apparently, the global search and replace all occurrences of NULL will be removed, where even "ALA PUHU MINULLE" will become "ALA PUHU MIE", which is incorrect.

I suppose the use of regex perhaps can be useful to apply the rule? But if so, will "DJ Null Bee" be affected or will it become "DJ Bee"? The desired outcome should really be:

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Given that NULL is a special keyword for any databases, but there is no stopping anyone from calling themselves a DJ NULL, or have the word NULL because it means differently in another language.

Any ideas on how to resolve this? Any suggestions welcomed. Thank you!

答:
All you need is:

```<code>$ sed 's/|[[:space:]]*NULL[[:space:]]*|/|  |/g; s/|[[:space:]]*NULL[[:space:]]*|/|  |/g' file
| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET |  | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

That will work in any POSIX sed.

You have to do the substitution twice because each match consumes all of the characters in the match so when you have | NULL | NULL | the middle | is consumed by the match on | NULL | and so all that's left is NULL | which does not match | NULL |, so you need 2 passes to match every | NULL |.

Body:
Exporting a table from MySQL where fields that have no value will have the keyword NULL within.

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |

I have written a script to automatically remove all occurrences of NULL using a one-liner sed, which will remove the NULL in date column correctly:

sed -i 's/NULL//g'

However, how do we handle IF we have the following?

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

Apparently, the global search and replace all occurrences of NULL will be removed, where even "ALA PUHU MINULLE" will become "ALA PUHU MIE", which is incorrect.

I suppose the use of regex perhaps can be useful to apply the rule? But if so, will "DJ Null Bee" be affected or will it become "DJ Bee"? The desired outcome should really be:

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

Given that NULL is a special keyword for any databases, but there is no stopping anyone from calling themselves a DJ NULL, or have the word NULL because it means differently in another language.

Any ideas on how to resolve this? Any suggestions welcomed. Thank you!

Body:
All you need is:

$ sed 's/|[[:space:]]*NULL[[:space:]]*|/|  |/g; s/|[[:space:]]*NULL[[:space:]]*|/|  |/g' file
| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET |  | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

That will work in any POSIX sed.

You have to do the substitution twice because each match consumes all of the characters in the match so when you have | NULL | NULL | the middle | is consumed by the match on | NULL | and so all that's left is NULL | which does not match | NULL |, so you need 2 passes to match every | NULL |.


问:
Wikipedia links API returns links that aren't on the page
I'm experimenting with the python module wikipedia which is a wrapper for the wikipedia API.  In particular I'm looking at the links API, which as I understand should return a 'List of titles of Wikipedia page links on a page', i.e. all the references to other wikipedia pages within the text of the page I'm querying about.  When I look at the result for the article on Google, I get a list of links as expected (wikipedia titles in JSON format). The problem is that there seem to be links listed there that do not appear on the Google page.  I thought maybe it's including links to Google, but that doesn't work either, in particular, the third link returned in the JSON structure is to ADATA.  I don't see a link to ADATA anywhere on the Google page, nor a link to Google anywhere on the ADATA page.  Is this a bug or am I missing something obvious?

I believe this link is enough to reproduce the issue:

```<code>https://en.wikipedia.org/w/api.php?action=query&titles=Google&prop=links
</code>```

The result I see looks like this:

```<code>{
    "continue": {
        "plcontinue": "1092923|0|Aardvark_(search_engine)",
        "continue": "||"
    },
    "query": {
        "pages": {
            "1092923": {
                "pageid": 1092923,
                "ns": 0,
                "title": "Google",
                "links": [
                    {
                        "ns": 0,
                        "title": "111 Eighth Avenue"
                    },
                    {
                        "ns": 0,
                        "title": "2600: The Hacker Quarterly"
                    },
                    {
                        "ns": 0,
                        "title": "ADATA"
                    },
. . .
</code>```

In python you can reproduce like this:

```<code>import wikipedia
wikipedia.page('Google').links
</code>```

which produces output like this:

```<code>['111 Eighth Avenue',
 '2600: The Hacker Quarterly',
 'ADATA',
 'AI Challenge',
 'AKM Semiconductor, Inc.',
 'AOL',
 'API.AI',
</code>```

答: The list contains links which appear in the wikitext of the page or in templates called from the wikitext. It is updated by a queued job after every edit. Due to the async nature of job handling and the finite number of retries for failed jobs, it is possible for the list to differ from actual article content, but very unlikely. (It's probably possible to add links to wikitext in such a way that they don't show up in the article HTML at all, but again it's unlikely anyone would actually do that.)</p>

Body:
I'm experimenting with the python module wikipedia which is a wrapper for the wikipedia API.  In particular I'm looking at the links API, which as I understand should return a 'List of titles of Wikipedia page links on a page', i.e. all the references to other wikipedia pages within the text of the page I'm querying about.  When I look at the result for the article on Google, I get a list of links as expected (wikipedia titles in JSON format). The problem is that there seem to be links listed there that do not appear on the Google page.  I thought maybe it's including links to Google, but that doesn't work either, in particular, the third link returned in the JSON structure is to ADATA.  I don't see a link to ADATA anywhere on the Google page, nor a link to Google anywhere on the ADATA page.  Is this a bug or am I missing something obvious?

I believe this link is enough to reproduce the issue:

https://en.wikipedia.org/w/api.php?action=query&titles=Google&prop=links

The result I see looks like this:

{
    "continue": {
        "plcontinue": "1092923|0|Aardvark_(search_engine)",
        "continue": "||"
    },
    "query": {
        "pages": {
            "1092923": {
                "pageid": 1092923,
                "ns": 0,
                "title": "Google",
                "links": [
                    {
                        "ns": 0,
                        "title": "111 Eighth Avenue"
                    },
                    {
                        "ns": 0,
                        "title": "2600: The Hacker Quarterly"
                    },
                    {
                        "ns": 0,
                        "title": "ADATA"
                    },
. . .

In python you can reproduce like this:

import wikipedia
wikipedia.page('Google').links

which produces output like this:

['111 Eighth Avenue',
 '2600: The Hacker Quarterly',
 'ADATA',
 'AI Challenge',
 'AKM Semiconductor, Inc.',
 'AOL',
 'API.AI',


问:
Scala - Nested type keyword
I was going through Akka source code, and I came across the following

```<code>type Repr[+O] <: FlowOps[O, Mat] {
   type Repr[+OO] = FlowOps.this.Repr[OO]
   type Closed = FlowOps.this.Closed
}
type Closed
</code>```

Can someone explain me what's going on here ??

答:
```<code>FlowOps[O, Mat] {
   type Repr[+OO] = FlowOps.this.Repr[OO]
   type Closed = FlowOps.this.Closed
}
</code>```

is a compound type with a refinement. Namely, FlowOps[O, Mat] by itself can have any Repr and Closed type members; here we require specific ones. This type is used as an upper bound for the type member type Repr[+O].

Title: Scala - Nested type keyword

Body:
I was going through Akka source code, and I came across the following

type Repr[+O] <: FlowOps[O, Mat] {
   type Repr[+OO] = FlowOps.this.Repr[OO]
   type Closed = FlowOps.this.Closed
}
type Closed

Can someone explain me what's going on here ??

Body:
FlowOps[O, Mat] {
   type Repr[+OO] = FlowOps.this.Repr[OO]
   type Closed = FlowOps.this.Closed
}

is a compound type with a refinement. Namely, FlowOps[O, Mat] by itself can have any Repr and Closed type members; here we require specific ones. This type is used as an upper bound for the type member type Repr[+O].


问:
ASP.net MVC SecretManager
I have an ASP.net MVC 5.2 project on a macOS Sierra (not my choice unfortunately) and I am trying to set the client secrets with the SecretManager. I have tried running

```<code>dotnet user-secrets set Authentication:Twitter:ConsumerKey <consumer-key>
</code>```

but I get that

```<code>No executable found matching command "dotnet-user-secrets"
</code>```

I executed the command in the project root and after googling the problem, apparently I need to run the command in the same folder as the project.json which I cannot find in my project structure. (do I need to create it manually?)

I apologise in advance for these beginner questions but I am just getting on board with the .net framework.
Any tips/ideas would be greatly appreciated!

答:
As far as I know now projects use .csproj files instead of project.json, so you have to use it in the folder containing .csproj file

Judging from your project structure I guess it's "TwitterMania" folder - the one nested inside another "TwitterMania" folder

Title: ASP.net MVC SecretManager

Body:
I have an ASP.net MVC 5.2 project on a macOS Sierra (not my choice unfortunately) and I am trying to set the client secrets with the SecretManager. I have tried running

dotnet user-secrets set Authentication:Twitter:ConsumerKey <consumer-key>

but I get that

No executable found matching command "dotnet-user-secrets"

I executed the command in the project root and after googling the problem, apparently I need to run the command in the same folder as the project.json which I cannot find in my project structure. (do I need to create it manually?)

I apologise in advance for these beginner questions but I am just getting on board with the .net framework.
Any tips/ideas would be greatly appreciated!


问:
R sapply loop to replace for loop
I have successfully switched for loops to sapply loops before,
and I know for a fact (system.time()) that they are faster.

BUT my mind still works in a for loop way...

Please help me to convert this for loop case:

```<code>names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")
misspell.list <- c("Anna", "Albort", "Robb", "Tommie")
fix.list <- c("Ana", "Albert", "Rob", "Tommy")

for(i in 1:length(fix.list)) {
        names.list[which(names.list == misspell.list[i])] <- fix.list[i]

}

names.list
</code>```

To a sapply()

So far, I got:

```<code>sapply(seq_along(fix.list), function(x)
        names.list[which(names.list == misspell.list[x])]  <- fix.list[x]
)
</code>```

But it only returns me the original vector.

Thanks!

EDIT 1:

the misspell.list and fix.list were created automatically by adist() bellow and the original names.list has 665 elements. My for() solution returns length(unique(names.list)) = 653 elements

```<code># will do another sapply() substitution here soon
for(i in 1:(length(names.list)-1)) {
        distancias[i] <- adist(names.list[i], names.list[i+1])
}

# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]
</code>```

EDIT 2: thanks to you, now I'm a sapply overlord and I'm here just to show my other for-sapply substitution used with adist()

```<code>nomes <- sort(unique(names.list))
distancias <- rep(10, length(nomes))

#adist() for finding misspelling
sapply(seq_along(nomes),
       function(x) {
                if(x<length(nomes)) {
                        distancias[x] <<- adist(nomes[x], nomes[x+1])
                        }
        }
       )
# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]
</code>```

The other part you already know, thanks again!

答:
I would propose a small change to your whole setup. When using indexes like you do, you need to be sure that the order is always the same. If you add or remove a name, the whole thing falls apart.

Using a named list and lapply or sapply, your code stays dynamic and you can potentially match multiple misspellings to one name.

```<code>misspell.list  <-  list(
  'Anna' = 'Ana',
  'Albort' = 'Albert',
  'Robb' = 'Rob',
  'Tommie' = 'Tommy'
)

names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")

> sapply(names.list,function(x) ifelse(x %in% names(misspell.list),misspell.list[[x]],x))
    Anna      Ana   Albert   Albort      Rob     Robb    Tommy   Tommie
   "Ana"    "Ana" "Albert" "Albert"    "Rob"    "Rob"  "Tommy"  "Tommy"
</code>```

To illustrate what I mean, I'm using sample to shuffle up  your names.list vector and extend it to 20 names. This shows that order and length have no influence.

```<code>sapply(names.list[sample(1:length(names.list),20,replace = T)],function(x) ifelse(x %in% names(misspell.list),misspell.list[[x]],x))
  Albert   Tommie      Rob   Tommie      Rob    Tommy      Ana     Robb   Tommie      Ana   Tommie   Albort      Ana   Albert   Albert   Albort
"Albert"  "Tommy"    "Rob"  "Tommy"    "Rob"  "Tommy"    "Ana"    "Rob"  "Tommy"    "Ana"  "Tommy" "Albert"    "Ana" "Albert" "Albert" "Albert"
   Tommy    Tommy    Tommy      Ana
 "Tommy"  "Tommy"  "Tommy"    "Ana"
</code>```

Title: R sapply loop to replace for loop

Body:
I have successfully switched for loops to sapply loops before,
and I know for a fact (system.time()) that they are faster.

BUT my mind still works in a for loop way...

Please help me to convert this for loop case:

names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")
misspell.list <- c("Anna", "Albort", "Robb", "Tommie")
fix.list <- c("Ana", "Albert", "Rob", "Tommy")

for(i in 1:length(fix.list)) {
        names.list[which(names.list == misspell.list[i])] <- fix.list[i]

}

names.list

To a sapply()

So far, I got:

sapply(seq_along(fix.list), function(x)
        names.list[which(names.list == misspell.list[x])]  <- fix.list[x]
)

But it only returns me the original vector.

Thanks!

EDIT 1:

the misspell.list and fix.list were created automatically by adist() bellow and the original names.list has 665 elements. My for() solution returns length(unique(names.list)) = 653 elements

# will do another sapply() substitution here soon
for(i in 1:(length(names.list)-1)) {
        distancias[i] <- adist(names.list[i], names.list[i+1])
}

# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]

EDIT 2: thanks to you, now I'm a sapply overlord and I'm here just to show my other for-sapply substitution used with adist()

nomes <- sort(unique(names.list))
distancias <- rep(10, length(nomes))

#adist() for finding misspelling
sapply(seq_along(nomes),
       function(x) {
                if(x<length(nomes)) {
                        distancias[x] <<- adist(nomes[x], nomes[x+1])
                        }
        }
       )
# fix list
misspell.list <- names.list[which(distancias < 2)]
fix.list <- names.list[which(distancias < 2) +1]

The other part you already know, thanks again!

Body:
I would propose a small change to your whole setup. When using indexes like you do, you need to be sure that the order is always the same. If you add or remove a name, the whole thing falls apart.

Using a named list and lapply or sapply, your code stays dynamic and you can potentially match multiple misspellings to one name.

misspell.list  <-  list(
  'Anna' = 'Ana',
  'Albort' = 'Albert',
  'Robb' = 'Rob',
  'Tommie' = 'Tommy'
)

names.list <- c("Anna", "Ana", "Albert", "Albort", "Rob", "Robb", "Tommy", "Tommie")

> sapply(names.list,function(x) ifelse(x %in% names(misspell.list),misspell.list[[x]],x))
    Anna      Ana   Albert   Albort      Rob     Robb    Tommy   Tommie
   "Ana"    "Ana" "Albert" "Albert"    "Rob"    "Rob"  "Tommy"  "Tommy"

To illustrate what I mean, I'm using sample to shuffle up  your names.list vector and extend it to 20 names. This shows that order and length have no influence.

sapply(names.list[sample(1:length(names.list),20,replace = T)],function(x) ifelse(x %in% names(misspell.list),misspell.list[[x]],x))
  Albert   Tommie      Rob   Tommie      Rob    Tommy      Ana     Robb   Tommie      Ana   Tommie   Albort      Ana   Albert   Albert   Albort
"Albert"  "Tommy"    "Rob"  "Tommy"    "Rob"  "Tommy"    "Ana"    "Rob"  "Tommy"    "Ana"  "Tommy" "Albert"    "Ana" "Albert" "Albert" "Albert"
   Tommy    Tommy    Tommy      Ana
 "Tommy"  "Tommy"  "Tommy"    "Ana"


问:
OSX Server: apache2 running but “Problem loading page”
I have setup OSX Server 10.6, all updates installed, started apache2, which is running:

```<code>sudo apachectl graceful
</code>```

I see in /var/log/apache2/errorlog

```<code>[Fri Dec 17 10:11:49 2010] [notice] Apache/2.2.15 (Unix) configured -- resuming normal operations
</code>```

Also

```<code>ps -ef | grep httpd
</code>```

shows several processes:

```<code>    0 49388     1   0   0:00.05 ??         0:00.07 /usr/sbin/httpd -D FOREGROUND
   70 49389 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49390 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49391 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49392 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
...
</code>```

In httpd.conf I edited DocumentRoot:

```<code>ServerName bioinfo.mni.fh-giessen.de:80
DocumentRoot "/Volumes/ServerHD2/Web_Documents"
ErrorLog "/var/log/apache2/error_log"
<Directory "/Volumes/ServerHD2/Web_Documents">
   Order Allow,Deny
   Allow from All
</Directory>
</code>```

Syntax is OK:

```<code>apachectl configtest
Syntax OK
</code>```

Yet, I get timeouts at http://bioinfo.mni.fh-giessen.de :

```<code>Problem loading page
</code>```

Any clue ?

答:
No direct local GUI access possible for a few days, no access via Remote Desktop either. My only way is ssh right now, but I will be happy to try Server Admin utility in a few days. For now I am restricted to the command line. Yes, I edited both /etc/apache2/httpd.conf and /etc/apache2/sites/0000_any_80_.conf, without avail. Is

```<code>sudo serveradmin fullstatus web
</code>```

anyhow instructive :

```<code>web:readWriteSettingsVersion = 1
web:totalKBytes = 0
web:emailRulesRunning = no
web:boundToKerberos = yes
web:teamsRunning = yes
web:postfixRunning = no
web:servicePortsRestrictionInfo = _empty_array
web:health = _empty_dictionary
web:currentThroughput = 0
web:passwordResetRunning = no
web:ApacheMode = 2
web:statusMessage = ""
web:apacheVersion = "Unknown"
web:state = "RUNNING"
web:setStateVersion = 1
web:apacheState = "RUNNING"
web:proxyState = "STOPPED"
web:htCacheCleanRunning = no
web:calendarRunning = yes
web:servicePortsAreRestricted = "YES"
web:currentRequestsBy10 = 0
web:logPaths:logPathsArray = _empty_array
web:totalRequests = 0
web:startedTime = ""
</code>```

?

Body:
I have setup OSX Server 10.6, all updates installed, started apache2, which is running:

sudo apachectl graceful

I see in /var/log/apache2/errorlog

[Fri Dec 17 10:11:49 2010] [notice] Apache/2.2.15 (Unix) configured -- resuming normal operations

Also

ps -ef | grep httpd

shows several processes:

    0 49388     1   0   0:00.05 ??         0:00.07 /usr/sbin/httpd -D FOREGROUND
   70 49389 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49390 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49391 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
   70 49392 49388   0   0:00.00 ??         0:00.00 /usr/sbin/httpd -D FOREGROUND
...

In httpd.conf I edited DocumentRoot:

ServerName bioinfo.mni.fh-giessen.de:80
DocumentRoot "/Volumes/ServerHD2/Web_Documents"
ErrorLog "/var/log/apache2/error_log"
<Directory "/Volumes/ServerHD2/Web_Documents">
   Order Allow,Deny
   Allow from All
</Directory>

Syntax is OK:

apachectl configtest
Syntax OK

Yet, I get timeouts at http://bioinfo.mni.fh-giessen.de :

Problem loading page

Any clue ?

Body:
No direct local GUI access possible for a few days, no access via Remote Desktop either. My only way is ssh right now, but I will be happy to try Server Admin utility in a few days. For now I am restricted to the command line. Yes, I edited both /etc/apache2/httpd.conf and /etc/apache2/sites/0000_any_80_.conf, without avail. Is

sudo serveradmin fullstatus web

anyhow instructive :

web:readWriteSettingsVersion = 1
web:totalKBytes = 0
web:emailRulesRunning = no
web:boundToKerberos = yes
web:teamsRunning = yes
web:postfixRunning = no
web:servicePortsRestrictionInfo = _empty_array
web:health = _empty_dictionary
web:currentThroughput = 0
web:passwordResetRunning = no
web:ApacheMode = 2
web:statusMessage = ""
web:apacheVersion = "Unknown"
web:state = "RUNNING"
web:setStateVersion = 1
web:apacheState = "RUNNING"
web:proxyState = "STOPPED"
web:htCacheCleanRunning = no
web:calendarRunning = yes
web:servicePortsAreRestricted = "YES"
web:currentRequestsBy10 = 0
web:logPaths:logPathsArray = _empty_array
web:totalRequests = 0
web:startedTime = ""

?


问:
R - Calculate difference (similarity measure) between similar datasets
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData1:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

imputedData2:

```<code>> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4
</code>```

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

Body:
I have seen many questions that touch on this topic but haven't yet found an answer. If I have missed a question that does answer this question, please do mark this and point us to the question.

Scenario: We have a benchmark dataset, we have imputation methods, we systematically delete values from the benchmark and use two different imputation methods. Thus we have a benchmark, imputedData1 and imputedData2.

Question: Is there a function that can produce a number that represents the difference between the benchmark and imputedData1 or/and the difference between the benchmark and imputedData2. Ie function(benchmark, imputedData1) = 3.3 and function(benchmark, imputedData2) = 2.8

Note: Datasets are numerical, datasets are the same size, method should work at the data level if possible (ie not creating a regression and comparing regressions - unless it can work with ANY numerical dataset).

Reproducible datasets, they have only been changed in the first row:

benchmark:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData1:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

imputedData2:

> head(mtcars,n=10)
                   mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4         18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
Mazda RX4 Wag     21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710        22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
Merc 230          22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
Merc 280          19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4

I have tried to use RMSE (root mean squared error) but it didn't work very well so I am trying to find other ways to tackle this problem.

Body:
You could also check out package ftsa. It has about 20 error measures that can be calculated. In your case, a scaled error would make sense as the units differ from column to column.

library(ftsa)
error(forecast=unlist(imputedData1),true=unlist(bench),
          insampletrue = unlist(bench), method = "mase")
[1] 0.035136

error(forecast=unlist(imputedData2),true=unlist(bench),
          insampletrue = unlist(bench), method = "mase")
[1] 0.031151

data

bench <- read.table(text='mpg cyl  disp  hp drat    wt  qsec vs am gear carb
21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4',header=TRUE,stringsAsFactors=FALSE)

imputedData1 <- read.table(text='mpg cyl  disp  hp drat    wt  qsec vs am gear carb
22.0   4 108.0 100 3.90 2.200 16.46  0  1    4    4
21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4',header=TRUE,stringsAsFactors=FALSE)

imputedData2 <- read.table(text='mpg cyl  disp  hp drat    wt  qsec vs am gear carb
18.0   6 112.0 105 3.90 2.620 16.46  0  0    3    4
21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
22.8   4 140.8  95 3.92 3.150 22.90  1  0    4    2
19.2   6 167.6 123 3.92 3.440 18.30  1  0    4    4',header=TRUE,stringsAsFactors=FALSE)


问:
errbot: scripted plugin installation for docker?
I have a Dockerfile to run errbot, looking for a way to script plugin installation.  The documentation only seems to list the manual !repos install ... method.

Is there any way for automatic plugin installation from git repo?

答:
Yes, you can simply use the BOT_EXTRA_PLUGIN_DIR config parameter and put any plugins you want to preload there.
https://github.com/errbotio/errbot/blob/master/errbot/config-template.py#L85</p>


问:
how to split the json response using java having [{
Hi i am storing a json response as string. And unable to split my json response using the below text

```<code>{["id"
</code>```

I tried using the java split  command as split.("{["id"")  but not able to split. Please help

答:
You need to escape the quotes in the string:</p>

```<code>json.split("{[\"id\"");
</code>```

Body:
Hi i am storing a json response as string. And unable to split my json response using the below text

{["id"

I tried using the java split  command as split.("{["id"")  but not able to split. Please help

Body:
You need to escape the quotes in the string:

json.split("{[\"id\"");


问:
How to code a Netty client to connect to a Signalr hub?
I am trying to create a client to receive streaming data from a third party Signalr hub. Currently we use the Netty framework for some other websocket streams so it would be good if I could adapt this to work with a Signalr hub.

The hub exposes a subscription function as well as two invocable functions.

What are the differences between a normal Netty websocket client and a Netty client for a Signalr hub if any?

Any help is much appreciated.

答:
Netty WebSockets and SignalR are two separate frameworks to that you can use to pass messages through WebSockets.

Using WebSockets directly is not easy and you will have to write a lot of additional codes to address different practical issues. Using the APIs given by one above frameworks is a way to address these.
Since these are two different frameworks, they are not supporting communicating each other.

In your case, Netty client will not connect with Signalr hub.
The only option is using a Signalr client for that specific programming language. In your case use the SignalR client for Java.


问:
Brackets in Doctrine query
hi
i have to nest some or / and conditions
but i need brackets in my sql statement to do it in the right order
but how do you make this

is should be in this form
(... OR ...) AND ...

thnx

答:
According to this blog post, "Solving the Doctrine Parenthesis Problem", you need to do a $query->where("(ConditionA OR ConditionB) AND ConditionC");

That may look like:

```<code>Doctrine_Query::create()
    ->from(...)
    ->where('A = ? OR B = ?', array(valA, valB))
    ->andWhere('C = ?', valC);
</code>```

The poster does, however, provide a more generic solution, whereParenWrap(), by extending Doctrine_Query:

```<code>DQ::create()
->from(...)
->where('A = ?', valA)
->orWhere('B = ?', valB)
->whereParenWrap()
->andWhere('C = ?', valC);
</code>```

Title: Brackets in Doctrine query

Body:
According to this blog post, "Solving the Doctrine Parenthesis Problem", you need to do a $query->where("(ConditionA OR ConditionB) AND ConditionC");

That may look like:

Doctrine_Query::create()
    ->from(...)
    ->where('A = ? OR B = ?', array(valA, valB))
    ->andWhere('C = ?', valC);

The poster does, however, provide a more generic solution, whereParenWrap(), by extending Doctrine_Query:

DQ::create()
->from(...)
->where('A = ?', valA)
->orWhere('B = ?', valB)
->whereParenWrap()
->andWhere('C = ?', valC);


问:
Error in passing string arrgument to method in java
```<code>    class Smartphone
    {
        private float screensize;
        private float androidversion;
        private int ram;
        private int memory;
        private int processor;
        private String brand;
//I also created String brand variable...at the rite position
    public void setData(String brand,int screensize,int ram,int memory,int processor,float androidversion)
    {
        this.screensize=screensize;
        this.androidversion=androidversion;
        this.ram=ram;
        this.memory=memory;
        this.processor=processor;
        this.brand=brand;
    }
    public void dispData()
    {
        System.out.println("the brand of the mobile is "+brand+"Smartphones");
        System.out.println("the screensize of the mobile is "+screensize+"inches");
        System.out.println("the ram of the mobile is "+ram);
        System.out.println("the memory of the mobile is "+memory+"GB");
        System.out.println("the processor of the mobile is "+processor+"Ghz");
        System.out.println("the androidversion of the mobile is "+androidversion);
    }
    }
    class App
    {
        public static void main(String args[])
        {
            Smartphone xiaomi=new Smartphone();
//Error is causing here...the xiaomi string is not passing..
            xiaomi.setData("Xiaomi",5.5,3,32,2.6,8.0);
        }
    }
</code>```

答:
you have passed invalid parameters.you can fix by fixing your sending parameters like :

```<code>xiaomi.setData("Xiaomi",5.5f,3,32,2,8.0f);
</code>```

or change your function signature to

```<code>String brand,float screensize,int ram,int memory,double processor,float androidversion
</code>```

and also change variables to
private float screensize;

```<code>private float androidversion;
private int ram;
private int memory;
private double processor;
private String brand;
</code>```

Body:
you have passed invalid parameters.you can fix by fixing your sending parameters like :

xiaomi.setData("Xiaomi",5.5f,3,32,2,8.0f);

or change your function signature to

String brand,float screensize,int ram,int memory,double processor,float androidversion

and also change variables to
private float screensize;

private float androidversion;
private int ram;
private int memory;
private double processor;
private String brand;


问:
call data-id on ajax success response
Originally I have a "like button" that is working very smoothly, and it looked like this:

```<code><a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <span><?php echo likes($row['id']); ?></span></a>
</code>```

Here is the Ajax code:

```<code><script>
    $(function(){
        $(".like").click(function(){

            var postid = $(this).attr("id");
              $.ajax({
                type:'POST',
                url:'addlike.php',
                data:'id='+postid,
                success:function(data){
                   if(data=="you already liked this post"){
                       alert(data);
                     }
                   else{
                      $('a#'+postid).html(data);
                      }
                }
            });

        });
    });

</script>
</code>```

If AJAX is successful, addlike.php will have two kinds of response, either alert "you already liked the post" if the user already liked it, or the updated number of likes. For example, if there are currently 10 likes, when the user clicked the button, $('a#'+postid).html(data) will change 10 to 11, because in this case the data will be the updated number of likes, and $('a#'+postid) selects the "like button" that is just being clicked.

For some reason, I have to use data-id instead of id for the html id of the button. For more detailed explanation, see here:Disable boostrap toggle collapse for one class and enable it for another

Now I have to call the element which has a data-id instead of id on ajax success response, how can I do it? I tried the following:

```<code>     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);
</code>```

but none of them works. Thanks in advance.

答:
Select element by data attribute:

```<code>$('a[data-id="'+postid +'"]').html(data);
</code>```

Title: call data-id on ajax success response

Body:
Originally I have a "like button" that is working very smoothly, and it looked like this:

<a href="javascript:void();" class="like" id="<?php echo $row['id']; ?>">Like <?php echo likes($row['id']); ?>

Here is the Ajax code:

If AJAX is successful, addlike.php will have two kinds of response, either alert "you already liked the post" if the user already liked it, or the updated number of likes. For example, if there are currently 10 likes, when the user clicked the button, $('a#'+postid).html(data) will change 10 to 11, because in this case the data will be the updated number of likes, and $('a#'+postid) selects the "like button" that is just being clicked.

For some reason, I have to use data-id instead of id for the html id of the button. For more detailed explanation, see here:Disable boostrap toggle collapse for one class and enable it for another

Now I have to call the element which has a data-id instead of id on ajax success response, how can I do it? I tried the following:

     $('a#data-id'+postid).html(data);
     $('.[data-id="postid"]').html(data);
     $('a[data-id='+postid']').html(data);
     $('a#'+"[data-id=postid"]).text(data);

but none of them works. Thanks in advance.

Body:
Select element by data attribute:

$('a[data-id="'+postid +'"]').html(data);


问:
Android Build and Installation error: INSTALL_PARSE_FAILED_NOT_APK

Have these erro when i'm trying to build the  apk to some devices. Have no idea whats going on.

I get that when i build and install apk on device at the first time.

Someone have some tips for that?

[[EDIT]]

Well, after creating a debug key on keystore, i can build and deploy the apk via ADP to the device. But, dont know why, the error just return...

And now, we have other error:

UPDATE:

I Fix that issue removing all Android SDK and Android Studio and ReInstall it.

答:
When you've installed an APK from another source, Android Studio warns you before overwriting.

For example, if I've developed an application, uploaded it onto the Google Play Store, downloaded it, then try to re-deploy that same application from Android Studio, I'll get this warning.

It's trying to tell you that the way the package is signed is different; it's warning you that another app might be masquerading as the original.


问:
JQuery adds a comma when sending a variable to the server
I am using the https://jqueryvalidation.org/ library for form validation. When passing a variable to the controller, a comma is added to the beginning of the string. I do not know why.

Validation code

```<code>$('#registrationForm').validate({
    rules: {
        username: {
            nowhitespace: true,
            required: true,
            minlength: 6,
            maxlength: 36,
            remote : {
                url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
                type: "GET",
                data: {
                    username: function() {
                        return $('#username').val();
                    }
                }
            }
        },
</code>```

And this is my controller

```<code>@GetMapping("/checkUsername")
public boolean checkUsername(@RequestParam("username") String username) {
    System.out.println("User: " + username);
    return !userService.existsByUsername(username);
}
</code>```

In addition to checking what happens, I added a username display and when passing the username to the controller the result is the following

```<code>User: ,j
User: ,jo
User: ,jon
User: ,jonk
User: ,jonki
</code>```

I did not enter this comma. He added himself at the beginning. Appears out of nowhere.

答: Why have you appended username to url part as well as data field in post data. It is a get request. Do not use post data in that scenario.</p>

Body:
I am using the https://jqueryvalidation.org/ library for form validation. When passing a variable to the controller, a comma is added to the beginning of the string. I do not know why.

Validation code

$('#registrationForm').validate({
    rules: {
        username: {
            nowhitespace: true,
            required: true,
            minlength: 6,
            maxlength: 36,
            remote : {
                url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
                type: "GET",
                data: {
                    username: function() {
                        return $('#username').val();
                    }
                }
            }
        },

And this is my controller

@GetMapping("/checkUsername")
public boolean checkUsername(@RequestParam("username") String username) {
    System.out.println("User: " + username);
    return !userService.existsByUsername(username);
}

In addition to checking what happens, I added a username display and when passing the username to the controller the result is the following

User: ,j
User: ,jo
User: ,jon
User: ,jonk
User: ,jonki

I did not enter this comma. He added himself at the beginning. Appears out of nowhere.


问:
Partial class spanning assemblies
In my framework project I have a class that represents tabs in a content management system. In some framewrok implementations it is desirable to extend this class with defintions of tabs that are specific to that implementation. I had though to do this by changing the CmsTabs class to be partial, like this:

```<code>namespace Framework
{
/// <summary>
/// Class containing common CMS Tab names
/// </summary>
public static partial class CmsTab
{
    /// <summary>
    /// Information Tab
    /// </summary>
    public const string Information = "Information";
</code>```

And then creating a class with the same name and namespace in the assembly that implements the framework.

However, when I build the framework assembly, the CmsTabs class appears no longer to be partial - it's members are hidden in the implementing assembly when I add the partial class to that. When disassembled in Reflector, I get this:

```<code>public class CmsTab
{...
</code>```

Is there something I need to do to make it retain its partial status, assuming that it is possible to do what I am trying to do.

Thanks.

答:
You can't have a partial class span assemblies:

All partial-type definitions meant to
  be parts of the same type must be
  defined in the same assembly and the
  same module (.exe or .dll file).
  Partial definitions cannot span
  multiple modules.

MSDN On Partial Classes

Title: Partial class spanning assemblies

Body:
In my framework project I have a class that represents tabs in a content management system. In some framewrok implementations it is desirable to extend this class with defintions of tabs that are specific to that implementation. I had though to do this by changing the CmsTabs class to be partial, like this:

namespace Framework
{
///
/// Class containing common CMS Tab names
///
public static partial class CmsTab
{
    ///
    /// Information Tab
    ///
    public const string Information = "Information";

And then creating a class with the same name and namespace in the assembly that implements the framework.

However, when I build the framework assembly, the CmsTabs class appears no longer to be partial - it's members are hidden in the implementing assembly when I add the partial class to that. When disassembled in Reflector, I get this:

public class CmsTab
{...

Is there something I need to do to make it retain its partial status, assuming that it is possible to do what I am trying to do.

Thanks.


问:
Wrong position of rightBarButtonItem in iOS 10
I want to put the view of a UINavigationController into another view controller's view. The problem is that the right bar button is misplaced on iOS 10. On iOS 8 and 9 it looks good.

iOS 8 and 9:

iOS 10:

Here's the code how i add the navigation controller:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let viewController = MyViewController()
    navController = UINavigationController(rootViewController: viewController)
    navController.willMove(toParentViewController: self)
    addChildViewController(navController)
    navController.view.frame = view.bounds
    view.addSubview(navController.view)
    navController.didMove(toParentViewController: self)
}
</code>```

In MyViewController

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(
        barButtonSystemItem: .done,
        target: self,
        action: #selector(doneButtonPressed)
    )
}
</code>```

Also there are no clipped views (except the button itself). See snapshot of IB Debug View Hierachy:

Any ideas?

答:
I solved the problem by forwarding the viewWillAppear and viewDidAppear events to the navigation controller's root view controller.

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    navController.viewControllers.first?.viewWillAppear(animated)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    navController.viewControllers.first?.viewDidAppear(animated)
}
</code>```

Body:
I want to put the view of a UINavigationController into another view controller's view. The problem is that the right bar button is misplaced on iOS 10. On iOS 8 and 9 it looks good.

iOS 8 and 9:

iOS 10:

Here's the code how i add the navigation controller:

override func viewDidLoad() {
    super.viewDidLoad()

    let viewController = MyViewController()
    navController = UINavigationController(rootViewController: viewController)
    navController.willMove(toParentViewController: self)
    addChildViewController(navController)
    navController.view.frame = view.bounds
    view.addSubview(navController.view)
    navController.didMove(toParentViewController: self)
}

In MyViewController

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(
        barButtonSystemItem: .done,
        target: self,
        action: #selector(doneButtonPressed)
    )
}

Also there are no clipped views (except the button itself). See snapshot of IB Debug View Hierachy:

Any ideas?

Body:
I solved the problem by forwarding the viewWillAppear and viewDidAppear events to the navigation controller's root view controller.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    navController.viewControllers.first?.viewWillAppear(animated)
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    navController.viewControllers.first?.viewDidAppear(animated)
}


问:
Functional Programming style growing array loop
What is the smartest way to iterate over an array that grows during iteration in javascript? I want to iterate over all added elemets, even elements added during iterations. I'd like do to it in functional programming style.

For example see this code

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

for (let i=0; i0){
      a.push(a[i]+'-')
    }
}

console.log(a)```
</div>
</div>
</p>

<p>After execution got </p>

```[
  "x",
  "y",
  "x-",
  "y-",
  "x--"
]
```

<p>But if I try with an alternative "funcional" mode like forEach the new added elements are not printed</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

a.forEach( (e) => {
    console.log(e)
    limit--
    if(limit>0){
      a.push(e+'-')
    }
})

console.log(a)</code>```

答:
In a functional way, the best approach to do this is using Observables (reactive programing). This array can be turned into a "producer" (Observable) that emit values whenever this collection grows, so you can safely do whatever you want even if this collection is growing over the time.
Maybe this is "over engineering" for just "log" some values, but depending on your real problem, it can be a good solution.

You can have a look on the docs here.

But if you look to your code, in functional programing, you're not going to change the current array (using the reference), but instead, create a entire new array. In functional programing the variables tends to being "read only", following the "immutability" concept.
JS doesn't have natively yet, you can use libs for that tough.
Anyway, I've made this code as an example of that:

function dashAccumulator(arr, times) {
  if(times) {
    const dashed = arr.map(val => `${val}-`);
    return [...arr, ...dashAccumulator(dashed, --times)];
  }
  else return arr;
}

const a = ['x', 'y'];
const iter = 4;
console.log(dashAccumulator(a, iter));```

The map will create a new array and also, when returning, I'm creating another one based on the values of the map result and the "original" array in that context. This way you doesn't need to change any references and keep the same final result.

Body:
What is the smartest way to iterate over an array that grows during iteration in javascript? I want to iterate over all added elemets, even elements added during iterations. I'd like do to it in functional programming style.

For example see this code

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

for (let i=0; i0){
      a.push(a[i]+'-')
    }
}

console.log(a)

After execution got

[
  "x",
  "y",
  "x-",
  "y-",
  "x--"
]

But if I try with an alternative "funcional" mode like forEach the new added elements are not printed

let a = [
 'x',
  'y'
]

let limit = 4  // limit the test

a.forEach( (e) => {
    console.log(e)
    limit--
    if(limit>0){
      a.push(e+'-')
    }
})

console.log(a)

Body:
In a functional way, the best approach to do this is using Observables (reactive programing). This array can be turned into a "producer" (Observable) that emit values whenever this collection grows, so you can safely do whatever you want even if this collection is growing over the time.
Maybe this is "over engineering" for just "log" some values, but depending on your real problem, it can be a good solution.

You can have a look on the docs here.

But if you look to your code, in functional programing, you're not going to change the current array (using the reference), but instead, create a entire new array. In functional programing the variables tends to being "read only", following the "immutability" concept.
JS doesn't have natively yet, you can use libs for that tough.
Anyway, I've made this code as an example of that:

function dashAccumulator(arr, times) {
  if(times) {
    const dashed = arr.map(val => `${val}-`);
    return [...arr, ...dashAccumulator(dashed, --times)];
  }
  else return arr;
}

const a = ['x', 'y'];
const iter = 4;
console.log(dashAccumulator(a, iter));

The map will create a new array and also, when returning, I'm creating another one based on the values of the map result and the "original" array in that context. This way you doesn't need to change any references and keep the same final result.


问:
Contact Form 7 hide label of empty field
I am using Contact Form 7 in a Wordpress site. I have a couple of non-required fields that have labels next to them in the email I am sending. For example..

In the form:

Origin City or Airport Code[text origin-city3]

So in the email:
    Origin City: [origin-city3]

I need 'Origin City: [origin-city3]' to not display if the user did not input a value in the form for origin-city-3 since it is not required.

I have a pretty good understanding of jquery, but do not know if I can use that in the output email.

Any help is much appreciated.

答:
I know it's been years but I want to help others just in case they are looking for the same answer.

You can check the "Exclude lines with blank mail-tags from output" option in the Mail Tab.


问:
Redirect echo output in shell script to logfile
I have a shell script with lots of echo in it. I would like to redirect the output to a logfile.
I know there is the command call cmd > logfile.txt, or to do it in the file echo 'xy' > logfile.txt, but is it possible to simply set the filename in the script which then automatically writes all echo's to this file?

答:
```<code>LOG_LOCATION="/path/to/logs"
exec >> $LOG_LOCATION/mylogfile.log 2>&1
</code>```


问:
Multiple timers in a loop
I have an array of characters, eg.

```<code>["A","E","I","O","U","Y"]
</code>```

I should loop this array and, for every character, start a timer. That is: if the current letter is A, A must be printed and last 2 seconds. After A has been printed, we need to print "E" and it should last 3 seconds, "I" one second, "O" four seconds, etc.

I think I should create a new timer for every character, this way:

```<code>Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector:
#selector(printCharacter), userInfo: nil, repeats: false)
</code>```

but I can't do it inside the loop.

I hoped there was a way to build an array of timers and then fire them sequentially, but this is not possible. Any idea?

答:
You can achieve this using recursion and DispatchQueue only. If you are not familiar with recursion a simple way to understand it's by googling it

A sample code if print duration isn't linear would look like following :

```<code>var currentIndex = 0
let charactersArray = ["A","B","C","D"]
let durations : [TimeInterval] = [1.0,2.0,3.0,4.0]

func printCharacter(){

    guard currentIndex < charactersArray.count else { return }

    print(charactersArray[currentIndex])

    DispatchQueue.main.asyncAfter(deadline: .now() + durations[currentIndex], execute: {

        currentIndex = currentIndex + 1

        printCharacter()
    })
}

printCharacter()
</code>```

where durations array represent time shown for each character

Title: Multiple timers in a loop

Body:
I have an array of characters, eg.

["A","E","I","O","U","Y"]

I should loop this array and, for every character, start a timer. That is: if the current letter is A, A must be printed and last 2 seconds. After A has been printed, we need to print "E" and it should last 3 seconds, "I" one second, "O" four seconds, etc.

I think I should create a new timer for every character, this way:

Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector:
#selector(printCharacter), userInfo: nil, repeats: false)

but I can't do it inside the loop.

I hoped there was a way to build an array of timers and then fire them sequentially, but this is not possible. Any idea?

Body:
You can achieve this using recursion and DispatchQueue only. If you are not familiar with recursion a simple way to understand it's by googling it

A sample code if print duration isn't linear would look like following :

var currentIndex = 0
let charactersArray = ["A","B","C","D"]
let durations : [TimeInterval] = [1.0,2.0,3.0,4.0]

func printCharacter(){

    guard currentIndex < charactersArray.count else { return }

    print(charactersArray[currentIndex])

    DispatchQueue.main.asyncAfter(deadline: .now() + durations[currentIndex], execute: {

        currentIndex = currentIndex + 1

        printCharacter()
    })
}

printCharacter()

where durations array represent time shown for each character


问:
What are the options to build an installer on a build-server without Visual Studio
It seems like it's still not possible to build .vdproj on a build-server without having Visual Studio installed. However, using Wix seems to be a lot more complicated.

Are there any other options to do the following task:

Visual Studio 2010 Solution with multiple projects (.csproj)

Many loose content files (not inside assemblies)

Installer must be built on Build-server without Visual Studio on it (devenv.exe / devenv.com)

Installer must create Registry keys

Installer must associate file extensions with installed product

Installer must support upgrades (version upgrades)

Installer should be able to register COM components

Installer should be able to pre-JIT assemblies

My goal is:

Effort to maintain installer is low

Minimal changes if new project (assembly) is added to solution

Ideal: no changes if new content files are added to any of the projects

Maybe I just did not get the point with Wix, but including project output (like in .vdproj) seems very complicated.

Any suggestions very much appreciated!

答: Check out InstallShield 2010 Limited Edition ( Free for Visual Studio 2010 users ).  It has pretty much all the functionality that VDPROJ ( being retired btw ) has and supports silent builds.  You can get one license for your dev box and one license for your build machine pretty easily.</p>


问:
Select a row based on two other columns R
I have a dataframe df

```<code>df = data.frame(L = rep(letters[1:6], each = 2),
                M = rep(letters[7:12]),
                freq = sample(c(5, 10), replace = FALSE))

   L M freq
1  a g    5
2  a h   10
3  b i    5
4  b j   10
5  c k    5
6  c l   10
7  d g    5
8  d h   10
9  e i    5
10 e j   10
11 f k    5
12 f l   10
</code>```

I want to select the most frequent M for each L.

In this example the output would show:

```<code>h, j, l, h, j, l
</code>```

Frequency is not necessarily every second value in the actual problem.

How can I do this easily?

I've tried a tapply approach, but get stuck here because this seems to only apply to variables and can't be used to subset a subset data frame. (This didn't result in anything close so I won't post the approach)

答:
Another solution using dplyr

```<code>df %>% group_by(L) %>% top_n(1, freq) %>% .$M
#### [1] h j l h j l
</code>```

eventually transform into character at the end...

Body:
I have a dataframe df

df = data.frame(L = rep(letters[1:6], each = 2),
                M = rep(letters[7:12]),
                freq = sample(c(5, 10), replace = FALSE))

   L M freq
1  a g    5
2  a h   10
3  b i    5
4  b j   10
5  c k    5
6  c l   10
7  d g    5
8  d h   10
9  e i    5
10 e j   10
11 f k    5
12 f l   10

I want to select the most frequent M for each L.

In this example the output would show:

h, j, l, h, j, l

Frequency is not necessarily every second value in the actual problem.

How can I do this easily?

I've tried a tapply approach, but get stuck here because this seems to only apply to variables and can't be used to subset a subset data frame. (This didn't result in anything close so I won't post the approach)

Body:
Another solution using dplyr

df %>% group_by(L) %>% top_n(1, freq) %>% .$M
#### [1] h j l h j l

eventually transform into character at the end...


问:
Count back the week numbers based on user input (not current week number)
I'm trying to make a logic in PHP that returns the week number of 4 week before a given week number instead of the current weeknumber. The input for the given week number is $argv[1] because the script is executed CLI.

```<code>$FOURWEEKSAGO = date("W", strtotime("-4 week"));
</code>```

Above example is with the current timestamp but i'm trying to do the same with the following. The example below doesn't work but it illustrates what I want to do.

```<code>$FOURWEEKSAGO = $argv[1], strtotime("-4 week");
</code>```

The functionality must ensure that when its week 2 it will count back and results in 51 (4 week earlier)

A little help would be appreciated

答:
Let $inputWeek be the numerical input value and $week the numerical resulting week.

If last year wasn't a leap-year:

```<code>$week = ($inputWeek + 48) % 52
</code>```

If last year was a leap-year:

```<code>$week = ($inputWeek + 49) % 53
</code>```

In order to decide whether last year was a leap-year, I assume that you can use:

```<code>if ((date("Y") - 2017) % 4 == 0)
</code>```

...since 2017 is a "year-after-a-leap-year", and so every 4th year from that one is.

As pointed out in the comments, the code will get 0 if the input is 4, which can be fixed using an if-statement. Note though that it's important to distinguish if week 0 is identical to week 53 or week 52. All in all:

```<code>if ((date("Y") - 2017) % 4 == 0)
{
    $week = ($inputWeek + 49) % 53;
    if ($week == 0) $week = 53;
}
else
{
    $week = ($inputWeek + 48) % 52;
    if ($week == 0) $week = 52;
}
</code>```

Body:
I'm trying to make a logic in PHP that returns the week number of 4 week before a given week number instead of the current weeknumber. The input for the given week number is $argv[1] because the script is executed CLI.

$FOURWEEKSAGO = date("W", strtotime("-4 week"));

Above example is with the current timestamp but i'm trying to do the same with the following. The example below doesn't work but it illustrates what I want to do.

$FOURWEEKSAGO = $argv[1], strtotime("-4 week");

The functionality must ensure that when its week 2 it will count back and results in 51 (4 week earlier)

A little help would be appreciated

Body:
Let $inputWeek be the numerical input value and $week the numerical resulting week.

If last year wasn't a leap-year:

$week = ($inputWeek + 48) % 52

If last year was a leap-year:

$week = ($inputWeek + 49) % 53

In order to decide whether last year was a leap-year, I assume that you can use:

if ((date("Y") - 2017) % 4 == 0)

...since 2017 is a "year-after-a-leap-year", and so every 4th year from that one is.

As pointed out in the comments, the code will get 0 if the input is 4, which can be fixed using an if-statement. Note though that it's important to distinguish if week 0 is identical to week 53 or week 52. All in all:

if ((date("Y") - 2017) % 4 == 0)
{
    $week = ($inputWeek + 49) % 53;
    if ($week == 0) $week = 53;
}
else
{
    $week = ($inputWeek + 48) % 52;
    if ($week == 0) $week = 52;
}


问:
The URL is not being matched/found: django
In my urls.py, i have this entry:

```<code>url(r'^get-advice/(?P<groupid>[0-9]+)/(?P<catid>[0-9]+)/(?P<style>[a-zA-Z]{6,11})/(?P<zone>[0-9]+)/$', views.give_insight, name='get-advice'),
</code>```

I was hoping this would work:

http://localhost:9000/tips/get-adivce/6/1/sqare/1200

http://localhost:9000/land/get-adivce/6/1/sqare/1

http://localhost:9000/land/get-adivce/6/1/sqare/13

But nothing is being matched. The following works fine:

http://localhost:9000/tips/view-tips/6/1/

for url:

```<code>url(r'^view-tips/(?P<groupid>[0-9]+)/(?P<catid>[0-9]+)/$', views.give_insight, name='view-tips'),
</code>```

答: The style group ((?P

Body:
In my urls.py, i have this entry:

url(r'^get-advice/(?P<groupid>[0-9]+)/(?P<catid>[0-9]+)/(?P

Body:
The style group ((?P<style>[a-zA-Z]{6,11})) matches 6 to 11 characters, sqare only has 5 so it does not match.

Either you meant square either you need to change the character count.

Also you have a typo in the URLs you show: get-adivce -> get-advice


问:
Multithreading & shared resource: Periodically copy data from buffer (data structure) to a file using C++
My code has a data structure say for example "vector of vecor of Strings. I've 2 threads:

THread 1 is writing data to this data structure (buffer in RAM).

Thread 2 running in parallel which should copy data FROM the above buffer i.e data structure TO  a file for every "x" miliseconds.

I'm wondering how would I achieve this in C++ ? It should consider key
  points in problem statement like:

a) The copy from buffer to file should happen only once in "X"
  miliseconds.

b) Synchronization between both threads.

EDITING THE QUERY WITH MORE DETAILS PER THE ASK

I want to build a library (*.lib) & this library exposes some APIs hence it gets input data from EXE or any entity which uses my library through these APIs.
Say the data received by my library is in the form of a vector of strings.

```<code>FillLibraryDataStructure(std::vector<std::string>); // is the API of this library. Any app can call this API & pass a vector of string to this library.

Example app code:
for(int i=100; i<100;i))
{
std::vector<std::string> vec = GetVectorOfString(); // GetVectorOfString from business logic
FillLibraryDataStructure(vec);
}
</code>```

Library code havin a shared resource:

```<code>    // Within library I've a 2D vector i.e. vector of vector of
 strings where all the vector of strings passed by application to this librray are added as a new row in vecofvecofstr.
</code>```

SHARED RESOURCE:

```<code>std::vector<std::vector<string>> vecofvecofstr;
</code>```

THREAD 1: is copying the data it receives from  API to the data structure i.e. vector of vector of strings.

```<code>vecofvecofstr.push_back(vec);
</code>```

THREAD 2: is copying the contents of this vector of vector of string (which was written to in 1st thread ) to files (XML, HTML etc..)
for every "X" miiliseconds.

Few more points about thread1: 1) Thread 1 should be running
  continuously i.e. as and when application calls the API the data
  received should be put to the data structure vecofvecofstr. 2) After
  "X" miliseonds of copying the data to the buffer, 2nd thread should
  get started & it should copy all the stuff that was dumped to buffer
  till date. Again after "X" milisonds the thread 2 should pause & wait
  for "X" ms.

How do I achieve this. Here the 1st thread is the default one in which my library code would be running.
How do i achieve this using C++?

答:
You could use std::mutex and std::condition_variable> to your advantage.  And a double buffer would keep locking to a minimum.

std::condition_variable> is the nearest thing to an event the std has to offer, its use is a bit contrived, but it works.

The example below uses a double buffer so you can keep on buffering data while thread 2 is saving to file, without locking.

The std:condition_variable is used so your application can exit without waiting.  This is only needed if you want your application to exit promptly, else you can use a timer.  The call to notify_all() will prevent the wait_for() from timing out, and wake the writing thread immediately, so it can exit without waiting for the timeout to occur.  See ref at :http://en.cppreference.com/w/cpp/thread/condition_variable

Header:

```<code>#include <mutex>

// a generic double buffer
template<typename _Data>
class DoubleBuffer
{
private:
   std::mutex mutex_;

   std::vector<std::vector<_Data>> storeBuffer_;
   std::vector<std::vector<_Data>> saveBuffer_;

public:
   void lock() { mutex_.lock(); }
   void unlock() { mutex_.unlock();}

   auto& GetStoreBuffer() { return storeBuffer_; }
   auto& GetSaveBuffer()  { return saveBuffer_; }
   auto& Swap()
   {
     std::lock_guard<std::mutex> lock(mutex_);
     std::swap(storeBuffer_, saveBuffer_);
   }
};
</code>```

In your library:

```<code>#include <condition_variable>
#include <thread>
#include <chrono>
#include <mutex>
#include <vector>
#include <string>

// As an example, could be inside a class, or struct
static std::condition_variable exiting;
static std::mutex lk_exiting;

static DoubleBuffer<std::string> yourBuffer;

void FillLibraryDataStructure(std::vector<std::string> strings)
{
    // the lock is only for the duration of a swap - very short at worst.
    std::lock_guard<DoubleBuffer<std::string>> lock(yourBuffer);
    yourBuffer.GetStoreBuffer().emplace_back(strings);
}

void StoreLoop()
{
    for(;;)
    {
       {   // wait_for() unlocks lk_exiting, doc says lock should
           // be set before cv is triggered.
           std::unique_lock<std::mutex> lk_exiting;
           if (std::cv_status::no_timeout == exiting.wait_for(lk_exiting, 60s))
               break;  // app is exiting
       }

      yourBuffer.Swap();

      auto& stringsToSave = GetSaveBuffer();
      // save...  You do have plenty of time.
    }
}

// as an example.  A destructor would be a good place for this
void Exit_Application()
{
  // stops the wait_for operation in StoreLoop()
  exiting.notify_all();
}
</code>```

Body:
My code has a data structure say for example "vector of vecor of Strings. I've 2 threads:

THread 1 is writing data to this data structure (buffer in RAM).

Thread 2 running in parallel which should copy data FROM the above buffer i.e data structure TO  a file for every "x" miliseconds.

I'm wondering how would I achieve this in C++ ? It should consider key
  points in problem statement like:

a) The copy from buffer to file should happen only once in "X"
  miliseconds.

b) Synchronization between both threads.

EDITING THE QUERY WITH MORE DETAILS PER THE ASK

I want to build a library (*.lib) & this library exposes some APIs hence it gets input data from EXE or any entity which uses my library through these APIs.
Say the data received by my library is in the form of a vector of strings.

FillLibraryDataStructure(std::vector<std::string>); // is the API of this library. Any app can call this API & pass a vector of string to this library.

Example app code:
for(int i=100; i<100;i))
{
std::vector<std::string> vec = GetVectorOfString(); // GetVectorOfString from business logic
FillLibraryDataStructure(vec);
}

Library code havin a shared resource:

    // Within library I've a 2D vector i.e. vector of vector of
 strings where all the vector of strings passed by application to this librray are added as a new row in vecofvecofstr.

SHARED RESOURCE:

std::vector<std::vector<string>> vecofvecofstr;

THREAD 1: is copying the data it receives from  API to the data structure i.e. vector of vector of strings.

vecofvecofstr.push_back(vec);

THREAD 2: is copying the contents of this vector of vector of string (which was written to in 1st thread ) to files (XML, HTML etc..)
for every "X" miiliseconds.

Few more points about thread1: 1) Thread 1 should be running
  continuously i.e. as and when application calls the API the data
  received should be put to the data structure vecofvecofstr. 2) After
  "X" miliseonds of copying the data to the buffer, 2nd thread should
  get started & it should copy all the stuff that was dumped to buffer
  till date. Again after "X" milisonds the thread 2 should pause & wait
  for "X" ms.

How do I achieve this. Here the 1st thread is the default one in which my library code would be running.
How do i achieve this using C++?

Body:
You could use std::mutex and std::condition_variable> to your advantage.  And a double buffer would keep locking to a minimum.

std::condition_variable> is the nearest thing to an event the std has to offer, its use is a bit contrived, but it works.

The example below uses a double buffer so you can keep on buffering data while thread 2 is saving to file, without locking.

The std:condition_variable is used so your application can exit without waiting.  This is only needed if you want your application to exit promptly, else you can use a timer.  The call to notify_all() will prevent the wait_for() from timing out, and wake the writing thread immediately, so it can exit without waiting for the timeout to occur.  See ref at :http://en.cppreference.com/w/cpp/thread/condition_variable

Header:

#include <mutex>

// a generic double buffer
template<typename _Data>
class DoubleBuffer
{
private:
   std::mutex mutex_;

   std::vector<std::vector<_Data>> storeBuffer_;
   std::vector<std::vector<_Data>> saveBuffer_;

public:
   void lock() { mutex_.lock(); }
   void unlock() { mutex_.unlock();}

   auto& GetStoreBuffer() { return storeBuffer_; }
   auto& GetSaveBuffer()  { return saveBuffer_; }
   auto& Swap()
   {
     std::lock_guard<std::mutex> lock(mutex_);
     std::swap(storeBuffer_, saveBuffer_);
   }
};

In your library:

#include <condition_variable>
#include <thread>
#include <chrono>
#include <mutex>
#include <vector>
#include <string>

// As an example, could be inside a class, or struct
static std::condition_variable exiting;
static std::mutex lk_exiting;

static DoubleBuffer<std::string> yourBuffer;

void FillLibraryDataStructure(std::vector<std::string> strings)
{
    // the lock is only for the duration of a swap - very short at worst.
    std::lock_guard<DoubleBuffer<std::string>> lock(yourBuffer);
    yourBuffer.GetStoreBuffer().emplace_back(strings);
}

void StoreLoop()
{
    for(;;)
    {
       {   // wait_for() unlocks lk_exiting, doc says lock should
           // be set before cv is triggered.
           std::unique_lock<std::mutex> lk_exiting;
           if (std::cv_status::no_timeout == exiting.wait_for(lk_exiting, 60s))
               break;  // app is exiting
       }

      yourBuffer.Swap();

      auto& stringsToSave = GetSaveBuffer();
      // save...  You do have plenty of time.
    }
}

// as an example.  A destructor would be a good place for this
void Exit_Application()
{
  // stops the wait_for operation in StoreLoop()
  exiting.notify_all();
}


问:
Can't update vars inside Angularjs Factory
Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.

```<code>angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        Authentication.setABCKey(abc);

        console.log(Authentication.showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(Authentication.showABCKey())

    }

    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey
    };

    return Authentication;
}]);
</code>```

答:
dont use var its single tone class you need to define ABCkey in this

var ABCKey;

try with this

```<code>this.ABCKey = '';
</code>```

Body:
Anyone can help with this? Can't update var ABCKey. Execute setAuthenticatedAccount and console.log return correct value. After that, run getAuthenticatedAccount, and receive undefined.

angular.module('authentication.service', [
])

.factory('Authentication', ['$state', '$cookies', '$http', 'app', 'routes', 'cfCryptoHttpInterceptor',
    function($state, $cookies, $http, app, routes, cfCryptoHttpInterceptor) {

    var ABCKey;

    var setAuthenticatedAccount = function (account, tokenAuth) {
        var accountInfo = {'email': account.email, 'username': account.username, 'token': tokenAuth}
        var abc = CryptoJS.enc.Base64.parse(account.abc);

        Authentication.setABCKey(abc);

        console.log(Authentication.showABCKey())

    }

    var getAuthenticatedAccount = function() {
        if(!$cookies.authenticatedAccount) {
            return;
        }

        console.log(Authentication.showABCKey())

    }

    var setABCKey = function(key) {
        ABCKey = key;
    };

    var showABCKey = function() {
        return ABCKey;
    };

    var Authentication = {
        setAuthenticatedAccount: setAuthenticatedAccount,
        getAuthenticatedAccount: getAuthenticatedAccount,
        setABCKey: setABCKey,
        showABCKey: showABCKey
    };

    return Authentication;
}]);

Body:
dont use var its single tone class you need to define ABCkey in this

var ABCKey;

try with this

this.ABCKey = '';


问:
How to check in JSTL whether object is javabean or Collection?
I want to get the filled from an object; it may be a javabean or a collection.

I tried this:

```<code> ${rolesInfo.name}
</code>```

but it was wrong if the rolesInfo are an array,I have to write like this:

```<code>${rolesInfo[0].name}
</code>```

I try to use ${rolesInfo[0]['class']} to get the object type ,but it do not work in tomcat8.May be it only be used in tomcat 6.

答: You can use ${rolesInfo.getClass().simpleName} in tomcat 8. I would like to emphasize on one more point that ${rolesInfo['class'].simpleName} do not work too.

Body:
I want to get the filled from an object; it may be a javabean or a collection.

I tried this:

 ${rolesInfo.name}

but it was wrong if the rolesInfo are an array,I have to write like this:

${rolesInfo[0].name}

I try to use ${rolesInfo[0]['class']} to get the object type ,but it do not work in tomcat8.May be it only be used in tomcat 6.