问:
How to deregister / unregister Firebase user when registered using Phone Auth
I have registered users using Firebase convenience FUIPhoneAuth. When I try to delete the user with:

```<code>[user deleteWithCompletion:^(NSError * _Nullable error) ..
</code>```

I get an error message saying the only recently authenticate users can be deleted.

```<code>"This operation is sensitive and requires recent authentication. Log in again before retrying this request."
</code>```

In order to deregister the user, I first need to re-authenticate the user which requires a FIRAuthCredential "credential" parameter:

```<code>[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {
</code>```

Firebase doc mentions that one should save FIRAuthCredential when a delegate gets called.(store it in NSUserDefaults)

```<code>[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput
                                    UIDelegate:nil
                                    completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
</code>```

I have used FUIPhoneAuth with signInWithPresentingViewController: and did not receive a FIRAuthCredential upon registration.
I am thinking that if I can get hold of the "FIRAuthCredential" I can re-use it
to deregister the user. But when using the FUIPhoneAuth this does not seem possible.
*How do I get hold of the FIRAuthCredential in order to deregister a user?*

Can one reuse the "FIRAuthCredential or does one need to do a complete re-authentication with a SMS before the user can be
deleted?

How does one deregister a user when registered using FUIPhoneAuth?

答:
Re-Authenticate as per normal and then call deleteWithCompletion.
Since you already have the cell number, you do not need to recapture that.</p>

```<code>FIRAuth *auth = [(AppDelegate*)[UIApplication sharedApplication].delegate auth];
FIRPhoneAuthProvider *provider = [FIRPhoneAuthProvider providerWithAuth:auth];

[provider verifyPhoneNumber:user.phoneNumber
                 UIDelegate:nil
                 completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
                        if (error) {
                            return;
                        }

                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Verification"
                                                                                message:@"Enter the SMS verfication code" preferredStyle:UIAlertControllerStyleAlert];

                        [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                            textField.placeholder = @"SMS Code";
                            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                            textField.borderStyle = UITextBorderStyleRoundedRect;
                        }];

                        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK"
                                                                                style:UIAlertActionStyleDefault
                                                                              handler:^(UIAlertAction * action) {

                                                                                NSArray *textfields = alert.textFields;
                                                                                UITextField *codeField = textfields[0];

                                                                                FIRAuthCredential *credential = [provider credentialWithVerificationID:verificationID verificationCode:codeField.text];

                                                                                [user reauthenticateWithCredential:credential completion:^(NSError * _Nullable error) {
                                                                                // unregister
                                                                                [user deleteWithCompletion:^(NSError * _Nullable error) {
                                                                                if (error) {
                                                                                NSLog(@"FIR: User delete failed: %@",error.localizedDescription);

                                                                                }
                                                                                NSLog(@"FIR: User Deleted success");
                                                                                }];
                                                                                }];
                                                                              }];

                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler: ^(UIAlertAction * action) {
                        }];

                        [alert addAction:defaultAction];
                        [alert addAction:cancelAction];
                        [self presentViewController:alert animated:YES completion:nil];

                    }];
</code>```

Body:
I have registered users using Firebase convenience FUIPhoneAuth. When I try to delete the user with:

