问:
How to determine what changed a DependencyProperty
I've got two objects bound to the same dependencyProperty (in Silverlight).
Is there a way to determine which of these two objects changed the property?
I want to take different actions based on that information.

Unfortunately, I cannot attach two different eventHandlers (because it's a dependencyProperty)

```<code>   public int StartTime
    {
        get { return (int)GetValue(StartTimeProperty); }
        set { SetValue(StartTimeProperty, value); }
    }
    public static readonly DependencyProperty StartTimeProperty =
        DependencyProperty.Register("StartTime", typeof(int), typeof(Step),
        new PropertyMetadata(-1, new PropertyChangedCallback(OnStartTimeChanged)));

    private static void OnStartTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((Step)d).OnStartTimeChanged(e);
    }

    protected virtual void OnStartTimeChanged(DependencyPropertyChangedEventArgs e)
    {
        //if set from obj1 -> do something
        //if set from obj2 -> do something else
    }
</code>```

In this example I would be setting StartTime property from different objects and I want to know which of these object changed the property.

Thanks

答:
You can either:

look at the sender in the event handler

attach both controls to different event handlers

Body:
I've got two objects bound to the same dependencyProperty (in Silverlight).
Is there a way to determine which of these two objects changed the property?
I want to take different actions based on that information.

Unfortunately, I cannot attach two different eventHandlers (because it's a dependencyProperty)

   public int StartTime
    {
        get { return (int)GetValue(StartTimeProperty); }
        set { SetValue(StartTimeProperty, value); }
    }
    public static readonly DependencyProperty StartTimeProperty =
        DependencyProperty.Register("StartTime", typeof(int), typeof(Step),
        new PropertyMetadata(-1, new PropertyChangedCallback(OnStartTimeChanged)));

    private static void OnStartTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((Step)d).OnStartTimeChanged(e);
    }

    protected virtual void OnStartTimeChanged(DependencyPropertyChangedEventArgs e)
    {
        //if set from obj1 -> do something
        //if set from obj2 -> do something else
    }

In this example I would be setting StartTime property from different objects and I want to know which of these object changed the property.

Thanks


来源: stackexchange

问:
Is a View Engine necessary for Express/Node?
So i've dove into Node/Express head first (w/Learning Javascript Intermediate stuff) and im a bit confused at why a "view engine" like Jade or EJS is required?

I can't seem to find something that uses just normal HTML5? Or is it that I cannot pass values to normal HTML with express?

Lets pretend I had an index.html page that loads and when I "Login" it loads with the user name posted at the top (Just for example). Can I not pass values to a normal .html file within express?

答:
To answer the main question - a view engine is not necessary for express/node.

You're right though, you can't pass variables/values to pure html. The view engine is something that looks at the data you pass and generates the html markup for you.

Another approach to using a view engine is to use s front-end library/framework like jquery, react, or angular (or you can use plain javascript). The javascript can retrieve data (with ajax/fetch) and bind it to your html - well I guess it wouldn't be bound if you're using plain javascript or jquery, but you can update the DOM with your data.

ContentLicense: CC BY-SA 3.0


问:
Member reference base type 'Class' is not a structure or union - has the Fixit led me in the right direction?
I’m trying to make a delegate that will send messages from UIButtons within a custom UIView called SGView and am a bit out of my depth following the error messages. I recently learned how to get a delegate to send messages successfully from within an instance method.

SGView includes a class method that arranges multiple UIButtonsin a circle and was designed to be used by different UIViews. The geometry works when the method is called from a parent UIView. I have now declared the delegate by adding @protocol and @property to the class method declaration

like so ...

SGView.h

```<code>#import <UIKit/UIKit.h>

@protocol SGViewDelegate <NSObject>
    -(void)buttonPressed:(UIButton*)button;
@end

@interface SGView : UIView {
    }
    +(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

@property (assign) id<SGViewDelegate> delegate;

@end
</code>```

SGView.m is essentially like this

```<code>#import "SGView.h"

    @implementation SGView : UIView

    +(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews       = [self new];

    // … circular geometry …

    [circleButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [multipleViews addSubview:circleButton];
    }
    return multipleViews;
    }
    @end
</code>```

The moment I change the target from self to self.delegate in the target action statement above, Xcode reports three errors

Definition of 'objc_class' must be imported from module
  'ObjectiveC.runtime' before it is required

No member named 'delegate' in 'struct objc_class'

Member reference type 'struct objc_class *' is a pointer; did you mean
  to use '->'?

Xcode offers a Fixit for the last of these

```<code>    Fixit Replace”.” with “->”
</code>```

By accepting the Fixit I removed the three issues and introduced another

Member reference base type 'Class' is not a structure or union

If this Fixit has lead me in the right direction, what exactly should I be doing next ?

I need to ask this question to make sense of what might seem a straight forward problem before diving back into the Apple documentation and these tutorials trying to solve it. Any help is most appreciated. Thanks.

SOLUTION

This can be found in my answer to my own question.

答:
Changing the class method to an instance method appears to have solved my problem.

This involved making the class method +(id)circleOfButtons:... etc into an instance method (-(id)circleOfButtons:... etc) in both .m and .h files. It was also necessary to change the call in the parent UIView from

```<code>    SGView *sgView              = [SGView circleOfButtons:count buttonSize:size circleRadius:radius];
</code>```

to

```<code>    SGView *sgView              = [[SGView alloc] circleOfButtons:count buttonSize:size circleRadius:radius];
</code>```

and change the declaration in SGView from

```<code>    UIView *multipleViews       = [self new];
</code>```

to

```<code>    UIView *multipleViews       = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
</code>```

SGView can be now reused from different UIViews that change the number and size of UIButtons arranged in a circle. The delegate in SGView also allows each button to send a tagged message to a method in another class - in my case the ViewController.

The complete listing is included below and I'd welcome suggestions or improvements from others with more experience in OO programming.

ViewController.h

```<code>#import <UIKit/UIKit.h>

    @interface ViewController : UIViewController <UIContentContainer> {
    }
@end
</code>```

ViewController.m

```<code>#import "ViewController.h"
#import "FamilyView.h"

@interface ViewController ()

@end

@implementation ViewController

    - (void)viewDidLoad                                             {
    [super viewDidLoad];

    NSLog(@"load FamilyView");

    CGRect rect             = [UIScreen mainScreen].bounds;
    float  statusBarHeight  = [[UIApplication sharedApplication] statusBarFrame].size.height;
    CGRect screenFrame      = CGRectMake(0, statusBarHeight, rect.size.width, rect.size.height - statusBarHeight);
    self.view               = [[UIView alloc] initWithFrame: screenFrame];

    FamilyView *cv          = [[FamilyView alloc]initWithFrame:screenFrame];
    [self.view addSubview:cv];
}

    - (void)buttonPressed:(UIButton*)button                          {
    NSLog(@"Button %ld clicked.", (long int)[button tag]);

    switch (button.tag) {
        case 1:
        //            [self goToFamily1];
            break;
        case 2:
        //            [self goToFamily2];
            break;
        case 3:
        //            [self goToFamily3];
            break;
        case 4:
        //            [self goToFamily4];
            break;
        case 5:
        //            [self goToFamily5];
            break;
        default:
        //            [self goToHelp];
            break;
        }
    }
    @end
</code>```

FamilyView.h

```<code>#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "SGView.h"

    @interface FamilyView : UIView {
    }
@end
</code>```

FamilyView.m

```<code>#import <UIKit/UIKit.h>
#import "FamilyView.h"
#import "SGView.h"

    @implementation FamilyView : UIView

    - (id)initWithFrame:(CGRect)frame {
    self                                    = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {

    self.backgroundColor                    = [UIColor lightGrayColor];

    int     count                           = 5;  //16;
    CGFloat size                            = 80; //41;
    CGFloat radius                          = 68; //105;

    SGView *sgView                          = [[SGView alloc] circleOfButtons:count buttonSize:size circleRadius:radius];
    [self addSubview:sgView];
    }
    return self;
}
@end
</code>```

SGView.h

```<code>#import <UIKit/UIKit.h>

    @protocol SGViewDelegate <NSObject>
    -(void)buttonPressed:(UIButton*)button;
    @end

    @interface SGView : UIView {
    }

      -(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

    @property (assign) id<SGViewDelegate> delegate;

    @end
</code>```

SGView.m

```<code>#import "SGView.h"

    @implementation SGView : UIView

    -(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews                   = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];

    CGPoint screenCentre;
    CGPoint buttonCentre;

    screenCentre.x                          = CGRectGetWidth  ([UIScreen mainScreen].bounds) / 2;
    screenCentre.y                          = CGRectGetHeight ([UIScreen mainScreen].bounds) / 2;

    for (int i = 1; i <= buttonCount; i++) {
        CGFloat radians                     = 2 * M_PI * i / buttonCount;
        CGFloat arcStartPoint               = - M_PI / 2; // first point clockwise after 12 o'clock
        buttonCentre.x                      = screenCentre.x + circleRadius * cos(radians + arcStartPoint);
        buttonCentre.y                      = screenCentre.y + circleRadius * sin(radians + arcStartPoint);

        CGPoint target                      = CGPointMake(buttonCentre.x, buttonCentre.y);
        CGFloat x                           = screenCentre.x - buttonSize / 2;
        CGFloat y                           = screenCentre.y - buttonSize / 2;
        CGFloat wide                        = buttonSize;
        CGFloat high                        = buttonSize;
        UIButton *circleButton              = [[UIButton alloc] initWithFrame:CGRectMake(x, y, wide, high)];

        [circleButton setTag:i];
        [circleButton addTarget:self.delegate action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

        circleButton.clipsToBounds          = YES;
        circleButton.layer.masksToBounds    = NO;
        circleButton.layer.shadowOffset     = CGSizeMake(-15, 20);
        circleButton.layer.shadowRadius     = 5;
        circleButton.layer.shadowOpacity    = 0.0;
        circleButton.layer.borderWidth      = 0.25f;
        circleButton.layer.cornerRadius     = buttonSize/2;
        circleButton.layer.borderColor      = [UIColor blackColor].CGColor;
        circleButton.backgroundColor        = UIColor.whiteColor;
        [circleButton setTitle:[NSString stringWithFormat:@"%i", i] forState:UIControlStateNormal];

        if (buttonCount > 25) {
            [circleButton setTitleColor: [UIColor clearColor] forState:UIControlStateNormal];
            } else {
            [circleButton setTitleColor: [UIColor grayColor] forState:UIControlStateNormal];
        }

        [multipleViews addSubview:circleButton];

    // animation 1
        [UIView animateWithDuration:0.5 animations:^{
        circleButton.transform              = CGAffineTransformMakeScale(1.0, 1.0);
        circleButton.center                 = screenCentre;
        }
                     completion:^(BOOL finished){}];

    // animation 2
        [UIView animateWithDuration:0.5f animations:^{
        circleButton.transform              = CGAffineTransformIdentity;
        circleButton.center                 = target;
        }
                     completion:^(BOOL finished){}];
    }
    return multipleViews;
}
@end
</code>```

Body:
I’m trying to make a delegate that will send messages from UIButtons within a custom UIView called SGView and am a bit out of my depth following the error messages. I recently learned how to get a delegate to send messages successfully from within an instance method.

SGView includes a class method that arranges multiple UIButtonsin a circle and was designed to be used by different UIViews. The geometry works when the method is called from a parent UIView. I have now declared the delegate by adding @protocol and @property to the class method declaration

like so ...

SGView.h

#import <UIKit/UIKit.h>

@protocol SGViewDelegate <NSObject>
    -(void)buttonPressed:(UIButton*)button;
@end

@interface SGView : UIView {
    }
    +(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

@property (assign) id<SGViewDelegate> delegate;

@end

SGView.m is essentially like this

#import "SGView.h"

    @implementation SGView : UIView

    +(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews       = [self new];

    // … circular geometry …

    [circleButton addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [multipleViews addSubview:circleButton];
    }
    return multipleViews;
    }
    @end

The moment I change the target from self to self.delegate in the target action statement above, Xcode reports three errors

Definition of 'objc_class' must be imported from module
  'ObjectiveC.runtime' before it is required

No member named 'delegate' in 'struct objc_class'

Member reference type 'struct objc_class *' is a pointer; did you mean
  to use '->'?

Xcode offers a Fixit for the last of these

    Fixit Replace”.” with “->”

By accepting the Fixit I removed the three issues and introduced another

Member reference base type 'Class' is not a structure or union

If this Fixit has lead me in the right direction, what exactly should I be doing next ?

I need to ask this question to make sense of what might seem a straight forward problem before diving back into the Apple documentation and these tutorials trying to solve it. Any help is most appreciated. Thanks.

SOLUTION

This can be found in my answer to my own question.

Body:
Changing the class method to an instance method appears to have solved my problem.

This involved making the class method +(id)circleOfButtons:... etc into an instance method (-(id)circleOfButtons:... etc) in both .m and .h files. It was also necessary to change the call in the parent UIView from

    SGView *sgView              = [SGView circleOfButtons:count buttonSize:size circleRadius:radius];

to

    SGView *sgView              = [[SGView alloc] circleOfButtons:count buttonSize:size circleRadius:radius];

and change the declaration in SGView from

    UIView *multipleViews       = [self new];

to

    UIView *multipleViews       = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];

SGView can be now reused from different UIViews that change the number and size of UIButtons arranged in a circle. The delegate in SGView also allows each button to send a tagged message to a method in another class - in my case the ViewController.

The complete listing is included below and I'd welcome suggestions or improvements from others with more experience in OO programming.

ViewController.h

#import <UIKit/UIKit.h>

    @interface ViewController : UIViewController <UIContentContainer> {
    }
@end

ViewController.m

#import "ViewController.h"
#import "FamilyView.h"

@interface ViewController ()

@end

@implementation ViewController

    - (void)viewDidLoad                                             {
    [super viewDidLoad];

    NSLog(@"load FamilyView");

    CGRect rect             = [UIScreen mainScreen].bounds;
    float  statusBarHeight  = [[UIApplication sharedApplication] statusBarFrame].size.height;
    CGRect screenFrame      = CGRectMake(0, statusBarHeight, rect.size.width, rect.size.height - statusBarHeight);
    self.view               = [[UIView alloc] initWithFrame: screenFrame];

    FamilyView *cv          = [[FamilyView alloc]initWithFrame:screenFrame];
    [self.view addSubview:cv];
}

    - (void)buttonPressed:(UIButton*)button                          {
    NSLog(@"Button %ld clicked.", (long int)[button tag]);

    switch (button.tag) {
        case 1:
        //            [self goToFamily1];
            break;
        case 2:
        //            [self goToFamily2];
            break;
        case 3:
        //            [self goToFamily3];
            break;
        case 4:
        //            [self goToFamily4];
            break;
        case 5:
        //            [self goToFamily5];
            break;
        default:
        //            [self goToHelp];
            break;
        }
    }
    @end

FamilyView.h

#import <UIKit/UIKit.h>
#import "ViewController.h"
#import "SGView.h"

    @interface FamilyView : UIView {
    }
@end

FamilyView.m

#import <UIKit/UIKit.h>
#import "FamilyView.h"
#import "SGView.h"

    @implementation FamilyView : UIView

    - (id)initWithFrame:(CGRect)frame {
    self                                    = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {

    self.backgroundColor                    = [UIColor lightGrayColor];

    int     count                           = 5;  //16;
    CGFloat size                            = 80; //41;
    CGFloat radius                          = 68; //105;

    SGView *sgView                          = [[SGView alloc] circleOfButtons:count buttonSize:size circleRadius:radius];
    [self addSubview:sgView];
    }
    return self;
}
@end

SGView.h

#import <UIKit/UIKit.h>

    @protocol SGViewDelegate <NSObject>
    -(void)buttonPressed:(UIButton*)button;
    @end

    @interface SGView : UIView {
    }

      -(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius;

    @property (assign) id<SGViewDelegate> delegate;

    @end

SGView.m

#import "SGView.h"

    @implementation SGView : UIView

    -(id)circleOfButtons:(int)buttonCount buttonSize:(CGFloat)buttonSize circleRadius:(CGFloat)circleRadius
    {
    UIView *multipleViews                   = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];

    CGPoint screenCentre;
    CGPoint buttonCentre;

    screenCentre.x                          = CGRectGetWidth  ([UIScreen mainScreen].bounds) / 2;
    screenCentre.y                          = CGRectGetHeight ([UIScreen mainScreen].bounds) / 2;

    for (int i = 1; i <= buttonCount; i++) {
        CGFloat radians                     = 2 * M_PI * i / buttonCount;
        CGFloat arcStartPoint               = - M_PI / 2; // first point clockwise after 12 o'clock
        buttonCentre.x                      = screenCentre.x + circleRadius * cos(radians + arcStartPoint);
        buttonCentre.y                      = screenCentre.y + circleRadius * sin(radians + arcStartPoint);

        CGPoint target                      = CGPointMake(buttonCentre.x, buttonCentre.y);
        CGFloat x                           = screenCentre.x - buttonSize / 2;
        CGFloat y                           = screenCentre.y - buttonSize / 2;
        CGFloat wide                        = buttonSize;
        CGFloat high                        = buttonSize;
        UIButton *circleButton              = [[UIButton alloc] initWithFrame:CGRectMake(x, y, wide, high)];

        [circleButton setTag:i];
        [circleButton addTarget:self.delegate action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

        circleButton.clipsToBounds          = YES;
        circleButton.layer.masksToBounds    = NO;
        circleButton.layer.shadowOffset     = CGSizeMake(-15, 20);
        circleButton.layer.shadowRadius     = 5;
        circleButton.layer.shadowOpacity    = 0.0;
        circleButton.layer.borderWidth      = 0.25f;
        circleButton.layer.cornerRadius     = buttonSize/2;
        circleButton.layer.borderColor      = [UIColor blackColor].CGColor;
        circleButton.backgroundColor        = UIColor.whiteColor;
        [circleButton setTitle:[NSString stringWithFormat:@"%i", i] forState:UIControlStateNormal];

        if (buttonCount > 25) {
            [circleButton setTitleColor: [UIColor clearColor] forState:UIControlStateNormal];
            } else {
            [circleButton setTitleColor: [UIColor grayColor] forState:UIControlStateNormal];
        }

        [multipleViews addSubview:circleButton];

    // animation 1
        [UIView animateWithDuration:0.5 animations:^{
        circleButton.transform              = CGAffineTransformMakeScale(1.0, 1.0);
        circleButton.center                 = screenCentre;
        }
                     completion:^(BOOL finished){}];

    // animation 2
        [UIView animateWithDuration:0.5f animations:^{
        circleButton.transform              = CGAffineTransformIdentity;
        circleButton.center                 = target;
        }
                     completion:^(BOOL finished){}];
    }
    return multipleViews;
}
@end


问:
What is the best way to add two numbers without using the + operator?
A friend and I are going back and forth with brain-teasers and I have no idea how to solve this one.  My assumption is that it's possible with some bitwise operators, but not sure.</p>

答:
The most voted answer will not work if the inputs are of opposite sign. The following however will. I have cheated at one place, but only to keep the code a bit clean. Any suggestions for improvement welcome

def add(x, y):
if (x >= 0 and y >= 0) or (x < 0 and y < 0):
    return _add(x, y)
else:
    return __add(x, y)

def _add(x, y):
if y == 0:
    return x
else:
    return _add((x ^ y), ((x & y) << 1))

def __add(x, y):
if x < 0 < y:
    x = _add(~x, 1)
    if x > y:
        diff = -sub(x, y)
    else:
        diff = sub(y, x)
    return diff
elif y < 0 < x:
    y = _add(~y, 1)
    if y > x:
        diff = -sub(y, x)
    else:
        diff = sub(y, x)
    return diff
else:
    raise ValueError("Invalid Input")

def sub(x, y):
if y > x:
    raise ValueError('y must be less than x')
while y > 0:
    b = ~x & y
    x ^= y
    y = b << 1
return x
```

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
Problems with C strings and atoi function
I'm working on a program that requires the user to enter a C string of numbers, my program will then convert the characters to ints and then sum them.

However, when I run it, my program is multiplying the number provided by the number of digits there, i.e: if I put 123 it returns 369 or 123*3 or 123+123+123. It is summing the whole C string , instead of adding one element of the string at a time like I am trying to get it too.

When I try to do sum+=atoi(numbers[i]); it tells me that it can't convert char to const char*, however with it just as sum+=atoi(numbers); it is doing the whole string.

Please explain how to do this properly for myself and others.

```<code>#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
    const int SIZE=9000;   //max size of c string
    char numbers[SIZE];    //declare an char array
    int sum=0;             //initialize at 0
    cout << "Enter a series of single digit numbers with nothing separating them.\n";
    cout << "And I will tell you sum of those single digits\n";

    //prompt user

    cin.getline(numbers,SIZE);
    //get input

    //for loop till the end of the string
    for (int i=0; i<strlen(numbers);i++)
    {
        sum+=atoi(numbers);
        //if i put "atoi(numbers[i]);" then it tells me I
        //can't convert char to const char*
    }

    cout << "The sum of these single digits is "<< sum <<endl;  //display result
    return 0;
}
</code>```

答:
if i put "atoi(numbers[i]);" then it tells me i cannot conver char to const char*

That is true. It's because dereferencing a char pointer will give you a char. And, since atoi wants a C-style string, that should be an array of characters terminated with a \0 (or the address of the first character of that array).

So you could take the character and make a string out of it but there's probably a better way:

```<code>sum += numbers[i] - '0';
</code>```

This will take the actual character at the given position and subtract the character '0' from it. Assuming it's a digit character will mean you will get the integer equivalent, a number between 0 and 9 inclusive, which you can then add to the sum.

If you must use atoi, the method will be as follows:

copy the character into a separate string area.

append the terminator.

use atoi.

The loop that would do this goes something like:

```<code>// Create buffer and terminate string.

char str[2];
str[1] = '\0';

// Loop over all characters.

for (int i = 0; i < strlen (numbers); i++) {
    // Make string from character, str[1] stays as '\0'.

    str[0] = numbers[i];

    // Use atoi on that string.

    sum += atoi (str);
}
</code>```

Body:
I'm working on a program that requires the user to enter a C string of numbers, my program will then convert the characters to ints and then sum them.

However, when I run it, my program is multiplying the number provided by the number of digits there, i.e: if I put 123 it returns 369 or 123*3 or 123+123+123. It is summing the whole C string , instead of adding one element of the string at a time like I am trying to get it too.

When I try to do sum+=atoi(numbers[i]); it tells me that it can't convert char to const char*, however with it just as sum+=atoi(numbers); it is doing the whole string.

Please explain how to do this properly for myself and others.

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
    const int SIZE=9000;   //max size of c string
    char numbers[SIZE];    //declare an char array
    int sum=0;             //initialize at 0
    cout << "Enter a series of single digit numbers with nothing separating them.\n";
    cout << "And I will tell you sum of those single digits\n";

    //prompt user

    cin.getline(numbers,SIZE);
    //get input

    //for loop till the end of the string
    for (int i=0; i<strlen(numbers);i++)
    {
        sum+=atoi(numbers);
        //if i put "atoi(numbers[i]);" then it tells me I
        //can't convert char to const char*
    }

    cout << "The sum of these single digits is "<< sum <<endl;  //display result
    return 0;
}

Body:
if i put "atoi(numbers[i]);" then it tells me i cannot conver char to const char*

That is true. It's because dereferencing a char pointer will give you a char. And, since atoi wants a C-style string, that should be an array of characters terminated with a \0 (or the address of the first character of that array).

So you could take the character and make a string out of it but there's probably a better way:

sum += numbers[i] - '0';

This will take the actual character at the given position and subtract the character '0' from it. Assuming it's a digit character will mean you will get the integer equivalent, a number between 0 and 9 inclusive, which you can then add to the sum.

If you must use atoi, the method will be as follows:

copy the character into a separate string area.

append the terminator.

use atoi.

The loop that would do this goes something like:

// Create buffer and terminate string.

char str[2];
str[1] = '\0';

// Loop over all characters.

for (int i = 0; i < strlen (numbers); i++) {
    // Make string from character, str[1] stays as '\0'.

    str[0] = numbers[i];

    // Use atoi on that string.

    sum += atoi (str);
}


问:
Two apps share one Redis. How to prevent cache collisions?
Two different versions of the application (debug and release) share same instance of Redis.
Both Debug and Release have identical source code and therefore identical caching keys for being stored in Redis.

Thus when Debug does redis.StringSet(key1, value1) Release could easily overwrite key1 or read incorrect value (since it should have its own key1).

Is there a way to avoid such interference?

答:
One another way is to give your keys a common naming pattern(prefix), and config the prefix in property files.

You can easily use different property files in different environment.


问:
How to gracefully handle exception inside AsyncTask in Android?
I have an AsyncTask to do SQLite database migration in the background (create or upgrade). Let's say somehow an IOException or SQLiteException is thrown inside doInBackground and it's pointless for the app to continue running because database state might be not in desired state. I'm kind of confused on what to do in this situation.

I'm thinking about letting the application crash as soon as possible and show dialog with error message, but I'm not really sure how to this inside doInBackground, because:

This function is not executed in UI thread so I don't know if I can show a dialog.

I don't know how to access current activity within AsyncTask, so I can't finish() it.

I want to somehow throw the exception to the upper layer and let an activity handle it, but it's not possible because doInBackground doesn't list IOException as a checked exception.

Anyone has an advice on how to gracefully handle this situation?

答:
My approach to handle it.</p>

```<code>/**
 * Created by Daniel on 02/04/2016.
 */
public abstract class AsyncTaskEnhanced<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    // Avoids cyclic calls.
    private boolean onPostExecuteCalled = false;
    private Exception exception;

    @Override
    protected final Result doInBackground(Params... params) {

        try {

            return this.doInBackgroundWithFaultTolerance(params);
        } catch (Exception exception) {

            this.exception = nre;
        }

        return null;
    }

    @Override
    protected final void onPostExecute(Result result) {

        if (this.onPostExecuteCalled) return;

        this.onPostExecuteCalled = true;

        super.onPostExecute(result);

        this.onPostExecuteWithFaultTolerance(result, this.exception);
    }

    protected abstract Result doInBackgroundWithFaultTolerance(Params... params) throws Exception;

    protected abstract void onPostExecuteWithFaultTolerance(Result result, Exception ex);

}
</code>```

Body:
My approach to handle it.

/**
 * Created by Daniel on 02/04/2016.
 */
public abstract class AsyncTaskEnhanced<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {

    // Avoids cyclic calls.
    private boolean onPostExecuteCalled = false;
    private Exception exception;

    @Override
    protected final Result doInBackground(Params... params) {

        try {

            return this.doInBackgroundWithFaultTolerance(params);
        } catch (Exception exception) {

            this.exception = nre;
        }

        return null;
    }

    @Override
    protected final void onPostExecute(Result result) {

        if (this.onPostExecuteCalled) return;

        this.onPostExecuteCalled = true;

        super.onPostExecute(result);

        this.onPostExecuteWithFaultTolerance(result, this.exception);
    }

    protected abstract Result doInBackgroundWithFaultTolerance(Params... params) throws Exception;

    protected abstract void onPostExecuteWithFaultTolerance(Result result, Exception ex);

}


问:
Table CSS Issue
I have this in HTML:

```<code><div class="dataBurst" title="What is the Matrix?">
    <table align="center" height="100%">
        <tr>
            <td id="matrixTD">
                <span onclick="alert('Not Yet Online');" class="coredump"
                    title="How Would You Know the Difference Between the Dream World And the Real World?">
                    Click for System Core Dump
                </span>
            </td>
        </tr>
    </table>
