问:
How can I validate a copy constructor's parameter?
```<code>public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}
</code>```

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

答:
Probably the simplest workaround is not to have your constructor call another constructor.  There's no advantage to it, unless you're doing a classroom assignment where you're told you have to do it:

```<code>public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
}

public Rectangle(Rectangle rectangle) {
    if (rectangle == null) {
        throw new IllegalArgumentException(...);
    }
    this.width = rectangle.width;
    this.height = rectangle.height;
}
</code>```

Of course you now have duplicated code, but it's simple to extract that into a new private method used by both constructors.

This seems more straightforward to me than inventing a way to shoehorn a null check into the this(...), as a couple other answers are trying to do.

Body:
public class Rectangle {

  int width, height;

  public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  public Rectangle(Rectangle source) {
    this(source.width, source.height);
  }
}

Let's say I have a class with multiple constructors, one of which is a copy-constructor (to copy an object).

Is there any way I can make check if source is null in the copy-constructor and throw an IllegalArgumentException if it is? Because the other constructor call has to be the first statement in my constructor.

Body:
Probably the simplest workaround is not to have your constructor call another constructor.  There's no advantage to it, unless you're doing a classroom assignment where you're told you have to do it:

public Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
}

public Rectangle(Rectangle rectangle) {
    if (rectangle == null) {
        throw new IllegalArgumentException(...);
    }
    this.width = rectangle.width;
    this.height = rectangle.height;
}

Of course you now have duplicated code, but it's simple to extract that into a new private method used by both constructors.

This seems more straightforward to me than inventing a way to shoehorn a null check into the this(...), as a couple other answers are trying to do.


来源: stackexchange

问:
what are sql server index disable advantages?
Most people use "index disable" for bulk import / update operations.

There are 2 approches used. Like these:

1- drop index -> bulk import/update operations -> create index

2- disable index -> bulk import/update operations -> rebuild index

What are the superiorities of second one?

答:
With the second solution you basically don't need to keep the exact DDL for the index, that might be quite complicated.

The only detail you need is an index name to rebuild, which is both easier and less error prone.

References:

ALTER INDEX (Transact-SQL)

ContentLicense: CC BY-SA 3.0


问:
Testing Django Channels background task end-to-end
I am trying to perform end-to-end tests of my Django app which uses Channels and Websockets.
In my case a request triggers a complex background calculation and I would like to observe the effects of it.
As far as I understand, in the Django test suite there is no way of running workers, which will consume the background tasks of Django Channels.

Is there any way of triggering however the background tasks with the right parameters? Do I have to modify my code to make it testable?

The following is simplified skeleton of my setup:

views.py

```<code>def calculation(request):
    # doing some simple calculation depending on request
    simple_result, parameter = simple_calculation(request)
    # trigger complex asynchronous calculation depending on parameter
    Channel('background-calculations').send({
        "parameter": parameter,
    })
    # return results of simple calculation
    return render(request, 'simple_reponse.html',{'simple_result': simple_result})
</code>```

routing.py

```<code>channel_routing = [
    route("background-calculations", run_background_calculations),
    route("websocket.connect", ws_connect),
    route("websocket.receive", ws_message),
]
</code>```

consumers.py

```<code>def run_background_calculations(message):
    # perform complex calculation depending on parameter from simple calculation
    result = complex_calculation(message)
    # update frontend via websocket
    Group("frontend-updates").send({
        "text": json.dumps({
            "result": result,
        })
    })

@channel_session
def ws_connect(message):
    message.reply_channel.send({"accept": True})
    Group("frontend-updates").add(message.reply_channel)

@channel_session_user
def ws_message(message):
    message.reply_channel.send({
        "text": message.content['text'],
    })
</code>```

When I try to access the view with a client (e.g. REST APIClient) I do receive the response, but the background task is never executed. Is there no way of testing the whole chain?

答:
So I have figured it out eventually.

If anyone finds this question, here is how to perform the end-to-end test:

```<code>from channels.test import Client
from rest_framework.test import APIClient

# setup
rest = APIClient()
channelclient = Client()
Group("frontend-updates").add(u"test-channel")
rest.login(username="username",password="password")

class CopyTestCase(ChannelTestCase):
    def test_end_to_end(self):
        # trigger HTTP POST request
        response = rest.post("/calculate/")
        #...check response...

        # consume the background-calculation task (has to be done manually)
        channelclient.consume(u"background-calculations")

        # check data sent to the front-end as a result of this calculation
        message = testcase.get_next_message(u"test-channel")
        #...check message...
</code>```

Body:
I am trying to perform end-to-end tests of my Django app which uses Channels and Websockets.
In my case a request triggers a complex background calculation and I would like to observe the effects of it.
As far as I understand, in the Django test suite there is no way of running workers, which will consume the background tasks of Django Channels.

Is there any way of triggering however the background tasks with the right parameters? Do I have to modify my code to make it testable?

The following is simplified skeleton of my setup:

views.py

def calculation(request):
    # doing some simple calculation depending on request
    simple_result, parameter = simple_calculation(request)
    # trigger complex asynchronous calculation depending on parameter
    Channel('background-calculations').send({
        "parameter": parameter,
    })
    # return results of simple calculation
    return render(request, 'simple_reponse.html',{'simple_result': simple_result})

routing.py

channel_routing = [
    route("background-calculations", run_background_calculations),
    route("websocket.connect", ws_connect),
    route("websocket.receive", ws_message),
]

consumers.py

def run_background_calculations(message):
    # perform complex calculation depending on parameter from simple calculation
    result = complex_calculation(message)
    # update frontend via websocket
    Group("frontend-updates").send({
        "text": json.dumps({
            "result": result,
        })
    })

@channel_session
def ws_connect(message):
    message.reply_channel.send({"accept": True})
    Group("frontend-updates").add(message.reply_channel)

@channel_session_user
def ws_message(message):
    message.reply_channel.send({
        "text": message.content['text'],
    })

When I try to access the view with a client (e.g. REST APIClient) I do receive the response, but the background task is never executed. Is there no way of testing the whole chain?

Body:
So I have figured it out eventually.

If anyone finds this question, here is how to perform the end-to-end test:

from channels.test import Client
from rest_framework.test import APIClient

# setup
rest = APIClient()
channelclient = Client()
Group("frontend-updates").add(u"test-channel")
rest.login(username="username",password="password")

class CopyTestCase(ChannelTestCase):
    def test_end_to_end(self):
        # trigger HTTP POST request
        response = rest.post("/calculate/")
        #...check response...

        # consume the background-calculation task (has to be done manually)
        channelclient.consume(u"background-calculations")

        # check data sent to the front-end as a result of this calculation
        message = testcase.get_next_message(u"test-channel")
        #...check message...


问:
iOS Auto-Renewable Subscriptions Free Trial Not Being Indicated
I am having some issues adding a free trial to an existing Auto-Renewable IAP. From what I understand, you only need to add a "free trial" duration in iTunesConnect in your IAP for this to work. but I am not seeing any update in the description of the purchase indicating the free trial. When looking at other apps that do offer a free trial, the apple subscription dialog that pops up indicates:

```<code>Subscription Terms
Subscribe to <IAP NAME>. this subscription will start with a free trial lasting <TRIAL DURATION> after which youy will be charged <PRICE> on a <Duration> basis
</code>```

while my own dialog still shows (not indicating that there is a free trial):

```<code>Subscription Terms
Subscrube to <IAP NAME>. This subscription will automatically renew every year for <PRICE>
</code>```

Am I missing something in iTunes connect? Do I need to enable free trials another way?

What I have tried:

Using a sandbox account with an Auto-Renewable Sub that is not
cleared for sale

Using a fresh iTunes account on an Auto-Renewable
    Sub that is cleared for sale and I have temporarily added the free
    trial duration in iTunes connect

Using a sandbox account on an Auto-Renewable Sub that is cleared for
        sale and I have temporarily added the free trial duration in iTunes
        connect

答:
Had the same issue. In my case, it even didn't show me the Subscription Terms alert only the Subscription Confirmation.

The problem seems to be with the Sandbox Testing account rather than with the implementation. You probably didn't have the trial set up in your IAP and then you created Sandbox tester and tested it like this. Then you added the free trial to the IAP, but the Sandbox tester has in cache or somewhere that this IAP doesn't have trial.

QUICK FIX: Create a new Sandbox Tester in iTunesConnect.

Body:
I am having some issues adding a free trial to an existing Auto-Renewable IAP. From what I understand, you only need to add a "free trial" duration in iTunesConnect in your IAP for this to work. but I am not seeing any update in the description of the purchase indicating the free trial. When looking at other apps that do offer a free trial, the apple subscription dialog that pops up indicates:

Subscription Terms
Subscribe to <IAP NAME>. this subscription will start with a free trial lasting <TRIAL DURATION> after which youy will be charged <PRICE> on a <Duration> basis

while my own dialog still shows (not indicating that there is a free trial):

Subscription Terms
Subscrube to <IAP NAME>. This subscription will automatically renew every year for <PRICE>

Am I missing something in iTunes connect? Do I need to enable free trials another way?

What I have tried:

Using a sandbox account with an Auto-Renewable Sub that is not
cleared for sale

Using a fresh iTunes account on an Auto-Renewable
    Sub that is cleared for sale and I have temporarily added the free
    trial duration in iTunes connect

Using a sandbox account on an Auto-Renewable Sub that is cleared for
        sale and I have temporarily added the free trial duration in iTunes
        connect


问:
Scroll lock for body while mobile menu is open is not working
I have found several other solutions that demonstrate how you can lock scroll behaviour for a website by using CSS overflow property. As such I have implemented this solution and added the overflow: hidden; to the body tag when the menu is open. However when using iOS Safari or Chrome the body is still scrollable.

CSS:

```<code>    body.opened-drawer {
      overflow: hidden !important;
      height: 100% !important;
      width: 100% !important;
      position: fixed !important;
      z-index: 0 !important;
    }
</code>```

JS:

