问:
Kotlin Ternary Conditional Operator
What is the equivalent of this expression in Kotlin?

```<code>a ? b : c
</code>```

This is not valid code in Kotlin.

答:
as Drew Noakes quoted, kotlin use if statement as expression,
so Ternary Conditional Operator is not necessary anymore,

but with the extension function and infix overloading, you could implement that yourself, here is an example

```<code>infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value)

class TernaryExpression<out T>(val flag: Boolean, val truly: T?) {
    infix fun <T> or(falsy: T?) = if (flag) truly else falsy
}
</code>```

then use it like this

```<code>val grade = 90
val clazz = (grade > 80) then "A" or "B"
</code>```

Title: Kotlin Ternary Conditional Operator

Body:
What is the equivalent of this expression in Kotlin?

a ? b : c

This is not valid code in Kotlin.

Body:
as Drew Noakes quoted, kotlin use if statement as expression,
so Ternary Conditional Operator is not necessary anymore,

but with the extension function and infix overloading, you could implement that yourself, here is an example

infix fun <T> Boolean.then(value: T?) = TernaryExpression(this, value)

class TernaryExpression<out T>(val flag: Boolean, val truly: T?) {
    infix fun <T> or(falsy: T?) = if (flag) truly else falsy
}

then use it like this

val grade = 90
val clazz = (grade > 80) then "A" or "B"


来源: stackexchange

问:
DeadSystemException start service Android 7
For the past few weeks, I have on my crash reporter:

```<code>Fatal Exception: java.lang.RuntimeException: Unable to start service com.####.MyService@ef705d8 with Intent { act=HIDE cmp=com.####/.MyService (has extras) }: java.lang.RuntimeException: android.os.DeadSystemException
       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3344)
       at android.app.ActivityThread.-wrap21(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1583)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6121)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
</code>```

This crash is present on:

all Samsung devices 7.0

all Nexus devices on 7.1.2

Note:

It is not due to a recent update of our application, just an OS updates on theses phones.

It is a very very frequent crashes (by far our biggest).

Our users don't report crashes than before (is this crash actually visible for the user?)

We are not able to reproduce it on our side

As you can see into the stack trace, the code impacted is system only. Not much I can do from my side to try and catch and handle the issue.

I checked the thread Android DeadSystemException but that doesn't help me much.

I know that DeadSystemException is:

The core Android system has died and is going through a runtime restart. All running apps will be promptly killed.

Is there anything we can do but to say "that's system, we cannot do anything"?

答:
When the device is being restarted, you cannot run an app. Any app, not just yours but any given app cannot run when the device is restarting. AFAIK it occurs when you try to do something when the system crashes. Meaning if the system crashes and as it restarts your app starts a service or does something you get that error.

Meaning the exception is not connected to your app, but the Android OS and there is nothing you can do about it.

The crash being related to starting a service is because that is what your app did when the system crashed.

So: The error is something the system threw because your app did something when the system did a run-time reboot. There is nothing you can do about this, as you cannot control the Android OS from an app.

ContentLicense: CC BY-SA 3.0

Body:
For the past few weeks, I have on my crash reporter:

Fatal Exception: java.lang.RuntimeException: Unable to start service com.####.MyService@ef705d8 with Intent { act=HIDE cmp=com.####/.MyService (has extras) }: java.lang.RuntimeException: android.os.DeadSystemException
       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3344)
       at android.app.ActivityThread.-wrap21(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1583)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:154)
       at android.app.ActivityThread.main(ActivityThread.java:6121)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

This crash is present on:

all Samsung devices 7.0

all Nexus devices on 7.1.2

Note:

It is not due to a recent update of our application, just an OS updates on theses phones.

It is a very very frequent crashes (by far our biggest).

Our users don't report crashes than before (is this crash actually visible for the user?)

We are not able to reproduce it on our side

As you can see into the stack trace, the code impacted is system only. Not much I can do from my side to try and catch and handle the issue.

I checked the thread Android DeadSystemException but that doesn't help me much.

I know that DeadSystemException is:

The core Android system has died and is going through a runtime restart. All running apps will be promptly killed.

Is there anything we can do but to say "that's system, we cannot do anything"?


问:
Android "tabindex"
I have several LinearLayouts contained inside their respective ScrollView which in turn are contained by a ViewFlipper. The odd stuff is that in some of the Layouts once they have the focus, it starts automatically in a place other than the top.

So what can be causing this ? In order to force them to start at the top, is there something like the tabindex property in html ?

Thanks

答:
if you have problem called focus is gone automatically on other place instead of top position's field then you have to write this code simply at onStart() method of activity life cycle with respective field id in my case first field
is referenced by firstfield_et this is the variable of Activity.java file and it is also already referenced by etfirstfield from .xml file

the code is simply as below:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText firstfield_et= (EditText) findViewById(R.id.etfirstfield);
}

@Override
protected void onStart() {
    super.onStart();
    if(TextUtils.isEmpty(firstfield_et.getText().toString())){
        firstfield_et.requestFocus();
    }
}
</code>```

Title: Android "tabindex"

Body:
if you have problem called focus is gone automatically on other place instead of top position's field then you have to write this code simply at onStart() method of activity life cycle with respective field id in my case first field
is referenced by firstfield_et this is the variable of Activity.java file and it is also already referenced by etfirstfield from .xml file

the code is simply as below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    EditText firstfield_et= (EditText) findViewById(R.id.etfirstfield);
}

@Override
protected void onStart() {
    super.onStart();
    if(TextUtils.isEmpty(firstfield_et.getText().toString())){
        firstfield_et.requestFocus();
    }
}


问:
Random Non-White Colors That Look Okay As Background for Black Text
I'd like to generate random, non-white colors using hue, saturation and brightness that can be used as a background for black text. I've created a generator for random colors, but when I scan the numbers, I can't see any clear pattern in the colors that look too dark.

How can I generate random non-white background colors for black text? Feel free to answer with code or pseudo-code, but it's definitely not necessary.

答:
Only generate colors with high brightness values - for example, if you were using the range 0-255 for each of {H,S,V}, you'd generate H in [0,255], S in [0,255], V in [168,255]. That should give you colors that are bright enough. You may want to restrict saturation as well (e.g. S in [0,192]), since black on full-bright, full-saturation colors may not be very readable.

You'll probably need to play with the values to get ranges that will give you usable colors.

ContentLicense: CC BY-SA 2.5


问:
Why my access to non static string variable doesn't work
Why my access to non static string variable doesn't work. Try to do it and my IDE found it already but when I run it show "Cannot find symbol"
Please help me, Thank You.</p>

```<code>public class Main
{
    public static void main(String[] args)
    {
        testWrong obj = new testWrong();
        System.out.println(obj.public_non_static()); //Doesn't Work

    }

}

public class testWrong
{
    public String public_non_static = "It is Public non Static";

    public void in_non_static_method()
    {
        testWrong obj1 = new testWrong();
        obj1.public_non_static();   //Doesn't Work

    }