</div>
</code>```

The CSS I'm using:

```<code>div.dataBurst
{
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

td#matrixTD
{
    text-align:justify;
    cursor:default;
}
</code>```

The issue is when I try to create a class/id using:
, it does not work; how can I implement this?

my site is at: http://guygar.com

答:
I am not sure, but you want to move the attributes of table align="center" height="100%" to css? If yes then you have to delete this attributes from the table and add a class like this
  when you do this, then in your css file you add the following rule

```<code>.mytable  {
    height: 100%;
    width: auto;
    margin: 0 auto;
}
</code>```

you can change the class name in any name that you like (in html and css also).

Title: Table CSS Issue

Body:
I have this in HTML:

                    Click for System Core Dump

The CSS I'm using:

div.dataBurst
{
    vertical-align:middle;
    width:500px;
    height:321px;
    background-color:#FFF;
    margin-left:auto;
    margin-right:auto;
    border-width:1px;
    border-style:solid;
    margin-bottom:20px;
    padding:5px;
    float:left;
    cursor:pointer;
    cursor:default;
    font-weight:normal;
    font-size:9px;

    overflow:auto;
    overflow-y: scroll;
    overflow-x: hide;
    text-align:justify;

    scrollbar-base-color:#575757;
    scrollbar-3dlight-color:#a6a6a6;
    scrollbar-track-color: #a6a6a6;
}

td#matrixTD
{
    text-align:justify;
    cursor:default;
}

The issue is when I try to create a class/id using:
, it does not work; how can I implement this?

my site is at: http://guygar.com

Body:
I am not sure, but you want to move the attributes of table align="center" height="100%" to css? If yes then you have to delete this attributes from the table and add a class like this <table class="mytable">  when you do this, then in your css file you add the following rule

.mytable  {
    height: 100%;
    width: auto;
    margin: 0 auto;
}

you can change the class name in any name that you like (in html and css also).


问:
PowerShell dir /ah not working?
When I try dir /ah under Windows 10 I get the following:

```<code>PS C:\Users\Robert\dev\fiedz> dir /ah
dir : Cannot find path 'C:\ah' because it does not exist.
At line:1 char:1
+ dir /ah
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\ah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
</code>```

Any idea why ?

答:
If you want to run the dos command dir /ah, and not the Get-ChildItem alias:

```<code>cmd /c <command>
</code>```

In your case:

```<code>cmd /c dir /ah
</code>```

Title: PowerShell dir /ah not working?

Body:
When I try dir /ah under Windows 10 I get the following:

PS C:\Users\Robert\dev\fiedz> dir /ah
dir : Cannot find path 'C:\ah' because it does not exist.
At line:1 char:1
+ dir /ah
+ ~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\ah:String) [Get-ChildItem], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand

Any idea why ?

Body:
If you want to run the dos command dir /ah, and not the Get-ChildItem alias:

cmd /c <command>

In your case:

cmd /c dir /ah


问:
Xamarin Forms Unhandled exception on a ListView in a TableView
I'm trying to dabble a bit by moving from WPF to Xamarin using MVVM, and as the title says, I'm having a problem.

I first tried this code in a ContentPage XAML with a ListView, like this:

```<code><ListView ItemsSource="{Binding EmailList}">
    <TextCell Text="{Binding .}" />
</ListView>
</code>```

and the EmailList is just a simple List<string>. I've tested it, and it works. I get a list of strings ("abc@test.com", "john@doe.com", etc)

I then try my luck doing a TableView, with the Intent set at Form in XAML. I did a few TableSelections, like Name, Address, etc, and they seem to work fine. However, when I put this in:

```<code><TableSection Title="Emails">
   <ViewCell>
     <ListView ItemsSource="{Binding EmailList}">
        <TextCell Text="{Binding .}"/>
    <ListView>
  <ViewCell>
</TableSection>
</code>```

This is when I get an unhandled exception error and the app drops out.

I then tried this:

```<code>  <TableSection Title="Emails">
 <ViewCell>
    <ListView ItemsSource="{Binding EmailList}">
       <ListView.ItemTemplate>
           <DataTemplate>
               <ViewCell>
                  <Label Text="{Binding .}" />
               <ViewCell>
           </DataTemplate>
       </ListView.ItemTemplate>
    </ListView>
 </ViewCell>
</code>```

And I still get the same unhandled exception error.

So what am I doing wrong here?

答:
Seeing that I cannot find the reason for it, and what other guys are saying in the comments, I think I have to take another approach. I'll have to go old school here and use a StackLayout and/or Grids to achieve on what I need the app to do.

Thanks for your input guys!

Body:
I'm trying to dabble a bit by moving from WPF to Xamarin using MVVM, and as the title says, I'm having a problem.

I first tried this code in a ContentPage XAML with a ListView, like this:

<ListView ItemsSource="{Binding EmailList}">
    <TextCell Text="{Binding .}" />
</ListView>

and the EmailList is just a simple List<string>. I've tested it, and it works. I get a list of strings ("abc@test.com", "john@doe.com", etc)

I then try my luck doing a TableView, with the Intent set at Form in XAML. I did a few TableSelections, like Name, Address, etc, and they seem to work fine. However, when I put this in:

<TableSection Title="Emails">
   <ViewCell>
     <ListView ItemsSource="{Binding EmailList}">
        <TextCell Text="{Binding .}"/>
    <ListView>
  <ViewCell>
</TableSection>

This is when I get an unhandled exception error and the app drops out.

I then tried this:

  <TableSection Title="Emails">
 <ViewCell>
    <ListView ItemsSource="{Binding EmailList}">
       <ListView.ItemTemplate>
           <DataTemplate>
               <ViewCell>

               <ViewCell>
           </DataTemplate>
       </ListView.ItemTemplate>
    </ListView>
 </ViewCell>

And I still get the same unhandled exception error.

So what am I doing wrong here?


问:
How to sort through list of a list and remove a list if less not least value
Currently, this takes the list of the candidates and sorts it so that the candidates with the lowest score are in the first positions, how would I get it so that it checks each list and if the number in the second field is not equal to the first one it deletes this list?
I am trying to remove all lists that are not the lowest or equal lowest number in candidate [x][1]:

```<code>candidates = [[name, 3, characteristic], [name, 7, characteristic], [name, 3, characteristic]]
</code>```

so the following code should only delete candidates [1]

```<code>from operator import itemgetter

candidates.sort(key=itemgetter(1))

for [x][1] in candidates:
    if candidates[x][1] != candidates[0][1] :
        candidates.remove(candidates[x])
</code>```

Thanks!

答:
You can try this, if I don't misunderstand your meaning:

```<code>from operator import itemgetter
candidates = [['name', 3, 'characteristic'], ['name', 7, 'characteristic'], ['name', 3, 'characteristic']]

candidates=filter(lambda x:x[1]==sorted(candidates,key=itemgetter(1))[0][1],candidates)

print(candidates)
</code>```

Use filter() method to remove the sublist, if the second field is not equal to the lowest score.

If you're using Python3.x, you should use list(filter(...))

Output:

```<code>[['name', 3, 'characteristic'], ['name', 3, 'characteristic']]
</code>```

Update

I forgot that you can use min() to get the lowest score, it is an more efficient way:

```<code>candidates = [['name', 3, 'characteristic'], ['name', 7, 'characteristic'], ['name', 3, 'characteristic']]

candidates=list(filter(lambda x:x[1]==min([i[1] for i in candidates]),candidates))

print(candidates)
</code>```

Body:
Currently, this takes the list of the candidates and sorts it so that the candidates with the lowest score are in the first positions, how would I get it so that it checks each list and if the number in the second field is not equal to the first one it deletes this list?
I am trying to remove all lists that are not the lowest or equal lowest number in candidate [x][1]:

candidates = [[name, 3, characteristic], [name, 7, characteristic], [name, 3, characteristic]]

so the following code should only delete candidates [1]

from operator import itemgetter

candidates.sort(key=itemgetter(1))

for [x][1] in candidates:
    if candidates[x][1] != candidates[0][1] :
        candidates.remove(candidates[x])

Thanks!

Body:
You can try this, if I don't misunderstand your meaning:

from operator import itemgetter
candidates = [['name', 3, 'characteristic'], ['name', 7, 'characteristic'], ['name', 3, 'characteristic']]

candidates=filter(lambda x:x[1]==sorted(candidates,key=itemgetter(1))[0][1],candidates)

print(candidates)

Use filter() method to remove the sublist, if the second field is not equal to the lowest score.

If you're using Python3.x, you should use list(filter(...))

Output:

[['name', 3, 'characteristic'], ['name', 3, 'characteristic']]

Update

I forgot that you can use min() to get the lowest score, it is an more efficient way:

candidates = [['name', 3, 'characteristic'], ['name', 7, 'characteristic'], ['name', 3, 'characteristic']]

candidates=list(filter(lambda x:x[1]==min([i[1] for i in candidates]),candidates))

print(candidates)


问:
Javascript skips seconds
I'm a newbie to javascript and I am trying to create a 6 hours countdown timer before it executes a specified function but the time display is totally wrong

what am I doing wrong and how do I get this to properly display in Hours, Minutes and Seconds?

Here is the code

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  function timer() {
    // get the number of seconds that have elapsed since
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);

    // does the same job as parseInt truncates the float
    minutes = (diff / 60 * 360) | 0;
    seconds = (diff % 60) | 0;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (diff <= 0) {
      // add one second so that the count down starts at the full duration
      // example 05:00 not 04:59
      start = Date.now() + 1000;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 2,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="time" style="background:white;border:2px solid green;color:green;paddding:5px;"></span> To Delete Your Account</code>```

答:
You are calculating the minute each and every execution. Calculate minute only when the seconds hit 0.

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  function timer() {
    // get the number of seconds that have elapsed since
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);
    // does the same job as parseInt truncates the float
    if(!minutes) minutes = (diff / 60 * 360) | 0
    seconds = (diff % 60) | 0;
    minutes = seconds<=0?(minutes-1) : minutes;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (diff <= 0) {
      // add one second so that the count down starts at the full duration
      // example 05:00 not 04:59
      start = Date.now() + 1000;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 2,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="time" style="background:white;border:2px solid green;color:green;paddding:5px;"></span> To Delete Your Account</code>```

Title: Javascript skips seconds

Body:
I'm a newbie to javascript and I am trying to create a 6 hours countdown timer before it executes a specified function but the time display is totally wrong

what am I doing wrong and how do I get this to properly display in Hours, Minutes and Seconds?

Here is the code

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  function timer() {
    // get the number of seconds that have elapsed since
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);

    // does the same job as parseInt truncates the float
    minutes = (diff / 60 * 360) | 0;
    seconds = (diff % 60) | 0;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (diff <= 0) {
      // add one second so that the count down starts at the full duration
      // example 05:00 not 04:59
      start = Date.now() + 1000;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 2,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

 To Delete Your Account

Body:
You are calculating the minute each and every execution. Calculate minute only when the seconds hit 0.

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  function timer() {
    // get the number of seconds that have elapsed since
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);
    // does the same job as parseInt truncates the float
    if(!minutes) minutes = (diff / 60 * 360) | 0
    seconds = (diff % 60) | 0;
    minutes = seconds<=0?(minutes-1) : minutes;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (diff <= 0) {
      // add one second so that the count down starts at the full duration
      // example 05:00 not 04:59
      start = Date.now() + 1000;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 2,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

<span id="time" style="background:white;border:2px solid green;color:green;paddding:5px;"></span> To Delete Your Account


问:
Simple file writing with ostream_iterator creates file, but doesn't write
I have a really simple code to create a text file called "Input.txt", and write to it using ostream_iterator:

```<code>using namespace std;

int main()
{
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}
</code>```

The code above creates a "Input.txt", but there is nothing written to it. Am I missing something really obvious and fundamental?

答:
I figured it out, it was because I had "System("PAUSE")" in the code, blocking the output stream going into the file. This is the working code:

```<code>int main()
{
    ofstream os{ "Input.txt" }; // output stream for file "to"
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    return 0;
}
</code>```

Can't believe I missed this....

Body:
I have a really simple code to create a text file called "Input.txt", and write to it using ostream_iterator:

using namespace std;

int main()
{
    ofstream os{ "Input.txt" };
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);

    system("PAUSE");
    return 0;
}

The code above creates a "Input.txt", but there is nothing written to it. Am I missing something really obvious and fundamental?

Body:
I figured it out, it was because I had "System("PAUSE")" in the code, blocking the output stream going into the file. This is the working code:

int main()
{
    ofstream os{ "Input.txt" }; // output stream for file "to"
    ostream_iterator<int> oo{ os,"," };

    vector<int> ints;
    for (int i = 0; i < 1000; i++)
    {
        ints.push_back(i);
    }

    unique_copy(ints.begin(), ints.end(), oo);
    return 0;
}

Can't believe I missed this....


问:
Webpack: There's some JavaScript code in the compiled file even when the source file is empty
I'm using Laravel and Laravel Mix. Out of the box, the included app.js file bootstraps quite a few dependencies like jQuery, Bootstrap-sass etc.

When I delete everything in the app.js file, why is there still some code in the compiled js file? Is it a Webpack thing? Even after running npm run production it stays there and I haven't been able to figure out what it does or what it means and not knowing makes me really uncomfortable.

Here's the code that gets left behind:

```<code>! function(n) {
function t(e) {
    if (r[e]) return r[e].exports;
    var o = r[e] = {
        i: e,
        l: !1,
        exports: {}
    };
    return n[e].call(o.exports, o, o.exports, t), o.l = !0, o.exports
}
var r = {};
t.m = n, t.c = r, t.i = function(n) {
    return n
}, t.d = function(n, r, e) {
    t.o(n, r) || Object.defineProperty(n, r, {
        configurable: !1,
        enumerable: !0,
        get: e
    })
}, t.n = function(n) {
    var r = n && n.__esModule ? function() {
        return n.default
    } : function() {
        return n
    };
    return t.d(r, "a", r), r
}, t.o = function(n, t) {
    return Object.prototype.hasOwnProperty.call(n, t)
}, t.p = "", t(t.s = 3)
}([function(n, t) {}, function(n, t) {}, function(n, t) {}, function(n, t, r) {
r(0), r(1), n.exports = r(2)
}]);
</code>```

答:
Webpack adds some code to the bundle to handle modules correctly. This code is referred to as webpack bootstrap. If you want to know what the code does, you should look at the non-uglified version. There are plenty of comments and it's generally easy to get the gist of it, although you don't need to understand every detail.

Here is the non-uglified code (this is the entire bundle with an empty module):

```<code>/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;
/******/
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // identity function for calling harmony imports with the correct context
/******/    __webpack_require__.i = function(value) { return value; };
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

/***/ })
/******/ ]);
</code>```

It's basically mimicking the require from Node.js while also handling ES modules. All this is to make it work in the browser (all browsers for that matter). See also Node.js - Modules.

Body:
I'm using Laravel and Laravel Mix. Out of the box, the included app.js file bootstraps quite a few dependencies like jQuery, Bootstrap-sass etc.

When I delete everything in the app.js file, why is there still some code in the compiled js file? Is it a Webpack thing? Even after running npm run production it stays there and I haven't been able to figure out what it does or what it means and not knowing makes me really uncomfortable.

Here's the code that gets left behind:

! function(n) {
function t(e) {
    if (r[e]) return r[e].exports;
    var o = r[e] = {
        i: e,
        l: !1,
        exports: {}
    };
    return n[e].call(o.exports, o, o.exports, t), o.l = !0, o.exports
}
var r = {};
t.m = n, t.c = r, t.i = function(n) {
    return n
}, t.d = function(n, r, e) {
    t.o(n, r) || Object.defineProperty(n, r, {
        configurable: !1,
        enumerable: !0,
        get: e
    })
}, t.n = function(n) {
    var r = n && n.__esModule ? function() {
        return n.default
    } : function() {
        return n
    };
    return t.d(r, "a", r), r
}, t.o = function(n, t) {
    return Object.prototype.hasOwnProperty.call(n, t)
}, t.p = "", t(t.s = 3)
}([function(n, t) {}, function(n, t) {}, function(n, t) {}, function(n, t, r) {
r(0), r(1), n.exports = r(2)
}]);

Body:
Webpack adds some code to the bundle to handle modules correctly. This code is referred to as webpack bootstrap. If you want to know what the code does, you should look at the non-uglified version. There are plenty of comments and it's generally easy to get the gist of it, although you don't need to understand every detail.

Here is the non-uglified code (this is the entire bundle with an empty module):

/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;
/******/
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // identity function for calling harmony imports with the correct context
/******/    __webpack_require__.i = function(value) { return value; };
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {

/***/ })
/******/ ]);

It's basically mimicking the require from Node.js while also handling ES modules. All this is to make it work in the browser (all browsers for that matter). See also Node.js - Modules.


问:
Unable to register for push notification in Oracle JET
I followed the steps given in below link.

https://community.oracle.com/community/cloud_computing/oracle-cloud-developer-solutions/blog/2016/08/16/your-first-push-notification-based-oracle-jet-hybrid-application

But I am unable to register for Push Notification while logging in.

```<code>function registerDeviceForMCSPush(mcsBackend) {
    var defer = $.Deferred();
    if (typeof PushNotification !== 'undefined') {
        try {
            var push = PushNotification.init({
                "android": {
                    // TODO replace Google Project Number here
                    senderID: "55926"
                }
            });
            push.on('registration', function (data) {
                var regId = data.registrationId;
                deviceHandshakeforCordova(mcsBackend, regId);
            });
            push.on('notification', function (data) {
                alert("Push Notification from Oracle MCS: " + data.message);
            });
            push.on('error', function (e) {
                alert("Push Notification Error=" + e.message);
            });
        } catch (ex) {
            alert("Error registering device with MCS" + ex);
            defer.reject();
        }
    } else {
        alert("PushNotification NOT Defined!");
        defer.reject();
    }
    return $.when(defer);
}
</code>```

I receive the alert message "Push Notification is not defined" from the code

答:
Oracle JET based on Cordova doesn't come with push notifications out of the box, rather it's typical to add a 3rd party Cordova plugin such as https://github.com/phonegap/phonegap-plugin-push. I suspect the error you're getting is indicating you haven't added the 3rd party plugin.

You add this to your JET project by

a) cd'ing into your application directory then cd'ing into the hybrid directory

b) executing the following command:

cordova plugin add phonegap-plugin-push --variable SENDER_ID="XXXXXXXX"

...where XXXXXXX maps to the project number in the Firebase developer console.

This video explains the complete set of steps for setting up push notifications in JET with Oracle Mobile Cloud Service inline with the steps from the article and should provide you assistance in learning how it all works: https://youtu.be/6n-1-bo2_iQ

Body:
I followed the steps given in below link.

https://community.oracle.com/community/cloud_computing/oracle-cloud-developer-solutions/blog/2016/08/16/your-first-push-notification-based-oracle-jet-hybrid-application

But I am unable to register for Push Notification while logging in.

function registerDeviceForMCSPush(mcsBackend) {
    var defer = $.Deferred();
    if (typeof PushNotification !== 'undefined') {
        try {
            var push = PushNotification.init({
                "android": {
                    // TODO replace Google Project Number here
                    senderID: "55926"
                }
            });
            push.on('registration', function (data) {
                var regId = data.registrationId;
                deviceHandshakeforCordova(mcsBackend, regId);
            });
            push.on('notification', function (data) {
                alert("Push Notification from Oracle MCS: " + data.message);
            });
            push.on('error', function (e) {
                alert("Push Notification Error=" + e.message);
            });
        } catch (ex) {
            alert("Error registering device with MCS" + ex);
            defer.reject();
        }
    } else {
        alert("PushNotification NOT Defined!");
        defer.reject();
    }
    return $.when(defer);
}

I receive the alert message "Push Notification is not defined" from the code


问:
solution for having standard menu functionality,
I'm learning Symfony2 and I'm trying
to find a solution for my problem ,
What's the best solution for having standard menu functionality, like in CMSes (WordPress, Drupal, )? The solution that will allow admin to edit the menu and adding images , articles , alerts ..  from the back end and push it to the front end ,
The solution that will work with Sonata or some other admin bundle.</p>

答:
I'd say the KNP menu bundle is the closest you will get to a general purpose menu builder, it's what is already used in Sonata Admin if memory serves correct.

You'd still need to cookup an admin for the definitions and compiler for generating the menu's however.

The short answer is that, if you are needing menu builders in your solution, Symfony might not be the best bit of code to build on. Look up Symfony Content Management Framework if you're determined to use Symfony

Symfony is about putting together a custom solution


问:
Angular 2 Lazy Module and Shared modules singleton
I am learning angular2's  lazy loading and shared dependencies using this article. I understood that lazy module has a separate dependency tree and it doesn't share the same instance of service with eager module.

When I removed SharedModule import from the imports section of lazy module, the behavior changed and I got singleton service between eager and lazy modules.

As per the documentation in order to reuse same shared service there is more to be done as described in this article . But I could make it work just by removing the import from shared module definition. Can someone explain this behavior

Here is the plnkr

```<code>@NgModule({
  imports: [
    //SharedModule   //This is removed
    routing
  ],
  declarations: [LazyComponent]
})
</code>```

答:
Lazy loading doesn't create a separate dependency tree - at least, not in the way you're describing.

As you are probably aware, Angular's dependency injection system is actually a tree of injectors - one for each component in the view hierarchy. When you request a dependency, Angular walks this tree of injectors, starting from the component that's requesting the dependency until it finds the first injector that's able to provide that dependency.
This gives you a lot of power if you need it, since at any level of the component tree, you can specify a provider for a dependency on the component and have that component get its own instance of that dependency. Furthermore, any children of that component will also share that same instance of the dependency.

That's the basic synopsis of how the hierarchal dependency injection works with respect to components. When it comes to modules, however, things are a bit different. By default, any dependencies provided by an NgModule are added to the root injector, meaning that a single instance of that dependency will be shared by the entire application. The exception to this is if the NgModule is lazy loaded. In that case, the dependencies provided by the lazy loaded module won't be added to the root injector. Instead, those dependencies will be added to the root component of the lazy loaded module (i learned this the hard way - if you have multiple 'root components' of your lazy loaded module, each 'root component' will get its own instance of the dependency).

So, it's still the same basic hierarchy - it's just that eager loaded modules add their dependencies to the root injector, whereas lazy loaded modules add theirs to the root component of their module. In addition, if a lazy loaded module imports an NgModule that also provides dependencies (for eg your SharedModule), those dependencies will also be added to that root component of the module.  (Note that if SharedModule is also eager-loaded, its dependencies will also be added to the root injector - leading to multiple instances of those dependencies being available).

That last point is why you're seeing the behaviour you're seeing. When your lazy module imports SharedModule, SharedModules provided dependencies get added to the root component of the lazy module - leading to duplicate instances of those dependencies.

Body:
I am learning angular2's  lazy loading and shared dependencies using this article. I understood that lazy module has a separate dependency tree and it doesn't share the same instance of service with eager module.

When I removed SharedModule import from the imports section of lazy module, the behavior changed and I got singleton service between eager and lazy modules.

As per the documentation in order to reuse same shared service there is more to be done as described in this article . But I could make it work just by removing the import from shared module definition. Can someone explain this behavior

Here is the plnkr

@NgModule({
  imports: [
    //SharedModule   //This is removed
    routing
  ],
  declarations: [LazyComponent]
})


问:
google cloud hosting for database
I want to host database on google cloud. My application is dating app  and I want to know monthly charges of initially accommodate 100,000 users with that the capacity to have 15 second video (5 mb max) for each user.

And also suggest hosting service for the apis.

答:
Use this following calculator to figure out the costs for your app,

https://cloud.google.com/products/calculator/

google recommend Google Cloud Storage for Multimedia files, therefore look at the pricing options for that as well.

https://cloud.google.com/storage-options/

Title: google cloud hosting for database


问:
can we have methods as arguments in a class definition?
Following is the snippet of code I was going thru a scala book.
One of the parameter of the Car class is "def color: String"

I didn't understand. "def" is a keyword to define a method. how can that be used in paramenters?

```<code>scala> abstract class Car {
 |   val year: Int
 |   val automatic: Boolean = true
 |   def color: String
 | }