```<code>timber.openDrawerMenu = function () {
  var $mobileMenu = $('.nav-bar'),
      $mobileMenuButton = $('#menu-opener'),
      $body = $('body');
      $mobileMenuButton.addClass('opened');
      $mobileMenu.addClass('opened');
      $body.addClass('opened-drawer');

  // Make drawer a11y accessible
  timber.cache.$navBar.attr('aria-hidden', 'false');

  // Set focus on drawer
  timber.trapFocus({
     $container: timber.cache.$navBar,
     namespace: 'drawer_focus'
  });

  // Escape key closes menu
  timber.cache.$html.on('keyup.drawerMenu', function(evt) {
    if (evt.keyCode == 27) {
      timber.closeDrawerMenu();
    }
  });
}

timber.closeDrawerMenu = function () {

  var $mobileMenu = $('.nav-bar'),
      $mobileMenuButton = $('#menu-opener'),
      $body = $('body');

  $mobileMenuButton.removeClass('opened');
  $mobileMenu.removeClass('opened');
  $body.removeClass('opened-drawer');

  // Make drawer a11y unaccessible
  timber.cache.$navBar.attr('aria-hidden', 'true');

  // Remove focus on drawer
  timber.removeTrapFocus({
    $container: timber.cache.$navBar,
    namespace: 'drawer_focus'
  });

  timber.cache.$html.off('keyup.drawerMenu');
}
</code>```

答:
The solution I came to is more of a hack and less a solution but gets the job done either way. What I did was fix the position on the body when the menu was opened and calculate and set the scrollTop position as the menu was opened or closed.

jQuery:

```<code>    var tempScrollTop = null;

    tempScrollTop = $(window).scrollTop();

    $(window).scrollTop(tempScrollTop);

    var fixed = document.getElementById('fixed--nav');
       fixed.addEventListener('touchmove', function(e) {
       e.preventDefault();
    }, false);
</code>```

Body:
I have found several other solutions that demonstrate how you can lock scroll behaviour for a website by using CSS overflow property. As such I have implemented this solution and added the overflow: hidden; to the body tag when the menu is open. However when using iOS Safari or Chrome the body is still scrollable.

CSS:

    body.opened-drawer {
      overflow: hidden !important;
      height: 100% !important;
      width: 100% !important;
      position: fixed !important;
      z-index: 0 !important;
    }

JS:

timber.openDrawerMenu = function () {
  var $mobileMenu = $('.nav-bar'),
      $mobileMenuButton = $('#menu-opener'),
      $body = $('body');
      $mobileMenuButton.addClass('opened');
      $mobileMenu.addClass('opened');
      $body.addClass('opened-drawer');

  // Make drawer a11y accessible
  timber.cache.$navBar.attr('aria-hidden', 'false');

  // Set focus on drawer
  timber.trapFocus({
     $container: timber.cache.$navBar,
     namespace: 'drawer_focus'
  });

  // Escape key closes menu
  timber.cache.$html.on('keyup.drawerMenu', function(evt) {
    if (evt.keyCode == 27) {
      timber.closeDrawerMenu();
    }
  });
}

timber.closeDrawerMenu = function () {

  var $mobileMenu = $('.nav-bar'),
      $mobileMenuButton = $('#menu-opener'),
      $body = $('body');

  $mobileMenuButton.removeClass('opened');
  $mobileMenu.removeClass('opened');
  $body.removeClass('opened-drawer');

  // Make drawer a11y unaccessible
  timber.cache.$navBar.attr('aria-hidden', 'true');

  // Remove focus on drawer
  timber.removeTrapFocus({
    $container: timber.cache.$navBar,
    namespace: 'drawer_focus'
  });

  timber.cache.$html.off('keyup.drawerMenu');
}

Body:
The solution I came to is more of a hack and less a solution but gets the job done either way. What I did was fix the position on the body when the menu was opened and calculate and set the scrollTop position as the menu was opened or closed.

jQuery:

    var tempScrollTop = null;

    tempScrollTop = $(window).scrollTop();

    $(window).scrollTop(tempScrollTop);

    var fixed = document.getElementById('fixed--nav');
       fixed.addEventListener('touchmove', function(e) {
       e.preventDefault();
    }, false);


问:
CLI error on an amazon ec2 when trying to copy file from s3
An error occurred (InvalidRequest) when calling the ListObjects operation:

Missing required header for this request: x-amz-content-sha256

答:
check your ~/.aws/config file and add proper region value.
or
re run aws configure</p>


问:
Can one ElasticBeanstalk environment ever have multiple AutoScaling groups?
I was looking at the AWS SDK to get information about my EB environment when I found that it appears that the SDK is returning AutoScaling groups as an array.

Can an EB environment even have multiple autoscaling groups?

And why might multiple autoscaling groups be used?

答: An Elastic Beanstalk environment would have an Elastic load balancer on it and that allows for multiple auto scaling groups. One use of multiple Auto Scaling groups is blue/green deployments. You can spin new version of an application, test it, attach it to the load balancer to receive production traffic and slowly terminate old instances. You can read more about blue/green deployments here</p>


问:
How to close/hide app main window?
I have an app that has a main window and secondary windows.

In certain situations, I would like to only display a secondary window when the user launches the app.

The problem is that the app's main window is automatically launched, so I after programamtically opening the secondary window I am left with both the main and secondary windows.

Is there any way I can hide the main window?  (Ie, emulate the user pressing the "close button" in the top right corner of the main window?)

答:
After creating the secondary view I switch to this new view specifying the fromViewId as the main view id, and using the ApplicationViewSwitchingOptions.ConsolidateViews option, which hides it:

```<code>// Create seprate secondary window
await ApplicationViewSwitcher.TryShowAsStandaloneAsync(secondaryWindowViewId);

// Switch to secondary window just created, which hides the main view
await ApplicationViewSwitcher.SwitchAsync(
    secondaryWindowViewId,
    mainWindowViewId,
    ApplicationViewSwitchingOptions.ConsolidateViews);
</code>```

Not the most elegant solution, but it works :)  More elegant solutions are welcome!

Title: How to close/hide app main window?

Body:
After creating the secondary view I switch to this new view specifying the fromViewId as the main view id, and using the ApplicationViewSwitchingOptions.ConsolidateViews option, which hides it:

// Create seprate secondary window
await ApplicationViewSwitcher.TryShowAsStandaloneAsync(secondaryWindowViewId);

// Switch to secondary window just created, which hides the main view
await ApplicationViewSwitcher.SwitchAsync(
    secondaryWindowViewId,
    mainWindowViewId,
    ApplicationViewSwitchingOptions.ConsolidateViews);

Not the most elegant solution, but it works :)  More elegant solutions are welcome!


问:
GLUT substitute for AUX_RGBImageRec?
I'm going through some old code that uses glaux everywhere.

Well, I'm required to use glut in my project, and I'm wondering if it has a structure for a rgb bitmap like glaux has.

Something that would allow me to replace this pointer declaration.

```<code>AUX_RGBImageRec *pBitmap;
</code>```

答: Might give SOIL a whirl.</p>

ContentLicense: CC BY-SA 2.5

Title: GLUT substitute for AUX_RGBImageRec?

Body:
I'm going through some old code that uses glaux everywhere.

Well, I'm required to use glut in my project, and I'm wondering if it has a structure for a rgb bitmap like glaux has.

Something that would allow me to replace this pointer declaration.

AUX_RGBImageRec *pBitmap;

Body: Might give SOIL a whirl.


问:
Sorting map by LocalDate
I have the following map:

```<code>var result = collection.mutable.Map[LocalDate,String]
</code>```

I need to sort it by LocalDate, this doesn't work, as I get the following compilation error: missing parameter type for expanded function ((x$1) ⇒ x$1._1.isAfter(((x$2) ⇒ x$2._1))):

```<code>result.toSeq.sortWith(_._1.isAfter(_._1))
</code>```

Any ideas?

答:
Either of these will compile.

```<code>result.toSeq.sortWith(_._1 isAfter _._1)
// or
result.toSeq.sortWith((a,b) => a._1.isAfter(b._1))
</code>```

Putting the passed-parameter underscore _ inside inner parentheses changes its meaning.

Title: Sorting map by LocalDate

Body:
I have the following map:

var result = collection.mutable.Map[LocalDate,String]

I need to sort it by LocalDate, this doesn't work, as I get the following compilation error: missing parameter type for expanded function ((x$1) ⇒ x$1._1.isAfter(((x$2) ⇒ x$2._1))):

result.toSeq.sortWith(_._1.isAfter(_._1))

Any ideas?

Body:
Either of these will compile.

result.toSeq.sortWith(_._1 isAfter _._1)
// or
result.toSeq.sortWith((a,b) => a._1.isAfter(b._1))

Putting the passed-parameter underscore _ inside inner parentheses changes its meaning.


问:
Search bar rounded corner
How to change the border of search bar to rounded corner. Below is my code and I need the orange coloured border to be rounded not as sharp rectangle. Please help

```<code>// Search bar
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 60, 270, 41)];
self.searchBar.delegate = self;
self.searchBar.placeholder = MEGLocalizedString(@"search_hint_home_screen", nil);
UIColor *searchBarBackgroundColor = [UIColor clearColor];
self.searchBar.backgroundImage = [UIImage imageFromColor:searchBarBackgroundColor];
[self.searchBar setImage:[[UIImage imageNamed:@"search_icon_general.png"] imageTintedWithColor:primaryEventColor] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    UIView *textField = [self.searchBar subviewWithKindOfClass:[UITextField class]];
    textField.backgroundColor = [UIColor orangeColor];
//        textField.layer.borderWidth = 1;
    textField.layer.cornerRadius = 14;
    [(UITextField *)textField setBorderStyle:UITextBorderStyleNone];
    // Change the search bar placeholder text color
    [textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
}
self.searchBar.layer.cornerRadius = 14;
self.searchBar.layer.borderColor = [UIColor orangeColor].CGColor;
</code>```

答:
This solve your problem

textField.layer.masksToBounds = true

Title: Search bar rounded corner

Body:
How to change the border of search bar to rounded corner. Below is my code and I need the orange coloured border to be rounded not as sharp rectangle. Please help

