问:
How to pass a full array in an array of pointers
I wrote a program that sorts the values of an array. It has 5 arrays,

```<code>    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };
</code>```

and an array of pointers that holds those 5 arrays,

```<code>int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };
</code>```

I want to sort the values of each array, but when I pass the arrays to the sorting function

```<code>sortArrValues(&pArr[i]);
</code>```

it sees the first index of each array (arr1,arr2...) as the element of that array (pArr[i]), so pArr[i] is (3,2,0,1,4).

But I want pArr[i] to be the full array it meant to be, so in the first iteration pArr[i] will be (3,9,6,7).

Notes: the first index of each array indicates the length of that array (not including that index).

The sorting will skip the first index.

There are two additional functions,they're not used (you can skip them).

Here's the full code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 5

void sortArrValues(int** arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(&pArr[i]);
    }

    //sortArrAdress(pArr);
    //printArr(pArr);

    return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int** arr)
{
    int tmp = 0;
    int i = 0;

    for (i = 1; i < *arr; i++)
    {
        if (*arr[i] > *arr[i+1])
        {
            tmp = *arr[i];
            *arr[i] = *arr[i + 1];
            *arr[i + 1] = tmp;
        }
    }
}
</code>```

答:
There is some errors in your code.

First, you don't need to send &pArr[i], pArr[i] is enough to order your arrays. then your void sortArrValues(int** arr) become void sortArrValues(int* arr) which is clearer to read.

Second, in your sortValues, you when you change a value, you should restart (I know that's not very optimized but if you would want to make something really faster, you should use a quick sort. with your code, { 4, 5, 6, 2, 1 } will become { 4 5 2 1 6 }.

So that's your code with the fixes:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 5

void sortArrValues(int* arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(pArr[i]);
    }

    //sortArrAdress(pArr);
    //printArr(pArr);

    for (int i = 0 ; i < LEN ; i++) {
        for (int j = 0 ; j < pArr[i][0] + 1 ; j++)
            printf("%d ", pArr[i][j]);
        printf("\n");
    }

    return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int* arr)
{
    int tmp = 0;
    int i = 0;

    for (i = 1; i < *arr; i++)
    {
        if (arr[i] > arr[i+1])
        {
            tmp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = tmp;
            i = 0;

        }
    }
}
</code>```

Body:
I wrote a program that sorts the values of an array. It has 5 arrays,

    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

and an array of pointers that holds those 5 arrays,

int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

I want to sort the values of each array, but when I pass the arrays to the sorting function

sortArrValues(&pArr[i]);

it sees the first index of each array (arr1,arr2...) as the element of that array (pArr[i]), so pArr[i] is (3,2,0,1,4).

But I want pArr[i] to be the full array it meant to be, so in the first iteration pArr[i] will be (3,9,6,7).

Notes: the first index of each array indicates the length of that array (not including that index).

The sorting will skip the first index.

There are two additional functions,they're not used (you can skip them).

Here's the full code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 5

void sortArrValues(int** arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(&pArr[i]);
    }

    //sortArrAdress(pArr);
    //printArr(pArr);

    return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int** arr)
{
    int tmp = 0;
    int i = 0;

    for (i = 1; i < *arr; i++)
    {
        if (*arr[i] > *arr[i+1])
        {
            tmp = *arr[i];
            *arr[i] = *arr[i + 1];
            *arr[i + 1] = tmp;
        }
    }
}

Body:
There is some errors in your code.

First, you don't need to send &pArr[i], pArr[i] is enough to order your arrays. then your void sortArrValues(int** arr) become void sortArrValues(int* arr) which is clearer to read.