[user deleteWithCompletion:^(NSError * _Nullable error) ..

I get an error message saying the only recently authenticate users can be deleted.

"This operation is sensitive and requires recent authentication. Log in again before retrying this request."

In order to deregister the user, I first need to re-authenticate the user which requires a FIRAuthCredential "credential" parameter:

[user reauthenticateWithCredential:credential completion:^(NSError *_Nullable error) {

Firebase doc mentions that one should save FIRAuthCredential when a delegate gets called.(store it in NSUserDefaults)

[[FIRPhoneAuthProvider provider] verifyPhoneNumber:userInput
                                    UIDelegate:nil
                                    completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {

I have used FUIPhoneAuth with signInWithPresentingViewController: and did not receive a FIRAuthCredential upon registration.
I am thinking that if I can get hold of the "FIRAuthCredential" I can re-use it
to deregister the user. But when using the FUIPhoneAuth this does not seem possible.
*How do I get hold of the FIRAuthCredential in order to deregister a user?*

Can one reuse the "FIRAuthCredential or does one need to do a complete re-authentication with a SMS before the user can be
deleted?

How does one deregister a user when registered using FUIPhoneAuth?

Body:
Re-Authenticate as per normal and then call deleteWithCompletion.
Since you already have the cell number, you do not need to recapture that.

FIRAuth *auth = [(AppDelegate*)[UIApplication sharedApplication].delegate auth];
FIRPhoneAuthProvider *provider = [FIRPhoneAuthProvider providerWithAuth:auth];

[provider verifyPhoneNumber:user.phoneNumber
                 UIDelegate:nil
                 completion:^(NSString * _Nullable verificationID, NSError * _Nullable error) {
                        if (error) {
                            return;
                        }

                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Verification"
                                                                                message:@"Enter the SMS verfication code" preferredStyle:UIAlertControllerStyleAlert];

                        [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                            textField.placeholder = @"SMS Code";
                            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
                            textField.borderStyle = UITextBorderStyleRoundedRect;
                        }];

                        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK"
                                                                                style:UIAlertActionStyleDefault
                                                                              handler:^(UIAlertAction * action) {

                                                                                NSArray *textfields = alert.textFields;
                                                                                UITextField *codeField = textfields[0];

                                                                                FIRAuthCredential *credential = [provider credentialWithVerificationID:verificationID verificationCode:codeField.text];

                                                                                [user reauthenticateWithCredential:credential completion:^(NSError * _Nullable error) {
                                                                                // unregister
                                                                                [user deleteWithCompletion:^(NSError * _Nullable error) {
                                                                                if (error) {
                                                                                NSLog(@"FIR: User delete failed: %@",error.localizedDescription);

                                                                                }
                                                                                NSLog(@"FIR: User Deleted success");
                                                                                }];
                                                                                }];
                                                                              }];

                        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler: ^(UIAlertAction * action) {
                        }];

                        [alert addAction:defaultAction];
                        [alert addAction:cancelAction];
                        [self presentViewController:alert animated:YES completion:nil];

                    }];


来源: stackexchange

问:
system.Drawing.Drawing2d.GraphicsPath
I have a c# class library that supports Silverlight4 as well.

The problem is , I need to use System.Drawing.Drawing2d.GraphicsPath in my code. for drawing a shape. but it is not there in silverlight. Can anyone suggest me an alternative?

Thanks in advance.

Regards,
James

答:
take a look at http://www.c-sharpcorner.com/UploadFile/mahesh/PathInSL03252009005946AM/PathInSL.aspx

Snippet XAML:

```<code><Path Stroke="Black" StrokeThickness="4"
        Data="M 80,200 A 100,50 45 1 0 100,50" />
</code>```

Snippet Dynamic:

```<code>public void CreateAPath()

{

    // Create a blue and a black Brush

    SolidColorBrush blueBrush = new SolidColorBrush();

    blueBrush.Color = Colors.Blue;

    SolidColorBrush blackBrush = new SolidColorBrush();

    blackBrush.Color = Colors.Black;

    // Create a Path with black brush and blue fill

    Path bluePath = new Path();

    bluePath.Stroke = blackBrush;

    bluePath.StrokeThickness = 3;

    bluePath.Fill = blueBrush;

    // Create a line geometry

    LineGeometry blackLineGeometry = new LineGeometry();

    blackLineGeometry.StartPoint = new Point(20, 200);

    blackLineGeometry.EndPoint = new Point(300, 200);

    // Create an ellipse geometry

    EllipseGeometry blackEllipseGeometry = new EllipseGeometry();

    blackEllipseGeometry.Center = new Point(80, 150);

    blackEllipseGeometry.RadiusX = 50;

    blackEllipseGeometry.RadiusY = 50;

    // Create a rectangle geometry

    RectangleGeometry blackRectGeometry = new RectangleGeometry();

    Rect rct = new Rect();

    rct.X = 80;

    rct.Y = 167;

    rct.Width = 150;

    rct.Height = 30;

    blackRectGeometry.Rect = rct;

    // Add all the geometries to a GeometryGroup.

    GeometryGroup blueGeometryGroup = new GeometryGroup();

    blueGeometryGroup.Children.Add(blackLineGeometry);

    blueGeometryGroup.Children.Add(blackEllipseGeometry);

    blueGeometryGroup.Children.Add(blackRectGeometry);

    // Set Path.Data

    bluePath.Data = blueGeometryGroup;

    LayoutRoot.Children.Add(bluePath);

}
</code>```

ContentLicense: CC BY-SA 2.5

Title: system.Drawing.Drawing2d.GraphicsPath

Body:
take a look at http://www.c-sharpcorner.com/UploadFile/mahesh/PathInSL03252009005946AM/PathInSL.aspx

Snippet XAML:

<Path Stroke="Black" StrokeThickness="4"
        Data="M 80,200 A 100,50 45 1 0 100,50" />

Snippet Dynamic:

public void CreateAPath()

{

    // Create a blue and a black Brush

    SolidColorBrush blueBrush = new SolidColorBrush();

    blueBrush.Color = Colors.Blue;

    SolidColorBrush blackBrush = new SolidColorBrush();

    blackBrush.Color = Colors.Black;

    // Create a Path with black brush and blue fill

    Path bluePath = new Path();

    bluePath.Stroke = blackBrush;

    bluePath.StrokeThickness = 3;

    bluePath.Fill = blueBrush;

    // Create a line geometry

    LineGeometry blackLineGeometry = new LineGeometry();

    blackLineGeometry.StartPoint = new Point(20, 200);

    blackLineGeometry.EndPoint = new Point(300, 200);

    // Create an ellipse geometry

    EllipseGeometry blackEllipseGeometry = new EllipseGeometry();

    blackEllipseGeometry.Center = new Point(80, 150);

    blackEllipseGeometry.RadiusX = 50;

    blackEllipseGeometry.RadiusY = 50;

    // Create a rectangle geometry

    RectangleGeometry blackRectGeometry = new RectangleGeometry();

    Rect rct = new Rect();

    rct.X = 80;

    rct.Y = 167;

    rct.Width = 150;

    rct.Height = 30;

    blackRectGeometry.Rect = rct;

    // Add all the geometries to a GeometryGroup.

    GeometryGroup blueGeometryGroup = new GeometryGroup();

    blueGeometryGroup.Children.Add(blackLineGeometry);

    blueGeometryGroup.Children.Add(blackEllipseGeometry);

    blueGeometryGroup.Children.Add(blackRectGeometry);

    // Set Path.Data

    bluePath.Data = blueGeometryGroup;

    LayoutRoot.Children.Add(bluePath);

}


问:
Retrieving Redmine issues via API for several projects and trackers
I would like to retrieve all Redmine issues that belong to a list of projects, and have either one of three trackers.

I was hoping to use query parameters project_id and tracker_id with multiple values. I tried tracker_id=3,1,5 and tracker_id=[1,3,5] as well as tracker_id=1&tracker_id=3&tracker_id=5 (and similar for project_id) but none of them will work.

The API page (http://www.redmine.org/projects/redmine/wiki/Rest_Issues) doesn't give any indication that it's possible.  This might mean that I'd have to make a large number of API calls which may be hard to maintain ...

Any help or pointers are appreciated.

答:
You need to use | instead of , character.
http://www.redmine.org/projects/redmine/issues.xml?tracker_id=1|2

source: https://github.com/redmine/redmine/blob/edbc9611de355e7933793b1eb155474d88d46fbd/app/models/query.rb#L621

ContentLicense: CC BY-SA 3.0


问:
Jquery: acces link using ctrl+lclick combination
I'm trying to make my Laravel application to access a link from an input field using ctrl pressed key and left click button.

My div looks something like this:

```<code><input type="text" class="linkAccess" id="" name="" value="{{ $DBtable->tableColumn->value }}"
</code>```

After I save my form and access it again, in this "input" I want my link to be shown and I want to access using that specific combination (ctrl+left click).

I have tried something like this:

```<code>$('.linkAccess').click( function (event) {
  event.preventDefault();
  if(true === event.ctrlKey) {

    /* Extract the value */
    var $link = $('.linkAccess');
    var value = $link.val();

    /* Filter out the requests that don't have a key word. */
    if('' !== value){
      $link.replaceWith( $("<a />").attr({"href" : value, "target":"_blank"}).html(value) );
    }
  }
})
</code>```

Any Ideas?

答:
```<code>var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;
});

$(document).keyup(function (e) {
    delete keys[e.which];
});
</code>```

you can keep keys in array, and control in click event

Body:
I'm trying to make my Laravel application to access a link from an input field using ctrl pressed key and left click button.

My div looks something like this:

<input type="text" class="linkAccess" id="" name="" value="{{ $DBtable->tableColumn->value }}"

After I save my form and access it again, in this "input" I want my link to be shown and I want to access using that specific combination (ctrl+left click).

I have tried something like this:

$('.linkAccess').click( function (event) {
  event.preventDefault();
  if(true === event.ctrlKey) {

    /* Extract the value */
    var $link = $('.linkAccess');
    var value = $link.val();

    /* Filter out the requests that don't have a key word. */
    if('' !== value){
      $link.replaceWith( $("").attr({"href" : value, "target":"_blank"}).html(value) );
    }
  }
})

Any Ideas?

Body:
var keys = {};

$(document).keydown(function (e) {
    keys[e.which] = true;
});

$(document).keyup(function (e) {
    delete keys[e.which];
});

you can keep keys in array, and control in click event


问:
Is there a better conditional setTimeout pattern?
I have the following code:

```<code>if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}
</code>```

It seems like there should be a better pattern than calling flyOut in each if  condition.  Seems wasteful to me and pollutes the code.

Is there a better way?

答:
If you can use promises, conditionals are simple:</p>

```<code>function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
}

async function example() {
    if (!isFlyoutAnimationDisabled)
        await delay(250);
    flyOut();
}
// or without async/await:
function example() {
    return (isFlyoutAnimationDisabled
      ? Promise.resolve()
      : delay(250)
    ).then(flyOut);
}
</code>```

Body:
I have the following code:

if (isFlyoutAnimationDisabled) {
  flyOut();
} else {
  setTimeout(flyOut, 250);
}

It seems like there should be a better pattern than calling flyOut in each if  condition.  Seems wasteful to me and pollutes the code.

Is there a better way?

Body:
If you can use promises, conditionals are simple:

function delay(t) {
    return new Promise(resolve => setTimeout(resolve, t));
}

async function example() {
    if (!isFlyoutAnimationDisabled)
        await delay(250);
    flyOut();
}
// or without async/await:
function example() {
    return (isFlyoutAnimationDisabled
      ? Promise.resolve()
      : delay(250)
    ).then(flyOut);
}


问:
"J2OBJC_HOME\ not\ correctly\ defined\ in\ Settings.xcconfig
Guys last 2 to 3 day I am trying to run an example project for J2OBJC conversion. First I faced issue for the j2objc command not found, fixed this issue by adding the path to the /etc/paths file. Now I am facing an issue like J2OBJC_HOME path not defined correctly.

`/bin/sh -c if\ [\ !\ -f\ \"${J2OBJC_HOME}/j2objc\"\ ];\ then\ echo\ \"J2OBJC_HOME\ not\ correctly\ defined\ in\ Settings.xcconfig,\ currently\ set\ to\ \'${J2OBJC_HOME}\'\";\ exit\ 1;\ fi;\
\"${J2OBJC_HOME}/j2objc\"\ -d\ ${DERIVED_FILES_DIR}\ -sourcepath\ \"${PROJECT_DIR}/Classes\"\ --no-package-directories\ -use-arc\ --prefix\ Othello.Engine=JOE\ -g\ ${INPUT_FILE_PATH};

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.google.devtools.j2objc.javac.JavacEnvironment (file:/Users/*****/Documents/j2objc-2.0.5/lib/j2objc.jar) to field com.sun.tools.javac.code.Symtab.java_base
WARNING: Please consider reporting this to the maintainers of com.google.devtools.j2objc.javac.JavacEnvironment
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
error: internal error translating "/Users/*****/Downloads/j2objc-sample-reversi-master/Classes/Othello/Engine/Score.java"
java.lang.NoSuchFieldError: operator
    at com.google.devtools.j2objc.javac.TreeConverter.convertBinary(TreeConverter.java:513)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:346)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertArrayAccess(TreeConverter.java:476)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:230)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertAssignment(TreeConverter.java:497)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:236)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertExpressionStatement(TreeConverter.java:691)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:263)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertBlock(TreeConverter.java:543)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:238)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertMethodDeclaration(TreeConverter.java:888)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:283)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertAbstractTypeDeclaration(TreeConverter.java:390)
    at com.google.devtools.j2objc.javac.TreeConverter.convertClassDeclaration(TreeConverter.java:603)
    at com.google.devtools.j2objc.javac.TreeConverter.convertInner(TreeConverter.java:246)
    at com.google.devtools.j2objc.javac.TreeConverter.convert(TreeConverter.java:202)
    at com.google.devtools.j2objc.javac.TreeConverter.convertCompilationUnit(TreeConverter.java:173)
    at com.google.devtools.j2objc.javac.JavacParser.parseFiles(JavacParser.java:173)
    at com.google.devtools.j2objc.pipeline.FileProcessor.processBatch(FileProcessor.java:141)
    at com.google.devtools.j2objc.pipeline.FileProcessor.processInputs(FileProcessor.java:70)
    at com.google.devtools.j2objc.pipeline.TranslationProcessor.processInputs(TranslationProcessor.java:78)
    at com.google.devtools.j2objc.J2ObjC.run(J2ObjC.java:127)
    at com.google.devtools.j2objc.J2ObjC.main(J2ObjC.java:177)

Exception in thread "main" java.lang.NullPointerException
    at com.google.devtools.j2objc.javac.JavacParser.parseFiles(JavacParser.java:175)
    at com.google.devtools.j2objc.pipeline.FileProcessor.processBatch(FileProcessor.java:141)
    at com.google.devtools.j2objc.pipeline.FileProcessor.processInputs(FileProcessor.java:70)
    at com.google.devtools.j2objc.pipeline.TranslationProcessor.processInputs(TranslationProcessor.java:78)
    at com.google.devtools.j2objc.J2ObjC.run(J2ObjC.java:127)
    at com.google.devtools.j2objc.J2ObjC.main(J2ObjC.java:177)`

Guys, please help me to fix the above, anyone already faces such issue.

Thanks in advance.

答:
Like most "*_HOME" settings, it's something you need to specify (like JAVA_HOME, KOTLIN_HOME, GROOVY_HOME, etc.). Edit Settings.xconfig and set J2OBJC_HOME to the same path you added to /etc/paths.

The next problem is that j2objc does not run with a Java 9 JDK (coming soon). The good news is that multiple JDKs can be installed on your Mac, and the j2objc script will pick the latest Java 8 JDK installed, regardless of whether the Java 9 JDK is the default. Go to Oracle's Java SE Downloads page, get the latest Java 8 JDK and install it.


问:
Get value of <select> on change
I have the following code:

component.html:

```<code><select id="select" (change)="selectInputUpdate(this.value)">
      <option *ngFor="let option of filteredOptions" value="{{option .Id}}" class="select-option"></option>
</select>
</code>```

component.ts:

```<code>selectInputUpdate(newVal: number){
        this.selectVal = newVal;
    }
</code>```

I can get the (change) event to fire off fine, but I can't seem to pass in the value of the select. I can get the value from jquery or vanilla JS by selecting the  by ID, but I can't seem to do it more elegantly in-line.

答:
```<code><select id="select" (change)="selectInputUpdate($event.target.value)">
      <option *ngFor="let option of filteredOptions" value="{{option .Id}}" class="select-option"></option>
</select>
</code>```

or

```<code><select id="select" [(ngModel)]="selectedInput">
      <option *ngFor="let option of filteredOptions" [ngValue]="option" class="select-option"></option>
</select>
</code>```

Title: Get value of <select> on change

Body:
I have the following code:

component.html:

<select id="select" (change)="selectInputUpdate(this.value)">
      <option *ngFor="let option of filteredOptions" value="{{option .Id}}" class="select-option"></option>
</select>

component.ts:

selectInputUpdate(newVal: number){
        this.selectVal = newVal;
    }

I can get the (change) event to fire off fine, but I can't seem to pass in the value of the select. I can get the value from jquery or vanilla JS by selecting the  by ID, but I can't seem to do it more elegantly in-line.

Body:
<select id="select" (change)="selectInputUpdate($event.target.value)">
      <option *ngFor="let option of filteredOptions" value="{{option .Id}}" class="select-option"></option>
</select>

or

<select id="select" [(ngModel)]="selectedInput">
      <option *ngFor="let option of filteredOptions" [ngValue]="option" class="select-option"></option>
</select>


问:
How to change image during a scroll on Android
I'm a beginner on Android development and am trying to build my first app. I have an activity with a round target image and I'd like to make this image vanish at scroll down and display an another image instead that would snap to the toolBar (see the example images below).

I've researched this, but have only found information about using effects in apps where the image just vanishes. Perhaps, the Coordinator Layout could be useful here?

Initial state of my layout

After scrolling up, I want to change to a state like this.

To summarize, I have to :
- make my round Image go behind de ToolBar
- make the rectangular ImageView2 appear below the ToolBar
- Align my buttons (I guess it's about speed ? The one in the middle should go faster or something like that).
- Display new infos coming from below

答:
You should surely use CoordinatorLayout. The point is that you should add custom behavior to your ImageView.
You can see an example here:
https://www.bignerdranch.com/blog/customizing-coordinatorlayouts-behavior/ </p>


问:
(iphone) how to set 'atomic' @property for a variable?
I want to use an integer variable from multiple threads.

Hence I want to make getter/setter atomic operation.

at header file

```<code>@property (retain) NSNumber* myNumber;
</code>```

at implementation file

```<code>@synthesize myNumber;
</code>```

won't compile, what am i missing?

(type of property ‘myNumber’ does not match type of ivar ‘myNumber’)

- edit, I declared it as int myNumber; compilation problem solved

Also, can I use plain int for this? (not NSNumber* )

答:
@property (assign) int myNumber;

Add in @interface NSNumber *myNumber;

Body:
I want to use an integer variable from multiple threads.

Hence I want to make getter/setter atomic operation.

at header file

@property (retain) NSNumber* myNumber;

at implementation file

@synthesize myNumber;

won't compile, what am i missing?

(type of property ‘myNumber’ does not match type of ivar ‘myNumber’)

- edit, I declared it as int myNumber; compilation problem solved

Also, can I use plain int for this? (not NSNumber* )


问:
Loop in a query to return the next 3 values from given variable
REXTESTER Sample

The query I have below returns the date 3 days later from the given variable @incoming_date. The catch is that the returned date cannot be a weekend or one of the ten federal holidays. For example, if today's date (11/16/2017) was given then it would return 11/20/2017. If the 20th was a federal holiday it would return the 21st. Or if 11/20 is given, 11/22nd is returned (today is inclusive). To determine if it is a holiday, I put the list of federal holidays in a table called TEST_Holiday_dates in a column called Holiday_Date.

```<code>declare @incoming_date date
declare @mydate date
declare @if_date_is_Holiday date
declare @if_weekend varchar(10)

set @incoming_date = '2018-01-11' --change this date to test
set @mydate = dateadd(day, 2, @incoming_date)

set @if_date_is_Holiday = (
                           select Holiday_Date
                           from TEST_Holiday_Dates
                           where Holiday_Date = @mydate
                          )
set @if_weekend = (
                   select convert(varchar(10), datename(dw, @mydate))
                   where
                   convert(varchar(10), datename(dw, @mydate)) = 'Saturday'
                   or
                   convert(varchar(10), datename(dw, @mydate)) = 'Sunday'
                  )

--select @mydate, @if_weekend, @if_date_is_Holiday

--Is a Holiday and not a weekend
if @if_date_is_Holiday is not null and @if_weekend is null
    begin
        if @if_weekend = 'Friday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 3, @mydate)) is null
                    begin
                        select dateadd(day, 3, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 4, @mydate)
                    end
            end
        else
            begin
                select dateadd(day, 1, @mydate)
            end
    end
--I think this is the same as "not a holiday and is a weekend logic"
--Is a Holiday and a weekend
else if @if_date_is_Holiday is not null and @if_weekend is not null
    begin
        if @if_weekend = 'Saturday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 2, @mydate)) is null
                    begin
                        select dateadd(day, 2, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 3, @mydate)
                    end
            end
        else if @if_weekend = 'Sunday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 1, @mydate)) is null
                    begin
                        select dateadd(day, 1, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 2, @mydate)
                    end
            end
    end
--Is not a Holiday and not a weekend
else if @if_date_is_Holiday is null and @if_weekend is null
    begin
        select @mydate
    end
--Is not a Holiday but is a weekend
else if @if_date_is_Holiday is null and @if_weekend is not null
    begin
            if @if_weekend = 'Saturday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 2, @mydate)) is null
                    begin
                        select dateadd(day, 2, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 3, @mydate)
                    end
            end
        else if @if_weekend = 'Sunday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 1, @mydate)) is null
                    begin
                        select dateadd(day, 1, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 2, @mydate)
                    end
            end
    end
</code>```

The query works fine to return one value. But what if I wanted to return the next 3 dates? i.e. If today's date is given (11/16) it would return 11/20, 11/22 and 11/24 (again, dates are inclusive). I am using sql-server 2014. Thanks in advance.

Example:

If I do set @incoming_date = '2017-11-16'

It will return the date 2017-11-20

Which is correct, but I would like to include the next 3 inclusive dates so it would return:

```<code>2017-11-20
2017-11-22
2017-11-24
</code>```

Or if I do set @incoming_date = '2017-11-21'

It currently returns 2017-11-24 (which is correct because the 23rd is Thanksgiving)

What I would like it to return:

```<code>2017-11-24
2017-11-27
2017-11-29
</code>```

答:
Place the query you've provided in your question into a stored procedure or function. For example:

```<code>dbo.ProcedureThatReturnsNextBusinessDay(@BaseDate DateTime, @Result DATETIME OUTPUT)
</code>```

Then call this for every date you'd like to retrieve.  In your question you stated you wanted the next 3 dates:

```<code>DECLARE @BaseDate DATETIME = '11/20/2017',
        @DateOne DATETIME,
        @DateTwo DATETIME,
        @DateThree DATETIME;

EXEC dbo.ProcedureThatReturnsNextBusinessDay @BaseDate, @DateOne OUTPUT
EXEC dbo.ProcedureThatReturnsNextBusinessDay @DateOne, @DateTwo OUTPUT
EXEC dbo.ProcedureThatReturnsNextBusinessDay @DateTwo , @DateThree OUTPUT
</code>```

Now the three dates you wanted exist in variables @DateOne, @DateTwo and @DateThree.

Body:
REXTESTER Sample

The query I have below returns the date 3 days later from the given variable @incoming_date. The catch is that the returned date cannot be a weekend or one of the ten federal holidays. For example, if today's date (11/16/2017) was given then it would return 11/20/2017. If the 20th was a federal holiday it would return the 21st. Or if 11/20 is given, 11/22nd is returned (today is inclusive). To determine if it is a holiday, I put the list of federal holidays in a table called TEST_Holiday_dates in a column called Holiday_Date.

declare @incoming_date date
declare @mydate date
declare @if_date_is_Holiday date
declare @if_weekend varchar(10)

set @incoming_date = '2018-01-11' --change this date to test
set @mydate = dateadd(day, 2, @incoming_date)

set @if_date_is_Holiday = (
                           select Holiday_Date
                           from TEST_Holiday_Dates
                           where Holiday_Date = @mydate
                          )
set @if_weekend = (
                   select convert(varchar(10), datename(dw, @mydate))
                   where
                   convert(varchar(10), datename(dw, @mydate)) = 'Saturday'
                   or
                   convert(varchar(10), datename(dw, @mydate)) = 'Sunday'
                  )

--select @mydate, @if_weekend, @if_date_is_Holiday

--Is a Holiday and not a weekend
if @if_date_is_Holiday is not null and @if_weekend is null
    begin
        if @if_weekend = 'Friday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 3, @mydate)) is null
                    begin
                        select dateadd(day, 3, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 4, @mydate)
                    end
            end
        else
            begin
                select dateadd(day, 1, @mydate)
            end
    end
--I think this is the same as "not a holiday and is a weekend logic"
--Is a Holiday and a weekend
else if @if_date_is_Holiday is not null and @if_weekend is not null
    begin
        if @if_weekend = 'Saturday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 2, @mydate)) is null
                    begin
                        select dateadd(day, 2, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 3, @mydate)
                    end
            end
        else if @if_weekend = 'Sunday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 1, @mydate)) is null
                    begin
                        select dateadd(day, 1, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 2, @mydate)
                    end
            end
    end
--Is not a Holiday and not a weekend
else if @if_date_is_Holiday is null and @if_weekend is null
    begin
        select @mydate
    end
--Is not a Holiday but is a weekend
else if @if_date_is_Holiday is null and @if_weekend is not null
    begin
            if @if_weekend = 'Saturday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 2, @mydate)) is null
                    begin
                        select dateadd(day, 2, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 3, @mydate)
                    end
            end
        else if @if_weekend = 'Sunday'
            begin
                if (select Holiday_Date from TEST_Holiday_Dates where Holiday_Date = dateadd(day, 1, @mydate)) is null
                    begin
                        select dateadd(day, 1, @mydate)
                    end
                else
                    begin
                        select dateadd(day, 2, @mydate)
                    end
            end
    end

The query works fine to return one value. But what if I wanted to return the next 3 dates? i.e. If today's date is given (11/16) it would return 11/20, 11/22 and 11/24 (again, dates are inclusive). I am using sql-server 2014. Thanks in advance.

Example:

If I do set @incoming_date = '2017-11-16'

It will return the date 2017-11-20

Which is correct, but I would like to include the next 3 inclusive dates so it would return:

2017-11-20
2017-11-22
2017-11-24

Or if I do set @incoming_date = '2017-11-21'

It currently returns 2017-11-24 (which is correct because the 23rd is Thanksgiving)

What I would like it to return:

2017-11-24
2017-11-27
2017-11-29

Body:
Place the query you've provided in your question into a stored procedure or function. For example:

dbo.ProcedureThatReturnsNextBusinessDay(@BaseDate DateTime, @Result DATETIME OUTPUT)

Then call this for every date you'd like to retrieve.  In your question you stated you wanted the next 3 dates:

DECLARE @BaseDate DATETIME = '11/20/2017',
        @DateOne DATETIME,
        @DateTwo DATETIME,
        @DateThree DATETIME;

EXEC dbo.ProcedureThatReturnsNextBusinessDay @BaseDate, @DateOne OUTPUT
EXEC dbo.ProcedureThatReturnsNextBusinessDay @DateOne, @DateTwo OUTPUT
EXEC dbo.ProcedureThatReturnsNextBusinessDay @DateTwo , @DateThree OUTPUT

Now the three dates you wanted exist in variables @DateOne, @DateTwo and @DateThree.


问:
Why does SerializeJSON return an int with .0?
The following code:

```<code><cfscript>
struct = StructNew();
struct.x = 1;
struct.y = 2;
</cfscript>

<cfoutput>#SerializeJSON(struct)#</cfoutput>
</code>```

Results in the following output:

```<code>{"Y":2.0,"X":1.0}
</code>```

So my question is why does the .0 get added? and is there some way to remove it?

答:
Two ways to remove it:

```<code>NumberFormat(x, "9")
</code>```

<cfset x = 1.0>
<cfset y = x * 1>

Body:
The following code:

<cfscript>
struct = StructNew();
struct.x = 1;
struct.y = 2;
</cfscript>

<cfoutput>#SerializeJSON(struct)#</cfoutput>

Results in the following output:

{"Y":2.0,"X":1.0}

So my question is why does the .0 get added? and is there some way to remove it?

Body:
Two ways to remove it:

NumberFormat(x, "9")

<cfset x = 1.0>
<cfset y = x * 1> <!--- will convert to an int --->


问:
how can I see which queries have been sent to the ArangoDB server
I want to quickly gather all queries sent to my ArangoDB server from an application that uses the python-arangodb driver without digging through the source and without resorting to sniffing HTTP traffic to the REST API.

Isn't there some admin/audit log on the ArangoDB web UI which shows me what queries have been sent to the server?

Using 3.2.5 here.

答:
You can have all the queries sent to a log file from 3.x and up.

Start with option: --log.level queries=trace --log.output queries=file:///path/to/queries.log

From: https://docs.arangodb.com/devel/Manual/ReleaseNotes/NewFeatures30.html

Only other way is to implement the logging at the driver level, as far as I know.


问:
multidex error on android studio 3
Before upgrading to AS 3, I used multidex in my project just fine, after upgrading It started getting this error each time i try to run the app on a device or even generate an APK

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp;
  Error:com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp; Error:  at
  com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
  Error:    at
  com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
  Error:    at
  com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
  Error:    at
  com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
  Error:    at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
  Error:    at
  java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
  Error:    at
  java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
  Error:    at
  java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
  Error:    at
  java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
  Error:    at
  java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Please not that all i did was update AS and gradle plguin to 3.0.0. I tried going back to 2.3.3, but It tells me the project is incompatible.

Here is my Multidex code:

```<code>android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "net.mohammed.billmob"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
</code>```

and my application class:

```<code>public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    }

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}
</code>```

and these are the app dependencies:

```<code>dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:mediarouter-v7:26.1.0'

   // compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'

    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-perf:11.6.0'

    compile 'com.karumi:dexter:4.1.0'

    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    compile 'com.facebook.android:facebook-android-sdk:4.28.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    compile 'com.android.support:support-v4:26.1.0'

    compile 'com.android.support:multidex:1.0.1'
/*    compile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex-instrumentation:1.0.2'*/

    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0'
    testCompile 'junit:junit:4.12'
}
</code>```

答:
Try it:

1. Enable multiDex:

```<code>android {
    defaultConfig {
        ...
        multiDexEnabled true
    }
    ...
}
</code>```

More info:

https://developer.android.com/studio/build/multidex.html

Configure gradle plugin and gradle version:

```<code>//gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
//project build.gradle
classpath 'com.android.tools.build:gradle:3.0.0'
</code>```

More info:

https://developer.android.com/studio/releases/gradle-plugin.html

Title: multidex error on android studio 3

Body:
Before upgrading to AS 3, I used multidex in my project just fine, after upgrading It started getting this error each time i try to run the app on a device or even generate an APK

Error:Error converting bytecode to dex: Cause:
  com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp;
  Error:com.android.dex.DexException: Multiple dex files define
  Lcom/google/android/gms/auth/api/signin/internal/zzp; Error:  at
  com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
  Error:    at
  com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
  Error:    at
  com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
  Error:    at
  com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
  Error:    at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
  Error:    at
  com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
  Error:    at
  java.util.concurrent.ForkJoinTask$AdaptedCallable.exec(ForkJoinTask.java:1424)
  Error:    at
  java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:289)
  Error:    at
  java.util.concurrent.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1056)
  Error:    at
  java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1692)
  Error:    at
  java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:157)