    public static void in_static_method()
    {
        testWrong obj2 = new testWrong();
        obj2.public_non_static(); //Doesn't Work also
    }
}
</code>```

答:
You are accessing like a method :public_non_static();

Use this instead : obj2.public_non_static;

And since you are like very new to OOP, it's the best practice to not to use public keyword and you should make them private and make getters and setters for them.

Body:
Why my access to non static string variable doesn't work. Try to do it and my IDE found it already but when I run it show "Cannot find symbol"
Please help me, Thank You.

public class Main
{
    public static void main(String[] args)
    {
        testWrong obj = new testWrong();
        System.out.println(obj.public_non_static()); //Doesn't Work

    }

}

public class testWrong
{
    public String public_non_static = "It is Public non Static";

    public void in_non_static_method()
    {
        testWrong obj1 = new testWrong();
        obj1.public_non_static();   //Doesn't Work

    }

    public static void in_static_method()
    {
        testWrong obj2 = new testWrong();
        obj2.public_non_static(); //Doesn't Work also
    }
}


问:
I am not able to find the .exe file in Visual Studio 2013
I am trying to create a c++ blank project
I am not able to find the .exe file in the debug folder.
Where can I find it or should I search in a new directory or should I do something else?
Pls help.
Thanks </p>

答:
First, write a program in the blank project then build your project, a debug/Release (based on the mode you select) folder will be created inside bin folder which is present in the same directory as the .sln (solution) file.

You can find the .exe file inside the debug/Release folder.


问:
When Developing the database then compolsury to define the primary key or forign key in each tables of the database?
When Developing the database then compolsury to  define the primary key or forign key in each tables of the databse if any tables that do not contain any unique field that time how can we connect the table with other table.
Suppose i have three tabe.

table1 Personel Detail

```<code>Emai_Address (PK)
Name
City
ContactNo
Land_Line_No
D_O_B
Gender
Marital_Status
Language_Known
</code>```

Table2 Professiona_Detail

```<code>Total_Experiance
Annual_Salary
Functional_Area
Current_Industry
Key_Skill
Resume_HeadLine
</code>```

Table3 WorkPreference

```<code>Specify Your Preference
Start Working
Prefered Location
Job Type
</code>```

The Obove Table1 contain the PK but Table2 or Table 3 does not contain any Pk Or FK then  how can connect this three table.

答: Table2 and Table3 should have a FK to Table1. Otherwise you will not know what person the records in those tables are for. Each table should also have a PK defined for it. This is so that you can uniquely identify a row when doing UPDATES or DELETES.

OwnerDisplayName: harikrishna

Body:
When Developing the database then compolsury to  define the primary key or forign key in each tables of the databse if any tables that do not contain any unique field that time how can we connect the table with other table.
Suppose i have three tabe.

table1 Personel Detail

Emai_Address (PK)
Name
City
ContactNo
Land_Line_No
D_O_B
Gender
Marital_Status
Language_Known

Table2 Professiona_Detail

Total_Experiance
Annual_Salary
Functional_Area
Current_Industry
Key_Skill
Resume_HeadLine

Table3 WorkPreference

Specify Your Preference
Start Working
Prefered Location
Job Type

The Obove Table1 contain the PK but Table2 or Table 3 does not contain any Pk Or FK then  how can connect this three table.


问:
Sails.JS cannot find a route when redirecting
I try to implement an login process correctly, i'm using a server render view approch for the frontend. Based on what a sails.js offical documentation says about setting routes, so in my routes.js, i have this :

```<code>module.exports.routes = {

  '/': {
    view: 'login'
  },
  // Server render HTML views

  'POST /signup':'UserController.signup',
  'PUT /login': 'UserController.login',
  'GET /logout':'UserController.logout',
  'GET /profile': 'PageController.showProfilePage',
  'GET /dashboard': 'PageController.showDashboardPage',
  'GET /products': 'PageController.showProductPage'

  };
</code>```

Normally the dashboard route exists so what i wanted to do is when i login, i'm automatically redirected to the dashboard.
So in my UserController.js, i have this:

```<code>  login : function (req, res){
    //... some code here
            success : function (){
                if(userFound.deleted){
                    return res.forbidden("'Your account has been deleted.
  Please visit ecommerce.com/restore to restore your account'");
                }
                if(userFound.banned){
                    return res.forbidden("'Your account has been banned
  completly because you didn't respect the use term of our site");
                }
                // Store user id in a session
                req.session.userId = userFound.id;
                console.log(req.session);
                res.redirect('/dashboard');
                return;
            }
        })
       })
       }