// Search bar
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 60, 270, 41)];
self.searchBar.delegate = self;
self.searchBar.placeholder = MEGLocalizedString(@"search_hint_home_screen", nil);
UIColor *searchBarBackgroundColor = [UIColor clearColor];
self.searchBar.backgroundImage = [UIImage imageFromColor:searchBarBackgroundColor];
[self.searchBar setImage:[[UIImage imageNamed:@"search_icon_general.png"] imageTintedWithColor:primaryEventColor] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    UIView *textField = [self.searchBar subviewWithKindOfClass:[UITextField class]];
    textField.backgroundColor = [UIColor orangeColor];
//        textField.layer.borderWidth = 1;
    textField.layer.cornerRadius = 14;
    [(UITextField *)textField setBorderStyle:UITextBorderStyleNone];
    // Change the search bar placeholder text color
    [textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
}
self.searchBar.layer.cornerRadius = 14;
self.searchBar.layer.borderColor = [UIColor orangeColor].CGColor;


问:
Laravel file web editor
I work at a place where software installations and internet is heavily monitored, and they won't allow FTP or SSH connections. I'm also working on a Laravel project that is due very soon, and I would like to use some of the free time at work to write a line or two to help expedite the finish date. My question is: is there a web file editor that would allow me to edit my Laravel dist files from the browser and run commands like php artisan?

if NOT, I thought of using php's scandir and shell_exec to accomplish the task, but I always get routeNotFoundException. Any Ideas? Thank you all

答: I have successfully managed to create a little web editor using php. The trick is to move the files outside of the Laravel dist. All commands used are pretty simple such as chdir() and shell_exec.

Title: Laravel file web editor


问:
How would I replace a single character in a string?
I'm coding a little python program for ROT13.

If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'.

A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front.

This means I need to replace each character, now who would I do that?

I tried importing the re function but It didn't work. This is what I got so far.

```<code>import re

Alpha = input("Input the word you would like translated")

Alpha = re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm',
Alpha)
print(Alpha)
</code>```

Help would be very much appreciated.

答:
You can try this:</p>

```<code>import string

l = list(string.ascii_lowercase)

new_letters = {a:l[(i+13)%26] for i, a in enumerate(l)}

Alpha = input("Input the word you would like translated")

print(''.join(new_letters[i] for i in Alpha))
</code>```

Body:
I'm coding a little python program for ROT13.

If you don't know what it means, it means it will replace the letter of the alphabet to 13th letter in front of it therefore 'a' would become 'n'.

A user will ask for an input and I shall replace each character in the sentence to the 13th letter in front.

This means I need to replace each character, now who would I do that?

I tried importing the re function but It didn't work. This is what I got so far.

import re

Alpha = input("Input the word you would like translated")

Alpha = re.sub('[abcdefghijklmnopqrstuvwxyz]', 'nopqrstuvwxyzabcdefghijklm',
Alpha)
print(Alpha)

Help would be very much appreciated.

Body:
You can try this:

import string

l = list(string.ascii_lowercase)

new_letters = {a:l[(i+13)%26] for i, a in enumerate(l)}

Alpha = input("Input the word you would like translated")

print(''.join(new_letters[i] for i in Alpha))


问:
RegEx NPP - Need some assistance with a lookaround
In NPP, I am attempting a search/replace to turn a broken line back into a single line of text. (This will be used often)

However, when I search/replace in Notepad++, it removes the entire first line. Clearly I am doing something wrong with my look-around.

Regex101 fiddle to work with.

```<code>50TH-ST-TA5000-1#sh in efm-g 1/11/4
  Alias                           : EZE-P SCHOENFELD ASSET
  Provisioned Links               : 11/5,    11/6,    11/30,   11/31,
                                    13/1,    13/2
  Active Links                    : 11/5,    13/2
  Inhibited Links                 : None
                                   Upstream               Downstream
  Rate                       kbps : 6400                   6400
</code>```

答:
You went too complex way. Please try this:

find: ,\s+[\r\n]+\s+

replace: ,--- (comma and 3 spaces)

Body:
In NPP, I am attempting a search/replace to turn a broken line back into a single line of text. (This will be used often)

However, when I search/replace in Notepad++, it removes the entire first line. Clearly I am doing something wrong with my look-around.

Regex101 fiddle to work with.

50TH-ST-TA5000-1#sh in efm-g 1/11/4
  Alias                           : EZE-P SCHOENFELD ASSET
  Provisioned Links               : 11/5,    11/6,    11/30,   11/31,
                                    13/1,    13/2
  Active Links                    : 11/5,    13/2
  Inhibited Links                 : None
                                   Upstream               Downstream
  Rate                       kbps : 6400                   6400


问:
Getting back to back error using "wait_on_rate_limit" parameter
In order to avoid rate limit error I used the parameter:

```<code>wait_on_rate_limit
</code>```

in function

```<code>api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)
</code>```

At first my program worked fine. When I surpass the rate limit I got the message:

      "Rate limit reached. Sleeping for: 909". My program was sleeping for this amount of time and then my program continued to collect data. At some point I got some back to back errors.

```<code>...
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

...
urllib3.exceptions.ProtocolError: ('Connection aborted.',
ConnectionResetError(10054, 'An existing connection was forcibly closed by
the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

...
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

...
tweepy.error.TweepError: Failed to send request: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
</code>```

My code:

```<code>for user in tweepy.Cursor(api.friends, id="twitter").items():
    friendsOfUser=user.screen_name
    ## Do something with friendsOfUser
</code>```

Is there anything that I can do?

答:
You can't do anything with the fact that host closes the connection. If you are waiting for the rate limit, I bet you're a bit aggressive in API usage :) Try catching TweepError and explicitly waiting for some time and them try again.

You can try something like this:

```<code>import time

...
try:
    for user in tweepy.Cursor(api.friends, id="twitter").items():
        friendsOfUser=user.screen_name
        ...
except tweepy.TweepError:
    time.sleep(120) # sleep for 2 minutes. You may try different time
</code>```

Body:
In order to avoid rate limit error I used the parameter:

wait_on_rate_limit

in function

api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True)

At first my program worked fine. When I surpass the rate limit I got the message:

      "Rate limit reached. Sleeping for: 909". My program was sleeping for this amount of time and then my program continued to collect data. At some point I got some back to back errors.

...
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

During handling of the above exception, another exception occurred:

...
urllib3.exceptions.ProtocolError: ('Connection aborted.',
ConnectionResetError(10054, 'An existing connection was forcibly closed by
the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

...
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

During handling of the above exception, another exception occurred:

...
tweepy.error.TweepError: Failed to send request: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))

My code:

for user in tweepy.Cursor(api.friends, id="twitter").items():
    friendsOfUser=user.screen_name
    ## Do something with friendsOfUser

Is there anything that I can do?

Body:
You can't do anything with the fact that host closes the connection. If you are waiting for the rate limit, I bet you're a bit aggressive in API usage :) Try catching TweepError and explicitly waiting for some time and them try again.

You can try something like this:

import time

...
try:
    for user in tweepy.Cursor(api.friends, id="twitter").items():
        friendsOfUser=user.screen_name
        ...
except tweepy.TweepError:
    time.sleep(120) # sleep for 2 minutes. You may try different time


问:
The reason to use masking
```<code>gcc 4.4.1 c89
</code>```

I am using a API that our previous programmer has produced. However, I am a bit confused as to why they do masking in this why.

What is the reason to OR the hex with a mask. And what would be the reason to have IPEV_ERROR_MASK OR'ed with IPEV_START. Why not have just the hex values?

```<code>#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)
</code>```

Many thanks for any suggestions,

答:
It looks like a categorization (or grouping) method.  It would seem that all "IPEV" values have that 0x9000 included.  The subsequent values certainly could have been defined as a simple hex value, but the method as given is somewhat self-documenting and helps avoid making an error when adding a new value.

One possible use would be that a piece of code could check the IPEV_MASK portion of a value to see if a "code" belongs to that group.

```<code>if (( someCode & IPEV_MASK ) == IPEV_MASK )
  // do something
</code>```

Title: The reason to use masking

Body:
gcc 4.4.1 c89

I am using a API that our previous programmer has produced. However, I am a bit confused as to why they do masking in this why.

What is the reason to OR the hex with a mask. And what would be the reason to have IPEV_ERROR_MASK OR'ed with IPEV_START. Why not have just the hex values?

#define IPEV_MASK               0x9000
#define IPEV_ERROR_MASK     (IPEV_MASK | 0x0800)
#define IPEV_OPEN               (IPEV_MASK | 0x01)
#define IPEV_START              (IPEV_MASK | 0x02)
#define IPEV_MEDIA_FAIL     (IPEV_ERROR_MASK | IPEV_START)

Many thanks for any suggestions,

Body:
It looks like a categorization (or grouping) method.  It would seem that all "IPEV" values have that 0x9000 included.  The subsequent values certainly could have been defined as a simple hex value, but the method as given is somewhat self-documenting and helps avoid making an error when adding a new value.

One possible use would be that a piece of code could check the IPEV_MASK portion of a value to see if a "code" belongs to that group.

if (( someCode & IPEV_MASK ) == IPEV_MASK )
  // do something


问:
Sort Vector with custom sort
This works for cmp function having A.num>B.num but for lesser than it outputs zeros for all the values, idk why thanks. i'd like to know if im doing something wrong when im calling the function?

```<code>#include <bits/stdc++.h>
using namespace std;

typedef struct node
{
    int num;
}Node;
</code>```

this gives an error when A.num

```<code>bool cmpNode(Node A,Node B){
    return A.num<=B.num;
}

int main(){

    int n;
    cin>>n;

    //std::vector<char> v;
    vector<Node> vec(n);

    for (int i = 0; i < n; ++i)
    {
        Node temp;//    =new Node;
        cin>>temp.num;
        vec.push_back(temp);

    }

    sort(vec.begin(), vec.end(),cmpNode);

    for (int i = 0; i < n; ++i)
    {
        cout<<vec[i].num<<" ";
    }
    return 0;
}
</code>```

答:
I think the main issue is statement vector<Node> vec(n), which initialises the vector with n "empty" nodes before you additionally add another n nodes with individual values. So if you sort ascending, and then print the first n nodes, it is very likely that you print the "empty" ones, i.e. the ones with value 0 (which shine up in the beginning).

So mainly you should write

```<code>vector<Node> vec;
</code>```

Further, as stated by others, a comparison function used for std::sort must meet
a strict weak ordering relation (cf. cppreference.com):

The return value of the function call operation applied to an object
  of type Compare, when contextually converted to bool, yields true if
  the first argument of the call appears before the second in the strict
  weak ordering relation induced by this Compare type, and false
  otherwise.

This means, among other requirements, that...

For all a, comp(a,a)==false

Title: Sort Vector with custom sort

Body:
This works for cmp function having A.num>B.num but for lesser than it outputs zeros for all the values, idk why thanks. i'd like to know if im doing something wrong when im calling the function?

#include <bits/stdc++.h>
using namespace std;

typedef struct node
{
    int num;
}Node;

this gives an error when A.num

bool cmpNode(Node A,Node B){
    return A.num<=B.num;
}