Second, in your sortValues, you when you change a value, you should restart (I know that's not very optimized but if you would want to make something really faster, you should use a quick sort. with your code, { 4, 5, 6, 2, 1 } will become { 4 5 2 1 6 }.

So that's your code with the fixes:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LEN 5

void sortArrValues(int* arr);
void sortArrAdress(int* pArr);
void printArr(int * pArr);

int main()
{
    int arr1[] = { 3, 9, 6, 7 };
    int arr2[] = { 2, 5, 5 };
    int arr3[] = { 0 };
    int arr4[] = { 1, 6 };
    int arr5[] = { 4, 5, 6, 2, 1 };

    int* pArr[LEN] = { arr1, arr2, arr3, arr4, arr5 };

    int  i = 0;

    for (i = 0; i < LEN; i++)
    {
        sortArrValues(pArr[i]);
    }

    //sortArrAdress(pArr);
    //printArr(pArr);

    for (int i = 0 ; i < LEN ; i++) {
        for (int j = 0 ; j < pArr[i][0] + 1 ; j++)
            printf("%d ", pArr[i][j]);
        printf("\n");
    }

    return 0;
}
/*
this function will sort the given arrays' values.
in: array
out: none
*/
void sortArrValues(int* arr)
{
    int tmp = 0;
    int i = 0;

    for (i = 1; i < *arr; i++)
    {
        if (arr[i] > arr[i+1])
        {
            tmp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = tmp;
            i = 0;

        }
    }
}


来源: stackexchange

问:
How to get the correct device Id (shown in portal) from iOS App for Azure Mobile Engagement
Azure Mobile Engagement:
Device Id received from RegisteredForRemoteNotifications method is different than what it is show in portal.
I'm able to send notifications via DeviceId from Portal but this is not accessible in app.

```<code> public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
 {
     // Register device token on Engagement
     EngagementAgent.RegisterDeviceToken(deviceToken);
 }
</code>```

Notification is not sent to the to device id with the deviceToken.
Also if tried to addDevice on portal for testing then this deviceToken is not completely added, it gets trimmed.
e.g.

Device Id on Portal is - 9dfe6c8f70e8541e233d247475940558

Device Id from App is - 39955dbcf85ac8dc3f39c8f6302c5438cfe22711864314f4fe83951211c013c6

If I call REST API to get all device Ids from Engagement I get following where both Ids are present.

```<code>  {
      "value": [
    {
          "meta": {
            "lastSeen": 1490598143383,
            "firstSeen": 1490597807881,
            "lastLocation": 1490597810680,
            "lastInfo": 1490597808834,
            "nativePushEnabled": true
          },
          "appInfo": {
            "apsEnabledNotifications": "7",
            "DeviceID": "39955dbcf85ac8dc3f39c8f6302c5438cfe22711864314f4fe83951211c013c6"
          },
          "deviceId": "9dfe6c8f70e8541e233d247475940558"
        }
    ]
    }
</code>```

My Question is how to get the correct device Id (shown in portal) from iOS App?

答:
Just for your information, be aware that Microsoft just announced that they will shut down Azure Mobile Engagement next year. SDK won't be updated to support iOS 10 (from last September) or future version. You should consider to switch from AzME and look for alternatives.

https://azure.microsoft.com/en-us/services/mobile-engagement/

I'm the Co-founder of https://batch.com, we develop a solution for mobile engagement through push notifications and in-app messaging. And we do support Custom user or device identifiers if that's a requirement for you.

ContentLicense: CC BY-SA 3.0

Body:
Azure Mobile Engagement:
Device Id received from RegisteredForRemoteNotifications method is different than what it is show in portal.
I'm able to send notifications via DeviceId from Portal but this is not accessible in app.

 public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
 {
     // Register device token on Engagement
     EngagementAgent.RegisterDeviceToken(deviceToken);
 }

Notification is not sent to the to device id with the deviceToken.
Also if tried to addDevice on portal for testing then this deviceToken is not completely added, it gets trimmed.
e.g.

Device Id on Portal is - 9dfe6c8f70e8541e233d247475940558

Device Id from App is - 39955dbcf85ac8dc3f39c8f6302c5438cfe22711864314f4fe83951211c013c6

If I call REST API to get all device Ids from Engagement I get following where both Ids are present.

  {
      "value": [
    {
          "meta": {
            "lastSeen": 1490598143383,
            "firstSeen": 1490597807881,
            "lastLocation": 1490597810680,
            "lastInfo": 1490597808834,
            "nativePushEnabled": true
          },
          "appInfo": {
            "apsEnabledNotifications": "7",
            "DeviceID": "39955dbcf85ac8dc3f39c8f6302c5438cfe22711864314f4fe83951211c013c6"
          },
          "deviceId": "9dfe6c8f70e8541e233d247475940558"
        }
    ]
    }

My Question is how to get the correct device Id (shown in portal) from iOS App?


问:
How to adding space in middle of alphanumeric string?
I have a string like cs123 and I want to add space in the middle alphanumeric values in PHP. Is there any function for doing this specifically in PHP?

I have cs123 and I want cs 123.

答:
try this:

$array = preg_split('#(?<=[a-z])(?=\d)#i', "cs123")

it will check every character in given string and split it at position where 'before' element is a letter

(?<=[a-z])

and 'after' element is a digit

(?=\d)

then you can just implode this array with a ' ' as a $glue parameter.

ContentLicense: CC BY-SA 4.0


问:
Deep link into macOS app is not recognized
I'm trying to implement a deep link into an macOS application, but nothing seems to work.

So far, my AppDelegate.swift contains the following

```<code>func application(app: NSApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    print("opened by link");
    return true
}
</code>```

I also configured the info.plist with URLSchemes beeing my bundle identifier and URLIdentifier beeing simply zst

In a simple html-file I use the following code to test the deep link

```<code><a href="zst://test/link">Test</a>
</code>```

My app gets opened (or becomes active when already running), but the print statement is not executed.

What am I doing wrong here?

答:
Thanks to @Ssswift I found a solution.
Used this code:
How do you set your Cocoa application as the default web browser?

and converted it to swift with: https://objectivec2swift.com

works with Swift 3

in AppDelegate.swift added these lines

```<code>func applicationDidFinishLaunching(_ aNotification: Notification) {
    var em = NSAppleEventManager.shared()
    em.setEventHandler(self, andSelector: #selector(self.getUrl(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}

func getUrl(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
    // Get the URL
    var urlStr: String = event.paramDescriptor(forKeyword: keyDirectObject)!.stringValue!
    print(urlStr);

}
</code>```

Body:
I'm trying to implement a deep link into an macOS application, but nothing seems to work.

So far, my AppDelegate.swift contains the following

func application(app: NSApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
    print("opened by link");
    return true
}

I also configured the info.plist with URLSchemes beeing my bundle identifier and URLIdentifier beeing simply zst

In a simple html-file I use the following code to test the deep link

Test

My app gets opened (or becomes active when already running), but the print statement is not executed.

What am I doing wrong here?

Body:
Thanks to @Ssswift I found a solution.
Used this code:
How do you set your Cocoa application as the default web browser?

and converted it to swift with: https://objectivec2swift.com

works with Swift 3

in AppDelegate.swift added these lines

func applicationDidFinishLaunching(_ aNotification: Notification) {
    var em = NSAppleEventManager.shared()
    em.setEventHandler(self, andSelector: #selector(self.getUrl(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}

func getUrl(_ event: NSAppleEventDescriptor, withReplyEvent replyEvent: NSAppleEventDescriptor) {
    // Get the URL
    var urlStr: String = event.paramDescriptor(forKeyword: keyDirectObject)!.stringValue!
    print(urlStr);

}


问:
How do I limit the dragging area for image views
My first post and I am currently making an app in Xcode 8.1 using Swift 3

I have 9 images that I have made draggable with touchesBegan and touchesMoved functions.

However they are able to be dragged ANYWHERE on the screen and this can cause them to cover up other images I have. I would like to limit their movement by setting a boundary for them so that even when the user tries to drag the images out of that boundary they wont be able to.

I have created this code in draggedimageview.swift this allows the Image views to be dragged.

I have been spending a long time trying to figure out how to do this and if anyone can help I would appreciate it.

Thanks...

```<code>import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}
</code>```

答:
Try to define your "allowed area" in a rect, such as:

```<code>import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        // This is the area in which the dragging is allowed
        let coolArea = CGRect(x: 0, y: 0, width: 100, height: 100)

        let newCenter = CGPoint(x: self.center.x+dx, y: self.center.y+dy)

        // If the allowed area contains the new point, we can assign it
        if coolArea.contains(newCenter) {
            self.center = newCenter
        }
        // else {
        //    print("Out of boundaries!")
        // }

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}
</code>```

You may want to change the code if you want something different to happen when user is dragging out of the bounds.

Body:
My first post and I am currently making an app in Xcode 8.1 using Swift 3

I have 9 images that I have made draggable with touchesBegan and touchesMoved functions.

However they are able to be dragged ANYWHERE on the screen and this can cause them to cover up other images I have. I would like to limit their movement by setting a boundary for them so that even when the user tries to drag the images out of that boundary they wont be able to.

I have created this code in draggedimageview.swift this allows the Image views to be dragged.

I have been spending a long time trying to figure out how to do this and if anyone can help I would appreciate it.

Thanks...

import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}

Body:
Try to define your "allowed area" in a rect, such as:

import UIKit

class DraggedImageView: UIImageView {

    var startLocation: CGPoint?

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        startLocation = touches.first?.location(in: self)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        let currentLocation = touches.first?.location(in: self)
        let dx = currentLocation!.x - startLocation!.x
        let dy = currentLocation!.y - startLocation!.y

        // This is the area in which the dragging is allowed
        let coolArea = CGRect(x: 0, y: 0, width: 100, height: 100)

        let newCenter = CGPoint(x: self.center.x+dx, y: self.center.y+dy)

        // If the allowed area contains the new point, we can assign it
        if coolArea.contains(newCenter) {
            self.center = newCenter
        }
        // else {
        //    print("Out of boundaries!")
        // }

        self.center = CGPoint(x: self.center.x+dx, y: self.center.y+dy)
    }
}

You may want to change the code if you want something different to happen when user is dragging out of the bounds.


问:
Is there a reason to double parametrize generics in Java?
Is there any reason to do this:

```<code>List<Integer> integers = new ArrayList<Integer>();
</code>```

versus this:

```<code>List<Integer> integers = new ArrayList<>();
</code>```

I've seen the first usage a few times, and it seems to provide no benefit, which begs the question: why use it?

I understand that the diamond operator (<>) is necessary to differentiate between new LinkedList() and new LinkedList<>(), just to be clear.

答:
I've seen the first usage a few times, and it seems to provide no
  benefit, which begs the question: why use it?

<> operator has been introduced only in JDK1.7, so you might have seen a legacy code, which used new ArrayList<Integer>() (without <> operator)

Also, the support to the code (like <Integer>) without using <> operator still exists because of backward compatibility.

So, the answer is you will not use it if your project uses JDK1.7 or later.

Body:
Is there any reason to do this:

List<Integer> integers = new ArrayList<Integer>();

versus this:

List<Integer> integers = new ArrayList<>();

I've seen the first usage a few times, and it seems to provide no benefit, which begs the question: why use it?

I understand that the diamond operator (<>) is necessary to differentiate between new LinkedList() and new LinkedList<>(), just to be clear.


答: The first usage with the type redundantly stated was required before Java 7 when the type inferencing provided by the diamond syntax was introduced.</p>

Title: Is there a reason to double parametrize generics in Java?


问:
OpenTok appcelerator module using OpenTok CocoaPods
I am trying to create Appcelerator module for OpenTok using latest OpenTok module using cocoaPods. Module gets compiled successful and module is created. But now when I try to use it sample app it gives below error:

[ERROR] : ** BUILD FAILED ** [ERROR] : The following build commands failed: [ERROR] : Ld build/Products/Debug-iphonesimulator/SampleApp.app/SampleApp normal x86_64 [ERROR] : (1 failure)

When I open the xcode sample project it shows below error:

ld: framework not found OpenTok clang: error: linker command failed with exit code 1 (use -v to see invocation)

I have verified that the OpenTok framework exists in specific folder. I have properly set the below parameters in module.xcconfig file FRAMEWORK_SEARCH_PATHS= LD_RUNPATH_SEARCH_PATHS= OTHER_LDFLAGS=

Here is the module and sample code https://ufile.io/bbcbb

If somebody can point out what I am missing, would be great help.

答:
I don't believe you can use CocoaPods with a normal Appcelerator iOS module but it can be done in Titanium using Appcelerator Hyperloop.  Take a look at their documentation and let me know if you have any questions.  Thanks!

http://docs.appcelerator.com/platform/latest/#!/guide/iOS_Hyperloop_Programming_Guide-section-src-46253491_iOSHyperloopProgrammingGuide-CocoaPods


问:
Substitute everything but letters
I am trying to write a single line bash command that will replace every single not letter into a newline. (I am using bash)

Right now, I have this: tr ^[a-zA-Z]g '\n'

I have also tried tr [^a-zA-Z]g '\n' Both don't work.

I thought that the ^ character would have the regular expression match everything but a-z and A-Z, and thus turn all other characters into newlines, but instead it still jus turns a-z and A-Z into newlines, and keeps the other characters.

How can I make sure that I am using the ^ to reverse the regex, instead of anchor it to the beginning of the line?

Does anyone know the correct syntax? Or should I try using a different command? Thanks.

答:
sed approach(with BRE, Basic Regular Expression):

```<code>sed 's/[^a-zA-Z]/\n/g' testfile
</code>```

Title: Substitute everything but letters

Body:
sed approach(with BRE, Basic Regular Expression):

sed 's/[^a-zA-Z]/\n/g' testfile


问:
NullPointerException thrown when unit-testing a Play controller's action that processes a form
I encounter NullPointerException when testing an action that processes a form. There are two actions, one to display and one to process the form. Testing the first one is fine; however, testing the second one throws the exception. This only happens with unit-testing; the application works fine (i.e., via browser). I can't figure out what happens. Could anyone help me shed some light on it? The code I'm testing is as follows.

Scala: 2.11.8

SBT: 0.13.11

Play Framework: 2.5.2

build.sbt

```<code>lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
  "org.mockito" % "mockito-core" % "1.10.19" % Test,
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test
)
</code>```

project/plugins.sbt

```<code>addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.2")
</code>```

conf/routes

```<code>GET     /           controllers.FormController.showForm
POST    /           controllers.FormController.processForm
</code>```

app/controllers/FormController.scala

package controllers

import javax.inject.Inject

import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._

case class UserData(name: String, email: String)

class FormController @Inject()(val messagesApi: MessagesApi) extends
  Controller with
  I18nSupport {

  def showForm = Action {
    Ok(views.html.showForm(getForm))
  }

  def processForm = Action { implicit request =>
    getForm.bindFromRequest.fold(
      errForm => Ok(views.html.showForm(errForm)),
      userData => Ok(userData.toString)
    )
  }

  val getForm: Form[UserData] = Form(mapping(
    "name" -> nonEmptyText,
    "email" -> email
  )(UserData.apply)(UserData.unapply))
}
```

<p><strong>views/main.scala.html</strong></p>

```@(content: Html)

<!DOCTYPE html>

  @content

```

<p><strong>views/showForm.scala.html</strong></p>

```@import helper._

@(myForm: Form[UserData])(implicit messages: Messages)

@main {

Form

  @form(action = routes.FormController.processForm()) {
    @inputText(myForm("name"))
    @inputText(myForm("email"))
    <input type="submit" value="Submit">
  }
}
```

<p><strong>test/controllers/FormControllerSpec.scala</strong></p>

<pre class="lang-scala prettyprint-override"><code>package controllers

import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.i18n.MessagesApi
import play.api.test.Helpers._
import play.api.test._

class FormControllerSpec extends PlaySpec with MockitoSugar {
  "FormController" when {
    "showForm" should {
      "display the form" in {
        val cut = new FormController(mock[MessagesApi])
        val response = cut.showForm(FakeRequest())
        status(response) mustBe OK
      }
    }

    "processForm" should {
      "redisplay the form in case of form errors" in {
        val cut = new FormController(mock[MessagesApi])
        val req = FakeRequest(POST, routes.FormController.processForm.path)
        val response = cut.processForm(req)
        status(response) mustBe OK
      }
    }
  }
}
</code>```

Output from running test:

```<code>[info] FormControllerSpec:
[info] FormController
[info]   when showForm
[info]   - should display the form
[info]   when processForm
[info]   - should redisplay the form in case of form errors *** FAILED ***
[info]     java.lang.NullPointerException:
[info]     at views.html.helper.FieldElements$$anonfun$errors$2$$anonfun$apply$5.apply(Helpers.scala:35)
[info]     at views.html.helper.FieldElements$$anonfun$errors$2$$anonfun$apply$5.apply(Helpers.scala:35)
[info]     at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
[info]     at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
[info]     at scala.collection.immutable.List.foreach(List.scala:381)
[info]     at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
[info]     at scala.collection.immutable.List.map(List.scala:285)
[info]     at views.html.helper.FieldElements$$anonfun$errors$2.apply(Helpers.scala:35)
[info]     at views.html.helper.FieldElements$$anonfun$errors$2.apply(Helpers.scala:31)
[info]     at scala.Option.getOrElse(Option.scala:121)
[info]     ...
[info] ScalaTest
</code>```

答:
In the example you posted you haven't trained your mock. As a result when you try to render the template it's trying to call apply on the mock and it's going to throw. For reference, MessagesApi:

https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/i18n/Messages.scala#L320

Properly training this mock would be very difficult. Instead what you can do is build an instance of DefaultMessagesApi and provide that to be wired into your controller:

```<code>val config = Configuration(ConfigFactory.load("application.conf")) // Or test.conf, if you have test-specific config files
val messages = new DefaultMessagesApi(Environment.simple(), config, new DefaultLangs(config))
val controller = wire[MyController]
</code>```

Body:
I encounter NullPointerException when testing an action that processes a form. There are two actions, one to display and one to process the form. Testing the first one is fine; however, testing the second one throws the exception. This only happens with unit-testing; the application works fine (i.e., via browser). I can't figure out what happens. Could anyone help me shed some light on it? The code I'm testing is as follows.

Scala: 2.11.8

SBT: 0.13.11

Play Framework: 2.5.2

build.sbt

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
  "org.mockito" % "mockito-core" % "1.10.19" % Test,
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.1" % Test
)