</code>```

And finally, i have my PageController, where i show all the different views of web app based on whether or not the user is authenticated, in this case is dashboard. So , here is what my code says:

```<code>    showDashboardPage: function (req, res){
       if(!req.session.userId){
          console.log(req.session);
          return res.redirect('/')
       }
    if(req.session.userId){
        User.findOne(req.session.userId, function (err, user){
            if(err){
                console.log(req.session);
                return res.negotiate(err);
            }
            if(!user){
                console.log(req.session);
                sails.log.verbose('Session refers to a user who no longer exist');
                return res.redirect('/');
            }

            console.log(req.session);
            return res.view('user/dashboard', {
                layout: 'user/mainUserLayout',
                me: {
                    id: user.id,
                    username: user.username,
                    fullname: user.fullname,
                    profilePicture: user.profilePicture,
                    admin: user.admin
                }
            });
        });
    }
}
</code>```

When i login , i'm getting a 404 not found error from the server. I don't know if i'm really missing something. Some help will be verry appreciated. :)

答: If you're receiving a 404 it's likely that a view you're returning is not at the path you're specified. Have a look at the console log in your browser and check which resource it is that it not found. From here it should be easy for you to deduce the issue. If it is only after you've logged in then my suspicion is that one of your path is incorrect for one of your views. </p>

Body:
I try to implement an login process correctly, i'm using a server render view approch for the frontend. Based on what a sails.js offical documentation says about setting routes, so in my routes.js, i have this :

module.exports.routes = {

  '/': {
    view: 'login'
  },
  // Server render HTML views

  'POST /signup':'UserController.signup',
  'PUT /login': 'UserController.login',
  'GET /logout':'UserController.logout',
  'GET /profile': 'PageController.showProfilePage',
  'GET /dashboard': 'PageController.showDashboardPage',
  'GET /products': 'PageController.showProductPage'

  };

Normally the dashboard route exists so what i wanted to do is when i login, i'm automatically redirected to the dashboard.
So in my UserController.js, i have this:

  login : function (req, res){
    //... some code here
            success : function (){
                if(userFound.deleted){
                    return res.forbidden("'Your account has been deleted.
  Please visit ecommerce.com/restore to restore your account'");
                }
                if(userFound.banned){
                    return res.forbidden("'Your account has been banned
  completly because you didn't respect the use term of our site");
                }
                // Store user id in a session
                req.session.userId = userFound.id;
                console.log(req.session);
                res.redirect('/dashboard');
                return;
            }
        })
       })
       }

And finally, i have my PageController, where i show all the different views of web app based on whether or not the user is authenticated, in this case is dashboard. So , here is what my code says:

    showDashboardPage: function (req, res){
       if(!req.session.userId){
          console.log(req.session);
          return res.redirect('/')
       }
    if(req.session.userId){
        User.findOne(req.session.userId, function (err, user){
            if(err){
                console.log(req.session);
                return res.negotiate(err);
            }
            if(!user){
                console.log(req.session);
                sails.log.verbose('Session refers to a user who no longer exist');
                return res.redirect('/');
            }

            console.log(req.session);
            return res.view('user/dashboard', {
                layout: 'user/mainUserLayout',
                me: {
                    id: user.id,
                    username: user.username,
                    fullname: user.fullname,
                    profilePicture: user.profilePicture,
                    admin: user.admin
                }
            });
        });
    }
}

When i login , i'm getting a 404 not found error from the server. I don't know if i'm really missing something. Some help will be verry appreciated. :)


问:
Shared scope in Spring Controller
I have a Spring web app, it has a main controller which instantiates an object such as:

```<code>@Controller
public class testController {

private Boom boom = new Boom();

}
</code>```

This object would for example have a Get method to display an arraylist of strings for the user to edit and save.

But if there are 2 sessions open, if I edit the list on one and save, then refresh the second session (second browser) it shows on that one. I don't want this to happen. I'd want the controller to make this object unique for each user viewing the application

What are my options for scoping this?

答:
As a  best practice , Controller Object must be Singleton and beans which is being used by them, should have appropriate scope based on their functionality.

In you case as the bean Boom is used in a multiple requests across a user-session, hence you should create Boom with a scope of Session.

Read more about Spring scopes here and here.

Title: Shared scope in Spring Controller

Body:
I have a Spring web app, it has a main controller which instantiates an object such as:

@Controller
public class testController {

private Boom boom = new Boom();

}

This object would for example have a Get method to display an arraylist of strings for the user to edit and save.

But if there are 2 sessions open, if I edit the list on one and save, then refresh the second session (second browser) it shows on that one. I don't want this to happen. I'd want the controller to make this object unique for each user viewing the application

What are my options for scoping this?


答:
You have a variable named public_non_static but you try to access a method with that name which does not work in Java.

on the other hand you should not get used to access variables in other classes directly since it violates the most important OO principle information hiding/encapsulation.

The same is true for getter/setter methods which should only be used on stupid data transfer objects (DTOs) or Value Objects which have no (business) logic.

Title: Why my access to non static string variable doesn't work


问:
jQuery toggle with active class
I have a menu with "yes / no" options just like this.

The red color box containing word "yes" is my active button. I just want to show another options when users click yes. So I used jQuery toggle function.

When page load, it showing menu with options just like this.

But I don't want to show it until users click yes. I figured out the problem. It happened because yes button has an active class activated. That's why it showing its options. And also I need to hide that toggle menu options when click no.

I tried with jquery hide functions adding another class to no. It seems ok but expert advice needed.

```<code>$(".remove-toggle").click(function(){
 $(".wrap").hide();
});
</code>```

Working jsfiddle here.

答:
Yes, what you have looks fine, except that clicking 'yes' twice will hide and show, and you don't want that. To solve that, use fadeIn instead of fadeToggle for the .click() JQuery function.

To solve the other problem, use this CSS:

```<code>.wrap {
  display: none;
}
</code>```

And remove the active class from the 'yes' button.
See this:

$('.btn-switch').click(function() {
    var $group = $(this).closest('.form-group');
    $('.btn-switch', $group).removeClass("active");
    $(this).addClass("active");
  });
  $(".activate-toggle").click(function() {
    $(".wrap").fadeIn();
  });
  $(".remove-toggle").click(function() {
    $(".wrap").fadeOut();
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-switch.active {
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}
.wrap {
  display: none;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

    Do you have the car right now?

      <button type="button" class="btn btn-default btn-switch activate-toggle"> Yes
      </button>

        <button type="button" class="btn btn-default btn-switch remove-toggle">No
        </button>

    Qualification type

      <input type="text" class="form-control input-std" id="qualification-type">

```

Title: jQuery toggle with active class

Body:
I have a menu with "yes / no" options just like this.

The red color box containing word "yes" is my active button. I just want to show another options when users click yes. So I used jQuery toggle function.

When page load, it showing menu with options just like this.

But I don't want to show it until users click yes. I figured out the problem. It happened because yes button has an active class activated. That's why it showing its options. And also I need to hide that toggle menu options when click no.

I tried with jquery hide functions adding another class to no. It seems ok but expert advice needed.

$(".remove-toggle").click(function(){
 $(".wrap").hide();
});

Working jsfiddle here.

Body:
Yes, what you have looks fine, except that clicking 'yes' twice will hide and show, and you don't want that. To solve that, use fadeIn instead of fadeToggle for the .click() JQuery function.

To solve the other problem, use this CSS:

.wrap {
  display: none;
}

And remove the active class from the 'yes' button.
See this:

$('.btn-switch').click(function() {
    var $group = $(this).closest('.form-group');
    $('.btn-switch', $group).removeClass("active");
    $(this).addClass("active");
  });
  $(".activate-toggle").click(function() {
    $(".wrap").fadeIn();
  });
  $(".remove-toggle").click(function() {
    $(".wrap").fadeOut();
  });

.btn-switch.active {
  background: #e46a5d!important;
  color: #fff;
  font-weight: normal;
  text-shadow: none;
}
.wrap {
  display: none;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <label for="member" class="col-md-5 col-sm-12 control-label">
    Do you have the car right now?
  </label>
  <div class="col-lg-10">
    <div class="btn-group">
      <button type="button" class="btn btn-default btn-switch activate-toggle"> <span class="goods">Yes</span>
      </button>
      <div class="btn-group">
        <button type="button" class="btn btn-default btn-switch remove-toggle"><span class="services">No</span>
        </button>
      </div>
    </div>
  </div>
</div>

<div class="wrap">
  <div class="form-group">
    <label for="lastname" class="col-md-5 col-sm-12 control-label">Qualification type</label>
    <div class="col-lg-7 col-md-7 col-sm-12 form-input">
      <input type="text" class="form-control input-std" id="qualification-type">
    </div>
  </div>
</div>


问:
Python Tabs Fake or Real
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ????

[UPDATE]
Thanks! I am now switching to spaces of 4.

Added following to my .vimrc
"Python

```<code>au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
fu Select_c_style()
    if search('^\t', 'n', 150)
        set shiftwidth=8
        set noexpandtab
    el
        set shiftwidth=4
        set expandtab
    en
endf
</code>```

For other case:

```<code>set noexpandtab                " tabs are tabs, not spaces
</code>```

答:
As soon as you allow a tab character into a file, you will end up in a situation with mixed tabs and spaces, and then you will start to get parsing errors. This gets worse when multiple people are working on a project, and have their spacing settings set different from each other.

PEP8 recommends "4 spaces": http://www.python.org/dev/peps/pep-0008/

And this recommendation is made with experience, dealing with the kinds of problems that mixing tabs and spaces in Python brings. Much, much better to save yourself the pain, and just use 4 spaces for your Python code.

Title: Python Tabs Fake or Real

Body:
Many tutorial suggest users to use tab with width of 4 while 4 is made using spaces not real tab character. Using real tab also it works so why do people suggest to use spaces of 4 rather than real tab ? I'm a python beginner confused ????

[UPDATE]
Thanks! I am now switching to spaces of 4.

Added following to my .vimrc
"Python

au BufRead,BufNewFile *.py,*pyw set shiftwidth=4
au BufRead,BufNewFile *.py,*.pyw set expandtab
fu Select_c_style()
    if search('^\t', 'n', 150)
        set shiftwidth=8
        set noexpandtab
    el
        set shiftwidth=4
        set expandtab
    en
endf

For other case:

set noexpandtab                " tabs are tabs, not spaces


问:
Add one day to calendar to make test if-else
I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.

Let's say I create like this :

```<code>English - Beginning 07.05.2017 End 07.07.2017
</code>```

Then I want to modify the end of that lesson and put :

```<code>07.06.2017
</code>```

I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.

I wrote like this in my if else :

```<code>       String date1 = datedebut.getText().toString();
        String date2 = datefin.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date_debutnew = dateFormat.parse(date_initial);
        Date date_derniernew = dateFormat.parse(date_derniercours);
 Calendar calendar = Calendar.getInstance();

     if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))

    { ... }
</code>```

How can I add one day to that calendar ?

Thank you for the future hlep.

答:
From what I understand of the problem, your new Finish date should be after the new Start date and before the designated end Date.
so, the condition should be :</p>

```<code>if (date_derniernew.after(date_debutnew) || date_derniernew.before(date2)) {
..}
</code>```

Body:
I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.

Let's say I create like this :

English - Beginning 07.05.2017 End 07.07.2017

Then I want to modify the end of that lesson and put :

07.06.2017

I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.

I wrote like this in my if else :

       String date1 = datedebut.getText().toString();
        String date2 = datefin.getText().toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date_debutnew = dateFormat.parse(date_initial);
        Date date_derniernew = dateFormat.parse(date_derniercours);
 Calendar calendar = Calendar.getInstance();

     if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))

    { ... }