Please not that all i did was update AS and gradle plguin to 3.0.0. I tried going back to 2.3.3, but It tells me the project is incompatible.

Here is my Multidex code:

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    defaultConfig {
        applicationId "net.mohammed.billmob"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

and my application class:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);

    }

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

and these are the app dependencies:

dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:mediarouter-v7:26.1.0'

   // compile 'com.google.android.gms:play-services:11.6.0'
    compile 'com.google.android.gms:play-services-location:11.6.0'

    compile 'com.google.firebase:firebase-core:11.6.0'
    compile 'com.google.firebase:firebase-crash:11.6.0'
    compile 'com.google.firebase:firebase-auth:11.6.0'
    compile 'com.google.firebase:firebase-messaging:11.6.0'
    compile 'com.google.firebase:firebase-database:11.6.0'
    compile 'com.google.firebase:firebase-perf:11.6.0'

    compile 'com.karumi:dexter:4.1.0'

    compile 'com.firebaseui:firebase-ui-auth:3.1.0'

    compile 'com.facebook.android:facebook-android-sdk:4.28.0'
    compile 'com.android.support:design:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    compile 'com.android.support:support-v4:26.1.0'

    compile 'com.android.support:multidex:1.0.1'
/*    compile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex:1.0.2'
    androidTestCompile 'com.android.support:multidex-instrumentation:1.0.2'*/

    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0'
    testCompile 'junit:junit:4.12'
}