project/plugins.sbt

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.5.2")

conf/routes

GET     /           controllers.FormController.showForm
POST    /           controllers.FormController.processForm

app/controllers/FormController.scala

package controllers

import javax.inject.Inject

import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.{I18nSupport, MessagesApi}
import play.api.mvc._

case class UserData(name: String, email: String)

class FormController @Inject()(val messagesApi: MessagesApi) extends
  Controller with
  I18nSupport {

  def showForm = Action {
    Ok(views.html.showForm(getForm))
  }

  def processForm = Action { implicit request =>
    getForm.bindFromRequest.fold(
      errForm => Ok(views.html.showForm(errForm)),
      userData => Ok(userData.toString)
    )
  }

  val getForm: Form[UserData] = Form(mapping(
    "name" -> nonEmptyText,
    "email" -> email
  )(UserData.apply)(UserData.unapply))
}

views/main.scala.html

@(content: Html)

<!DOCTYPE html>

  @content

views/showForm.scala.html

@import helper._

@(myForm: Form[UserData])(implicit messages: Messages)

@main {

Form

  @form(action = routes.FormController.processForm()) {
    @inputText(myForm("name"))
    @inputText(myForm("email"))
    <input type="submit" value="Submit">
  }
}

test/controllers/FormControllerSpec.scala

package controllers

import org.scalatest.mock.MockitoSugar
import org.scalatestplus.play.PlaySpec
import play.api.i18n.MessagesApi
import play.api.test.Helpers._
import play.api.test._

class FormControllerSpec extends PlaySpec with MockitoSugar {
  "FormController" when {
    "showForm" should {
      "display the form" in {
        val cut = new FormController(mock[MessagesApi])
        val response = cut.showForm(FakeRequest())
        status(response) mustBe OK
      }
    }

    "processForm" should {
      "redisplay the form in case of form errors" in {
        val cut = new FormController(mock[MessagesApi])
        val req = FakeRequest(POST, routes.FormController.processForm.path)
        val response = cut.processForm(req)
        status(response) mustBe OK
      }
    }
  }
}

Output from running test:

[info] FormControllerSpec:
[info] FormController
[info]   when showForm
[info]   - should display the form
[info]   when processForm
[info]   - should redisplay the form in case of form errors *** FAILED ***
[info]     java.lang.NullPointerException:
[info]     at views.html.helper.FieldElements$$anonfun$errors$2$$anonfun$apply$5.apply(Helpers.scala:35)
[info]     at views.html.helper.FieldElements$$anonfun$errors$2$$anonfun$apply$5.apply(Helpers.scala:35)
[info]     at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
[info]     at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
[info]     at scala.collection.immutable.List.foreach(List.scala:381)
[info]     at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
[info]     at scala.collection.immutable.List.map(List.scala:285)
[info]     at views.html.helper.FieldElements$$anonfun$errors$2.apply(Helpers.scala:35)
[info]     at views.html.helper.FieldElements$$anonfun$errors$2.apply(Helpers.scala:31)
[info]     at scala.Option.getOrElse(Option.scala:121)
[info]     ...
[info] ScalaTest

Body:
In the example you posted you haven't trained your mock. As a result when you try to render the template it's trying to call apply on the mock and it's going to throw. For reference, MessagesApi:

https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/i18n/Messages.scala#L320

Properly training this mock would be very difficult. Instead what you can do is build an instance of DefaultMessagesApi and provide that to be wired into your controller:

val config = Configuration(ConfigFactory.load("application.conf")) // Or test.conf, if you have test-specific config files
val messages = new DefaultMessagesApi(Environment.simple(), config, new DefaultLangs(config))
val controller = wire[MyController]


问:
Font awesome is not showing icon
I am using Font Awesome and do not wish to add CSS with HTTP. I downloaded Font Awesome and included it in my code, yet Font Awesome is showing a bordered square box instead of an icon. Here is my code:

```<code><html>
<head>
<link rel="stylesheet" href="../css/font-awesome.css">
    <link rel="stylesheet" href="../css/font-awesome.min.css">
</head>
<body>
<div style="font-size: 44px;">
   <i class="fa fa-camera-retro fa-lg"></i> fa-lg
<i class="fa fa-camera-retro fa-2x"></i> fa-2x
</div>
</body>
</html>
</code>```

I would like to know how to make the icon display instead of the bordered square box.

答:
First, check that you have class="fa" as well as whatever the icon's class is. So, not just

```<code><i class="fa-pencil" title="Edit"></i>
</code>```

But also

```<code><i class="fa fa-pencil" title="Edit"></i>
</code>```

Then it works as expected. This solved my issue.

Title: Font awesome is not showing icon

Body:
I am using Font Awesome and do not wish to add CSS with HTTP. I downloaded Font Awesome and included it in my code, yet Font Awesome is showing a bordered square box instead of an icon. Here is my code:

<link rel="stylesheet" href="../css/font-awesome.css">
    <link rel="stylesheet" href="../css/font-awesome.min.css">

    fa-lg
 fa-2x

I would like to know how to make the icon display instead of the bordered square box.

Body:
First, check that you have class="fa" as well as whatever the icon's class is. So, not just

<i class="fa-pencil" title="Edit"></i>

But also

<i class="fa fa-pencil" title="Edit"></i>

Then it works as expected. This solved my issue.


问:
driver.setLocation() not working on iOS appium simulator
I have done a lot of searching online and I'm not sure what I'm doing wrong. The idea is that I want to launch my iOS app with the following location in a simulator. This works fine when I manually go to debug>location>custom location and set the longitude and latitude....however I need to do it programatically so that my app launches /picks up this location when I click enable locations. Here is my code</p>

```<code>public class SampleTest extends SampleBaseTest {

          private IOSDriver driver;
          private String sessionId;
          static UserData sampleUser = null;

          @Test(priority = 0)
          public void setUp() throws MalformedURLException {

              DesiredCapabilities caps = DesiredCapabilities.iphone();
              caps.setCapability("appiumVersion", "1.4.16");
              caps.setCapability("deviceName","iPhone 6");
              caps.setCapability("deviceOrientation", "portrait");
              caps.setCapability("platformVersion","9.1");
              caps.setCapability("platformName", "iOS");
              caps.setCapability("browserName", "");
              caps.setCapability("app","sauce-storage:sampleAppe.zip");

            URL sauceUrl = new URL("http://" + "sauceUserName" + ":"+ "sauceUserKey" + "@ondemand.saucelabs.com:80/wd/hub");

            driver = new IOSDriver(sauceUrl, caps);
            Location location = new Location(-8.78319, -114.509, 0.0);
            driver.setLocation(location);

            sessionId = driver.getSessionId().toString();

          @Test(priority = 1)
          public void navigateToPayAhead()
                          throws Exception {

              try{
                    // test logic here

              }
              catch(Exception e){
                  e.printStackTrace();
              }

          }
        }
    }
</code>```