How can I add one day to that calendar ?

Thank you for the future hlep.

Body:
From what I understand of the problem, your new Finish date should be after the new Start date and before the designated end Date.
so, the condition should be :

if (date_derniernew.after(date_debutnew) || date_derniernew.before(date2)) {
..}


问:
Mock an object which is part of mocked object
when I run the test case I get AnObj mocked. this is used from inside the target classes method. when that method gets invoked the 'anOtherObj' is accessed and that is found to be null. Can some one please point out how to make sure 'anOtherObj' is not null so that I dont get nullpointer there?</p>

```<code>    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();

    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}
</code>```

答: Why would you care what's inside mock (AnObj)? I assume you haven't yet declared interactions on that mock using Mockito.when.</p>

Body:
when I run the test case I get AnObj mocked. this is used from inside the target classes method. when that method gets invoked the 'anOtherObj' is accessed and that is found to be null. Can some one please point out how to make sure 'anOtherObj' is not null so that I dont get nullpointer there?

    @Test
    public class TestTargetTest {

    @Mock
    private AnObj anObj;

    @InjectMocks
    private TestTarget testTarget;

    @BeforeMethod
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testTarget() {

        when(anObj.someMethod()).thenCallRealMethod();

        testTarget.testTarget();

    }

}

@Component
public class TestTarget {

    @Autowired
    private AnObj anObj;

    public void testTarget(){

        anObj.someMethod();
    }
}

@Component
public class AnObj {

    @Autowired
    private AnOtherObj anOtherObj;

    public void someMethod(){
        syso(anOtherObj.toString());
    }
}


问:
Hide translation key on page load angular
I am using Angular-translate in combination with partial-loader,i want to hide translate key on page load.
 in app.js

```<code>       var app = angular.module('myapp', [
          'ngRoute',
          'appRoutes',
          'pascalprecht.translate',
          'angularTranslate',
          'indexCtrl'
        ]);

    angular.module('angularTranslateApp', ['pascalprecht.translate']).config(function($translateProvider) {
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'translation/{lang}/{part}.json'
        });
 $translateProvider.preferredLanguage('en-US');
</code>```

index.js

```<code>angular.module('indexCtrl', []).controller('indexController',
  function($scope, $translate, $translatePartialLoader) {

    $translatePartialLoader.addPart('test');
    $translate.refresh();

});
</code>```

test.json

```<code>{
"testkey":"testval"
}
</code>```

HTML

```<code>{{ "testkey" || translate }}
</code>```

so on page load its showing testkey for few seconds,i dont want to show this,how to acheive this. i have already used translate-cloak but its not working

答:
Either load one language statically and set it as preferred language with $translate.preferredLanguage(), so there is data to show right away, when the page loads for the very first time.

Or use the $translateChangeSuccess event to apply a custom CSS class to your elements, i.e. hide them on default and make them visible as soon as language was set properly. This way you will not see the translation keys, since they are hidden initially.

Also have a look at the paragraph about FOUC in this article.