Body:
Try it:

1. Enable multiDex:

android {
    defaultConfig {
        ...
        multiDexEnabled true
    }
    ...
}

More info:

https://developer.android.com/studio/build/multidex.html

Configure gradle plugin and gradle version:

//gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
//project build.gradle
classpath 'com.android.tools.build:gradle:3.0.0'

More info:

https://developer.android.com/studio/releases/gradle-plugin.html


问:
How to Auto increment column when using merge and in not matching case - SQL Server
Want to add a incremental number in MERGE when the NOT MATCHED case.

It only allows to write insert statements, I tried to set the value using the MAX() function too, but adds the same number to all the records.

What is expected

```<code>MERGE #targetTable AS [target]
USING #sourceTable AS [source] ON [target].key = [source].key

WHEN MATCHED
    UPDATE ROWS
WHEN NOT MATCHED THEN
   INSERT (id, Name)
   VALUES ([incremented_id], source.Name);
</code>```

Note : Table already have some records in it.

Any help would be appreciated

答:
Try to get max ID from the table and then add it to this parameter. With this select you will be creating a new id of every row that is inserted. Something like this should work</p>

```<code>     declare @root int = 64895
     WHEN MATCHED
     UPDATE ROWS
     WHEN NOT MATCHED THEN
     INSERT (id, Name)
     VALUES( ((@root - 1) + ROW_NUMBER() over(order by ID)), source.Name);
</code>```