int main(){

    int n;
    cin>>n;

    //std::vector<char> v;
    vector<Node> vec(n);

    for (int i = 0; i < n; ++i)
    {
        Node temp;//    =new Node;
        cin>>temp.num;
        vec.push_back(temp);

    }

    sort(vec.begin(), vec.end(),cmpNode);

    for (int i = 0; i < n; ++i)
    {
        cout<<vec[i].num<<" ";
    }
    return 0;
}

Body:
I think the main issue is statement vector<Node> vec(n), which initialises the vector with n "empty" nodes before you additionally add another n nodes with individual values. So if you sort ascending, and then print the first n nodes, it is very likely that you print the "empty" ones, i.e. the ones with value 0 (which shine up in the beginning).

So mainly you should write

vector<Node> vec;

Further, as stated by others, a comparison function used for std::sort must meet
a strict weak ordering relation (cf. cppreference.com):

The return value of the function call operation applied to an object
  of type Compare, when contextually converted to bool, yields true if
  the first argument of the call appears before the second in the strict
  weak ordering relation induced by this Compare type, and false
  otherwise.

This means, among other requirements, that...

For all a, comp(a,a)==false


问:
How to test an integration to mercadopago using test users?
In order to test a MercadoPago integration the documentation tells that you need at least two test users: a seller and a buyer. It also explains how to create them but not how to use them.
I suppose the seller info should be hard-coded somewhere in the server side. Where? Is there a field in the preference data to specify the seller user?

I know there is a payer field and I used it to specify the buyer. But what about the seller?

I already tried filling the client_id and collector_id fields of the preference data with the test-user id with no avail.

```<code>MP mp = new MP("???", "????");
JSONObject preference = mp.createPreference("{items:[...], client_id: 262046207}");
</code>```

Where 262046207 is the test-user id of one of the two test users I generated.
When the user submits a payment he gets this error message: "Una de las partes es un usuario de prueba."

答:
Steps:

Create two test users: one for acting as the buyer, and the other for acting as the seller. Here are the instructions to create a test user.

Log out if you are already logged in.

Log in to MercadoPago with the seller test user using the e-mail and password you obtained in step 1. If the login dialog asks for your password before the e-mail, click the link "no soy ..." which is below the login dialog.

Then go to this link to obtain the credential you need to authenticate programmatically from the server.

Then go to this link to configure the URL where your server will listen to the MercadoPago notifications. If you have a router, don't forget to open the port.

At the time of testing a purchase, log in to MercadoPago with the e-mail and password of the buyer test user.

To pay with credit cards, use any of these cards numbers. The other fields can be filled with anything, but the card holder's name should start with any of the prefixes enumerated at the bottom of the mentioned page.

Body:
In order to test a MercadoPago integration the documentation tells that you need at least two test users: a seller and a buyer. It also explains how to create them but not how to use them.
I suppose the seller info should be hard-coded somewhere in the server side. Where? Is there a field in the preference data to specify the seller user?

I know there is a payer field and I used it to specify the buyer. But what about the seller?

I already tried filling the client_id and collector_id fields of the preference data with the test-user id with no avail.

MP mp = new MP("???", "????");
JSONObject preference = mp.createPreference("{items:[...], client_id: 262046207}");

Where 262046207 is the test-user id of one of the two test users I generated.
When the user submits a payment he gets this error message: "Una de las partes es un usuario de prueba."


问:
Application won't start (0xc000007b) with GTK+ and C
I have written an really basic test application in C with GTK+ 3, but when I want to start this application I'm getting the following error:

The application was unable to start correctly (0xc000007b)

But Im getting this only with GTK+ 3.

My Code:

```<code>#include <stdio.h>
#include <gtk/gtk.h>

static void activate(GtkApplication *app, gpointer user_data) {
    GtkWidget *window;

    window = gtk_application_window_new(app);

    gtk_window_set_title(GTK_WINDOW (window), "Tutorial");
    gtk_window_set_default_size(GTK_WINDOW(window), 200, 200);
    gtk_widget_show_all(window);

}

int main(int argc, char **argv) {
    printf("Hello, World!\n");

    //printf("Ein akustisches Signal mit : (\\a)\a");
    printf("\nEin Backspace mit : (\\b) | \bx\n");
    printf("Ein Zeilenvorschub mit : (\\t) |\tx");
    printf("\n\tC\n\ti\n\ts\n\tt\n\ttoll\n");
    printf("\t   u\n\t   n\n\t   d\n");
    printf("\t   macht Spaß\n");

    //Kommentar 1
    /* Kommentar 2 */
    /*
     * Mehrzeiliges Kommentar
     */

    GtkApplication *app;
    int status;

    app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);

    g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);

    status = g_application_run(G_APPLICATION(app), argc, argv);

    g_object_unref(app);

    return status;
}
</code>```

CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.7)
project(tutorial)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)

set(PKG_CONFIG_EXECUTABLE "C:/msys64/mingw64/bin/pkg-config.exe")

FIND_PACKAGE(PkgConfig REQUIRED)
PKG_CHECK_MODULES(GTK3 REQUIRED gtk+-3.0)

INCLUDE_DIRECTORIES(${GTK3_INCLUDE_DIRS})
LINK_DIRECTORIES(${GTK3_LIBRARY_DIRS})

add_executable(tutorial ${SOURCE_FILES})

ADD_DEFINITIONS(${GTK3_CFLAGS_OTHER})

TARGET_LINK_LIBRARIES(tutorial ${GTK3_LIBRARIES})
</code>```

Im using Clion 2017.1.3, mingw-w64 5.0 and cmake 3.7.2 (x64) with gdb 7.11.1 (x64)

答:
Ok, I fixed my own bug ^^

I set an GTK_BASEPATH in my system variables and the PATH variable to an old version of GTK (32 bit) and It used these files as library.

Body:
I have written an really basic test application in C with GTK+ 3, but when I want to start this application I'm getting the following error:

The application was unable to start correctly (0xc000007b)

But Im getting this only with GTK+ 3.

My Code:

#include <stdio.h>
#include <gtk/gtk.h>

static void activate(GtkApplication *app, gpointer user_data) {
    GtkWidget *window;

    window = gtk_application_window_new(app);

    gtk_window_set_title(GTK_WINDOW (window), "Tutorial");
    gtk_window_set_default_size(GTK_WINDOW(window), 200, 200);
    gtk_widget_show_all(window);

}

int main(int argc, char **argv) {
    printf("Hello, World!\n");

    //printf("Ein akustisches Signal mit : (\\a)\a");
    printf("\nEin Backspace mit : (\\b) | \bx\n");
    printf("Ein Zeilenvorschub mit : (\\t) |\tx");
    printf("\n\tC\n\ti\n\ts\n\tt\n\ttoll\n");
    printf("\t   u\n\t   n\n\t   d\n");
    printf("\t   macht Spaß\n");

    //Kommentar 1
    /* Kommentar 2 */
    /*
     * Mehrzeiliges Kommentar
     */

    GtkApplication *app;
    int status;

    app = gtk_application_new("org.gtk.example", G_APPLICATION_FLAGS_NONE);

    g_signal_connect(app, "activate", G_CALLBACK(activate), NULL);

    status = g_application_run(G_APPLICATION(app), argc, argv);

    g_object_unref(app);

    return status;
}

CMakeLists.txt:

cmake_minimum_required(VERSION 3.7)
project(tutorial)

set(CMAKE_C_STANDARD 99)

set(SOURCE_FILES main.c)

set(PKG_CONFIG_EXECUTABLE "C:/msys64/mingw64/bin/pkg-config.exe")

FIND_PACKAGE(PkgConfig REQUIRED)
PKG_CHECK_MODULES(GTK3 REQUIRED gtk+-3.0)

INCLUDE_DIRECTORIES(${GTK3_INCLUDE_DIRS})
LINK_DIRECTORIES(${GTK3_LIBRARY_DIRS})

add_executable(tutorial ${SOURCE_FILES})

ADD_DEFINITIONS(${GTK3_CFLAGS_OTHER})

TARGET_LINK_LIBRARIES(tutorial ${GTK3_LIBRARIES})

Im using Clion 2017.1.3, mingw-w64 5.0 and cmake 3.7.2 (x64) with gdb 7.11.1 (x64)


问:
How to create a dataframe by applying a function on two vectors
I have two different sized character vectors, say a and b, which I would like to form the row names and column names of a new dataframe (df).

If I have a function which takes 2 arguments, an element from each of these vectors, which gives the data to go into the dataframe, how can I create it?

I've tried looking at map2 but it needs the two arguments to be the same size, and I can't quite see how I could use an apply function.

答:
Here's an example with a function that concatenates input strings</p>

```<code>#DATA
a = letters[1:5]
b = letters[7:9]

#FUNCTION
foo = function(string1, string2){
    paste(string1, string2, sep = "")
}

#Create a dataframe with input vectors and function
setNames(object = data.frame(sapply(a,
                    function(x) sapply(b,
                       function(y) foo(x, y))),
                row.names = b),
         nm = a)
#   a  b  c  d  e
#g ag bg cg dg eg
#h ah bh ch dh eh
#i ai bi ci di ei
</code>```

Body:
Here's an example with a function that concatenates input strings

#DATA
a = letters[1:5]
b = letters[7:9]

#FUNCTION
foo = function(string1, string2){
    paste(string1, string2, sep = "")
}

#Create a dataframe with input vectors and function
setNames(object = data.frame(sapply(a,
                    function(x) sapply(b,
                       function(y) foo(x, y))),
                row.names = b),
         nm = a)
#   a  b  c  d  e
#g ag bg cg dg eg
#h ah bh ch dh eh
#i ai bi ci di ei


问:
Sparklyr: sdf_copy_to fails with 350 MB dataset
I'm facing a problem trying to write 2 dataset using sparklyr::spark_write_csv(). This is my configuration:

```<code># Configure cluster
config <- spark_config()
config$spark.yarn.keytab <- "mykeytab.keytab"
config$spark.yarn.principal <- "myyarnprincipal"
config$sparklyr.gateway.start.timeout <- 10
config$spark.executor.instances <- 2
config$spark.executor.cores <- 4
config$spark.executor.memory <- "4G"
config$spark.driver.memory <- "4G"

config$spark.kryoserializer.buffer.max  <- "1G"

Sys.setenv(SPARK_HOME = "/opt/cloudera/parcels/CDH/lib/spark")
Sys.setenv(HADOOP_CONF_DIR = '/etc/hadoop/conf.cloudera.hdfs')
Sys.setenv(YARN_CONF_DIR = '/etc/hadoop/conf.cloudera.yarn')