Body:
I am using Angular-translate in combination with partial-loader,i want to hide translate key on page load.
 in app.js

       var app = angular.module('myapp', [
          'ngRoute',
          'appRoutes',
          'pascalprecht.translate',
          'angularTranslate',
          'indexCtrl'
        ]);

    angular.module('angularTranslateApp', ['pascalprecht.translate']).config(function($translateProvider) {
        $translateProvider.useLoader('$translatePartialLoader', {
            urlTemplate: 'translation/{lang}/{part}.json'
        });
 $translateProvider.preferredLanguage('en-US');

index.js

angular.module('indexCtrl', []).controller('indexController',
  function($scope, $translate, $translatePartialLoader) {

    $translatePartialLoader.addPart('test');
    $translate.refresh();

});

test.json

{
"testkey":"testval"
}

HTML

{{ "testkey" || translate }}

so on page load its showing testkey for few seconds,i dont want to show this,how to acheive this. i have already used translate-cloak but its not working


问:
MongoDB - Permission denied for socket: 127.0.0.1:27025
I am getting an erro log after the reboot of Redhat 7

```<code>listen(): bind() failed errno:13 Permission denied for socket: 127.0.0.1:27025
systemd[1]: mongod.service: main process exited, code=exited, status=100/n/a
</code>```

mongod.service

```<code>[Unit]
  Description=High-performance, schema-free document-oriented database
  After=network.target

 [Service]
   User=mongod
   Group=mongod
   Environment="OPTIONS=--quiet -f /etc/mongod1.conf"
   ExecStart=/usr/bin/mongod $OPTIONS run
   ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
   ExecStartPre=/usr/bin/chown root:root /var/run/mongodb
   ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb
   PermissionsStartOnly=true
   PIDFile=/var/run/mongodb/mongod1.pid

 [Install]
   WantedBy=multi-user.target
</code>```

mongod1.conf

```<code>#systemLog:
  destination: file
  logAppend: true
  path: /home/telenstanley/mongod1.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo/db1
  journal:
    enabled: true
#  engine:
  mmapv1:
    smallFiles: true
#  wiredTiger:

# how the process runs
processManagement:
  fork: false  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod1.pid  # location of pidfile

# network interfaces
net:
  port: 27025
  bindIp: 127.0.0.1  # Listen to local interface only, comment to listen on all interfaces.

#security:
 # authorization: enabled
#operationProfiling:

replication:
  oplogSizeMB: 1024
  replSetName: testrep
#sharding:

## Enterprise-Only Options
</code>```

I am not able to find any useful answer for my problem yet.but the mongod starts successfully by running as root user from cmd

sudo mongod -f mongod1.conf

答:
found the answer after a couple of time..

You must configure SELinux to allow MongoDB to start on Red Hat Linux-based systems (Red Hat Enterprise Linux or CentOS Linux).

The permission issue is solved by making access to the relevant ports (e.g. 27017) for SELinux if in enforcing mode. See Default MongoDB Port for more information on MongoDB’s default ports. For default settings, this can be accomplished by running

```<code>semanage port -a -t mongod_port_t -p tcp 27025
</code>```

Body:
I am getting an erro log after the reboot of Redhat 7

listen(): bind() failed errno:13 Permission denied for socket: 127.0.0.1:27025
systemd[1]: mongod.service: main process exited, code=exited, status=100/n/a

mongod.service

[Unit]
  Description=High-performance, schema-free document-oriented database
  After=network.target

 [Service]
   User=mongod
   Group=mongod
   Environment="OPTIONS=--quiet -f /etc/mongod1.conf"
   ExecStart=/usr/bin/mongod $OPTIONS run
   ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb
   ExecStartPre=/usr/bin/chown root:root /var/run/mongodb
   ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb
   PermissionsStartOnly=true
   PIDFile=/var/run/mongodb/mongod1.pid

 [Install]
   WantedBy=multi-user.target

mongod1.conf

#systemLog:
  destination: file
  logAppend: true
  path: /home/telenstanley/mongod1.log

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo/db1
  journal:
    enabled: true
#  engine:
  mmapv1:
    smallFiles: true
#  wiredTiger:

# how the process runs
processManagement:
  fork: false  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod1.pid  # location of pidfile

# network interfaces
net:
  port: 27025
  bindIp: 127.0.0.1  # Listen to local interface only, comment to listen on all interfaces.

#security:
 # authorization: enabled
#operationProfiling:

replication:
  oplogSizeMB: 1024
  replSetName: testrep
#sharding:

## Enterprise-Only Options

I am not able to find any useful answer for my problem yet.but the mongod starts successfully by running as root user from cmd

sudo mongod -f mongod1.conf

Body:
found the answer after a couple of time..

You must configure SELinux to allow MongoDB to start on Red Hat Linux-based systems (Red Hat Enterprise Linux or CentOS Linux).

The permission issue is solved by making access to the relevant ports (e.g. 27017) for SELinux if in enforcing mode. See Default MongoDB Port for more information on MongoDB’s default ports. For default settings, this can be accomplished by running

semanage port -a -t mongod_port_t -p tcp 27025


问:
In PostScript, define a procedure to define other procedures
The purpose of this question is to understand PostScript a bit better from a programming perspective. The goal described below is just an example used for illustration.

In the PostScript language, I can define a procedure to set the current graphics color as follows:

```<code>/cRED { 1 0 0 setrgbcolor } def  % define a procedure to set the color to red.
</code>```

I was wondering if there was a way to define a procedure that would define other color procedures. Assume that such a procedure called cdef were defined. I could use it as follows:

```<code>/cRED 1 0 0 cdef
</code>```

This should have the same effect as the previous definition of cRED.
The problem is that I can't seem to figure out how to "capture" the literal value of items on the stack in a procedure passed to def.

I tried the following:

```<code>/cdef { /B exch def /G exch def /R exch def { R G B setrgbcolor } bind def } def
/cRED 1 0 0  cdef
/cGRN 0 1 0  cdef
/cBLU 0 0 1  cdef
</code>```

My expectation was that by using bind the values of R G and B would be captured literally. I.e. I was expecting the code above to be equivalent to this:

```<code>/cRED { 1 0 0 setrgbcolor } def
/cGRN { 0 1 0 setrgbcolor } def
/cBLU { 0 0 1 setrgbcolor } def
</code>```

Unfortunately the actual result is that cRED cGRN and cBLU all set the color to blue. This is because cRED cGRN and cBLU are still dependent on the R G and B objects (which are globals). And so the color is blue for all because cBLU defined last, setting R G and B. Apparently bind didn't work the way I expected.

Is there a way to define cdef to achieve this? The crux of the issue is being able to pop a value off the stack and store it literally using def. E.g. something like this pseudo-code:

```<code>/cdef { { $ $ $ setrgbcolor } bind def } def
</code>```

Where $ woudl be replaced with the literal value of the item at the top of the stack when cdef is being evaluated. So /cCYN 0 1 1 cdef is evaluated as /cCYN { 0 1 1 setrgbcolor } bind def

Is there some operator that fulfills the purpose of the $ as described above? The operators pop, =, and index are close, but don't seem to work.
In addition, the use of Immediately Evaluated Names (e.g. //name) seems promising, but they seem to be evaluated even before cdef is executed.

Thanks

答:
Do it by "rolling" the parameters in place instead of assigning them

```<code>/cdef { [ 4 1 roll /setrgbcolor load ] cvx bind def } def
</code>```

In that way, when the ] cvx bind def inside is executed it finds on the operand stack

```<code>/YourNameForTheProcedure
[ (i.e. mark)
your three parameters (the mark has been rolled below them)
the setrgbcolor operator (or procedure?)
</code>```

Then the closing ] will make an array out of the three numbers and the setrgbcolor, that will be made into a procedure by cvx.

Note: Then You have to pass the r,g,b parameters in the correct order:

```<code>/CR 1 0 0 cdef
/CG 0 1 0 cdef
/CB 0 0 1 cdef
</code>```

Body:
The purpose of this question is to understand PostScript a bit better from a programming perspective. The goal described below is just an example used for illustration.

In the PostScript language, I can define a procedure to set the current graphics color as follows:

/cRED { 1 0 0 setrgbcolor } def  % define a procedure to set the color to red.

I was wondering if there was a way to define a procedure that would define other color procedures. Assume that such a procedure called cdef were defined. I could use it as follows:

/cRED 1 0 0 cdef

This should have the same effect as the previous definition of cRED.
The problem is that I can't seem to figure out how to "capture" the literal value of items on the stack in a procedure passed to def.

I tried the following:

/cdef { /B exch def /G exch def /R exch def { R G B setrgbcolor } bind def } def
/cRED 1 0 0  cdef
/cGRN 0 1 0  cdef
/cBLU 0 0 1  cdef

My expectation was that by using bind the values of R G and B would be captured literally. I.e. I was expecting the code above to be equivalent to this:

/cRED { 1 0 0 setrgbcolor } def
/cGRN { 0 1 0 setrgbcolor } def
/cBLU { 0 0 1 setrgbcolor } def

Unfortunately the actual result is that cRED cGRN and cBLU all set the color to blue. This is because cRED cGRN and cBLU are still dependent on the R G and B objects (which are globals). And so the color is blue for all because cBLU defined last, setting R G and B. Apparently bind didn't work the way I expected.

Is there a way to define cdef to achieve this? The crux of the issue is being able to pop a value off the stack and store it literally using def. E.g. something like this pseudo-code:

/cdef { { $ $ $ setrgbcolor } bind def } def

Where $ woudl be replaced with the literal value of the item at the top of the stack when cdef is being evaluated. So /cCYN 0 1 1 cdef is evaluated as /cCYN { 0 1 1 setrgbcolor } bind def

Is there some operator that fulfills the purpose of the $ as described above? The operators pop, =, and index are close, but don't seem to work.
In addition, the use of Immediately Evaluated Names (e.g. //name) seems promising, but they seem to be evaluated even before cdef is executed.

Thanks

Body:
Do it by "rolling" the parameters in place instead of assigning them

/cdef { [ 4 1 roll /setrgbcolor load ] cvx bind def } def

In that way, when the ] cvx bind def inside is executed it finds on the operand stack

/YourNameForTheProcedure
[ (i.e. mark)
your three parameters (the mark has been rolled below them)
the setrgbcolor operator (or procedure?)

Then the closing ] will make an array out of the three numbers and the setrgbcolor, that will be made into a procedure by cvx.

Note: Then You have to pass the r,g,b parameters in the correct order:

/CR 1 0 0 cdef
/CG 0 1 0 cdef
/CB 0 0 1 cdef


问:
How to specifiy the java/android platform with IntelliJ-IDEA?
I wanted to try out IntelliJ-IDEA but my experiments failed in a very early state. The Problem is that I found no way to set the Java platforms to be used.

Standard Java fails @Override annotation as IntelliJ-IDEA fails to to use the installed Java 6.

Android tells me to set the Android platform - only there is no setting so be seen to set any platform.

So what am I missing here?

答:
Use File -> Project Structure menu.

There you can specify jdk(by New button you can add your installed jdk).
In your android module settings(Project Structure : Modules) click the detected facet( Android ) and there choose your platform.


问:
Removing specific parts of the image in openCV
I am doing some image processing and need to do the following task in images ::

Image

From here I want to remove eyes, eyebrows, lips etc such that the smoothness of the image is not lost (eg, if the eyes are removed then the area should be replaced with neighboring colors).

I have the details(Points) of the area covering the part that needs to be flatten(eyes etc).Shown below::

答:
If you already have the points or even better contours you want to replace (like these drawn in green in your 2nd image), have a look at inpaint: http://docs.opencv.org/3.1.0/d1/d0d/group__photo.html#gaedd30dfa0214fec4c88138b51d678085

I think this is exactly what you are looking for! See here for an example: https://en.wikipedia.org/wiki/Inpainting

The procedure is pretty simple:

Make a mask filled with your contours (drawContours, thickness: CV_FILLED) to be inpainted/replaced with their respective environment and

inpaint with this mask.

I should mention that this does only work with 8bit-images.

The following (untested) code snippet should do it.

```<code>Mat mask = Mat::zeros(img.size(), CV_8UC1);
for (int i = 0; i < contours.size(); i++)
  drawContours(mask, contours, i, Scalar::all(255), CV_FILLED);
Mat dst;
double radius = 20;
inpaint(img, mask, dst, radius, INPAINT_NS);
//inpaint(img, mask, dst, radius, INPAINT_TELEA);
imshow("dst", dst);
waitKey();
</code>```

Edit: To make a contour of a couple of points:
A contour is just a vector of points, packed into another vector. So, the solution should be something like this with a given vector<Point> points.

```<code>vector<vector<Point> > contours;
contours.push_back(points);
drawContours(mask, contours, 0, Scalar::all(255), CV_FILLED);
</code>```

Body:
If you already have the points or even better contours you want to replace (like these drawn in green in your 2nd image), have a look at inpaint: http://docs.opencv.org/3.1.0/d1/d0d/group__photo.html#gaedd30dfa0214fec4c88138b51d678085

I think this is exactly what you are looking for! See here for an example: https://en.wikipedia.org/wiki/Inpainting

The procedure is pretty simple:

Make a mask filled with your contours (drawContours, thickness: CV_FILLED) to be inpainted/replaced with their respective environment and

inpaint with this mask.

I should mention that this does only work with 8bit-images.

The following (untested) code snippet should do it.

Mat mask = Mat::zeros(img.size(), CV_8UC1);
for (int i = 0; i < contours.size(); i++)
  drawContours(mask, contours, i, Scalar::all(255), CV_FILLED);
Mat dst;
double radius = 20;
inpaint(img, mask, dst, radius, INPAINT_NS);
//inpaint(img, mask, dst, radius, INPAINT_TELEA);
imshow("dst", dst);
waitKey();

Edit: To make a contour of a couple of points:
A contour is just a vector of points, packed into another vector. So, the solution should be something like this with a given vector<Point> points.

vector<vector<Point> > contours;
contours.push_back(points);
drawContours(mask, contours, 0, Scalar::all(255), CV_FILLED);


问:
Getting expression text
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:</p>

```<code>public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"
</code>```

答:
It gets ugly quite quickly...

```<code>public static string GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    bool needDot = false;

    Expression exp = expression.Body;

    string descr = string.Empty;

    while (exp != null)
    {
        if (exp.NodeType == ExpressionType.MemberAccess)
        {
            // Property or field
            var ma = (MemberExpression)exp;
            descr = ma.Member.Name + (needDot ? "." : string.Empty) + descr;
            exp = ma.Expression;
            needDot = true;
        }
        else if (exp.NodeType == ExpressionType.ArrayIndex)
        {
            // Array indexer
            var be = (BinaryExpression)exp;

            descr = GetParameters(new ReadOnlyCollection<Expression>(new[] { be.Right })) + (needDot ? "." : string.Empty) + descr;

            exp = be.Left;
            needDot = false;
        }
        else if (exp.NodeType == ExpressionType.Index)
        {
            // Object indexer (not used by C#. See ExpressionType.Call)
            var ie = (IndexExpression)exp;

            descr = GetParameters(ie.Arguments) + (needDot ? "." : string.Empty) + descr;

            exp = ie.Object;
            needDot = false;
        }
        else if (exp.NodeType == ExpressionType.Parameter)
        {
            break;
        }
        else if (exp.NodeType == ExpressionType.Call)
        {
            var ca = (MethodCallExpression)exp;

            if (ca.Method.IsSpecialName)
            {
                // Object indexer
                bool isIndexer = ca.Method.DeclaringType.GetDefaultMembers().OfType<PropertyInfo>().Where(x => x.GetGetMethod() == ca.Method).Any();

                if (!isIndexer)
                {
                    throw new Exception();
                }
            }
            else if (ca.Object.Type.IsArray && ca.Method.Name == "Get")
            {
                // Multidimensiona array indexer
            }
            else
            {
                throw new Exception();
            }

            descr = GetParameters(ca.Arguments) + (needDot ? "." : string.Empty) + descr;

            exp = ca.Object;
            needDot = false;
        }
    }

    return descr;
}

private static string GetParameters(ReadOnlyCollection<Expression> exps)
{
    var values = new string[exps.Count];

    for (int i = 0; i < exps.Count; i++)
    {
        if (exps[i].NodeType != ExpressionType.Constant)
        {
            throw new Exception();
        }

        var ce = (ConstantExpression)exps[i];

        // Quite wrong here... We should escape string values (\n written as \n and so on)
        values[i] = ce.Value == null ? "null" :
            ce.Type == typeof(string) ? "\"" + ce.Value + "\"" :
            ce.Type == typeof(char) ? "'" + ce.Value + "\'" :
            ce.Value.ToString();
    }

    return "[" + string.Join(", ", values) + "]";
}
</code>```

The code is quite easy to read, but it is quite long... There are 4 main cases: MemberAccess, that is accessing a property/field, ArrayIndex that is using the indexer of a single-dimensional array, Index that is unused by the C# compiler, but that should be using the indexer of an object (like the [...] of the List<> you are using), and Call that is used by C# for using an indexer or for accessing multi-dimensional arrays (new int[5, 4]) (and for other method calls, but we disregard them).

I support multidimensional arrays, jagged array s(arrays of arrays, new int[5][]) or arrays of indexable objects (new List<int>[5]) or indexable objects of indexable objects (new List<List<int>>). There is even support for multi-property indexers (indexers that use more than one key value, like obj[1, 2]). Small problem: printing the "value" of the indexers: I support only null, integers of various types, chars and strings (but I don't escape them... ugly... if there is a \n then it won't be printed as \n). Other types are not really supported... They will print what they will print (see GetParameters() if you want)

Title: Getting expression text

Body:
I want to pass the name of a property of a model to a method. Instead of using the name as string, I am using lambda expression as it is easy to make a typo, and also property names may be changed. Now if the property is a simple property (e.g: model.Name) I can get the name from the expression. But if it is a nested property (e.g: model.AnotherModel.Name) then how can I get full text ("AnotherModel.Name") from the expression. For example, I have the following classes:

public class BaseModel
{
    public ChildModel Child { get; set; }
    public List<ChildModel> ChildList { get; set; }

    public BaseModel()
    {
        Child = new ChildModel();
        ChildList = new List<ChildModel>();
    }
}

public class ChildModel
{
    public string Name { get;set; }
}

public void GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    string expText;
    //what to do??
    return expText;
}