答:
Try adding

```<code>caps.setCapability("locationServicesEnabled", true);
caps.setCapability("locationServicesAuthorized", true);
caps.setCapability("bundleId", "YOUR_BUNDLE_ID_HERE");
</code>```

To get your bundle id, see How to obtain Bundle ID for an IOS App when I have a '.ipa' file for the app installed on my iPAD

Body:
I have done a lot of searching online and I'm not sure what I'm doing wrong. The idea is that I want to launch my iOS app with the following location in a simulator. This works fine when I manually go to debug>location>custom location and set the longitude and latitude....however I need to do it programatically so that my app launches /picks up this location when I click enable locations. Here is my code

public class SampleTest extends SampleBaseTest {

          private IOSDriver driver;
          private String sessionId;
          static UserData sampleUser = null;

          @Test(priority = 0)
          public void setUp() throws MalformedURLException {

              DesiredCapabilities caps = DesiredCapabilities.iphone();
              caps.setCapability("appiumVersion", "1.4.16");
              caps.setCapability("deviceName","iPhone 6");
              caps.setCapability("deviceOrientation", "portrait");
              caps.setCapability("platformVersion","9.1");
              caps.setCapability("platformName", "iOS");
              caps.setCapability("browserName", "");
              caps.setCapability("app","sauce-storage:sampleAppe.zip");

            URL sauceUrl = new URL("http://" + "sauceUserName" + ":"+ "sauceUserKey" + "@ondemand.saucelabs.com:80/wd/hub");

            driver = new IOSDriver(sauceUrl, caps);
            Location location = new Location(-8.78319, -114.509, 0.0);
            driver.setLocation(location);

            sessionId = driver.getSessionId().toString();

          @Test(priority = 1)
          public void navigateToPayAhead()
                          throws Exception {

              try{
                    // test logic here

              }
              catch(Exception e){
                  e.printStackTrace();
              }

          }
        }
    }

Body:
Try adding

caps.setCapability("locationServicesEnabled", true);
caps.setCapability("locationServicesAuthorized", true);
caps.setCapability("bundleId", "YOUR_BUNDLE_ID_HERE");

To get your bundle id, see How to obtain Bundle ID for an IOS App when I have a '.ipa' file for the app installed on my iPAD


问:
Programmatically adjusting the number of rows in a grid with C#
I'm currently teaching myself XAML/C# and writing a calendar application. Right now it's creating a grid and then applying user control elements to the grid. It is correctly building my calendar but, instead of defining the number of rows in XAML, I want to be able to set the number via C# dynamically. Some months use more or less weeks (March needs 5 but April needs 6). I'm wondering how to do that or if I should be using a different control than grid.

This is what the UI looks like.

XAML code

```<code><UserControl x:Class="CMS.Control.MonthView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

    <Grid VerticalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Background="AliceBlue">
            <Image x:Name="MonthPrev" Source="/Images/Previous.png" Height="24" Margin="16,0,6,0" MouseLeftButtonUp="MonthPrev_MouseLeftButtonUp"/>
            <Image x:Name="MonthNext" Source="/Images/Next.png" Height="24" Margin="6,0,16,0" MouseLeftButtonUp="MonthNext_MouseLeftButtonUp"/>
            <Label x:Name="DateLabel" Content="January 2017" FontSize="16" FontFamily="Bold" VerticalAlignment="Center"/>
        </StackPanel>
        <Grid Grid.Row="1" Background="AliceBlue">
            <Grid.ColumnDefinitions>

                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
            </Grid.ColumnDefinitions>
            <Label Grid.Column="0" Content="Sunday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="1" Content="Monday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="2" Content="Tuesday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="3" Content="Wednesday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="4" Content="Thursday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="5" Content="Friday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
            <Label Grid.Column="6" Content="Saturday" FontSize="9" Margin="2,0,0,2" Padding="0,1,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="0,0,1,0"/>
        </Grid>

        <Grid x:Name="WeekRowGrid" Grid.Row="2">
            <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
        </Grid>
    </Grid>
</UserControl>
</code>```

C# Code

```<code>namespace CMS.Control
{
    /// <summary>
    /// Interaction logic for MonthView.xaml
    /// </summary>
    public partial class MonthView : UserControl
    {
        private DateTime _DispayDate;

        public MonthView()
        {
            InitializeComponent();
            _DispayDate = DateTime.Now;
            DrawMonth();
        }

        //Generates the
        private void DrawMonth()
        {
            DateTime FirstDayOfMonth = new DateTime(_DispayDate.Year, _DispayDate.Month, 1);
            int DisplayFrontPadding = (int)FirstDayOfMonth.DayOfWeek; // # of days that need to be displayed before the 1st of the month
            int DaysInDisplayMonth = DateTime.DaysInMonth(_DispayDate.Year, _DispayDate.Month);
            int DaysInDisplay = DisplayFrontPadding + DaysInDisplayMonth;
            DaysInDisplay += 7 - DaysInDisplay%7; // Rounds up the displayed days to a multiple of 7

            DateLabel.Content = _DispayDate.ToString("MMMM") + " " + _DispayDate.Year;

            for (int i = 0; i<DaysInDisplay; i++)
            {
                DateTime DisplayDay = FirstDayOfMonth.AddDays(i - DisplayFrontPadding);
                DayBox DB = DayBox.GetDay();   // DayBox factory
                DB.DrawDay(DisplayDay);

                Grid.SetRow(DB, i / 7);
                WeekRowGrid.Children.Add(DB);
                Grid.SetColumn(DB, i%7);
            }
        }

        //Generates a calendar for the previous month on button click.
        private void MonthPrev_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(-1);
            DrawMonth();
        }

        //Generates a calendar for the next month on button click.
        private void MonthNext_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(1);
            DrawMonth();
        }
    }
}
</code>```

I know I should really be using MVVM but I'm still wrapping my brain around programming in MVVM pattern and want to get this working. I'll probably refactor it once I'm more comfortable with it.

答:
I just wanted to finish this project

Understood. The thing is, the basic idea behind MVVM isn't really all that hard, and if you embrace it, you likely will finish the project faster, than if you continue to try to hard-code all your UI. I can't guarantee that, of course. But I've been through the same thing, and I can tell you that you can spend a lot of time fighting WPF trying to configure the UI in code-behind explicitly.

Without a good Minimal, Complete, and Verifiable code example to start with, it wasn't practical for me to replicate exactly your user interface. But here is a simple code example that shows the basic approach you might take to use MVVM to build the UI you want…

First, it's helpful to have a base class that implements INotifyPropertyChanged for you. It simplifies the view model boilerplate a lot:

```<code>class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void _UpdateField<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, newValue))
        {
            field = newValue;
            _OnPropertyChanged(propertyName);
        }
    }

    protected virtual void _OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
</code>```

Then, we'll need view models. In this UI, there are two basic components: the overall view, and the individual days of the month. So, I made a view model for each:

```<code>class DateViewModel : NotifyPropertyChangedBase
{
    private int _dayNumber;
    private bool _isCurrent;

    public int DayNumber
    {
        get { return _dayNumber; }
        set { _UpdateField(ref _dayNumber, value); }
    }

    public bool IsCurrent
    {
        get { return _isCurrent; }
        set { _UpdateField(ref _isCurrent, value); }
    }
}
</code>```

and…

```<code>class MonthViewViewModel : NotifyPropertyChangedBase
{
    private readonly ObservableCollection<DateViewModel> _dates = new ObservableCollection<DateViewModel>();

    private DateTime _selectedDate;

    public DateTime SelectedDate
    {
        get { return _selectedDate; }
        set { _UpdateField(ref _selectedDate, value); }
    }

    public IReadOnlyCollection<DateViewModel> Dates
    {
        get { return _dates; }
    }

    protected override void _OnPropertyChanged(string propertyName)
    {
        base._OnPropertyChanged(propertyName);

        switch (propertyName)
        {
            case nameof(SelectedDate):
                _UpdateDates();
                break;
        }
    }

    private void _UpdateDates()
    {
        _dates.Clear();

        DateTime firstDayOfMonth = new DateTime(SelectedDate.Year, SelectedDate.Month, 1),
            firstDayOfNextMonth = firstDayOfMonth.AddMonths(1);
        int previousMonthDates = (int)firstDayOfMonth.DayOfWeek; // assumes Sunday-start week
        int daysInView = previousMonthDates + DateTime.DaysInMonth(SelectedDate.Year, SelectedDate.Month);

        // round up to nearest week multiple
        daysInView = ((daysInView - 1) / 7 + 1) * 7;

        DateTime previousMonth = firstDayOfMonth.AddDays(-previousMonthDates);

        for (DateTime date = previousMonth; date < firstDayOfNextMonth; date = date.AddDays(1))
        {
            _dates.Add(new DateViewModel { DayNumber = date.Day, IsCurrent = date == SelectedDate.Date });
        }

        for (int i = 1; _dates.Count < daysInView; i++)
        {
            _dates.Add(new DateViewModel { DayNumber = i, IsCurrent = false });
        }
    }
}
</code>```

As you can see, so far there's been no mention of UI, and yet already all the logic exists to build a month's worth of dates. The UI part, the XAML, will have no idea that you are doing anything related with months or dates. The closest it gets is a hard-coded invariant, i.e. the number of days in a week which are used to control the number of columns in the UniformGrid that will display your data.

The XAML looks like this:

```<code><Window x:Class="TestSO43147585CalendarMonthView.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:p="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:l="clr-namespace:TestSO43147585CalendarMonthView"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        SizeToContent="Height"
        Title="MainWindow" Height="350" Width="525">
  <Window.DataContext>
    <l:MonthViewViewModel SelectedDate="{x:Static s:DateTime.Today}"/>
  </Window.DataContext>

  <Window.Resources>
    <DataTemplate DataType="{x:Type l:MonthViewViewModel}">
      <ItemsControl ItemsSource="{Binding Dates}">
        <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
            <UniformGrid IsItemsHost="True" Columns="7"/>
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
      </ItemsControl>
    </DataTemplate>

    <DataTemplate DataType="{x:Type l:DateViewModel}">
      <Border BorderBrush="Black" BorderThickness="0, 0, 1, 0">
        <StackPanel>
          <TextBlock Text="{Binding DayNumber}">
            <TextBlock.Style>
              <p:Style TargetType="TextBlock">
                <Setter Property="Background" Value="LightBlue"/>
                <p:Style.Triggers>
                  <DataTrigger Binding="{Binding IsCurrent}" Value="True">
                    <Setter Property="Background" Value="Yellow"/>
                  </DataTrigger>
                </p:Style.Triggers>
              </p:Style>
            </TextBlock.Style>
          </TextBlock>
          <Grid Height="{Binding ActualWidth, RelativeSource={x:Static RelativeSource.Self}}"/>
        </StackPanel>
      </Border>
    </DataTemplate>
  </Window.Resources>

  <Grid>
    <ContentControl Content="{Binding}" VerticalAlignment="Top"/>
  </Grid>
</Window>
</code>```

The XAML does three things:

It declares a MonthViewViewModel object to be used as the DataContext for the Window. An object in the visual tree, i.e. children of the Window, will inherit their parent's context if they have none of their own.

It declares data templates for the two view models. These tell WPF how it should visually represent the data. A view model contains the data that you want to represent, and this data is referenced in the template via {Binding...} syntax. In many cases (e.g. text, numbers, enum values), you can just bind directly and the default conversion will do what you want (as is the case above). If not, you can implement your own IValueConverter and incorporate that in the binding.

It provides a place for the MonthViewViewModel to be displayed, by declaring a ContentControl, where the content of that control is bound simply to the current data context (a {Binding} expression without a path will bind to the source, and the default source is the current data context).

In the context of the ContentControl, as well as the individual items being displayed in the ItemsControl, WPF will search for the template that is appropriate for the data object defined for that context, and will automatically populate your visual tree, binding to the necessary properties, according to that object.

There are a number of advantages to this approach, the primary ones being that you can describe your UI instead of having to code it, and that you maintain the OOP principle of "separation of concerns", which is key in reducing the mental work-load involved by allowing you to focus on one thing at a time, instead of having to deal with UI and data logic together.

A couple of side-notes regarding the XAML above:

You might notice that I have added the p: XML namespace and used it for the Style element. This is only work around a Stack Overflow bug, in which the Style element by itself confuses the XML formatter and prevents the element and its children from being formatted correctly. The XAML will compile fine like this, but it's not actually necessary in real code. In your regular XAML, you can safely omit it.

I included a feature your code didn't, just for the purpose of illustration. That is, the current date is highlighted in yellow. The technique shown here is very useful, as it allows you to customize the appearance of an item in a single template, based on property values of the view model. But there is a little trap: in WPF, if you explicitly set an element's property via the attribute syntax, e.g. something like <TextBlock Text="{Binding DayNumber}" Background="LightBlue">, then that syntax will take precedence over any <Setter...> elements in a style. You have to remember to set the default value of any property that you intend to set via a trigger, in its own <Setter...> in the style as well (as shown above).

Body:
I'm currently teaching myself XAML/C# and writing a calendar application. Right now it's creating a grid and then applying user control elements to the grid. It is correctly building my calendar but, instead of defining the number of rows in XAML, I want to be able to set the number via C# dynamically. Some months use more or less weeks (March needs 5 but April needs 6). I'm wondering how to do that or if I should be using a different control than grid.

This is what the UI looks like.

XAML code

<UserControl x:Class="CMS.Control.MonthView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    HorizontalAlignment="Stretch" VerticalAlignment="Stretch" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">

    <Grid VerticalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal" Background="AliceBlue">
            <Image x:Name="MonthPrev" Source="/Images/Previous.png" Height="24" Margin="16,0,6,0" MouseLeftButtonUp="MonthPrev_MouseLeftButtonUp"/>
            <Image x:Name="MonthNext" Source="/Images/Next.png" Height="24" Margin="6,0,16,0" MouseLeftButtonUp="MonthNext_MouseLeftButtonUp"/>

        </StackPanel>
        <Grid Grid.Row="1" Background="AliceBlue">
            <Grid.ColumnDefinitions>

                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
                <ColumnDefinition MinWidth="60" Width="*"/>
            </Grid.ColumnDefinitions>

        </Grid>

        <Grid x:Name="WeekRowGrid" Grid.Row="2">
            <Grid.ColumnDefinitions>

                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
        </Grid>
    </Grid>
</UserControl>

C# Code

namespace CMS.Control
{
    ///
    /// Interaction logic for MonthView.xaml
    ///
    public partial class MonthView : UserControl
    {
        private DateTime _DispayDate;

        public MonthView()
        {
            InitializeComponent();
            _DispayDate = DateTime.Now;
            DrawMonth();
        }

        //Generates the
        private void DrawMonth()
        {
            DateTime FirstDayOfMonth = new DateTime(_DispayDate.Year, _DispayDate.Month, 1);
            int DisplayFrontPadding = (int)FirstDayOfMonth.DayOfWeek; // # of days that need to be displayed before the 1st of the month
            int DaysInDisplayMonth = DateTime.DaysInMonth(_DispayDate.Year, _DispayDate.Month);
            int DaysInDisplay = DisplayFrontPadding + DaysInDisplayMonth;
            DaysInDisplay += 7 - DaysInDisplay%7; // Rounds up the displayed days to a multiple of 7

            DateLabel.Content = _DispayDate.ToString("MMMM") + " " + _DispayDate.Year;

            for (int i = 0; i<DaysInDisplay; i++)
            {
                DateTime DisplayDay = FirstDayOfMonth.AddDays(i - DisplayFrontPadding);
                DayBox DB = DayBox.GetDay();   // DayBox factory
                DB.DrawDay(DisplayDay);

                Grid.SetRow(DB, i / 7);
                WeekRowGrid.Children.Add(DB);
                Grid.SetColumn(DB, i%7);
            }
        }

        //Generates a calendar for the previous month on button click.
        private void MonthPrev_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(-1);
            DrawMonth();
        }

        //Generates a calendar for the next month on button click.
        private void MonthNext_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            _DispayDate = _DispayDate.AddMonths(1);
            DrawMonth();
        }
    }
}

I know I should really be using MVVM but I'm still wrapping my brain around programming in MVVM pattern and want to get this working. I'll probably refactor it once I'm more comfortable with it.

Body:
I just wanted to finish this project

Understood. The thing is, the basic idea behind MVVM isn't really all that hard, and if you embrace it, you likely will finish the project faster, than if you continue to try to hard-code all your UI. I can't guarantee that, of course. But I've been through the same thing, and I can tell you that you can spend a lot of time fighting WPF trying to configure the UI in code-behind explicitly.

Without a good Minimal, Complete, and Verifiable code example to start with, it wasn't practical for me to replicate exactly your user interface. But here is a simple code example that shows the basic approach you might take to use MVVM to build the UI you want…

First, it's helpful to have a base class that implements INotifyPropertyChanged for you. It simplifies the view model boilerplate a lot:

class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void _UpdateField<T>(ref T field, T newValue, [CallerMemberName] string propertyName = null)
    {
        if (!EqualityComparer<T>.Default.Equals(field, newValue))
        {
            field = newValue;
            _OnPropertyChanged(propertyName);
        }
    }

    protected virtual void _OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Then, we'll need view models. In this UI, there are two basic components: the overall view, and the individual days of the month. So, I made a view model for each:

class DateViewModel : NotifyPropertyChangedBase
{
    private int _dayNumber;
    private bool _isCurrent;

    public int DayNumber
    {
        get { return _dayNumber; }
        set { _UpdateField(ref _dayNumber, value); }
    }

    public bool IsCurrent
    {
        get { return _isCurrent; }
        set { _UpdateField(ref _isCurrent, value); }
    }
}

and…

class MonthViewViewModel : NotifyPropertyChangedBase
{
    private readonly ObservableCollection<DateViewModel> _dates = new ObservableCollection<DateViewModel>();

    private DateTime _selectedDate;

    public DateTime SelectedDate
    {
        get { return _selectedDate; }
        set { _UpdateField(ref _selectedDate, value); }
    }

    public IReadOnlyCollection<DateViewModel> Dates
    {
        get { return _dates; }
    }

    protected override void _OnPropertyChanged(string propertyName)
    {
        base._OnPropertyChanged(propertyName);

        switch (propertyName)
        {
            case nameof(SelectedDate):
                _UpdateDates();
                break;
        }
    }