</code>```

答:
A function that takes other functions are arguments is known as a higher-order function, here is an example of that:

```<code>// A function that takes a list of Ints, and a function that takes an Int and returns a boolean.
def filterList(list: List[Int], filter: (Int) => Boolean) = { /* implementation */ }

// You might call it like this
def filter(i: Int) = i > 0
val list = List(-5, 0, 5, 10)
filterList(list, filter)

// Or shorthand like this
val list = List(-5, 0, 5, 10)
filterList(list, _ > 0)
</code>```

However that is not what is happening in your example.  In your example the Car class has three class members, two of them are variables, and one of them is a function.  If you were to extend your abstract class, you could test the values out:

```<code>abstract class Car {
  val year: Int
  val automatic: Boolean = true
  def color: String
}

case class Sedan(year: Int) extends Car {
  def color = "red"
}

val volkswagen = Sedan(2012)
volkswagen.year       // 2012
volkswagen.automatic  // true
volkswagen.color      // red
</code>```

Here, having color as a function (using def) doesn't make too much sense, because with my implementation, the color is always going to be "red".

A better example for using a function for a class member would be for some value that is going to change:

```<code>class BrokenClock {
  val currentTime = DateTime.now()
}

class Clock {
  def currentTime = DateTime.now()
}

// This would always print the same time, because it is a value that was computed once when you create a new instance of BrokenClock
val brokenClock = BrokenClock()
brokenClock.currentTime // 2017-03-31 22:51:00
brokenClock.currentTime // 2017-03-31 22:51:00
brokenClock.currentTime // 2017-03-31 22:51:00