GetExpressionText<BaseModel>(b => b.Child); //should return "Child"
GetExpressionText<BaseModel>(b => b.Child.Name); //should return "Child.Name"
GetExpressionText<BaseModel>(b => b.ChildList[0].Name); //should return "ChildList[0].Name"

Body:
It gets ugly quite quickly...

public static string GetExpressionText<T>(Expression<Func<T, object>> expression)
{
    bool needDot = false;

    Expression exp = expression.Body;

    string descr = string.Empty;

    while (exp != null)
    {
        if (exp.NodeType == ExpressionType.MemberAccess)
        {
            // Property or field
            var ma = (MemberExpression)exp;
            descr = ma.Member.Name + (needDot ? "." : string.Empty) + descr;
            exp = ma.Expression;
            needDot = true;
        }
        else if (exp.NodeType == ExpressionType.ArrayIndex)
        {
            // Array indexer
            var be = (BinaryExpression)exp;

            descr = GetParameters(new ReadOnlyCollection<Expression>(new[] { be.Right })) + (needDot ? "." : string.Empty) + descr;

            exp = be.Left;
            needDot = false;
        }
        else if (exp.NodeType == ExpressionType.Index)
        {
            // Object indexer (not used by C#. See ExpressionType.Call)
            var ie = (IndexExpression)exp;

            descr = GetParameters(ie.Arguments) + (needDot ? "." : string.Empty) + descr;

            exp = ie.Object;
            needDot = false;
        }
        else if (exp.NodeType == ExpressionType.Parameter)
        {
            break;
        }
        else if (exp.NodeType == ExpressionType.Call)
        {
            var ca = (MethodCallExpression)exp;

            if (ca.Method.IsSpecialName)
            {
                // Object indexer
                bool isIndexer = ca.Method.DeclaringType.GetDefaultMembers().OfType<PropertyInfo>().Where(x => x.GetGetMethod() == ca.Method).Any();

                if (!isIndexer)
                {
                    throw new Exception();
                }
            }
            else if (ca.Object.Type.IsArray && ca.Method.Name == "Get")
            {
                // Multidimensiona array indexer
            }
            else
            {
                throw new Exception();
            }

            descr = GetParameters(ca.Arguments) + (needDot ? "." : string.Empty) + descr;

            exp = ca.Object;
            needDot = false;
        }
    }

    return descr;
}