    private void _UpdateDates()
    {
        _dates.Clear();

        DateTime firstDayOfMonth = new DateTime(SelectedDate.Year, SelectedDate.Month, 1),
            firstDayOfNextMonth = firstDayOfMonth.AddMonths(1);
        int previousMonthDates = (int)firstDayOfMonth.DayOfWeek; // assumes Sunday-start week
        int daysInView = previousMonthDates + DateTime.DaysInMonth(SelectedDate.Year, SelectedDate.Month);

        // round up to nearest week multiple
        daysInView = ((daysInView - 1) / 7 + 1) * 7;

        DateTime previousMonth = firstDayOfMonth.AddDays(-previousMonthDates);

        for (DateTime date = previousMonth; date < firstDayOfNextMonth; date = date.AddDays(1))
        {
            _dates.Add(new DateViewModel { DayNumber = date.Day, IsCurrent = date == SelectedDate.Date });
        }

        for (int i = 1; _dates.Count < daysInView; i++)
        {
            _dates.Add(new DateViewModel { DayNumber = i, IsCurrent = false });
        }
    }
}

As you can see, so far there's been no mention of UI, and yet already all the logic exists to build a month's worth of dates. The UI part, the XAML, will have no idea that you are doing anything related with months or dates. The closest it gets is a hard-coded invariant, i.e. the number of days in a week which are used to control the number of columns in the UniformGrid that will display your data.

The XAML looks like this:

<Window x:Class="TestSO43147585CalendarMonthView.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:p="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:l="clr-namespace:TestSO43147585CalendarMonthView"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        mc:Ignorable="d"
        SizeToContent="Height"
        Title="MainWindow" Height="350" Width="525">
  <Window.DataContext>
    <l:MonthViewViewModel SelectedDate="{x:Static s:DateTime.Today}"/>
  </Window.DataContext>

  <Window.Resources>
    <DataTemplate DataType="{x:Type l:MonthViewViewModel}">
      <ItemsControl ItemsSource="{Binding Dates}">
        <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
            <UniformGrid IsItemsHost="True" Columns="7"/>
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
      </ItemsControl>
    </DataTemplate>

    <DataTemplate DataType="{x:Type l:DateViewModel}">
      <Border BorderBrush="Black" BorderThickness="0, 0, 1, 0">
        <StackPanel>
          <TextBlock Text="{Binding DayNumber}">
            <TextBlock.Style>
              <p:Style TargetType="TextBlock">
                <Setter Property="Background" Value="LightBlue"/>
                <p:Style.Triggers>
                  <DataTrigger Binding="{Binding IsCurrent}" Value="True">
                    <Setter Property="Background" Value="Yellow"/>
                  </DataTrigger>
                </p:Style.Triggers>
              </p:Style>
            </TextBlock.Style>
          </TextBlock>
          <Grid Height="{Binding ActualWidth, RelativeSource={x:Static RelativeSource.Self}}"/>
        </StackPanel>
      </Border>
    </DataTemplate>
  </Window.Resources>

  <Grid>
    <ContentControl Content="{Binding}" VerticalAlignment="Top"/>
  </Grid>
</Window>

The XAML does three things:

It declares a MonthViewViewModel object to be used as the DataContext for the Window. An object in the visual tree, i.e. children of the Window, will inherit their parent's context if they have none of their own.

It declares data templates for the two view models. These tell WPF how it should visually represent the data. A view model contains the data that you want to represent, and this data is referenced in the template via {Binding...} syntax. In many cases (e.g. text, numbers, enum values), you can just bind directly and the default conversion will do what you want (as is the case above). If not, you can implement your own IValueConverter and incorporate that in the binding.

It provides a place for the MonthViewViewModel to be displayed, by declaring a ContentControl, where the content of that control is bound simply to the current data context (a {Binding} expression without a path will bind to the source, and the default source is the current data context).

In the context of the ContentControl, as well as the individual items being displayed in the ItemsControl, WPF will search for the template that is appropriate for the data object defined for that context, and will automatically populate your visual tree, binding to the necessary properties, according to that object.

There are a number of advantages to this approach, the primary ones being that you can describe your UI instead of having to code it, and that you maintain the OOP principle of "separation of concerns", which is key in reducing the mental work-load involved by allowing you to focus on one thing at a time, instead of having to deal with UI and data logic together.

A couple of side-notes regarding the XAML above:

You might notice that I have added the p: XML namespace and used it for the Style element. This is only work around a Stack Overflow bug, in which the Style element by itself confuses the XML formatter and prevents the element and its children from being formatted correctly. The XAML will compile fine like this, but it's not actually necessary in real code. In your regular XAML, you can safely omit it.

I included a feature your code didn't, just for the purpose of illustration. That is, the current date is highlighted in yellow. The technique shown here is very useful, as it allows you to customize the appearance of an item in a single template, based on property values of the view model. But there is a little trap: in WPF, if you explicitly set an element's property via the attribute syntax, e.g. something like <TextBlock Text="{Binding DayNumber}" Background="LightBlue">, then that syntax will take precedence over any <Setter...> elements in a style. You have to remember to set the default value of any property that you intend to set via a trigger, in its own <Setter...> in the style as well (as shown above).


问:
JPA @OneToMany is not working when result is list
I'm working with JPA, Spring boot.
Using @OneToMany annotation, when I fetch orders containing cart items.
My domain codes are below.

Order:

```<code>@Data
@Entity
@Table(name="\"order\"")
@ToString
public class Order {

    @Id
    @GeneratedValue
    @Getter @Setter
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name="order_id")
    @Getter @Setter
    private List<Cart> carts;

    public void addCart(Cart cart) {
        if (this.carts == null) {
            carts = new ArrayList<Cart>();
        }
        carts.add(cart);
    }
}
</code>```

Cart:

```<code>@Data
@Entity
@Table(name="cart")
@ToString
public class Cart {

    @Id
    @GeneratedValue
    @Getter @Setter
    @Column(name="id")
    private Long id;

    @Column(name = "order_id")
    @Getter @Setter
    private Long orderId;

}
</code>```

This works very well when I fetch only one order, but doesn't work when I fetch more than two orders. I mean when I fetch only one order, carts field's size is 1 or more, but when I fetch two or more orders, the carts field's size is 0.

How can I solve this problem? Thank you in advance!

答:
It's nearly impossible to find out what the fetching problem is without seeing the code which is loading / querying your entities. So could you please add it to your question?

Meanwhile there are at least some things you could improve to have cleaner entities and faster code, maybe this also can help a little to hunt down the problem.

At first, you are using redundant configurations, respective annotations you are recreating the default values with.

I assume that is lombok what you are using, right? You could remove the @Getter and @Setter annotations on your fields in both entities and add it once on class level to avoid the declaration on every single field, but since you are using @Data you don't need it at all. Same with @toString, @Data is a convenience annotations for all of it (and a little more).

The JavaDoc of @Data says:

Equivalent to {@code @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode}.

Then, although the @Table(name="\"order\"") on the order entity is needed because order is a reserved word in some DBMS, the @Table(name="cart") on the cart entity is the default.

Up next, I would not recommend lazy initialization of collections, because in general there is no benefit to do that compared to the penalty it causes while checking for null before every access. Just initialize it within declaration and you will never have to care about handling null again. Beside of that you should think about using a Set instead a List for the carts (so you will have no duplicates).

Also think about the FetchType because EAGER is only useful if you work with detached entities and want to initialize the relation in every case. LAZY is the default for @OneToMany and should be preferred.

A thing you already improved is the @JoinColumn, that will prevent Hibernate (I brazenly assume you are using Hibernate) creating a join table. But even more important is thinking about turning the @OneToMany into a @ManyToOne on the other side or making it bidirectional. That would gain some performance on reading (it also prevents the join table so less joins are needed, faster indexing is possible) and writing time (relation managed by parent side).

So what do you think about this:

```<code>@Data
@Entity
@Table(name="\"order\"")
public class Order {

    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Cart> carts = new HashSet<>();

}
</code>```

and this:

```<code>@Data
@Entity
public class Cart {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private Order order;

}
</code>```

Body:
I'm working with JPA, Spring boot.
Using @OneToMany annotation, when I fetch orders containing cart items.
My domain codes are below.

Order:

@Data
@Entity
@Table(name="\"order\"")
@ToString
public class Order {

    @Id
    @GeneratedValue
    @Getter @Setter
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name="order_id")
    @Getter @Setter
    private List<Cart> carts;

    public void addCart(Cart cart) {
        if (this.carts == null) {
            carts = new ArrayList<Cart>();
        }
        carts.add(cart);
    }
}

Cart:

@Data
@Entity
@Table(name="cart")
@ToString
public class Cart {

    @Id
    @GeneratedValue
    @Getter @Setter
    @Column(name="id")
    private Long id;

    @Column(name = "order_id")
    @Getter @Setter
    private Long orderId;

}

This works very well when I fetch only one order, but doesn't work when I fetch more than two orders. I mean when I fetch only one order, carts field's size is 1 or more, but when I fetch two or more orders, the carts field's size is 0.

How can I solve this problem? Thank you in advance!

Body:
It's nearly impossible to find out what the fetching problem is without seeing the code which is loading / querying your entities. So could you please add it to your question?

Meanwhile there are at least some things you could improve to have cleaner entities and faster code, maybe this also can help a little to hunt down the problem.

At first, you are using redundant configurations, respective annotations you are recreating the default values with.

I assume that is lombok what you are using, right? You could remove the @Getter and @Setter annotations on your fields in both entities and add it once on class level to avoid the declaration on every single field, but since you are using @Data you don't need it at all. Same with @toString, @Data is a convenience annotations for all of it (and a little more).

The JavaDoc of @Data says:

Equivalent to {@code @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode}.

Then, although the @Table(name="\"order\"") on the order entity is needed because order is a reserved word in some DBMS, the @Table(name="cart") on the cart entity is the default.

Up next, I would not recommend lazy initialization of collections, because in general there is no benefit to do that compared to the penalty it causes while checking for null before every access. Just initialize it within declaration and you will never have to care about handling null again. Beside of that you should think about using a Set instead a List for the carts (so you will have no duplicates).