// This will be a different value every time, because each time we are calling a function that is computing a new value for us
val clock = Clock()
clock.currentTime // 2017-03-31 22:51:00
clock.currentTime // 2017-03-31 22:52:00
clock.currentTime // 2017-03-31 22:53:00
</code>```

Body:
Following is the snippet of code I was going thru a scala book.
One of the parameter of the Car class is "def color: String"

I didn't understand. "def" is a keyword to define a method. how can that be used in paramenters?

scala> abstract class Car {
 |   val year: Int
 |   val automatic: Boolean = true
 |   def color: String
 | }

Body:
A function that takes other functions are arguments is known as a higher-order function, here is an example of that:

// A function that takes a list of Ints, and a function that takes an Int and returns a boolean.
def filterList(list: List[Int], filter: (Int) => Boolean) = { /* implementation */ }

// You might call it like this
def filter(i: Int) = i > 0
val list = List(-5, 0, 5, 10)
filterList(list, filter)

// Or shorthand like this
val list = List(-5, 0, 5, 10)
filterList(list, _ > 0)

However that is not what is happening in your example.  In your example the Car class has three class members, two of them are variables, and one of them is a function.  If you were to extend your abstract class, you could test the values out:

abstract class Car {
  val year: Int
  val automatic: Boolean = true
  def color: String
}

case class Sedan(year: Int) extends Car {
  def color = "red"
}

val volkswagen = Sedan(2012)
volkswagen.year       // 2012
volkswagen.automatic  // true
volkswagen.color      // red

Here, having color as a function (using def) doesn't make too much sense, because with my implementation, the color is always going to be "red".

A better example for using a function for a class member would be for some value that is going to change:

class BrokenClock {
  val currentTime = DateTime.now()
}

class Clock {
  def currentTime = DateTime.now()
}

// This would always print the same time, because it is a value that was computed once when you create a new instance of BrokenClock
val brokenClock = BrokenClock()
brokenClock.currentTime // 2017-03-31 22:51:00
brokenClock.currentTime // 2017-03-31 22:51:00
brokenClock.currentTime // 2017-03-31 22:51:00

// This will be a different value every time, because each time we are calling a function that is computing a new value for us
val clock = Clock()
clock.currentTime // 2017-03-31 22:51:00
clock.currentTime // 2017-03-31 22:52:00
clock.currentTime // 2017-03-31 22:53:00


问:
Trying to return a structure pointer
I am using an assign() function to assign memory for a structure which I'm storing in the structure pointer variable l.

But when I run this code there is an error saying:

'return' was not declared in this scope.

Code

```<code>#include<stdio.h>
#include<stdlib.h>
typedef struct list {
        int a;
        char c;
    };