Body:
Want to add a incremental number in MERGE when the NOT MATCHED case.

It only allows to write insert statements, I tried to set the value using the MAX() function too, but adds the same number to all the records.

What is expected

MERGE #targetTable AS [target]
USING #sourceTable AS [source] ON [target].key = [source].key

WHEN MATCHED
    UPDATE ROWS
WHEN NOT MATCHED THEN
   INSERT (id, Name)
   VALUES ([incremented_id], source.Name);

Note : Table already have some records in it.

Any help would be appreciated

Body:
Try to get max ID from the table and then add it to this parameter. With this select you will be creating a new id of every row that is inserted. Something like this should work

     declare @root int = 64895
     WHEN MATCHED
     UPDATE ROWS
     WHEN NOT MATCHED THEN
     INSERT (id, Name)
     VALUES( ((@root - 1) + ROW_NUMBER() over(order by ID)), source.Name);


问:
matplotlib strings as labels on x axis
I am building a small tool for data analysis and I have come to the point, where I have to plot the prepared data. The code before this produces the following two lists with equal length.

```<code>t11 = ['00', '01', '02', '03', '04', '05', '10', '11', '12', '13', '14', '15', '20', '21', '22', '23', '24', '25', '30', '31', '32', '33', '34', '35', '40', '41', '42', '43', '44', '45', '50', '51', '52', '53', '54', '55']

t12 = [173, 135, 141, 148, 140, 149, 152, 178, 135, 96, 109, 164, 137, 152, 172, 149, 93, 78, 116, 81, 149, 202, 172, 99, 134, 85, 104, 172, 177, 150, 130, 131, 111, 99, 143, 194]
</code>```

Based on this, I want to built a histogram with matplotlib.plt.hist. However, there are a couple of problems:
 1. t11[x] and t12[x] are connected for all x. Where t11[x] is actually a string. It represents a certain detector combination. For example: '01' tells that the detection was made in the 0th segment of the first detector, and 1st segment of the second detector. My goal is to have each entry from t11 as a labeled point on the x axis. The t12 entry is going to define the hight of the bar above the t11 entry (on a logarithmic y axis)

How does one configure such an x axis?
 2. This is all very new to me. I could not find anything related in the documentation. Most probably because I did not know what to search for. SO: Is there an "official" name for what I am trying to achieve. This would also help me alot.

答:
Firstly you need to access the axis object:

```<code>fig, ax = plt.subplots(1,1)
</code>```

then:

```<code>ax.set_yticks([x for x in range(-10,11)])
ax.set_yticklabels( ['{0:2d}'.format(abs(x)) for x in range(-10, 11)])
</code>```

Title: matplotlib strings as labels on x axis

Body:
I am building a small tool for data analysis and I have come to the point, where I have to plot the prepared data. The code before this produces the following two lists with equal length.

t11 = ['00', '01', '02', '03', '04', '05', '10', '11', '12', '13', '14', '15', '20', '21', '22', '23', '24', '25', '30', '31', '32', '33', '34', '35', '40', '41', '42', '43', '44', '45', '50', '51', '52', '53', '54', '55']

t12 = [173, 135, 141, 148, 140, 149, 152, 178, 135, 96, 109, 164, 137, 152, 172, 149, 93, 78, 116, 81, 149, 202, 172, 99, 134, 85, 104, 172, 177, 150, 130, 131, 111, 99, 143, 194]

Based on this, I want to built a histogram with matplotlib.plt.hist. However, there are a couple of problems:
 1. t11[x] and t12[x] are connected for all x. Where t11[x] is actually a string. It represents a certain detector combination. For example: '01' tells that the detection was made in the 0th segment of the first detector, and 1st segment of the second detector. My goal is to have each entry from t11 as a labeled point on the x axis. The t12 entry is going to define the hight of the bar above the t11 entry (on a logarithmic y axis)

How does one configure such an x axis?
 2. This is all very new to me. I could not find anything related in the documentation. Most probably because I did not know what to search for. SO: Is there an "official" name for what I am trying to achieve. This would also help me alot.

Body:
Firstly you need to access the axis object:

fig, ax = plt.subplots(1,1)

then:

ax.set_yticks([x for x in range(-10,11)])
ax.set_yticklabels( ['{0:2d}'.format(abs(x)) for x in range(-10, 11)])


问:
How do I perform segue AFTER the sound has stopped playing
I have made a custom LaunchScreen in the Main.Storyboard to make it seem that a sound is actually coming from the LaunchScreen. The sound works fine and the segue to the next view controller as well. The only problem is that the segue happens before the sound has stopped playing. I would like the sound to complete before making the segue. Logically, it should work since the performSegue is directly after the .play(). But it seems that the two happens simultaneously. Here's my code:

```<code> super.viewDidLoad()

    //PLAY SOUND CLIP//
    let musicFile = Bundle.main.path(forResource: "fanfare", ofType: ".mp3")
    do {
        try musicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
    } catch { print("ERROR PLAYING MUSIC")}

            musicSound.play() //WORKS
    //

    DispatchQueue.main.async() {
        self.performSegue(withIdentifier: "myLaunchSegue", sender: self) //WORKS
    }
</code>```

I have tried to add:

```<code>perform(Selector(("showNavController")), with: self, afterDelay: 3)
</code>```

where "showNavController" simply is the segue:

```<code> func showNavController() {
    performSegue(withIdentifier: "myLaunchSegue", sender: nil)
}
</code>```

but the program crashes with the error "uncaught exception.... ....unrecognized selector sent to instance"

I have also tried to add a boolean to keep the program from progressing until the sound has played, but didn't get it to work. Any ideas?

//////////////////////////
Update:
Trying Russels answer, but have a few questions. Setting AVAudioPlayer as delegate, does that mean setting it next to the class like this:

```<code>class MyLaunchViewController: UIViewController, AVAudioPlayer { ...
</code>```

Also, how do I call the function audioPlayerDidFinishPlaying? Like so:

```<code>audioPlayerDidFinishPlaying(musicSound, successfully: true)
</code>```

I'll post the whole code block. Makes it easier to understand...

```<code>import UIKit
</code>```

import AVFoundation //FOR SOUND