# Configure cluster
sc <- spark_connect(master = "yarn-client", config = config, version = '1.6.0')
</code>```

Once the spark context is successfully created, I'm trying to save 2 datasets on hdfs using spark_write_csv(). As an intermediate step I need to transform the dataframe into a tbl_spark.
Unfortunately, I'm able to correctly save only the first one, meanwhile the second one (which is bigger but absolutely not big for hadoop standards i.e. 360 MB) takes a long time and finally crashes.

```<code># load datasets
tmp_small <- read.csv("first_one.csv", sep = "|") # 13 MB
tmp_big <- read.csv("second_one.csv", sep = "|") # 352 MB

tmp_small_Spark <- sdf_copy_to(sc, tmp_small, "tmp_small", memory = F, overwrite = T)
tables_preview <- dbGetQuery(sc, "SHOW TABLES")

tmp_big_Spark <- sdf_copy_to(sc, tmp_big, "tmp_big", memory = F, overwrite = T) # fail!!
tables_preview <- dbGetQuery(sc, "SHOW TABLES")
</code>```

It is probably a configuration problem but I can't figure it out.
This is the error:
|================================================================================| 100%  352 MB

```<code>Error in invoke_method.spark_shell_connection(sc, TRUE, class, method,  :
No status is returned. Spark R backend might have failed.
</code>```

Thanks

答:
I was also having issues loading larger files. Try adding this to the spark connection config file:

```<code>config$spark.rpc.message.maxSize <- 512
</code>```

It's a workaround, though.

Body:
I'm facing a problem trying to write 2 dataset using sparklyr::spark_write_csv(). This is my configuration:

# Configure cluster
config <- spark_config()
config$spark.yarn.keytab <- "mykeytab.keytab"
config$spark.yarn.principal <- "myyarnprincipal"
config$sparklyr.gateway.start.timeout <- 10
config$spark.executor.instances <- 2
config$spark.executor.cores <- 4
config$spark.executor.memory <- "4G"
config$spark.driver.memory <- "4G"

config$spark.kryoserializer.buffer.max  <- "1G"

Sys.setenv(SPARK_HOME = "/opt/cloudera/parcels/CDH/lib/spark")
Sys.setenv(HADOOP_CONF_DIR = '/etc/hadoop/conf.cloudera.hdfs')
Sys.setenv(YARN_CONF_DIR = '/etc/hadoop/conf.cloudera.yarn')

# Configure cluster
sc <- spark_connect(master = "yarn-client", config = config, version = '1.6.0')

Once the spark context is successfully created, I'm trying to save 2 datasets on hdfs using spark_write_csv(). As an intermediate step I need to transform the dataframe into a tbl_spark.
Unfortunately, I'm able to correctly save only the first one, meanwhile the second one (which is bigger but absolutely not big for hadoop standards i.e. 360 MB) takes a long time and finally crashes.

# load datasets
tmp_small <- read.csv("first_one.csv", sep = "|") # 13 MB
tmp_big <- read.csv("second_one.csv", sep = "|") # 352 MB

tmp_small_Spark <- sdf_copy_to(sc, tmp_small, "tmp_small", memory = F, overwrite = T)
tables_preview <- dbGetQuery(sc, "SHOW TABLES")

tmp_big_Spark <- sdf_copy_to(sc, tmp_big, "tmp_big", memory = F, overwrite = T) # fail!!
tables_preview <- dbGetQuery(sc, "SHOW TABLES")

It is probably a configuration problem but I can't figure it out.
This is the error:
|================================================================================| 100%  352 MB

Error in invoke_method.spark_shell_connection(sc, TRUE, class, method,  :
No status is returned. Spark R backend might have failed.

Thanks

Body:
I was also having issues loading larger files. Try adding this to the spark connection config file:

config$spark.rpc.message.maxSize <- 512

It's a workaround, though.


问:
Autofac wait for module to become available
Because the order of modules being resolved is not guaranteed I'm having some problem achieving this:

I have a module which registers a ScheduleService this ScheduleService is responsible for trigger events at set intervals etc.

I'm able to load in different IScheduable items which i do so using the XML Configuration. The problem that i have, is the IScheduable items require the IScheduleService to be ready so it can register it's self.

So in my <autofac><modules> I have

<module type="Namespace.ScheduleServiceModule, Namespace" />
```

<p>Then the idea was I could load in as many different <code>ISchedulable</code> items</p>

<pre class="lang-xml prettyprint-override"><code><module type="SomeNamespace.ScheudleItem1, SomeNamespace />
<module type="SomeNamespace.ScheudleItem2, SomeNamespace />
<module type="SomeNamespace.ScheudleItem3, SomeNamespace />
<module type="SomeNamespace.ScheudleItem4, SomeNamespace />
</code>```

This is currently how I do it in those scheduleitem modules:

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterCallback(registry =>
    {
        var scheduleService = new TypedService(typeof(IScheduleService));
        var registrations = registry.RegistrationsFor(scheduleService);
        if (registrations != null && registrations.Any())
        {
            IComponentRegistration componentRegistration = registrations.First();
            componentRegistration.Activated += (sender, args) =>
            {
                IScheduleService scheduleService = args.Instance as IScheduleService;
                if (scheduleService != null)
                {
                    OnScheduleServiceAvailable(args.Context, scheduleService);
                }
            };
        }
    });
    base.Load(builder);
}
```

<p>This is the override in each of ScheduleItems</p>

<pre class="lang-C# prettyprint-override"><code>protected override void OnScheduleServiceAvailable(IComponentContext context,
                                                   IScheduleService scheduleService)
{
    scheduleService.Add(
        new SqlSyncSchedulable(Enabled, IntervalMS, ConnectionString, SqlSelect,
            context.Resolve<ILoggerService>(),
            context.Resolve<IPersonService>(),
            context.Resolve<ILoggingEventService>(),
            context.Resolve<ITemplateService>(),
            context.Resolve<ITemplateLoggingEventService>(),
            context.Resolve<IRuntimeSettingsService>()));
 }
</code>```

Which is quite intermittent. The ISchedule item should register itself but the problem is the Schedule service might be registered after those items.

There must be a way to achieve this?

答:
I think your problem is not in the load order of the module, but is instead about dependency design.

You should design your modules and your dependencies in a way that they are not temporally coupled.

One of the many possible designs involves having the schedule service require a list of possible dependencies.

In this design, the responsibilitt of an ISchedule is in defining the parameters of a schedulable operation, you use Autofac Adapter pattern to wrap each schedule into a ISyncSchedulable operation, and the ScheduleService requires a List<ISyncSchedulable> in order to add them at initialization.

As an example (following your example, but not verbatim: I'm trying more to make a point than giving a complete solution):

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using NUnit.Framework;

namespace Example
{
    public interface ISchedule
    {
        bool Enabled { get; }
        long IntervalMs { get; }
        string ConnectionString { get; }
        string SqlSelect { get; }
    }

    public class Schedule : ISchedule
    {
        public bool Enabled
        {
            get { return true; }
        }

        public long IntervalMs
        {
            get { return 100000; }
        }

        public string ConnectionString
        {
            get { return "localhost;blabla"; }
        }

        public string SqlSelect
        {
            get { return "select 1 as A"; }
        }
    }

    // let's assume SqlSyncSchedulable inherits from a common
    // ISyncSchedulable interface
    public interface ISyncSchedulable
    {
        void RunSchedule(ScheduleService scheduleService);
    }

    public class SqlSyncSchedulable : ISyncSchedulable
    {
        public ISchedule Schedule { get; private set; }
        public OtherService OtherService { get; private set; }

        public SqlSyncSchedulable(ISchedule schedule,
            OtherService otherService
            /*,ILoggerService loggerService
            IPersonService personService, */
        )
        {
            Schedule = schedule;
            OtherService = otherService;
            // read interval and other data from schedule,
            // store service references as usual.
        }

        public void RunSchedule(ScheduleService scheduleService)
        {
            throw new NotImplementedException();
        }
    }

    public class OtherService
    {

    }

    public class ScheduleService
    {
        public ScheduleService(IList<ISyncSchedulable> schedulables, OtherService otherService /*, ... other dependencies */)
        {
            // there is no ADD! Autofac gives you a list of all possible
            // ISyncSchedulable components
            SyncSchedulables = schedulables;
            // ... other dependencies
        }

        public IList<ISyncSchedulable> SyncSchedulables { get; set; }

        // this code is not a proper implementation, nor a scheduler,
        // it's just a placeholder
        public void RunSchedules()
        {
            foreach (var schedule in SyncSchedulables)
            {
                // do your operations, involving ...
                schedule.RunSchedule(this);
            }
        }
    }

    public class TestModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterType<ScheduleService>().AsSelf();
            builder.RegisterType<OtherService>().AsSelf();

            // don't worry about which type should be registered,
            // and register each type inheriting from ISchedule
            // coming from the current assembly
            // You can even use a single registration for all the
            // possible implementations of ISchedule, using techniques
            // explained in http://docs.autofac.org/en/latest/register/scanning.html
            builder.RegisterAssemblyTypes(GetType().Assembly)
                .Where(t => t.GetInterfaces().Contains(typeof(ISchedule)))
                .AsImplementedInterfaces()
                .InstancePerDependency();

            // This registration is a partial, because
            // SqlSyncChedulable requires a single parameter
            // of type ISchedule
            builder.RegisterType<SqlSyncSchedulable>()
                .AsImplementedInterfaces();

            // for each ISchedule class, we register automatically
            // a corresponding ISyncSchedulable, which
            builder.RegisterAdapter<ISchedule, ISyncSchedulable>(RegisterISyncSchedulableForEachISchedule)
                .InstancePerDependency();
        }

        private ISyncSchedulable RegisterISyncSchedulableForEachISchedule(IComponentContext context, ISchedule schedule)
        {
            // the parameter of type ISchedule is the corresponding schedule
            var scheduleParam = new TypedParameter(typeof(ISchedule), schedule);
            // all the other params are resolved automatically by Autofac.
            return context.Resolve<ISyncSchedulable>(scheduleParam);
        }
    }

    [TestFixture]
    public class AutofacTest
    {
        [Test]
        public void TestServiceResolution()
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new TestModule());
            var container = builder.Build();

            var service = container.Resolve<ScheduleService>();

            Assert.That(service.SyncSchedulables[0].GetType(), Is.EqualTo(typeof(SqlSyncSchedulable)));
        }

    }
}
</code>```

Please note that the module resolution order is now completely decoupled with the runtime resolution.

Body:
Because the order of modules being resolved is not guaranteed I'm having some problem achieving this:

I have a module which registers a ScheduleService this ScheduleService is responsible for trigger events at set intervals etc.

I'm able to load in different IScheduable items which i do so using the XML Configuration. The problem that i have, is the IScheduable items require the IScheduleService to be ready so it can register it's self.

So in my <autofac><modules> I have

<module type="Namespace.ScheduleServiceModule, Namespace" />

Then the idea was I could load in as many different ISchedulable items

<module type="SomeNamespace.ScheudleItem1, SomeNamespace />
<module type="SomeNamespace.ScheudleItem2, SomeNamespace />
<module type="SomeNamespace.ScheudleItem3, SomeNamespace />
<module type="SomeNamespace.ScheudleItem4, SomeNamespace />

This is currently how I do it in those scheduleitem modules:

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterCallback(registry =>
    {
        var scheduleService = new TypedService(typeof(IScheduleService));
        var registrations = registry.RegistrationsFor(scheduleService);
        if (registrations != null && registrations.Any())
        {
            IComponentRegistration componentRegistration = registrations.First();
            componentRegistration.Activated += (sender, args) =>
            {
                IScheduleService scheduleService = args.Instance as IScheduleService;
                if (scheduleService != null)
                {
                    OnScheduleServiceAvailable(args.Context, scheduleService);
                }
            };
        }
    });
    base.Load(builder);
}