list *assign();
int main() {
   list *l;
   l = assign();
   l->a = 20;
   printf("%d",l->a);

   return 0;
}
list *assign() {
    list *ptr = (list*)malloc(sizeof(list));
    reutrn ptr;
}
</code>```

答:
```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct {
        int a;
        char c;
    }list;

list *assign();
int main() {
   list *l;
   l = assign();
   l->a = 20;
   printf("%d",l->a);

   return 0;
}
list *assign() {
    list *ptr = (list*)malloc(sizeof(list));
    return ptr;
}
</code>```

You misspelled return and you didn't give a name for your struct.

Title: Trying to return a structure pointer

Body:
I am using an assign() function to assign memory for a structure which I'm storing in the structure pointer variable l.

But when I run this code there is an error saying:

'return' was not declared in this scope.

Code

#include<stdio.h>
#include<stdlib.h>
typedef struct list {
        int a;
        char c;
    };

list *assign();
int main() {
   list *l;
   l = assign();
   l->a = 20;
   printf("%d",l->a);

   return 0;
}
list *assign() {
    list *ptr = (list*)malloc(sizeof(list));
    reutrn ptr;
}

Body:
#include <stdio.h>
#include <stdlib.h>

typedef struct {
        int a;
        char c;
    }list;

list *assign();
int main() {
   list *l;
   l = assign();
   l->a = 20;
   printf("%d",l->a);

   return 0;
}
list *assign() {
    list *ptr = (list*)malloc(sizeof(list));
    return ptr;
}

You misspelled return and you didn't give a name for your struct.


问:
jquery.js?v=1.9.1:4421 Uncaught Error: Syntax error, unrecognized expression: [object Object]
i have a dropdown menu with some submenus. When I click one li item, jquery should add a class to the closest ul to leave the ul open. But when I click one li item, it redirects to a new webpage. How to remember the added class after site refresh?

I have tried this:

```<code> jQuery(function () {
    jQuery('#mobile-menu').on('click', function (e) {
        localStorage.setItem('lastTab', jQuery(e.target).closest('ul').addClass('leave-open'));
    });
    var lastTab = localStorage.getItem('lastTab');
    if (lastTab) {

        jQuery(lastTab).addClass('leave-open');
    }
});
</code>```

But my console say:

jquery.js?v=1.9.1:4421 Uncaught Error: Syntax error, unrecognized expression: [object Object]

Can somebody help me?

Thx

答:
What you are trying to do is using an object as a selector.

Indeed, the lastTab variable don't return the selector but the JQuery object associated with the selected element.

So you should do instead :

```<code>lastTab.addClass('leave-open')
</code>```

By the way, please start using the $
alias instead of jQuery for readability

Body:
i have a dropdown menu with some submenus. When I click one li item, jquery should add a class to the closest ul to leave the ul open. But when I click one li item, it redirects to a new webpage. How to remember the added class after site refresh?

I have tried this:

 jQuery(function () {
    jQuery('#mobile-menu').on('click', function (e) {
        localStorage.setItem('lastTab', jQuery(e.target).closest('ul').addClass('leave-open'));
    });
    var lastTab = localStorage.getItem('lastTab');
    if (lastTab) {

        jQuery(lastTab).addClass('leave-open');
    }
});

But my console say:

jquery.js?v=1.9.1:4421 Uncaught Error: Syntax error, unrecognized expression: [object Object]

Can somebody help me?

Thx

Body:
What you are trying to do is using an object as a selector.

Indeed, the lastTab variable don't return the selector but the JQuery object associated with the selected element.

So you should do instead :

lastTab.addClass('leave-open')

By the way, please start using the $
alias instead of jQuery for readability


问:
Start date and end date datepicker
I have input date that contains start date and end date to filter period. I want to make start date is todays date and the end date is same with start date or one day after start date. The condition is if I choose start date in 01-04-2017 I just can choose 01-04-2017 or date after that in end date input.

This is what I have been done but still doesn't give best answer.

```<code><div class="col-md-4">
   <div class="input-group input-daterange">
        <input type="text" name="from_date_alt" id="from_date_alt" class="form-control datepicker" placeholder="Start date" value="">
        <span class="input-group-addon">to</span>
        <input type="text" name="to_date_alt" id="to_date_alt" class="form-control datepicker" placeholder="End date" value="">
   </div>