private static string GetParameters(ReadOnlyCollection<Expression> exps)
{
    var values = new string[exps.Count];

    for (int i = 0; i < exps.Count; i++)
    {
        if (exps[i].NodeType != ExpressionType.Constant)
        {
            throw new Exception();
        }

        var ce = (ConstantExpression)exps[i];

        // Quite wrong here... We should escape string values (\n written as \n and so on)
        values[i] = ce.Value == null ? "null" :
            ce.Type == typeof(string) ? "\"" + ce.Value + "\"" :
            ce.Type == typeof(char) ? "'" + ce.Value + "\'" :
            ce.Value.ToString();
    }

    return "[" + string.Join(", ", values) + "]";
}

The code is quite easy to read, but it is quite long... There are 4 main cases: MemberAccess, that is accessing a property/field, ArrayIndex that is using the indexer of a single-dimensional array, Index that is unused by the C# compiler, but that should be using the indexer of an object (like the [...] of the List<> you are using), and Call that is used by C# for using an indexer or for accessing multi-dimensional arrays (new int[5, 4]) (and for other method calls, but we disregard them).

I support multidimensional arrays, jagged array s(arrays of arrays, new int[5][]) or arrays of indexable objects (new List<int>[5]) or indexable objects of indexable objects (new List<List<int>>). There is even support for multi-property indexers (indexers that use more than one key value, like obj[1, 2]). Small problem: printing the "value" of the indexers: I support only null, integers of various types, chars and strings (but I don't escape them... ugly... if there is a \n then it won't be printed as \n). Other types are not really supported... They will print what they will print (see GetParameters() if you want)


问:
excel vba char(10) with special string value
I have a range with data and I am concatenating with line function and I want the output as follow

Range("A1:A3") has A,B,C and I want the output in single cell as

```<code>-A
-B
-C
</code>```

I am using following code; somehow it is not giving me desired output. Can anyone look into this and assist?

```<code>Dim X As String,cell as Range
For Each Cell in Range("A1:A3")
  If(Len(cell.value)>0) Then
  X="-" & X & CHAR(10) & Cell.Value
End If
Next
Range("B1").Value= X

Range("B1").WrapText = True
Range("B1").Columns.AutoFit
</code>```

答:
Try this

```<code>X = X & "-" & cell.Value & Chr(10)
</code>```

in full:

```<code>Sub ab_notsonull()
Dim X As String, cell As Range
For Each cell In Range("A1:A3")
  If (Len(cell.Value) > 0) Then
  X = X & ("-" & cell.Value & Chr(10))
End If
Next
Range("B2").Value = Left$(X, Len(X) - 1)
Range("B2").WrapText = True
Range("B2").Columns.AutoFit
End Sub
</code>```

Body:
I have a range with data and I am concatenating with line function and I want the output as follow

Range("A1:A3") has A,B,C and I want the output in single cell as

-A
-B
-C

I am using following code; somehow it is not giving me desired output. Can anyone look into this and assist?

Dim X As String,cell as Range
For Each Cell in Range("A1:A3")
  If(Len(cell.value)>0) Then
  X="-" & X & CHAR(10) & Cell.Value