Also think about the FetchType because EAGER is only useful if you work with detached entities and want to initialize the relation in every case. LAZY is the default for @OneToMany and should be preferred.

A thing you already improved is the @JoinColumn, that will prevent Hibernate (I brazenly assume you are using Hibernate) creating a join table. But even more important is thinking about turning the @OneToMany into a @ManyToOne on the other side or making it bidirectional. That would gain some performance on reading (it also prevents the join table so less joins are needed, faster indexing is possible) and writing time (relation managed by parent side).

So what do you think about this:

@Data
@Entity
@Table(name="\"order\"")
public class Order {

    @Id
    @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<Cart> carts = new HashSet<>();

}

and this:

@Data
@Entity
public class Cart {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToOne
    private Order order;

}


问:
Migrating C++ project to Java, protecting implementation details
I have a quite complex project to migrate from C++ (Linux) to Java
Currently, the C++ version is being distributed as a shared library (.so) followed by top-level interface header class. The implementation details are fully hidden from the final user.

This question is not about porting the C++ code to Java, but rather about creating similar distribution package.

Let's assume I have a very simple 'public' class in C++, topapi.h:

```<code>class TopApi
{
public:
  void do( const string& v );
}
</code>```

The actual implementation is hidden from the API user. The actual project may contain another 100 files/classes do() will call.

The distribution will contain 2 files: topapi.so and topapi.h

Users will #include "topapi.h" in their code, and link their applications with topapi.so.

The questions are:
1. How can I achieve a similar effect in Java (hide the IP related code)
2. How do I show public methods to the user ( not related to code protection, just a java version of the header file above )

答:
To answer the question of how to show public methods to the user. This is usually done through a combination of declaring the internal classes without an access modifier, which makes them only accessible from within the same package, and not documenting them. Don't depend on the former though, it's easily circumventable, but it sends the message to the user that those classes are internal.

Java 9 adds modules which allow you to encapsulate entire packages, but it's not here yet, and you would still be able to circumvent the encapsulation.

One side effect of ahead of time compilation (usually the case with C++) is that the distributed code is already optimized, and contains no metadata, so it's harder to reverse engineer. Java is distributed in an intermediate language, but the actual machine code is generated at runtime (JIT compilation). The intermediate language is practically un-optimized, so it's easier to reverse engineer. Java also merges the idea of header files and source files where a .class file will contain all the metadata you need to use it.

Body:
I have a quite complex project to migrate from C++ (Linux) to Java
Currently, the C++ version is being distributed as a shared library (.so) followed by top-level interface header class. The implementation details are fully hidden from the final user.

This question is not about porting the C++ code to Java, but rather about creating similar distribution package.

Let's assume I have a very simple 'public' class in C++, topapi.h:

class TopApi
{
public:
  void do( const string& v );
}

The actual implementation is hidden from the API user. The actual project may contain another 100 files/classes do() will call.

The distribution will contain 2 files: topapi.so and topapi.h

Users will #include "topapi.h" in their code, and link their applications with topapi.so.

The questions are:
1. How can I achieve a similar effect in Java (hide the IP related code)
2. How do I show public methods to the user ( not related to code protection, just a java version of the header file above )


问:
Allow scheduling of pods on Kubernetes master?
I set up Kubernetes on CoreOS on bare metal using the generic install scripts. It's running the current stable release, 1298.6.0, with Kubernetes version 1.5.4.

We'd like to have a highly available master setup, but we don't have enough hardware at this time to dedicate three servers to serving only as Kubernetes masters, so I would like to be able to allow user pods to be scheduled on the Kubernetes master. I set --register-schedulable=true in /etc/systemd/system/kubelet.service but it still showed up as SchedulingDisabled.

I tried to add settings for including the node as a worker, including adding worker TLS certs to /etc/kubernetes/ssl, adding those settings to kubelet.service, adding an /etc/kubernetes/worker-kubeconfig.yaml that pointed to those certs, and added that information to the /etc/kubernetes/manifests/kube-proxy.yaml. I used my existing nodes as a template for what to add. This registered another node under the master's hostname and then both it and the original master node showed up as NotReady,SchedulingDisabled.

This question indicates that scheduling pods on the master node should be possible, but there is barely anything else that I can find on the subject.

答:
I don't know why the master node shows up as NotReady; it shouldn't. Try executing kubectl describe node mymasternode to find out.

The SchedulingDisabled is because the master node is tainted with dedicated=master:NoSchedule

Execute this command against all your masters to remove the taint:

```<code>kubectl taint nodes mymasternode dedicated-
</code>```

To understand why that works read up on taints and tolerations.

Body:
I don't know why the master node shows up as NotReady; it shouldn't. Try executing kubectl describe node mymasternode to find out.

The SchedulingDisabled is because the master node is tainted with dedicated=master:NoSchedule

Execute this command against all your masters to remove the taint:

kubectl taint nodes mymasternode dedicated-

To understand why that works read up on taints and tolerations.


问:
Ruby/Rails - Get the previous Friday? (Friday of last week)
Is there a way to get the previous Friday's date in Rails?  I've seen ways to get the closest Friday, or the previous Monday or Sunday, but I specifically need the last Friday.

So up until and including Friday of this current week, it'd be the previous week's Friday. Then starting on Saturday, it'd be the Friday a day before.

For example:

Saturday, March 4th through Friday, March 10th -> Friday, March 3rd

Saturday, March 11th through Friday, March. 17th -> Friday, March 10th

答:
Try this extension, you can use it as Time.last_friday or Time.now.last_friday

```<code>class Time
  def self.last_friday
    time = (Time.now - 1.day)
    while !time.friday?
      time -= 1.day
    end
    time
  end
  def last_friday
    time = (self - 1.day)
    while !time.friday?
      time -= 1.day
    end
    time
  end
end
</code>```

Body:
Try this extension, you can use it as Time.last_friday or Time.now.last_friday

class Time
  def self.last_friday
    time = (Time.now - 1.day)
    while !time.friday?
      time -= 1.day
    end
    time
  end
  def last_friday
    time = (self - 1.day)
    while !time.friday?
      time -= 1.day
    end
    time
  end
end


问:
C++ Circular Link List - remove all nodes
I am trying to remove all the nodes in singly circular linked list. But I got following Error:

```<code>malloc: *** error for object 0x1005068f0: pointer being freed was not allocated
</code>```

Following is the function:

```<code>void StudentLinkList::removeAll() {
    StudentData *traversePointer = this->head;

    while (this->head != nullptr) {
        this->head = this->head->getNext();
        delete traversePointer;
        traversePointer = nullptr;
        traversePointer = this->head;
        this->size--;
    }
}
</code>```

I get error on this line:

```<code>delete traversePointer;
</code>```

My question is that why traversePointer not allocated in while loop as shown in the error?

答:
The while should be:

```<code>    while(this->size){
</code>```

When the loop completes, then set this->head = nullptr. There's no need to set traversePoitner = nullptr in the loop.