</div>
</code>```

This is the script.

```<code>var nowDate = new Date();
var today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);

$(".datepicker").datepicker({
    format: 'yyyy-mm-dd',
    startDate: today,
    autoclose: true
});
</code>```

How could I to do that ?

答:
$( function() {
    $( "#datepicker" ).datepicker( "option", "minDate", new Date(2017, 3 - 1, 31));
  } );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>
<p>Date: <input type="text" id="datepicker"></p></code>```

I do not understand, something like this?

Title: Start date and end date datepicker

Body:
I have input date that contains start date and end date to filter period. I want to make start date is todays date and the end date is same with start date or one day after start date. The condition is if I choose start date in 01-04-2017 I just can choose 01-04-2017 or date after that in end date input.

This is what I have been done but still doesn't give best answer.

        <input type="text" name="from_date_alt" id="from_date_alt" class="form-control datepicker" placeholder="Start date" value="">
        to
        <input type="text" name="to_date_alt" id="to_date_alt" class="form-control datepicker" placeholder="End date" value="">

This is the script.

var nowDate = new Date();
var today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);

$(".datepicker").datepicker({
    format: 'yyyy-mm-dd',
    startDate: today,
    autoclose: true
});

How could I to do that ?

Body:
$( function() {
    $( "#datepicker" ).datepicker( "option", "minDate", new Date(2017, 3 - 1, 31));
  } );

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>
<p>Date: <input type="text" id="datepicker"></p>