End If
Next
Range("B1").Value= X

Range("B1").WrapText = True
Range("B1").Columns.AutoFit

Body:
Try this

X = X & "-" & cell.Value & Chr(10)

in full:

Sub ab_notsonull()
Dim X As String, cell As Range
For Each cell In Range("A1:A3")
  If (Len(cell.Value) > 0) Then
  X = X & ("-" & cell.Value & Chr(10))
End If
Next
Range("B2").Value = Left$(X, Len(X) - 1)
Range("B2").WrapText = True
Range("B2").Columns.AutoFit
End Sub


问:
proper javascript usage of "this"
Which of the following two ways is better to call the Color property and why? Or does it make a difference?

```<code>lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
</code>```

OR

```<code>lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},
</code>```

Context CODE:

```<code>var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};
</code>```

答:
This code won't work as you expect it to.

Your LatLongLines is a plain object, but this only works on instances.

```<code> obj.method()
    ^----- DOT determines the value of this inside the called function
           If obj is an instance it will be used as 'this' otherwise
           'this' will default to the global 'window' object
</code>```

So either:

You get rid of all the this and use LatLongLines instead to have one global object

Or you create a LatLongLines instance, that way this will work, you can still go for a singleton (But you know singleton is still global state, and global state is evil)

If you need to create a new instance do something along these lines:

```<code>function LatLongLines() {
    this.Graticule = null;
    this.Color = "#000000";
};

// Let's use prototypical inheritance, these functions are shared between all
// LatLongLines instances, of course the this always refers the specific instance that was called
LatLongLines.prototype = {
    Show: function () {
        this.Graticule.activate();
    },

    Hide; function () {
        this.Graticule.deactivate()
    },

    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        // Maybe you want to pass map in? :)
        map.addControl(this.Graticule);
    }
};

var someLines = new LatLongLines();
</code>```

Title: proper javascript usage of "this"

Body:
Which of the following two ways is better to call the Color property and why? Or does it make a difference?

lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},

OR

lineSymbolizer:{strokeColor: LatLongLines.Color, strokeWidth: 2, strokeOpacity: 0.7},

Context CODE:

var LatLongLines = {
    Graticule: null,
    Color: "#000000",
    Show: function () {
        this.Graticule.activate();
    },
    Hide: function () {
        this.Graticule.deactivate()
    },
    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        map.addControl(this.Graticule);
    }
};

Body:
This code won't work as you expect it to.

Your LatLongLines is a plain object, but this only works on instances.

 obj.method()
    ^----- DOT determines the value of this inside the called function
           If obj is an instance it will be used as 'this' otherwise
           'this' will default to the global 'window' object

So either:

You get rid of all the this and use LatLongLines instead to have one global object

Or you create a LatLongLines instance, that way this will work, you can still go for a singleton (But you know singleton is still global state, and global state is evil)

If you need to create a new instance do something along these lines:

function LatLongLines() {
    this.Graticule = null;
    this.Color = "#000000";
};

// Let's use prototypical inheritance, these functions are shared between all
// LatLongLines instances, of course the this always refers the specific instance that was called
LatLongLines.prototype = {
    Show: function () {
        this.Graticule.activate();
    },

    Hide; function () {
        this.Graticule.deactivate()
    },

    Initialize: function () {
        this.Graticule = new OpenLayers.Control.Graticule({
            numPoints: 2,
            labelled: true,
            lineSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7},
            labelSymbolizer:{strokeColor: this.Color, strokeWidth: 2, strokeOpacity: 0.7}
        });

        // Maybe you want to pass map in? :)
        map.addControl(this.Graticule);
    }
};

var someLines = new LatLongLines();


问:
htaccess does not understand ^www\. rule , if paramters are appended to url
.htaccess does not understand ^www\. rule

```<code>#do not use this, because i want to redirect from https://www.somedomain.com
#RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$
RewriteRule ^/?$ "https\:\/\/somedomain\.com" [L,R=301]
#[NE,L,R=301] - NE|noescape
</code>```

This gives the following redirections, though very slow:

somedomain.com  -->  https://somedomain.com

www.somedomain.com  -->  https://www.somedomain.com

somedomain.com/folder/file  -->  https://somedomain.com/folder/file

www.somedomain.com/folder/file  -->  http://www.somedomain.com/folder/file

the last url www.somedomain.com/folder/file is not redirected to https. WHY?

答:
You have an additional condition with [OR] that can cause too many redirects. Fix it by using:

```<code>RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$ [NC]
RewriteRule ^/?$ https://somedomain.com [L,R=301]
</code>```

Completely clear browser cache before testing this.

Body:
.htaccess does not understand ^www\. rule

#do not use this, because i want to redirect from https://www.somedomain.com
#RewriteCond %{HTTPS} off

RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
RewriteCond %{HTTP_HOST} ^somedomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$
RewriteRule ^/?$ "https\:\/\/somedomain\.com" [L,R=301]
#[NE,L,R=301] - NE|noescape

This gives the following redirections, though very slow:

somedomain.com  -->  https://somedomain.com

www.somedomain.com  -->  https://www.somedomain.com

somedomain.com/folder/file  -->  https://somedomain.com/folder/file

www.somedomain.com/folder/file  -->  http://www.somedomain.com/folder/file

the last url www.somedomain.com/folder/file is not redirected to https. WHY?

Body:
You have an additional condition with [OR] that can cause too many redirects. Fix it by using:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\.somedomain\.com$ [NC]
RewriteRule ^/?$ https://somedomain.com [L,R=301]

Completely clear browser cache before testing this.


问:
Maven can't compile java 1.8
I'm trying to use maven to build a jar but I keep getting the error

```<code>ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
(default-compile) on project Application: Fatal error compiling: invalid target release: 1.8 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

mvn -v outputs

```<code>mvn -version
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T09:29:23-08:00)
Maven home: /usr/local/Cellar/maven/3.2.5/libexec
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.10.1", arch: "x86_64", family: "mac"
</code>```

So it looks like its pointing to the 1.6jdk

but I have the 1.8 jdk

java -version

```<code>java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
</code>```

POM.xml

```<code> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.brian.ridecellchallenge</groupId>
    <artifactId>Application</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.group.id.Launcher1</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>
</project>
</code>```

答:
I'm not sure but can you try to update your maven.plugin version

try

```<code><plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
            </configuration>
        <version>3.6.1</version>
</plugin>
</code>```

Title: Maven can't compile java 1.8

Body:
I'm trying to use maven to build a jar but I keep getting the error

ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
(default-compile) on project Application: Fatal error compiling: invalid target release: 1.8 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

mvn -v outputs

mvn -version
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T09:29:23-08:00)
Maven home: /usr/local/Cellar/maven/3.2.5/libexec
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.10.1", arch: "x86_64", family: "mac"

So it looks like its pointing to the 1.6jdk

but I have the 1.8 jdk

java -version

java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

POM.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.brian.ridecellchallenge</groupId>
    <artifactId>Application</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.group.id.Launcher1</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>
</project>

Body:
I'm not sure but can you try to update your maven.plugin version

try

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
            </configuration>
        <version>3.6.1</version>
</plugin>