class MyLaunchViewController: UIViewController, AVAudioPlayer {
    var musicSound: AVAudioPlayer = AVAudioPlayer() //FOR SOUND

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

    //PLAY SOUND CLIP//
    let musicFile = Bundle.main.path(forResource: "fanfare", ofType: ".mp3")
    do {
        try musicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
    } catch { print("ERROR PLAYING MUSIC")}

            musicSound.play() //WORKS
    //
    audioPlayerDidFinishPlaying(musicSound, successfully: true)
}

optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    DispatchQueue.main.async() {
        self.performSegue(withIdentifier: "myLaunchSegue", sender: self)
    }
}
</code>```

I get an error when writing AVAudioPlayer in the class (perhaps I misunderstood what I was supposed to do?). It says I have multiple inheritances. Also, it doesn't want me to set the new function as optional, as its only for protocol members. Finally, If I correct the errors and run the program, the next segue runs before the sound has finished playing... :( sad panda.

答:
You need to make your LaunchScreen an AVAudioPlayerDelegate, and then use the audioPlayerDidFinishPlaying callback.  Here's all you need in the first controller

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate
{
    var musicSound: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        //PLAY SOUND CLIP//
        let musicFile = Bundle.main.path(forResource: "sound", ofType: ".wav")
        do {
            try musicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
        } catch { print("ERROR PLAYING MUSIC")}

        musicSound?.delegate = self
        musicSound!.play() //WORKS
        print("Next line after play")
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        DispatchQueue.main.async() {
            print("audioPlayerDidFinishPlaying")
            self.performSegue(withIdentifier: "myLaunchSegue", sender: self)
        }
    }
}
</code>```

You can get more details here https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate/1389160-audioplayerdidfinishplaying

Body:
I have made a custom LaunchScreen in the Main.Storyboard to make it seem that a sound is actually coming from the LaunchScreen. The sound works fine and the segue to the next view controller as well. The only problem is that the segue happens before the sound has stopped playing. I would like the sound to complete before making the segue. Logically, it should work since the performSegue is directly after the .play(). But it seems that the two happens simultaneously. Here's my code:

 super.viewDidLoad()

    //PLAY SOUND CLIP//
    let musicFile = Bundle.main.path(forResource: "fanfare", ofType: ".mp3")
    do {
        try musicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
    } catch { print("ERROR PLAYING MUSIC")}

            musicSound.play() //WORKS
    //

    DispatchQueue.main.async() {
        self.performSegue(withIdentifier: "myLaunchSegue", sender: self) //WORKS
    }

I have tried to add:

perform(Selector(("showNavController")), with: self, afterDelay: 3)

where "showNavController" simply is the segue:

 func showNavController() {
    performSegue(withIdentifier: "myLaunchSegue", sender: nil)
}

but the program crashes with the error "uncaught exception.... ....unrecognized selector sent to instance"

I have also tried to add a boolean to keep the program from progressing until the sound has played, but didn't get it to work. Any ideas?

//////////////////////////
Update:
Trying Russels answer, but have a few questions. Setting AVAudioPlayer as delegate, does that mean setting it next to the class like this:

class MyLaunchViewController: UIViewController, AVAudioPlayer { ...

Also, how do I call the function audioPlayerDidFinishPlaying? Like so:

audioPlayerDidFinishPlaying(musicSound, successfully: true)

I'll post the whole code block. Makes it easier to understand...

import UIKit

import AVFoundation //FOR SOUND

class MyLaunchViewController: UIViewController, AVAudioPlayer {
    var musicSound: AVAudioPlayer = AVAudioPlayer() //FOR SOUND

override func viewDidLoad() {
    super.viewDidLoad()

    //PLAY SOUND CLIP//
    let musicFile = Bundle.main.path(forResource: "fanfare", ofType: ".mp3")
    do {
        try musicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
    } catch { print("ERROR PLAYING MUSIC")}

            musicSound.play() //WORKS
    //
    audioPlayerDidFinishPlaying(musicSound, successfully: true)
}

optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    DispatchQueue.main.async() {
        self.performSegue(withIdentifier: "myLaunchSegue", sender: self)
    }
}

I get an error when writing AVAudioPlayer in the class (perhaps I misunderstood what I was supposed to do?). It says I have multiple inheritances. Also, it doesn't want me to set the new function as optional, as its only for protocol members. Finally, If I correct the errors and run the program, the next segue runs before the sound has finished playing... :( sad panda.

Body:
You need to make your LaunchScreen an AVAudioPlayerDelegate, and then use the audioPlayerDidFinishPlaying callback.  Here's all you need in the first controller

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate
{
    var musicSound: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        //PLAY SOUND CLIP//
        let musicFile = Bundle.main.path(forResource: "sound", ofType: ".wav")
        do {
            try musicSound = AVAudioPlayer(contentsOf: URL (fileURLWithPath: musicFile!))
        } catch { print("ERROR PLAYING MUSIC")}

        musicSound?.delegate = self
        musicSound!.play() //WORKS
        print("Next line after play")
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        DispatchQueue.main.async() {
            print("audioPlayerDidFinishPlaying")
            self.performSegue(withIdentifier: "myLaunchSegue", sender: self)
        }
    }
}

You can get more details here https://developer.apple.com/documentation/avfoundation/avaudioplayerdelegate/1389160-audioplayerdidfinishplaying


问:
Django - Model.py
Just a simple question.

After I connect my django app to a remote database, I don't need to use Model.py to create tables in the database, then what is the function for Model.py at that moment?

答:
If you want to use the Django ORM, you'll need to create models in the models.py file that match your remote database.  If you don't want django creating or deleting tables on this DB, the managed=False option needs to be set for each model.
https://docs.djangoproject.com/en/1.11/ref/models/options/#managed</p>

Title: Django - Model.py


问:
C# Create an instance of a class from string
I am new in C# and I want to create an instance for MyTestClass in runtime. How can I do it ?

```<code>public class MyTestClass
{
    public int Value { get; set; }

    public MyTestClass()
    {
        Value = 5;
    }
}
</code>```

EDIT:
I just want to create an instance of MyTestClass from string variable like

```<code>string classInstance = "MyTestClass"
</code>```

I couldn't explain completely at first time, sorry for this.

答:
You can create a new instance in runtime using Activator class. Like this;

```<code>var instance = (MyTestClass)Activator.CreateInstance(typeof(MyTestClass));
</code>```

Body:
I am new in C# and I want to create an instance for MyTestClass in runtime. How can I do it ?

public class MyTestClass
{
    public int Value { get; set; }

    public MyTestClass()
    {
        Value = 5;
    }
}

EDIT:
I just want to create an instance of MyTestClass from string variable like

string classInstance = "MyTestClass"

I couldn't explain completely at first time, sorry for this.

Body:
You can create a new instance in runtime using Activator class. Like this;

var instance = (MyTestClass)Activator.CreateInstance(typeof(MyTestClass));


问:
javascript counter using for loop
I've created a simple counter using javascript but there is a problem Field "display" starts from 1, but it should start from 100 and goes low. The console logs shows values correctly from 100 to 1.
I have to use loops to do this tasks, so please not replace it using recursion :) Also the timeout is for sure does not equal to 100ms, it's more

function wyswietlLiczbe(j) {
    setTimeout(function() {
        document.getElementById("display").innerHTML = j;
    }, 100);
}