I do not understand, something like this?


问:
Turning a string into a dictionary
Having had a python class behind me, I was presented with this question in the next class and I seem to be having a mental block on how to even get started.

"Write a python program that asks the user for a string,  then create the following dictionary: The values are the letters in the string, with the corresponding key being the place in the string. For example if the user entered the string “ABC123” then the dictionary would be: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5}

I started with asking for the user input with something simple like

```<code>s = input('Enter string: ')
</code>```

however, I do not know how to proceed to the next step. Any help would be much appreciated.

答:
Are you sure you need this output: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5} and not D = {0:'A', 1:'B', 2:'C'...}? You can flip the key:values, but they will be unordered then (e.g. you would get something like: D = {‘B’:1, ‘3’:5, ‘A’:0, ‘C’:2, ‘1’:3, ‘2’:4 } or any other random combination).

It sounds like you are getting started with learning python. Welcome to a beautiful programming language. People are very helpful here, but you need to show some effort and initiative. This is not a place to get quick fix solutions. People may provide them to you, but you'll never learn.

I assume this was a HW related question? Unless I'm mistaken (someone please feel free to correct me), the output you are seeking is difficult, if not impossible to create (e.g in that specific order you want). I encourage you to read about python dictionaries.

Try and run this:

```<code>#user = input("Give me a string:")

#Just for demo purpose, lets
#stick with your orig example

user = "ABC123"

ls =[]  #create empty list
d = {}  #create empty dictionary

#Try to figure out and understand
#what the below code does
#what is a list, tuple, dict?
#what are key:values?

for l in enumerate(user):
    ls.append(l)

    for k,v in ls:
        d[k] = v

print('first code output')
print(ls)
print(d)

#What/how does enumerate work?
#the below will generate a
#ordered dict by key

for k,v in enumerate(user):
    d[k] = v

print('2nd code output')
print(d)

#you want to flip your key:value
#output, bases on origibal question
#notice what happens
#run this a few times

print('3rd code output')

print(dict(zip(d.values(), d.keys())))

#You can get the order you want,
#but as a list[(tuple)], not as
#a dict at least in the output
#from your orig question

print(list(zip(d.values(), d.keys())))
</code>```

Unless Im wrong, and someone more experienced can chime in, you cant get the "ordered" output in the format you want for your dictionary.

I'm on a mobile device, so anyone please feel free to correct things.

Title: Turning a string into a dictionary

Body:
Having had a python class behind me, I was presented with this question in the next class and I seem to be having a mental block on how to even get started.

"Write a python program that asks the user for a string,  then create the following dictionary: The values are the letters in the string, with the corresponding key being the place in the string. For example if the user entered the string “ABC123” then the dictionary would be: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5}

I started with asking for the user input with something simple like

s = input('Enter string: ')

however, I do not know how to proceed to the next step. Any help would be much appreciated.

Body:
Are you sure you need this output: D = {‘A’:0, ‘B’:1, ‘C’:2, ‘1’:3, ‘2’:4, ‘3’:5} and not D = {0:'A', 1:'B', 2:'C'...}? You can flip the key:values, but they will be unordered then (e.g. you would get something like: D = {‘B’:1, ‘3’:5, ‘A’:0, ‘C’:2, ‘1’:3, ‘2’:4 } or any other random combination).

It sounds like you are getting started with learning python. Welcome to a beautiful programming language. People are very helpful here, but you need to show some effort and initiative. This is not a place to get quick fix solutions. People may provide them to you, but you'll never learn.

I assume this was a HW related question? Unless I'm mistaken (someone please feel free to correct me), the output you are seeking is difficult, if not impossible to create (e.g in that specific order you want). I encourage you to read about python dictionaries.

Try and run this:

#user = input("Give me a string:")

#Just for demo purpose, lets
#stick with your orig example

user = "ABC123"

ls =[]  #create empty list
d = {}  #create empty dictionary

#Try to figure out and understand
#what the below code does
#what is a list, tuple, dict?
#what are key:values?

for l in enumerate(user):
    ls.append(l)

    for k,v in ls:
        d[k] = v

print('first code output')
print(ls)
print(d)

#What/how does enumerate work?
#the below will generate a
#ordered dict by key

for k,v in enumerate(user):
    d[k] = v

print('2nd code output')
print(d)

#you want to flip your key:value
#output, bases on origibal question
#notice what happens
#run this a few times

print('3rd code output')

print(dict(zip(d.values(), d.keys())))

#You can get the order you want,
#but as a list[(tuple)], not as
#a dict at least in the output
#from your orig question

print(list(zip(d.values(), d.keys())))

Unless Im wrong, and someone more experienced can chime in, you cant get the "ordered" output in the format you want for your dictionary.

I'm on a mobile device, so anyone please feel free to correct things.


问:
Randomly Generate a Word from a txt.file (Python)
I have a text file of sentences. I need to randomly read strings and output the string and its line number in an output file. I have written the following code:

```<code>ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random

i=0

for lines in ifile.readline():

  line = lines[i]

  words = line.split()
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n")
</code>```

However I am only getting one character and no line number. I have been trying to change the code but I am just creating errors. Any ideas?

(Edit)
Test2.txt has the following sentences:

```<code>Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.
</code>```

答:
This is the source of your bug:

```<code>for lines in ifile.readline():
    line = lines[i]
</code>```