This is the override in each of ScheduleItems

protected override void OnScheduleServiceAvailable(IComponentContext context,
                                                   IScheduleService scheduleService)
{
    scheduleService.Add(
        new SqlSyncSchedulable(Enabled, IntervalMS, ConnectionString, SqlSelect,
            context.Resolve<ILoggerService>(),
            context.Resolve<IPersonService>(),
            context.Resolve<ILoggingEventService>(),
            context.Resolve<ITemplateService>(),
            context.Resolve<ITemplateLoggingEventService>(),
            context.Resolve<IRuntimeSettingsService>()));
 }

Which is quite intermittent. The ISchedule item should register itself but the problem is the Schedule service might be registered after those items.

There must be a way to achieve this?

Body:
I think your problem is not in the load order of the module, but is instead about dependency design.

You should design your modules and your dependencies in a way that they are not temporally coupled.

One of the many possible designs involves having the schedule service require a list of possible dependencies.

In this design, the responsibilitt of an ISchedule is in defining the parameters of a schedulable operation, you use Autofac Adapter pattern to wrap each schedule into a ISyncSchedulable operation, and the ScheduleService requires a List<ISyncSchedulable> in order to add them at initialization.

As an example (following your example, but not verbatim: I'm trying more to make a point than giving a complete solution):

using System;
using System.Collections.Generic;
using System.Linq;
using Autofac;
using NUnit.Framework;

namespace Example
{
    public interface ISchedule
    {
        bool Enabled { get; }
        long IntervalMs { get; }
        string ConnectionString { get; }
        string SqlSelect { get; }
    }

    public class Schedule : ISchedule
    {
        public bool Enabled
        {
            get { return true; }
        }

        public long IntervalMs
        {
            get { return 100000; }
        }

        public string ConnectionString
        {
            get { return "localhost;blabla"; }
        }

        public string SqlSelect
        {
            get { return "select 1 as A"; }
        }
    }

    // let's assume SqlSyncSchedulable inherits from a common
    // ISyncSchedulable interface
    public interface ISyncSchedulable
    {
        void RunSchedule(ScheduleService scheduleService);
    }

    public class SqlSyncSchedulable : ISyncSchedulable
    {
        public ISchedule Schedule { get; private set; }
        public OtherService OtherService { get; private set; }

        public SqlSyncSchedulable(ISchedule schedule,
            OtherService otherService
            /*,ILoggerService loggerService
            IPersonService personService, */
        )
        {
            Schedule = schedule;
            OtherService = otherService;
            // read interval and other data from schedule,
            // store service references as usual.
        }

        public void RunSchedule(ScheduleService scheduleService)
        {
            throw new NotImplementedException();
        }
    }

    public class OtherService
    {

    }

    public class ScheduleService
    {
        public ScheduleService(IList<ISyncSchedulable> schedulables, OtherService otherService /*, ... other dependencies */)
        {
            // there is no ADD! Autofac gives you a list of all possible
            // ISyncSchedulable components
            SyncSchedulables = schedulables;
            // ... other dependencies
        }

        public IList<ISyncSchedulable> SyncSchedulables { get; set; }

        // this code is not a proper implementation, nor a scheduler,
        // it's just a placeholder
        public void RunSchedules()
        {
            foreach (var schedule in SyncSchedulables)
            {
                // do your operations, involving ...
                schedule.RunSchedule(this);
            }
        }
    }

    public class TestModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterType<ScheduleService>().AsSelf();
            builder.RegisterType<OtherService>().AsSelf();

            // don't worry about which type should be registered,
            // and register each type inheriting from ISchedule
            // coming from the current assembly
            // You can even use a single registration for all the
            // possible implementations of ISchedule, using techniques
            // explained in http://docs.autofac.org/en/latest/register/scanning.html
            builder.RegisterAssemblyTypes(GetType().Assembly)
                .Where(t => t.GetInterfaces().Contains(typeof(ISchedule)))
                .AsImplementedInterfaces()
                .InstancePerDependency();

            // This registration is a partial, because
            // SqlSyncChedulable requires a single parameter
            // of type ISchedule
            builder.RegisterType<SqlSyncSchedulable>()
                .AsImplementedInterfaces();

            // for each ISchedule class, we register automatically
            // a corresponding ISyncSchedulable, which
            builder.RegisterAdapter<ISchedule, ISyncSchedulable>(RegisterISyncSchedulableForEachISchedule)
                .InstancePerDependency();
        }

        private ISyncSchedulable RegisterISyncSchedulableForEachISchedule(IComponentContext context, ISchedule schedule)
        {
            // the parameter of type ISchedule is the corresponding schedule
            var scheduleParam = new TypedParameter(typeof(ISchedule), schedule);
            // all the other params are resolved automatically by Autofac.
            return context.Resolve<ISyncSchedulable>(scheduleParam);
        }
    }

    [TestFixture]
    public class AutofacTest
    {
        [Test]
        public void TestServiceResolution()
        {
            var builder = new ContainerBuilder();
            builder.RegisterModule(new TestModule());
            var container = builder.Build();

            var service = container.Resolve<ScheduleService>();

            Assert.That(service.SyncSchedulables[0].GetType(), Is.EqualTo(typeof(SqlSyncSchedulable)));
        }

    }
}

Please note that the module resolution order is now completely decoupled with the runtime resolution.


问:
State is returning new state without touching the state REACT/REDUX
Before I start posting the code I will explain what I want to happen and what is happening.

I have been working with this all day and finally got something to work. The problem is that I have no clue why it works and if it's the best way to do it.
What I want to happen  is when a User clicks delete on a comment I want the comment to be delete from the current post on the back end and from the state on the front end.

UPDATE: I did not really add enough to show what I was talking about. When a user clicks the delete button it will fire off this function here:

```<code>deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (<div></div>);
    }

    if(auth) {
      if(user._id === comment.author.id){
        this.props.deleteComments(post, comment._id, () => {
          this.props.history.push(`/posts/${post._id}`);
        });
      }
    }
  }
</code>```

which then calls the action:

```<code>export function deleteComments(post, comment_id, cb) {
  return function(dispatch) {
    axios.delete(`${ROOT_URL}/${post._id}/comments/${comment_id}`)
      .then(() => {
        dispatch({
          type: DELETE_COMMENTS,
          payload: comment_id,
          post: post
        });
      })
      .then(() => cb())
      .catch((error) => {
        console.log(error);
      });
  }
}
</code>```

What I am wondering:
Really all the code above works so it is more of a reference than anything. I am wondering why in the reducer when DELETE_COMMENTS is caught by the switch case how the current state which is below in the picture is changed to a new state without the comment I deleted. I don't explicitly ever edit the state or change it so how does return (state); actually change it here?

To elaborate more my current state looks as so:

As you can see I have a Post with comments inside of it. The comments are stored inside an array and each of them are objects with text, author.id, author.email, and createdAt values. Now as you can see in the reducer_post when the action is fired off it sends the DELETE_COMMENTS dispatch type off and the state is changed.

For help: action.payload is the comment._id, and action.post is the current post that is being viewed.

```<code>import {
  GET_ALL_POSTS,
  GET_POST,
  CREATE_POST,
  DELETE_POST,
  UPDATE_POST,
  DELETE_COMMENTS
} from '../actions/types';
import _ from 'lodash';

export default function(state = {}, action) {
  switch(action.type) {
    case GET_ALL_POSTS:
      return _.mapKeys(action.payload.data, '_id');
    break;
    case GET_POST:
      return {...state, [action.payload.data._id]: action.payload.data};
    break;
    case DELETE_POST:
      return _.omit(state, action.payload);
    break;
    case DELETE_COMMENTS:
      let newCommentArray = _.reject(action.post.comments, {'_id': action.payload});
      let newPost = action.post;
      newPost.comments = newCommentArray;
      return (state);
    case UPDATE_POST:
      let updates = {[action.payload.data._id]: action.payload.data};
      return _.merge(...state, updates);
    break;
    default:
      return state;
    break;
  }
}
</code>```

I know the back-end works just fine and this also works just fine. My question is how does it update the state with me just putting return (state);. I did not have to do something like return _.merge(...state, newPost); or something like that. How is all of this working just fine, and no I did not just copy some tutorial and come on here and ask this just to figure out how someone else did it. At the moment I believe in magic so it would be nice for an explanation.

Also since we are here, is this the best way to do it? Or is there a better more clean way of doing things here.

答:
I think you're actually directly mutating the state, and somehow getting away with it in the sense that the component is still updating.

Let's follow the trail of logic:

In deleteComment(), you reference this.props.post.  That object is presumably extracted from the store via mapStateToProps, so it's the object reference in the store.

post gets passed to this.props.deleteComments(post)

deleteComments() dispatches ({type : DELETE_COMMENTS, post})

In the reducer, you have let newPost = action.post; newPost.comments = newCommentArray.  But, at that point, newPost still points to the exact same object that's already in the store state.  So, you've directly mutated it.

Normally, this kind of mutation would result in your component not re-rendering, so I can only assume that some other value extracted in mapState is also getting updated properly, and thus causing a re-render.