for (var i= 100; i > 0; i--){
    console.log(i)
    wyswietlLiczbe(i);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="display"></p></code>```

答:
you can use setInterval instead</p>

```<code>function wyswietlLiczbe(j) {
    x = setInterval(function() {
        if(j==0) clearInterval(x);
      document.getElementById("display").innerHTML = j--;
    }, 100);
}
wyswietlLiczbe(100);
</code>```

Title: javascript counter using for loop

Body:
you can use setInterval instead

function wyswietlLiczbe(j) {
    x = setInterval(function() {
        if(j==0) clearInterval(x);
      document.getElementById("display").innerHTML = j--;
    }, 100);
}
wyswietlLiczbe(100);


问:
How to debug JWT Bearer Error "invalid_token"
I'm trying to secure an existing AspNet Core 2.0 / angular 4 app using jwt. I'm using angular2-jwt for the client part and it works just fine. However when it comes to my WebApi, my token is always rejected(using AuthHttp from angular2-jwt to launch my requests or even with postman). The only response I get is 401 Bearer error="invalid_token".  I've checked it with the jwt.io chrome extension and it seems just fine(signature, audience, issuer). I can't find anything in the IIS logs either as to why it is deemed invalid. So my question is how can I get more information on what is wrong with the token ?
Any help will be much appreciated.

For reference here's my startup.cs

```<code>public class Startup
  {

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseIISIntegration()
      .UseStartup<Startup>()
      .Build();

  host.Run();
}
public Startup(IHostingEnvironment env)
{
  var builder = new ConfigurationBuilder()
      .SetBasePath(env.ContentRootPath)
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      .AddEnvironmentVariables();
  Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

  IConfigurationSection jwtConf = this.Configuration.GetSection("jwt");

  services.Configure<Controls.JWTConf>(Configuration.GetSection("jwt"));

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
       options.TokenValidationParameters =
                       new TokenValidationParameters
                       {
                         ValidateIssuer = true,
                         ValidateAudience = true,
                         ValidateLifetime = true,
                         ValidateIssuerSigningKey = true,
                         ValidIssuer = jwtConf.GetValue<string>("issuer"),
                         ValidAudience = jwtConf.GetValue<string>("audience"),
                         IssuerSigningKey = Security.JwtSecurityKey.Create(jwtConf.GetValue<string>("keyBase"))
                       };
     });

  services.AddMvc(
          config =>
          {
            var policy = new AuthorizationPolicyBuilder()
                             .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                             .RequireClaim(ClaimTypes.Name)
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
          }
    ).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

  services.AddNodeServices();

  string conn = this.Configuration.GetConnectionString("optimumDB");

  services.AddDbContext<TracDbContext>(options =>
      options.UseSqlServer(conn));

  // Register the Swagger generator, defining one or more Swagger documents
  services.AddSwaggerGen(c =>
  {
    c.SwaggerDoc("v1", new Info { Title = "Angular 4.0 Universal & ASP.NET Core advanced starter-kit web API", Version = "v1" });
  });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TracDbContext context)
{
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseStaticFiles();

  app.UseAuthentication();

  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
    {
      HotModuleReplacement = true,
      HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
    });
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.

    app.MapWhen(x => !x.Request.Path.Value.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase), builder =>
    {
      builder.UseMvc(routes =>
      {
        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
      });
    });
  }
  else
  {
    app.UseMvc(routes =>
    {
      routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");

      routes.MapRoute(
       "Sitemap",
       "sitemap.xml",
       new { controller = "Home", action = "SitemapXml" });

      routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });

    });
    app.UseExceptionHandler("/Home/Error");

  }
}

  }
</code>```

My token generating controller

```<code>  [Route("api/token")]
  [AllowAnonymous]
  public class TokenController : Controller
  {

private IOptions<JWTConf> jwt;

public TokenController(IOptions<JWTConf> jwtConf)
{
  this.jwt = jwtConf;
}

[HttpPost]
public IActionResult Create([FromBody]string userCode)
{
  Model.Entities.Utilisateur user = new Model.Entities.Utilisateur { ID_UTILISATEUR = 6 };

  JwtToken token = new JwtTokenBuilder()
                      .AddSecurityKey(JwtSecurityKey.Create(this.jwt.Value.keyBase))
                      .AddSubject("User")
                      .AddIssuer(this.jwt.Value.issuer)
                      .AddAudience(this.jwt.Value.audience)
                      .AddClaim(ClaimTypes.Name,user.ID_UTILISATEUR.ToString())
                      .AddExpiry(1440)
                      .Build();

  var tok = new { token = token.Value };

  //return Ok(token);
  return Ok(JsonConvert.SerializeObject(tok));
}
  }
</code>```

And finally the controller that rejects the token :

```<code>  [Produces("application/json")]
  public class JobsController : BaseController
  {
public JobsController(IConfiguration config, TracDbContext db) : base(config, db)
{

}

// GET: api/Jobs
[HttpGet]
[Route("api/Jobs")]
public IEnumerable<Departement> Get()
{
  return new GroupedJobs(Db.GetJobs().ToList());
}

[HttpGet]
[Route("api/Jobs/{id}")]
public JOB_CLIENT Get(int id)
{
  return Db.GetDetailsJob(id);
}

 }
</code>```

答:
Found the problem ... turns out I was storing my token with quotes around it. So The authorization header that was being sent looked like this

Bearer "TOKEN"

instead of

Bearer TOKEN

Being new to the whole thing I tought the quotes were being added by the AuthHtpp and were part of the protocol.

Body:
I'm trying to secure an existing AspNet Core 2.0 / angular 4 app using jwt. I'm using angular2-jwt for the client part and it works just fine. However when it comes to my WebApi, my token is always rejected(using AuthHttp from angular2-jwt to launch my requests or even with postman). The only response I get is 401 Bearer error="invalid_token".  I've checked it with the jwt.io chrome extension and it seems just fine(signature, audience, issuer). I can't find anything in the IIS logs either as to why it is deemed invalid. So my question is how can I get more information on what is wrong with the token ?
Any help will be much appreciated.

For reference here's my startup.cs

public class Startup
  {

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseIISIntegration()
      .UseStartup<Startup>()
      .Build();

  host.Run();
}
public Startup(IHostingEnvironment env)
{
  var builder = new ConfigurationBuilder()
      .SetBasePath(env.ContentRootPath)
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      .AddEnvironmentVariables();
  Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{

  IConfigurationSection jwtConf = this.Configuration.GetSection("jwt");

  services.Configure<Controls.JWTConf>(Configuration.GetSection("jwt"));

  services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
     .AddJwtBearer(options =>
     {
       options.TokenValidationParameters =
                       new TokenValidationParameters
                       {
                         ValidateIssuer = true,
                         ValidateAudience = true,
                         ValidateLifetime = true,
                         ValidateIssuerSigningKey = true,
                         ValidIssuer = jwtConf.GetValue<string>("issuer"),
                         ValidAudience = jwtConf.GetValue<string>("audience"),
                         IssuerSigningKey = Security.JwtSecurityKey.Create(jwtConf.GetValue<string>("keyBase"))
                       };
     });

  services.AddMvc(
          config =>
          {
            var policy = new AuthorizationPolicyBuilder()
                             .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                             .RequireClaim(ClaimTypes.Name)
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
          }
    ).AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());

  services.AddNodeServices();

  string conn = this.Configuration.GetConnectionString("optimumDB");

  services.AddDbContext<TracDbContext>(options =>
      options.UseSqlServer(conn));

  // Register the Swagger generator, defining one or more Swagger documents
  services.AddSwaggerGen(c =>
  {
    c.SwaggerDoc("v1", new Info { Title = "Angular 4.0 Universal & ASP.NET Core advanced starter-kit web API", Version = "v1" });
  });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TracDbContext context)
{
  loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  loggerFactory.AddDebug();

  app.UseStaticFiles();

  app.UseAuthentication();

  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
    {
      HotModuleReplacement = true,
      HotModuleReplacementEndpoint = "/dist/__webpack_hmr"
    });
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.

    app.MapWhen(x => !x.Request.Path.Value.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase), builder =>
    {
      builder.UseMvc(routes =>
      {
        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
      });
    });
  }
  else
  {
    app.UseMvc(routes =>
    {
      routes.MapRoute(
       name: "default",
       template: "{controller=Home}/{action=Index}/{id?}");

      routes.MapRoute(
       "Sitemap",
       "sitemap.xml",
       new { controller = "Home", action = "SitemapXml" });

      routes.MapSpaFallbackRoute(
        name: "spa-fallback",
        defaults: new { controller = "Home", action = "Index" });

    });
    app.UseExceptionHandler("/Home/Error");

  }
}

  }

My token generating controller

  [Route("api/token")]
  [AllowAnonymous]
  public class TokenController : Controller
  {

private IOptions<JWTConf> jwt;

public TokenController(IOptions<JWTConf> jwtConf)
{
  this.jwt = jwtConf;
}

[HttpPost]
public IActionResult Create([FromBody]string userCode)
{
  Model.Entities.Utilisateur user = new Model.Entities.Utilisateur { ID_UTILISATEUR = 6 };

  JwtToken token = new JwtTokenBuilder()
                      .AddSecurityKey(JwtSecurityKey.Create(this.jwt.Value.keyBase))
                      .AddSubject("User")
                      .AddIssuer(this.jwt.Value.issuer)
                      .AddAudience(this.jwt.Value.audience)
                      .AddClaim(ClaimTypes.Name,user.ID_UTILISATEUR.ToString())
                      .AddExpiry(1440)
                      .Build();

  var tok = new { token = token.Value };

  //return Ok(token);
  return Ok(JsonConvert.SerializeObject(tok));
}
  }

And finally the controller that rejects the token :

  [Produces("application/json")]
  public class JobsController : BaseController
  {
public JobsController(IConfiguration config, TracDbContext db) : base(config, db)
{

}

// GET: api/Jobs
[HttpGet]
[Route("api/Jobs")]
public IEnumerable<Departement> Get()
{
  return new GroupedJobs(Db.GetJobs().ToList());
}

[HttpGet]
[Route("api/Jobs/{id}")]
public JOB_CLIENT Get(int id)
{
  return Db.GetDetailsJob(id);
}

 }


问:
android accessibility service is preferable or not for getting notifications?
I am bit confusion regarding Android accessibility services.

Android accessibility service is preferable or not for getting notifications?

答:
No, Accessibility Services are used to help visually impaired people.
To manage notifications refer the link below

https://developer.android.com/guide/topics/ui/notifiers/notifications.html


问:
ASP.NET: Error while accessing the JSON Webservice from server
I have a website where I am using the JSON webservice. I have uploaded my website on the server.

Problem:

When I try to access the webservice it gives me the error as shown in below screenshot. In the below screenshot MyServices is my webservice. MyServices.asmx is the name of the file that I am trying to access.

Troubleshooting that already has been done:

I tried cleaning the bin folder and rebuilding again. But it didn't work.

What could be wrong?

答:
This error might occur if you are using a Web Application type project (in contrast to Web Site) and you have put code in the App_Code special folder. This folder should be used only with WebSite project types. A Web Application is compiled meaning that all source code is precompiled into an assembly and placed into the bin folder. On the other hand App_Code is a special folder. ASP.NET automatically compiles dynamically everything in this folder when the first request arrives so you find yourself with two assemblies that contain the same class.

Visual Studio uses different icons to represent web site and web application which might help you find out which type you are using:


问:
How to add html title attribute to jquery ui date picker widget?
In an ASP.NET MVC 5 project,How do I add a html title attribute to jquery ui date picker widget? I have tried adding it directly to the HTML element and also using JQuery. I have also tried using .prop from one of the answers below.

HTML from the Index page

```<code><input class="form-control" type="text" id="datepicker1" title="Enter Date"/>
<input class="form-control" type="text" id="datepicker2"/>
<input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />
</code>```

Jquery from the _Layoyut.cshtml

```<code>$("#datepicker1").attr("title", "Enter Start Date");
$("#datepicker2").attr("title", "Enter End Date");
</code>```

_Layout.cshtml

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body id="bgrnd">
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink(" EDI", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Home" ? "active" : "")">
                    @Html.ActionLink("Home", "Index", "Home")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Error_Summaries" ? "active" : "")">
                    @Html.ActionLink("BOL-Errors", "Index", "Error_Summaries")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_TMS" ? "active" : "")">
                    @Html.ActionLink("BOL-", "Index", "web_BOL_Summary_TMS")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_Ext" ? "active" : "")">
                    @Html.ActionLink("BOL-Partners", "Index", "web_BOL_Summary_Ext")</li>
                    <li class="@(ViewContext.RouteData.Values["Controller"].ToString() == "Utilities" ? "active" : "")">
                    @Html.ActionLink("Utilities", "Index", "Utilities")</li>
                </ul>
                <p class="nav navbar-text navbar-right">@User.Identity.Name</p>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - Company Name</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/jqueryuicss")
    @RenderSection("scripts", required: false)

    @*Datepicker for BOL- Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_TMS")
    {
        <script>
            $(function ()
            {
                $('#datepicker1').prop('title', 'Enter Start Date');
                $("#datepicker2").prop("title", "Enter End Date");
                //$("#datepicker1").datepicker({});
                //$("#datepicker2").datepicker({});

            });

        </script>
    }

    @*Background picture for Home Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "Home")
    { <script>document.getElementById("bgrnd").className+="bgrnd"</script>
    }

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

Index.html

```<code>@{
    ViewBag.Title = "EDI_";

}
    <div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2>Bill of Ladings from  TMS</h2>
        </div>
    </div>
    <div class="row">
        <div class="col-md-4 text-center"></div>
        <div class="col-md-4 text-center">
            <ul class="list-group">
                <li class="list-group-item ">
                    <p class="h4">PD5200 Truck Loads Report</p>

                        @Html.ActionLink("This Week", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null) |
                        @Html.ActionLink("Last Week", "pd5200", "web_BOL_Summary_TMS", new { week = 0 }, null) <br />
                    <div class="h5">Enter Dates</div>
                    <div class="form-group-sm form-horizontal">
                        @using (Html.BeginForm("pd5200", "web_BOL_Summary_TMS", FormMethod.Post))                        {
                            <input class="form-control" type="text" id="datepicker1" title="Enter Date"/> <input class="form-control" type="text" id="datepicker2"/>
                            <input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />
                        }
                   </div>