Alternative version (I haven't confirmed this yet), that doesn't rely on this->size being correct, only that the list is circular:

```<code>void StudentLinkList::removeAll() {
    if(this->head == nullptr)
        return;
    StudentData *traversePointer = this->head;
    StudentData *deletePointer;
    do{
        deletePointer = traversePointer;
        traversePointer = traversePointer->getNext();
        delete deletePointer;
    }while(traversePointer != this->head);
    this->head = nullptr;
    this->size = 0;
}
</code>```

Body:
I am trying to remove all the nodes in singly circular linked list. But I got following Error:

malloc: *** error for object 0x1005068f0: pointer being freed was not allocated

Following is the function:

void StudentLinkList::removeAll() {
    StudentData *traversePointer = this->head;

    while (this->head != nullptr) {
        this->head = this->head->getNext();
        delete traversePointer;
        traversePointer = nullptr;
        traversePointer = this->head;
        this->size--;
    }
}

I get error on this line:

delete traversePointer;

My question is that why traversePointer not allocated in while loop as shown in the error?

Body:
The while should be:

    while(this->size){

When the loop completes, then set this->head = nullptr. There's no need to set traversePoitner = nullptr in the loop.

Alternative version (I haven't confirmed this yet), that doesn't rely on this->size being correct, only that the list is circular:

void StudentLinkList::removeAll() {
    if(this->head == nullptr)
        return;
    StudentData *traversePointer = this->head;
    StudentData *deletePointer;
    do{
        deletePointer = traversePointer;
        traversePointer = traversePointer->getNext();
        delete deletePointer;
    }while(traversePointer != this->head);
    this->head = nullptr;
    this->size = 0;
}


问:
How to process incoming sms using Twilio
I am using Twilio for sending SMS from my Java Web Application. I have a Twilio number purchased under my account. Now I am trying to process the incoming SMS to my Twilio number. All I am trying to do is to pass the message data and the sender of the message as an HTTP GET method to my application. I have found the following under my account settings:

In my application, I can add a REST service that can accept these details and save the required details to my database. But I am unable to find any example related to this. Is there any way to get the message details whenever a message is received.

答:
Twilio makes HTTP requests to your application just like a regular web
  browser. By including parameters and values in its requests, Twilio
  sends data to your application that you can act upon before
  responding.

https://www.twilio.com/docs/api/twiml/sms/twilio_request#twilio-data-passing

When Twilio receives a message for one of your Twilio numbers it makes a synchronous HTTP request to the message URL configured for that number, and expects to receive TwiML in response.

Twilio sends parameters with its request as POST parameters or URL query parameters, depending on which HTTP method you've configured. https://www.twilio.com/docs/api/twiml/sms/twilio_request#request-parameters

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

```<code>@RequestMapping(
  value = "/someEndPoint",
  method = RequestMethod.POST,
  consumes = "text/plain"
)
  public String someMethod(@RequestParam("param1") String paramOne) {
 //use paramOne variable here
}
</code>```

Body:
Twilio makes HTTP requests to your application just like a regular web
  browser. By including parameters and values in its requests, Twilio
  sends data to your application that you can act upon before
  responding.

https://www.twilio.com/docs/api/twiml/sms/twilio_request#twilio-data-passing

When Twilio receives a message for one of your Twilio numbers it makes a synchronous HTTP request to the message URL configured for that number, and expects to receive TwiML in response.

Twilio sends parameters with its request as POST parameters or URL query parameters, depending on which HTTP method you've configured. https://www.twilio.com/docs/api/twiml/sms/twilio_request#request-parameters

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(
  value = "/someEndPoint",
  method = RequestMethod.POST,
  consumes = "text/plain"
)
  public String someMethod(@RequestParam("param1") String paramOne) {
 //use paramOne variable here
}


问:
WinForms listbox keydown event won't fire
I am trying to make a WinForm ListBox in which you can loop trough using the arrow keys. I also have two buttons on which you can click to go up and down the list. The buttons do produce the desired effect. The problem is that the ListBox's keyDown event is never triggered

```<code>    public MainForm()
    {
        InitializeComponent();
        if (this.clipboardHistoryList.Items.Count > 0)
            this.clipboardHistoryList.SetSelected(0, true);
        clipboardHistoryList.Select();
    }

   private void goUpButton_Click(object sender, EventArgs e)
    {
        goUpList();
    }

    private void goDownButton_Click(object sender, EventArgs e)
    {
        goDownList();
    }

    private void goDownList()
    {
        if (clipboardHistoryList.SelectedIndex == clipboardHistoryList.Items.Count - 1)
        {
            clipboardHistoryList.SetSelected(0, true);
        }
        else
        {
            clipboardHistoryList.SetSelected(clipboardHistoryList.SelectedIndex + 1, true);
        }
    }

    private void goUpList()
    {
        if (clipboardHistoryList.SelectedIndex == 0)
        {
            clipboardHistoryList.SetSelected(clipboardHistoryList.Items.Count - 1, true);
        }
        else
        {
            int l_currentlySelected = clipboardHistoryList.SelectedIndex;
            clipboardHistoryList.SetSelected(l_currentlySelected - 1, true);
        }
    }

    private void clipboardHistoryList_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)         //Brekpoint is never reached
        {
            goUpList();
        }
        else if (e.KeyCode == Keys.Down)
        {
            goDownList();
        }
    }
</code>```

I have put the MainForm's keypreview proprety to true.

The arrow keys do work by default on a listbox but they won't let you go from last to first element if you press the down arrow on the last element --hopes this makes sense.

EDIT
I have seen on Microsoft's documentation that I need to override the ProcessDialogKey method but I am not exactly sure of what I need to do.

Perform special input or navigation handling on a control. For example, you want the use of arrow keys in your list control to change the selected item.  Override ProcessDialogKey

Is there already a built-in way to enable this behaviour?

What did I miss?

Thanks!

答:
From looking at the code in your Designer.cs file, it doesn't look like you've actually got your clipboardHistoryList control wired into your clipboardHistoryList_KeyDown event handler.  You can do that through the "Events" subtab of the Properties window in your visual studio form designer (look for the little lightning bolt icon) and wire up the event through the designer that way, or alternatively you can do it in code:</p>

```<code>public MainForm()
{
    InitializeComponent();
    if (this.clipboardHistoryList.Items.Count > 0)
        this.clipboardHistoryList.SetSelected(0, true);
    clipboardHistoryList.Select();

    clipboardHistoryList.KeyDown += clipboardHistoryList_KeyDown;
}
</code>```

Body:
I am trying to make a WinForm ListBox in which you can loop trough using the arrow keys. I also have two buttons on which you can click to go up and down the list. The buttons do produce the desired effect. The problem is that the ListBox's keyDown event is never triggered

    public MainForm()
    {
        InitializeComponent();
        if (this.clipboardHistoryList.Items.Count > 0)
            this.clipboardHistoryList.SetSelected(0, true);
        clipboardHistoryList.Select();
    }

   private void goUpButton_Click(object sender, EventArgs e)
    {
        goUpList();
    }

    private void goDownButton_Click(object sender, EventArgs e)
    {
        goDownList();
    }

    private void goDownList()
    {
        if (clipboardHistoryList.SelectedIndex == clipboardHistoryList.Items.Count - 1)
        {
            clipboardHistoryList.SetSelected(0, true);
        }
        else
        {
            clipboardHistoryList.SetSelected(clipboardHistoryList.SelectedIndex + 1, true);
        }
    }

    private void goUpList()
    {
        if (clipboardHistoryList.SelectedIndex == 0)
        {
            clipboardHistoryList.SetSelected(clipboardHistoryList.Items.Count - 1, true);
        }
        else
        {
            int l_currentlySelected = clipboardHistoryList.SelectedIndex;
            clipboardHistoryList.SetSelected(l_currentlySelected - 1, true);
        }
    }

    private void clipboardHistoryList_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)         //Brekpoint is never reached
        {
            goUpList();
        }
        else if (e.KeyCode == Keys.Down)
        {
            goDownList();
        }
    }

I have put the MainForm's keypreview proprety to true.

The arrow keys do work by default on a listbox but they won't let you go from last to first element if you press the down arrow on the last element --hopes this makes sense.

EDIT
I have seen on Microsoft's documentation that I need to override the ProcessDialogKey method but I am not exactly sure of what I need to do.

Perform special input or navigation handling on a control. For example, you want the use of arrow keys in your list control to change the selected item.  Override ProcessDialogKey

Is there already a built-in way to enable this behaviour?

What did I miss?

Thanks!

Body:
From looking at the code in your Designer.cs file, it doesn't look like you've actually got your clipboardHistoryList control wired into your clipboardHistoryList_KeyDown event handler.  You can do that through the "Events" subtab of the Properties window in your visual studio form designer (look for the little lightning bolt icon) and wire up the event through the designer that way, or alternatively you can do it in code:

public MainForm()
{
    InitializeComponent();
    if (this.clipboardHistoryList.Items.Count > 0)
        this.clipboardHistoryList.SetSelected(0, true);
    clipboardHistoryList.Select();

    clipboardHistoryList.KeyDown += clipboardHistoryList_KeyDown;
}


问:
Selenium C# chromedriver with DesiredCapabilities
I would like to implement DesiredCapabilities with a chrome driver instance in C# but from what I can find it isn't possible? For example...

```<code>DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
capabilities.SetCapability(CapabilityType.UnexpectedAlertBehavior, "accept");
Driver = new ChromeDriver(@"C:\Development\Projects\SeleniumObservatoryTests\", capabilities);
</code>```

ChromeDriver seems to require Options. Is there a way to provide UnexpectedAlertBehavior as an Option?

答:
I haven't been able to get it to work either for Chrome.  For Firefox I had to use DesiredCapabilities and for IE I had to use InternetExplorerOptions.

BUT, I have been successful at handling the popup with Chrome, with some code I wrote to handle it.

My code is posted below.  I hope it helps you and whoever else plagued with Modal dialogs.

```<code>    /// <summary>
    /// Returns a true or false if alert is present.
    /// </summary>
    /// <returns>true or false</returns>
    public static bool IsAlertPresent()
    {
        try
        {
            [YOUR DRIVER HERE].SwitchTo().Alert();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// Verifies if an alert is present or not.  If it is, it clicks "Accept".
    /// </summary>
    public static void Alert()
    {
        try
        {
            if (IsAlertPresent())
                [YOUR DRIVER HERE].SwitchTo().Alert().Accept();

        }
        catch (Exception ex)
        {
            ///Log your errors however you must.
        }
    }
</code>```

I know it's not fancy or anything, but it gets the job done.  Basically it tries to switch to an alert, if it's there it returns true, if it's not it returns false.  If true, it switches again and clicks accept.  Very simple.  Hasn't failed me yet.

Body:
I would like to implement DesiredCapabilities with a chrome driver instance in C# but from what I can find it isn't possible? For example...

DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
capabilities.SetCapability(CapabilityType.UnexpectedAlertBehavior, "accept");
Driver = new ChromeDriver(@"C:\Development\Projects\SeleniumObservatoryTests\", capabilities);

ChromeDriver seems to require Options. Is there a way to provide UnexpectedAlertBehavior as an Option?

Body:
I haven't been able to get it to work either for Chrome.  For Firefox I had to use DesiredCapabilities and for IE I had to use InternetExplorerOptions.

BUT, I have been successful at handling the popup with Chrome, with some code I wrote to handle it.

My code is posted below.  I hope it helps you and whoever else plagued with Modal dialogs.

    /// <summary>
    /// Returns a true or false if alert is present.
    /// </summary>
    /// <returns>true or false</returns>
    public static bool IsAlertPresent()
    {
        try
        {
            [YOUR DRIVER HERE].SwitchTo().Alert();
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    /// <summary>
    /// Verifies if an alert is present or not.  If it is, it clicks "Accept".
    /// </summary>
    public static void Alert()
    {
        try
        {
            if (IsAlertPresent())
                [YOUR DRIVER HERE].SwitchTo().Alert().Accept();

        }
        catch (Exception ex)
        {
            ///Log your errors however you must.
        }
    }

I know it's not fancy or anything, but it gets the job done.  Basically it tries to switch to an alert, if it's there it returns true, if it's not it returns false.  If true, it switches again and clicks accept.  Very simple.  Hasn't failed me yet.