As discussed in the Structuring Reducers - Immutable Update Patterns page in the Redux docs, let someVariable = anotherVariable doesn't create a new object reference - it merely creates a second variable that points to the same object reference.  Proper immutable updates require copies of every level of nesting that you're working with, not just the one level.  In your case, you're creating a new array via _.reject(), but you're not creating a copy of the post object.

So, in the end, your reducer logic is incorrect, and your application is sorta kinda working by accident :)

update

Responding to your question about a proper update: you need to create a copy of the post object and update it with the new comments array, and you need to copy the state object and update it with the new post object.  Based off what the rest of your code does, my guess is this should work:

```<code>case DELETE_COMMENTS:
     const newCommentArray = _.reject(action.post.comments, {'_id': action.payload});

     const newState = {
         ...state,
         [action.post.id] : {
             ...action.post,
             comments : newCommentArray
         }
     };

     return newState;
</code>```

Body:
Before I start posting the code I will explain what I want to happen and what is happening.

I have been working with this all day and finally got something to work. The problem is that I have no clue why it works and if it's the best way to do it.
What I want to happen  is when a User clicks delete on a comment I want the comment to be delete from the current post on the back end and from the state on the front end.

UPDATE: I did not really add enough to show what I was talking about. When a user clicks the delete button it will fire off this function here:

deleteComment(comment) {
    const {id} = this.props.match.params;
    const {user, post, auth} = this.props;

    if(!user) {
      return (

);
    }

    if(auth) {
      if(user._id === comment.author.id){
        this.props.deleteComments(post, comment._id, () => {
          this.props.history.push(`/posts/${post._id}`);
        });
      }
    }
  }

which then calls the action:

export function deleteComments(post, comment_id, cb) {
  return function(dispatch) {
    axios.delete(`${ROOT_URL}/${post._id}/comments/${comment_id}`)
      .then(() => {
        dispatch({
          type: DELETE_COMMENTS,
          payload: comment_id,
          post: post
        });
      })
      .then(() => cb())
      .catch((error) => {
        console.log(error);
      });
  }
}

What I am wondering:
Really all the code above works so it is more of a reference than anything. I am wondering why in the reducer when DELETE_COMMENTS is caught by the switch case how the current state which is below in the picture is changed to a new state without the comment I deleted. I don't explicitly ever edit the state or change it so how does return (state); actually change it here?

To elaborate more my current state looks as so:

As you can see I have a Post with comments inside of it. The comments are stored inside an array and each of them are objects with text, author.id, author.email, and createdAt values. Now as you can see in the reducer_post when the action is fired off it sends the DELETE_COMMENTS dispatch type off and the state is changed.

For help: action.payload is the comment._id, and action.post is the current post that is being viewed.

import {
  GET_ALL_POSTS,
  GET_POST,
  CREATE_POST,
  DELETE_POST,
  UPDATE_POST,
  DELETE_COMMENTS
} from '../actions/types';
import _ from 'lodash';

export default function(state = {}, action) {
  switch(action.type) {
    case GET_ALL_POSTS:
      return _.mapKeys(action.payload.data, '_id');
    break;
    case GET_POST:
      return {...state, [action.payload.data._id]: action.payload.data};
    break;
    case DELETE_POST:
      return _.omit(state, action.payload);
    break;
    case DELETE_COMMENTS:
      let newCommentArray = _.reject(action.post.comments, {'_id': action.payload});
      let newPost = action.post;
      newPost.comments = newCommentArray;
      return (state);
    case UPDATE_POST:
      let updates = {[action.payload.data._id]: action.payload.data};
      return _.merge(...state, updates);
    break;
    default:
      return state;
    break;
  }
}

I know the back-end works just fine and this also works just fine. My question is how does it update the state with me just putting return (state);. I did not have to do something like return _.merge(...state, newPost); or something like that. How is all of this working just fine, and no I did not just copy some tutorial and come on here and ask this just to figure out how someone else did it. At the moment I believe in magic so it would be nice for an explanation.

Also since we are here, is this the best way to do it? Or is there a better more clean way of doing things here.

Body:
I think you're actually directly mutating the state, and somehow getting away with it in the sense that the component is still updating.

Let's follow the trail of logic:

In deleteComment(), you reference this.props.post.  That object is presumably extracted from the store via mapStateToProps, so it's the object reference in the store.

post gets passed to this.props.deleteComments(post)

deleteComments() dispatches ({type : DELETE_COMMENTS, post})

In the reducer, you have let newPost = action.post; newPost.comments = newCommentArray.  But, at that point, newPost still points to the exact same object that's already in the store state.  So, you've directly mutated it.

Normally, this kind of mutation would result in your component not re-rendering, so I can only assume that some other value extracted in mapState is also getting updated properly, and thus causing a re-render.

As discussed in the Structuring Reducers - Immutable Update Patterns page in the Redux docs, let someVariable = anotherVariable doesn't create a new object reference - it merely creates a second variable that points to the same object reference.  Proper immutable updates require copies of every level of nesting that you're working with, not just the one level.  In your case, you're creating a new array via _.reject(), but you're not creating a copy of the post object.

So, in the end, your reducer logic is incorrect, and your application is sorta kinda working by accident :)

update

Responding to your question about a proper update: you need to create a copy of the post object and update it with the new comments array, and you need to copy the state object and update it with the new post object.  Based off what the rest of your code does, my guess is this should work:

case DELETE_COMMENTS:
     const newCommentArray = _.reject(action.post.comments, {'_id': action.payload});

     const newState = {
         ...state,
         [action.post.id] : {
             ...action.post,
             comments : newCommentArray
         }
     };

     return newState;


问:
Windows 10 - Make context menu of pinned items compact like win7 one.
I'd like the windows 10 context menu be more compact like the windows 7 one. It is too space-consuming and fits too few items in it as is.

I do already use classic shell, but I haven't found an option to alter this thing.

Windows 7 pinned item context menu

Windows 10 pinned item context menu

答: Windows 10 tries to be touch friendly and also wants to shove the UWP/Modern/Metro design down your throat so I think you are stuck with it unless you want to upgrade to Windows 7/8.</p>


问:
chefspec NoMethodError for cron_d
I have a successful resource: (converged, worked as expected)

```<code>cron_d 'zk_metric' do
  minute '*'
  command “something something"
end
</code>```

But after adding spec

```<code>it 'add cron_d' do
    expect(chef_run).to create_cron_d('zk_metric')
  end
</code>```

chefspec got the error:

```<code>Failures:

  1) myorg::myrecipe add cron_d
     Failure/Error: expect(chef_run).to create_cron_d('zk_metric')
     NoMethodError:
       undefined method `create_cron_d' for #<RSpec::ExampleGroups::Myorgmyrecipe:0x007fa726086e50>
     # ./spec/myrecipe_spec.rb:93:in `block (2 levels) in <top (required)>'

Finished in 12.17 seconds (files took 1.08 seconds to load)
</code>```

Why is this happening?

The matcher is already defined https://github.com/opscode-cookbooks/cron/blob/master/libraries/matchers.rb

Do I need to include  or require something in my spec file (neither worked so far)? Or I need to create my own?

(Edit: stackoverflow autobot asked me to add ruby-on-rails tag, and so I did.)

答:
You're missing a few things, and you have a spacing typo.

Here's how to do it with an example:

Make sure you have a script or something to be run with cron_d (in this example, script.py).

Don't forget to include the cron recipe

If your script is in your cookbook, copy it to the machine like the example below.

Create the cron, like in the example below.

cron_recipe.rb

```<code>include_recipe "cron"

cookbook_file '/etc/cron.d/script.py' do
  source 'folder/script.py'
  owner 'root'
  group 'root'
  mode '0777'
  action :create
end

cron_d "example_cron" do
  minute '0'
  hour '0'
  command '/etc/cron.d/script.py'
  user 'root'
end
</code>```

Now you can create your spec:

Make sure you have a spec_helper or other setup to construct your context.

cron_recipe_spec.rb

```<code># encoding: UTF-8
require 'spec_helper'

describe 'cookbook::cron_recipe' do
  CookbookTest.contexts.each do |ctext|
    context '#{ctext[:platform]}-#{ctext[:version]}' do
      cached(:chef_run) do
        CookbookTest.runner(ctext).converge(described_recipe)
      end

      it 'includes the cron_recipe that we are testing' do
        expect(chef_run).to include_recipe(described_recipe)
      end

      it 'includes the cron recipe' do
        expect(chef_run).to include_recipe('cron')
      end

      it 'creates a script.py file' do
        expect(chef_run).to create_cookbook_file('/etc/cron.d/script.py').with(
          :user => 'root',
          :group => 'root',
          :mode => '0777'
        )
      end

      it 'creates the cron' do
        expect(chef_run).to create_cron_d('example_cron').with(
          :command => '/etc/cron.d/script.py',
          :user => 'root',
          :minute => '0',
          :hour => '0'
        )
      end
    end
  end
end
</code>```

Title: chefspec NoMethodError for cron_d

Body:
I have a successful resource: (converged, worked as expected)

cron_d 'zk_metric' do
  minute '*'
  command “something something"
end

But after adding spec

it 'add cron_d' do
    expect(chef_run).to create_cron_d('zk_metric')
  end

chefspec got the error:

Failures:

  1) myorg::myrecipe add cron_d
     Failure/Error: expect(chef_run).to create_cron_d('zk_metric')
     NoMethodError:
       undefined method `create_cron_d' for #<RSpec::ExampleGroups::Myorgmyrecipe:0x007fa726086e50>
     # ./spec/myrecipe_spec.rb:93:in `block (2 levels) in <top (required)>'

Finished in 12.17 seconds (files took 1.08 seconds to load)

Why is this happening?

The matcher is already defined https://github.com/opscode-cookbooks/cron/blob/master/libraries/matchers.rb

Do I need to include  or require something in my spec file (neither worked so far)? Or I need to create my own?

(Edit: stackoverflow autobot asked me to add ruby-on-rails tag, and so I did.)

Body:
You're missing a few things, and you have a spacing typo.

Here's how to do it with an example:

Make sure you have a script or something to be run with cron_d (in this example, script.py).

Don't forget to include the cron recipe

If your script is in your cookbook, copy it to the machine like the example below.

Create the cron, like in the example below.

cron_recipe.rb

include_recipe "cron"

cookbook_file '/etc/cron.d/script.py' do
  source 'folder/script.py'
  owner 'root'
  group 'root'
  mode '0777'
  action :create