There are several aspects of your code that you could clean up. The problem is that you are iterating over a single line of a textfile in your for-loop, i.e. the value of ifile.readline() is a string! So when you do:

```<code>for lines in ifile.readline():
</code>```

The looping variable lines is iterating over individual characters of the first line of the file. I'm not sure what you intended by:

```<code>line = lines[i]
</code>```

But I would just delete it. You can iterate over file-handlers directly, line by line, simply by using a for-loop:

```<code>f = open('my_file.txt')

for line in f:
    words = line.split()
    < do something with words >
</code>```

In addition, I should point out again there are several aspect to your code that should be addressed. The use of enumerate instead of explicitely keeping track of the index variable iis one potential improvement as is the use of the with statement to open files. Your code should probably start something like this:

```<code>with open("test2.txt", "r") as ifile, open("OUT3.txt", "w") as otfile:
    otfile.write("Randomly Selected String \t\t\t Line Number")

    for i, line in enumerate(ifile):
        <do stuff with line and line number i>
</code>```

Body:
I have a text file of sentences. I need to randomly read strings and output the string and its line number in an output file. I have written the following code:

ifile = open("test2.txt", "r")
otfile = open("OUT3.txt", "w")
otfile.write("Randomly Selected String \t\t\t Line Number")

import random

i=0

for lines in ifile.readline():

  line = lines[i]

  words = line.split()
  myword = random.choice(words)

  otfile.write(myword)
  otfile.write(str(i))
  i +=1
  otfile.write("\n")

However I am only getting one character and no line number. I have been trying to change the code but I am just creating errors. Any ideas?

(Edit)
Test2.txt has the following sentences:

Brooklyn is the best place on Earth.
I had chocolate ice cream today.
I ate all the cookies in the cookie jar.
Today was a no good very bad day.
He got his clothes dirty playing outside.

Body:
This is the source of your bug:

for lines in ifile.readline():
    line = lines[i]

There are several aspects of your code that you could clean up. The problem is that you are iterating over a single line of a textfile in your for-loop, i.e. the value of ifile.readline() is a string! So when you do:

for lines in ifile.readline():

The looping variable lines is iterating over individual characters of the first line of the file. I'm not sure what you intended by:

line = lines[i]

But I would just delete it. You can iterate over file-handlers directly, line by line, simply by using a for-loop:

f = open('my_file.txt')

for line in f:
    words = line.split()
    < do something with words >

In addition, I should point out again there are several aspect to your code that should be addressed. The use of enumerate instead of explicitely keeping track of the index variable iis one potential improvement as is the use of the with statement to open files. Your code should probably start something like this:

with open("test2.txt", "r") as ifile, open("OUT3.txt", "w") as otfile:
    otfile.write("Randomly Selected String \t\t\t Line Number")

    for i, line in enumerate(ifile):
        <do stuff with line and line number i>


问:
Mount directory using docker-compose or dockerfile (without copying)
Im trying to move my Owncloud instance to docker. I have a "server" with 120GB root, and 500GB usb disk designated for owncloud data. I came up with such configuration:

```<code>    docker-owncloud
├── docker-compose.yml
├── mysql
│   ├── db <- mysql files
│   └── Dockerfile
└── owncloud
    ├── data <- owncloud files (300GB)
    └── Dockerfile
</code>```

My docker-compose:

```<code>version: '3'
services:
    owncloud:
        build: owncloud
        ports:
            - 8080:80
        links:
            - mysql
        volumes:
            - ./owncloud/data:/var/www/html
    mysql:
        build: mysql
        environment:
            - MYSQL_ROOT_PASSWORD=XXX
        volumes:
            - ./mysql/db:/var/lib/mysql
</code>```

Mysql dockerfile:

```<code>from mysql:5.7.17
ENV LANG=C.UTF-8
ENV TZ=Europe/Warsaw
</code>```

Owncloud dockerfile:

```<code>FROM owncloud:9.1.4-apache
ENV LANG=C.UTF-8
ENV TZ=Europe/Warsaw
</code>```

Now if I do "docker-compose build", data from owncloud/data (300GB) is being copied to new volume, which is impossible because I don't have such amount of free disk space.

Is there a way to mount those two directories using docker-compose or dockerfile without copying the data? Is there any other known way of dealing with such situation ?

I have spend more that 3 hours finding that this is impossible, but I can't believe that it is the case. Thanks in advance for your answers.

答:
When you build, docker is sending all the files in the current directory and subdirectories to the daemon. You know this as the context.

You have 2 options:

Move the data directory outside of the directory structure where you're building the images.

create a .dockerignore file and add the data directory

https://docs.docker.com/engine/reference/builder/#usage

Body:
Im trying to move my Owncloud instance to docker. I have a "server" with 120GB root, and 500GB usb disk designated for owncloud data. I came up with such configuration:

    docker-owncloud
├── docker-compose.yml
├── mysql
│   ├── db <- mysql files
│   └── Dockerfile
└── owncloud
    ├── data <- owncloud files (300GB)
    └── Dockerfile

My docker-compose:

version: '3'
services:
    owncloud:
        build: owncloud
        ports:
            - 8080:80
        links:
            - mysql
        volumes:
            - ./owncloud/data:/var/www/html
    mysql:
        build: mysql
        environment:
            - MYSQL_ROOT_PASSWORD=XXX
        volumes:
            - ./mysql/db:/var/lib/mysql

Mysql dockerfile:

from mysql:5.7.17
ENV LANG=C.UTF-8
ENV TZ=Europe/Warsaw

Owncloud dockerfile:

FROM owncloud:9.1.4-apache
ENV LANG=C.UTF-8
ENV TZ=Europe/Warsaw

Now if I do "docker-compose build", data from owncloud/data (300GB) is being copied to new volume, which is impossible because I don't have such amount of free disk space.

Is there a way to mount those two directories using docker-compose or dockerfile without copying the data? Is there any other known way of dealing with such situation ?

I have spend more that 3 hours finding that this is impossible, but I can't believe that it is the case. Thanks in advance for your answers.


答: Using "y = mod.predict(val_iter,num_batch=1)" instead of "y = mod.predict(val_iter)", then you can get only one batch labels. For example,if you batch_size is 10, then you will only  get the 10 labels.</p>

Title: mod.predict gives more columns than expected

Body:
I am using MXNet on IRIS dataset which has 4 features and it classifies the flowers as -'setosa', 'versicolor', 'virginica'. My training data has 89 rows. My label data is a row vector of 89 columns. I encoded the flower names into number -0,1,2 as it seems mx.io.NDArrayIter does not accept numpy ndarray with string values. Then I tried to predict using

re = mod.predict(test_iter)

I get a result which has the shape 14 * 10.
Why am I getting 10 columns when I have only 3 labels and how do I map these results to my labels. The result of predict is shown below:

[[ 0.11760861 0.12082944 0.1207106 0.09154381 0.09155304 0.09155869
  0.09154817 0.09155204 0.09154914 0.09154641] [ 0.1176083 0.12082954 0.12071151 0.09154379 0.09155323 0.09155825
  0.0915481 0.09155164 0.09154923 0.09154641] [ 0.11760829 0.1208293 0.12071083 0.09154385 0.09155313 0.09155875
  0.09154838 0.09155186 0.09154932 0.09154625] [ 0.11760861 0.12082901 0.12071037 0.09154388 0.09155303 0.09155875
  0.09154829 0.09155209 0.09154959 0.09154641] [ 0.11760896 0.12082863 0.12070955 0.09154405 0.09155299 0.09155875
  0.09154839 0.09155225 0.09154996 0.09154646] [ 0.1176089 0.1208287 0.1207095 0.09154407 0.09155297 0.09155882
  0.09154844 0.09155232 0.09154989 0.0915464 ] [ 0.11760896 0.12082864 0.12070941 0.09154408 0.09155297 0.09155882
  0.09154844 0.09155234 0.09154993 0.09154642] [ 0.1176088 0.12082874 0.12070983 0.09154399 0.09155302 0.09155872
  0.09154837 0.09155215 0.09154984 0.09154641] [ 0.11760852 0.12082904 0.12071032 0.09154394 0.09155304 0.09155876
  0.09154835 0.09155209 0.09154959 0.09154631] [ 0.11760963 0.12082832 0.12070873 0.09154428 0.09155257 0.09155893
  0.09154856 0.09155177 0.09155051 0.09154671] [ 0.11760966 0.12082829 0.12070868 0.09154429 0.09155258 0.09155892
  0.09154858 0.0915518 0.09155052 0.09154672] [ 0.11760949 0.1208282 0.12070852 0.09154446 0.09155259 0.09155893
  0.09154854 0.09155205 0.0915506 0.09154666] [ 0.11760952 0.12082817 0.12070853 0.0915444 0.09155261 0.09155891
  0.09154853 0.09155206 0.09155057 0.09154668] [ 0.1176096 0.1208283 0.12070892 0.09154423 0.09155267 0.09155882
  0.09154859 0.09155172 0.09155044 0.09154676]]


答: You wrote 'reutrn' instead of 'return' in your code. Check your last few lines.</p>

Title: Trying to return a structure pointer


问:
Realm issue with Swift 3.1
I've just updated Xcode using Swift 3.1. While waiting for Realm to update their library, just wondering if someone has a temporary workaround for this issue.

Module compiled with Swift 3.0.2 cannot be imported in Swift 3.1: RealmSwift.framework

EDIT:

@matt, @bdash, I followed the instruction, removed the old libraries and added new supporting swift 3.1. I got this error

Showing All Issues Command failed due to signal: Illegal instruction: 4

Any idea?

答: Realm Swift v2.5.0, released earlier this week, contains a precompiled framework binary for Swift 3.1. No waiting required.</p>

Title: Realm issue with Swift 3.1