</li>
                <li class="list-group-item">
                    <p class="h4">View  BOL</p>
                    <div class="form-group-sm form-horizontal">
                        @using (Html.BeginForm("ViewBol", "web_BOL_Summary_TMS"))
                        {
                            <input class="form-control" name="bolnumber" type="number" placeholder="Enter  BOL Number" title="Enter  BOL Number" />
                            <input id="btnViewBol" class="btn" type="submit" value="View" required="required" />
                        }
                    </div>
                </li>
                <li class="list-group-item">
                    <p class="h4">View Midnight Cut-offs</p>
                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                <span> | </span>
                            }
                        }

                    }
                </li>
                <li class="list-group-item">
                    <p class="h4">View Missing BOLS</p>
                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                <span> | </span>
                            }
                        }

                        @Html.ActionLink("Custom", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null) <span> | </span>
                        @Html.ActionLink("All", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null)
                    }
                </li>
            </ul>
        </div>
        <div class="col-md-4 text-center">
        </div>
    </div>
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

答:
If you are looking for a placeholder on for the datepicker input field you can just add the placeholder attribute: placeholder="Enter start date"

If you are looking to add text at the top of your datepicker you can implement the following:

```<code>$('#testID').datepicker().bind('click keyup', function() {
    if ($('#ui-datepicker-div:first').is('div'))
        $('#ui-datepicker-div').prepend('<p>Enter Start Date</p>');
});
</code>```

Body:
In an ASP.NET MVC 5 project,How do I add a html title attribute to jquery ui date picker widget? I have tried adding it directly to the HTML element and also using JQuery. I have also tried using .prop from one of the answers below.

HTML from the Index page

<input class="form-control" type="text" id="datepicker1" title="Enter Date"/>
<input class="form-control" type="text" id="datepicker2"/>
<input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />

Jquery from the _Layoyut.cshtml

$("#datepicker1").attr("title", "Enter Start Date");
$("#datepicker2").attr("title", "Enter End Date");

_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                @Html.ActionLink(" EDI", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

                    @Html.ActionLink("Home", "Index", "Home")

                    @Html.ActionLink("BOL-Errors", "Index", "Error_Summaries")

                    @Html.ActionLink("BOL-", "Index", "web_BOL_Summary_TMS")

                    @Html.ActionLink("BOL-Partners", "Index", "web_BOL_Summary_Ext")

                    @Html.ActionLink("Utilities", "Index", "Utilities")

@User.Identity.Name

        @RenderBody()

© @DateTime.Now.Year - Company Name

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/jqueryuicss")
    @RenderSection("scripts", required: false)

    @*Datepicker for BOL- Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "web_BOL_Summary_TMS")
    {

    }

    @*Background picture for Home Page*@
    @if (ViewContext.RouteData.Values["Controller"].ToString() == "Home")
    {
    }

Index.html

@{
    ViewBag.Title = "EDI_";

}

Bill of Ladings from  TMS

PD5200 Truck Loads Report

                        @Html.ActionLink("This Week", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null) |
                        @Html.ActionLink("Last Week", "pd5200", "web_BOL_Summary_TMS", new { week = 0 }, null)

Enter Dates

                        @using (Html.BeginForm("pd5200", "web_BOL_Summary_TMS", FormMethod.Post))                        {
                            <input class="form-control" type="text" id="datepicker1" title="Enter Date"/> <input class="form-control" type="text" id="datepicker2"/>
                            <input class="btn" id="sbmtCustomDates" type="submit" value="Submit" />
                        }

View  BOL

                        @using (Html.BeginForm("ViewBol", "web_BOL_Summary_TMS"))
                        {
                            <input class="form-control" name="bolnumber" type="number" placeholder="Enter  BOL Number" title="Enter  BOL Number" />
                            <input id="btnViewBol" class="btn" type="submit" value="View" required="required" />
                        }

View Midnight Cut-offs

                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                 |
                            }
                        }

                    }

View Missing BOLS

                    @using (Html.BeginForm("ViewMidnightCutOffs", "web_BOL_Summary_TMS"))
                    {
                        DateTime currentDate = DateTime.Today;
                        for (int i = 1; i <= 3; i++)
                        {
                            @Html.ActionLink(currentDate.AddDays(-i).ToShortDateString(), "ViewMidnightCutOffs", "web_BOL_Summary_TMS", new { dateToCheck = currentDate.AddDays(-i) }, null)

                            if (i < 4)
                            {
                                 |
                            }
                        }

                        @Html.ActionLink("Custom", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null)  |
                        @Html.ActionLink("All", "pd5200", "web_BOL_Summary_TMS", new { week = 1 }, null)
                    }

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Body:
If you are looking for a placeholder on for the datepicker input field you can just add the placeholder attribute: placeholder="Enter start date"

If you are looking to add text at the top of your datepicker you can implement the following:

$('#testID').datepicker().bind('click keyup', function() {
    if ($('#ui-datepicker-div:first').is('div'))
        $('#ui-datepicker-div').prepend('<p>Enter Start Date</p>');
});