end

cron_d "example_cron" do
  minute '0'
  hour '0'
  command '/etc/cron.d/script.py'
  user 'root'
end

Now you can create your spec:

Make sure you have a spec_helper or other setup to construct your context.

cron_recipe_spec.rb

# encoding: UTF-8
require 'spec_helper'

describe 'cookbook::cron_recipe' do
  CookbookTest.contexts.each do |ctext|
    context '#{ctext[:platform]}-#{ctext[:version]}' do
      cached(:chef_run) do
        CookbookTest.runner(ctext).converge(described_recipe)
      end

      it 'includes the cron_recipe that we are testing' do
        expect(chef_run).to include_recipe(described_recipe)
      end

      it 'includes the cron recipe' do
        expect(chef_run).to include_recipe('cron')
      end

      it 'creates a script.py file' do
        expect(chef_run).to create_cookbook_file('/etc/cron.d/script.py').with(
          :user => 'root',
          :group => 'root',
          :mode => '0777'
        )
      end

      it 'creates the cron' do
        expect(chef_run).to create_cron_d('example_cron').with(
          :command => '/etc/cron.d/script.py',
          :user => 'root',
          :minute => '0',
          :hour => '0'
        )
      end
    end
  end
end


问:
Why is a negative integer not a valid pattern in a macro?
Let us consider a simple enum implementation with a static method that check whether a value has an associated value (the efficiency of the implementation is not to be regarded here):

```<code>enum Letter {
    Alpha = -1,
    A = 0,
    B = 1,
    C = 2,
}

impl Letter {
    pub fn in_enum(value: isize) -> bool
    {
        match value {
            -1 => true,
            0 => true,
            1 => true,
            2 => true,
            _ => false,
        }
    }
}
</code>```

Now, let us write a macro for building enums with an equivalent in_enum method. The macro below was written with some guidance from the Serde guide for enum deserialization as numbers, in which matching for enum variant values also occurs.

```<code>macro_rules! my_enum {
    ($name:ident { $($variant:ident = $value:expr, )* }) => {
        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        pub enum $name {
            $($variant = $value,)*
        }

        impl $name {
            pub fn in_enum(value: isize) -> bool
            {
                match value {
                    $( $value => true, )*
                    _ => false,
                }
            }
        }
    }
}

my_enum!(Letter {
  Alpha = -1,
  A = 0,
  B = 1,
  C = 2,
});
</code>```

Playground.
With version 1.18.0, the compiler won't accept the variant with a negative integer.

error: expected pattern, found `-1`
  --> src/main.rs:13:24
   |
13 |                     $( $value => true, )*
   |                        ^^^^^^
```
<p>This seems to happen regardless of how I write this pattern down in the macro, or whether I use <code>i32</code> or <code>isize</code> for the <code>value</code> method parameter. Changing the fragment specifier of <code>$value</code> to <code>pat</code> is also out of the question: the compiler will refuse to build the enum, even without negative variant values.</p>
<pre class="lang-none prettyprint-override"><code>error: expected expression, found `-1`
 --> src/main.rs:5:26
  |
5 |             $($variant = $value,)*
  |                          ^^^^^^
</code>```

What's surprising about this is that it works without using macros, as well as when I discard the Alpha variant.

Why does this happen?

答: This is a bug in the compiler and is already fixed in the nightly version as of today (Jul 5, 2017), and released in stable version 1.20.0.</p>

ContentLicense: CC BY-SA 4.0

Body:
Let us consider a simple enum implementation with a static method that check whether a value has an associated value (the efficiency of the implementation is not to be regarded here):

enum Letter {
    Alpha = -1,
    A = 0,
    B = 1,
    C = 2,
}

impl Letter {
    pub fn in_enum(value: isize) -> bool
    {
        match value {
            -1 => true,
            0 => true,
            1 => true,
            2 => true,
            _ => false,
        }
    }
}

Now, let us write a macro for building enums with an equivalent in_enum method. The macro below was written with some guidance from the Serde guide for enum deserialization as numbers, in which matching for enum variant values also occurs.

macro_rules! my_enum {
    ($name:ident { $($variant:ident = $value:expr, )* }) => {
        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        pub enum $name {
            $($variant = $value,)*
        }

        impl $name {
            pub fn in_enum(value: isize) -> bool
            {
                match value {
                    $( $value => true, )*
                    _ => false,
                }
            }
        }
    }
}

my_enum!(Letter {
  Alpha = -1,
  A = 0,
  B = 1,
  C = 2,
});

Playground.
With version 1.18.0, the compiler won't accept the variant with a negative integer.

error: expected pattern, found `-1`
  --> src/main.rs:13:24
   |
13 |                     $( $value => true, )*
   |                        ^^^^^^

This seems to happen regardless of how I write this pattern down in the macro, or whether I use i32 or isize for the value method parameter. Changing the fragment specifier of $value to pat is also out of the question: the compiler will refuse to build the enum, even without negative variant values.

error: expected expression, found `-1`
 --> src/main.rs:5:26
  |
5 |             $($variant = $value,)*
  |                          ^^^^^^

What's surprising about this is that it works without using macros, as well as when I discard the Alpha variant.

Why does this happen?


问:
KTor or Spark? Which is production ready for Kotlin web services?
I am writing an enterprise web service application using Kotlin. I am now using KTor since it is async and high performant But as you may know, Ktor is somewhat young, and the feature 'coroutine' is experimental in Kotlin! Is it wise to use Ktor anyway?</p>

答:
Despite the experimental status, Kotlin coroutines are fully released and guarantied to work far in the future.

The experimental flag is mostly for library writers. Since you are doing an application, there will be no problem in using coroutines even after the final version is released. Your code will continue to work with the kotlinx.coroutines.experimental library, that's it.

As for the Ktor, then I can say that what it does it does well. Since it is a relatively light framework, I would not expect any bugs from it. So, if you like its API, there is no reason not to use it. After all, the integration with Kotlin is far beyond that of Spark.


问:
LibreOffice Headless
I am trying to convert .docx file to .pdf using the pdfgear as described in https://github.com/phpgearbox/pdf. This component defaults to libre-office-headless. I installed LibreOffice5 in my computer at

C:\Program Files (x86)\LibreOffice 5

with its binary lying at

C:\Program Files (x86)\LibreOffice 5\program.

Then in my Controller method i have:

```<code>$pdf = Gears\Pdf::convert($temp_filename);
shell_exec('libreoffice --headless --convert-to pdf $temp_filename');
</code>```

The first statement is resulting to the error:

An uncaught Exception was encountered

Type: RuntimeException

Message: The libreoffice command ("/usr/bin/libreoffice") was not
  found or is not executable by the current user!

While the next line is resulting to nothing (no error and no pdf document)!

How can i install libre-office-headless to ensure that the first line of code runs successfully? I hope you understand my question. Thank you.

答:
Looking through the pdfgear source code there are a number of locations hard coded that you might need to adapt. They seem to be written with a normal Linux distro installation of LibreOffice in mind.

One case that seems related to your problem is https://github.com/phpgearbox/pdf/blob/master/src/Pdf/Docx/Converter/LibreOffice.php#L73

Title: LibreOffice Headless

Body:
I am trying to convert .docx file to .pdf using the pdfgear as described in https://github.com/phpgearbox/pdf. This component defaults to libre-office-headless. I installed LibreOffice5 in my computer at

C:\Program Files (x86)\LibreOffice 5

with its binary lying at

C:\Program Files (x86)\LibreOffice 5\program.

Then in my Controller method i have:

$pdf = Gears\Pdf::convert($temp_filename);
shell_exec('libreoffice --headless --convert-to pdf $temp_filename');

The first statement is resulting to the error:

An uncaught Exception was encountered

Type: RuntimeException

Message: The libreoffice command ("/usr/bin/libreoffice") was not
  found or is not executable by the current user!

While the next line is resulting to nothing (no error and no pdf document)!

How can i install libre-office-headless to ensure that the first line of code runs successfully? I hope you understand my question. Thank you.


问:
Need help to create sql query MySQLi PHP
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

```<code>            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

            <div class="right">
                <form method="post">
                    <br/>
                    <input name="searchc" type="text" value=""><br/>
                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?><br />
            </div>
</code>```

答:
You just need to perform a INNER JOIN like

```<code>SELECT review_text
                   FROM review
                  JOIN  COMPANY on review.company_id = COMPANY.company_id;
</code>```

Well, in case you are getting company name as input then you are almost close

```<code>SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (select company_id from company where company_name = $company_name)
</code>```

Body:
I have two tables
COMPANY: company_id, company_name
REVIEW: review_id, company_id, review_text

I am trying to make search functional on site. I try to display all reviews of specific company. Example, I have search field, I enter there "Microsoft" and then I need all reviews about Microsoft.

I try to do such query, but it is not working

            $company_name = $_POST["company_name"] ?? '';
            $review_text = $_POST["review_text"] ?? '';
            $searchc = $_POST["searchc"] ?? '';

            if(isset($_POST['show'])){
                $result2 = $mysqli->prepare(
                    "SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (HERE I THINK I NEED EMBED QUERY... BUT NOT SURE..) ?");
                $result2->bind_param("s", $searchc);
                $result2->execute();
                $result2->store_result();
                $row2 = mysqli_fetch_assoc($result2);
            }

                <form method="post">

                    <input name="searchc" type="text" value="">

                    <input type="submit" value="show" name="show">

                  </form>

                    Text: <?=$row2['review_text']?>

Body:
You just need to perform a INNER JOIN like

SELECT review_text
                   FROM review
                  JOIN  COMPANY on review.company_id = COMPANY.company_id;

Well, in case you are getting company name as input then you are almost close

SELECT review_text
                   FROM review
                   WHERE company_id
                   IN (select company_id from company where company_name = $company_name)


问:
build maven project with propriatery libraries included
How to create maven pom, which will make project buildable, can I include propriatery jars with my project directly without having to take them from repository? anyone did this before ?

EDIT :

I don't want to make it runnable by building assembly with dependencies jar, I want it to be buildable. So anyone having this project is able to build it, even if jars are nowhere to be found at any repository.

答: A good way to achieve this is to have a Maven mirror server such as Sonatype Nexus. It is free and very easy to setup (Java web app). With Nexus one can have private (team, corporate etc) repository with a capability of deploying third party and internal apps into it, while also registering other Maven repositories as part of the same server. This way the local Maven settings would reference only the one private Nexus server and all the dependencies will be resolved using it.</p>