问:
How to compare current time with selected time in android
I have time picker and I don't want to select previous time from it.

It means that if I am selecting time before current time it can't display. I don't want to show time before current time.

```<code>public class ProfileDetail extends AppCompatActivity {
    Toolbar toolbar;
    String description, str_requirement, str_date, str_time, str_noofperson, str_address;
    TextView txt_description;
    EditText et_requirment, date_pick, time_set, et_no_of_person, et_address_service;
    Button btn_submit;
    int mYear, mMonth, mDay, mHour, mMinute;
    private Calendar cal;
    DateFormat fmtDateAndTime = DateFormat.getTimeInstance();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_details);
        Bundle extras = getIntent().getExtras();
        description = extras.getString("description");
        txt_description = (TextView) findViewById(R.id.txtservicedetails);
        toolbar = (Toolbar) findViewById(R.id.toolbarforprofile);
        setSupportActionBar(toolbar);
        cal = Calendar.getInstance();
        mDay = cal.get(Calendar.DAY_OF_MONTH);
        mMonth = cal.get(Calendar.MONTH);
        mYear = cal.get(Calendar.YEAR);
        mHour = cal.get(Calendar.HOUR_OF_DAY);
        mMinute = cal.get(Calendar.MINUTE);
        et_requirment = (EditText) findViewById(R.id.editText_requirement);
        et_no_of_person = (EditText) findViewById(R.id.et_noofperson);
        et_address_service = (EditText) findViewById(R.id.et_serviceaddress);
        time_set = (EditText) findViewById(R.id.et_time);
        date_pick = (EditText) findViewById(R.id.et_dateof_visit);
        btn_submit = (Button) findViewById(R.id.btn_submit);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setTitle("Need-Hlp");
        toolbar.setTitleTextColor(Color.WHITE);
        txt_description.setText(description);
        //date_pick.setInputType(InputType.TYPE_NULL);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentfromprevious = new Intent(ProfileDetail.this, NavigationDrawer.class);
                intentfromprevious.putExtra("description", description);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intentfromprevious);

            }
        });

        date_pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(0);
            }
        });

        final TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
                cal.set(Calendar.MINUTE, minute);

                updateLabel();
            }
        };

        time_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get Current Time

                new TimePickerDialog(ProfileDetail.this, t, cal
                        .get(Calendar.HOUR_OF_DAY), cal
                        .get(Calendar.MINUTE), true).show();
            }
        });
        //final TextView textView = (TextView)findViewById(R.id.textview23);

        //////Submit button onclicklistener
        btn_submit.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {

                str_date = date_pick.getText().toString();
                if (et_requirment.getText().toString().equals("")) {
                    et_requirment.setError("Requirement cannot be blank");
                    et_requirment.requestFocus();
                    return;
                }
                if (str_date.isEmpty() || str_date.length() == 0 || str_date.equals("") || str_date == null) {
                    Toast.makeText(ProfileDetail.this, "Date cannot be blank", Toast.LENGTH_SHORT).show();
                    //date_pick.setError("Date cannot be blank");
                    return;

                }

                if (time_set.getText().toString().equals("")) {
                    Toast.makeText(ProfileDetail.this, "Time cannot be blank", Toast.LENGTH_SHORT).show();
                    //time_set.setError("Time cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }

                if (et_no_of_person.getText().toString().toString().equals("")) {
                    et_no_of_person.setError("No of person cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }
                if (et_address_service.getText().toString().equals("")) {
                    et_address_service.setError("Address cannot be blank");
                    //edittext_Password.requestFocus();
                    return;
                }

                if (!et_requirment.getText().toString().trim().equals("") && !et_no_of_person.getText().toString().trim().equals("") && !et_address_service.getText().toString().equals("")) {

                    Toast.makeText(ProfileDetail.this, "You Request Submitted", Toast.LENGTH_SHORT).show();
                    Intent intentforlist = new Intent(ProfileDetail.this, NavigationDrawer.class);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(intentforlist);
                }

            }

        });

    }

    private void updateLabel() {
        Calendar c = Calendar.getInstance();

        String time = "23:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date timeCompare = null;
        Date currentTimes = new Date();
        int comareResult = timeCompare.compareTo(currentTimes);
        try {

            if (comareResult == 0) {
                timeCompare = sdf.parse(time);
                time_set.setText(time);
            }

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

    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        //return new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay);

        DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay) {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                if (year < mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (monthOfYear < mMonth && year == mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (dayOfMonth < mDay && year == mYear && monthOfYear == mMonth)
                    view.updateDate(mYear, mMonth, mDay);

            }
        };
        return _date;

    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {

            date_pick.setText(+selectedDay + " / " + (selectedMonth + 1) + " / "
                    + selectedYear);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem item1 = menu.findItem(R.id.action_cart);
        MenuItemCompat.setActionView(item1, R.layout.count);
        // notificationCount1 = (RelativeLayout) MenuItemCompat.getActionView(item1);
        return super.onCreateOptionsMenu(menu);
    }
}
</code>```

答:
To stop a user being able to pick a time in the past (I think that's what you're asking for!) just do this:</p>

```<code>myDatePicker.setMinDate(System.currentTimeMillis(););
</code>```

Body:
I have time picker and I don't want to select previous time from it.

It means that if I am selecting time before current time it can't display. I don't want to show time before current time.

public class ProfileDetail extends AppCompatActivity {
    Toolbar toolbar;
    String description, str_requirement, str_date, str_time, str_noofperson, str_address;
    TextView txt_description;
    EditText et_requirment, date_pick, time_set, et_no_of_person, et_address_service;
    Button btn_submit;
    int mYear, mMonth, mDay, mHour, mMinute;
    private Calendar cal;
    DateFormat fmtDateAndTime = DateFormat.getTimeInstance();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_details);
        Bundle extras = getIntent().getExtras();
        description = extras.getString("description");
        txt_description = (TextView) findViewById(R.id.txtservicedetails);
        toolbar = (Toolbar) findViewById(R.id.toolbarforprofile);
        setSupportActionBar(toolbar);
        cal = Calendar.getInstance();
        mDay = cal.get(Calendar.DAY_OF_MONTH);
        mMonth = cal.get(Calendar.MONTH);
        mYear = cal.get(Calendar.YEAR);
        mHour = cal.get(Calendar.HOUR_OF_DAY);
        mMinute = cal.get(Calendar.MINUTE);
        et_requirment = (EditText) findViewById(R.id.editText_requirement);
        et_no_of_person = (EditText) findViewById(R.id.et_noofperson);
        et_address_service = (EditText) findViewById(R.id.et_serviceaddress);
        time_set = (EditText) findViewById(R.id.et_time);
        date_pick = (EditText) findViewById(R.id.et_dateof_visit);
        btn_submit = (Button) findViewById(R.id.btn_submit);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setTitle("Need-Hlp");
        toolbar.setTitleTextColor(Color.WHITE);
        txt_description.setText(description);
        //date_pick.setInputType(InputType.TYPE_NULL);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentfromprevious = new Intent(ProfileDetail.this, NavigationDrawer.class);
                intentfromprevious.putExtra("description", description);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intentfromprevious);

            }
        });

        date_pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(0);
            }
        });

        final TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
                cal.set(Calendar.MINUTE, minute);

                updateLabel();
            }
        };

        time_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get Current Time

                new TimePickerDialog(ProfileDetail.this, t, cal
                        .get(Calendar.HOUR_OF_DAY), cal
                        .get(Calendar.MINUTE), true).show();
            }
        });
        //final TextView textView = (TextView)findViewById(R.id.textview23);

        //////Submit button onclicklistener
        btn_submit.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {

                str_date = date_pick.getText().toString();
                if (et_requirment.getText().toString().equals("")) {
                    et_requirment.setError("Requirement cannot be blank");
                    et_requirment.requestFocus();
                    return;
                }
                if (str_date.isEmpty() || str_date.length() == 0 || str_date.equals("") || str_date == null) {
                    Toast.makeText(ProfileDetail.this, "Date cannot be blank", Toast.LENGTH_SHORT).show();
                    //date_pick.setError("Date cannot be blank");
                    return;

                }

                if (time_set.getText().toString().equals("")) {
                    Toast.makeText(ProfileDetail.this, "Time cannot be blank", Toast.LENGTH_SHORT).show();
                    //time_set.setError("Time cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }

                if (et_no_of_person.getText().toString().toString().equals("")) {
                    et_no_of_person.setError("No of person cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }
                if (et_address_service.getText().toString().equals("")) {
                    et_address_service.setError("Address cannot be blank");
                    //edittext_Password.requestFocus();
                    return;
                }

                if (!et_requirment.getText().toString().trim().equals("") && !et_no_of_person.getText().toString().trim().equals("") && !et_address_service.getText().toString().equals("")) {

                    Toast.makeText(ProfileDetail.this, "You Request Submitted", Toast.LENGTH_SHORT).show();
                    Intent intentforlist = new Intent(ProfileDetail.this, NavigationDrawer.class);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(intentforlist);
                }

            }

        });

    }

    private void updateLabel() {
        Calendar c = Calendar.getInstance();

        String time = "23:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date timeCompare = null;
        Date currentTimes = new Date();
        int comareResult = timeCompare.compareTo(currentTimes);
        try {

            if (comareResult == 0) {
                timeCompare = sdf.parse(time);
                time_set.setText(time);
            }

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

    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        //return new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay);

        DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay) {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                if (year < mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (monthOfYear < mMonth && year == mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (dayOfMonth < mDay && year == mYear && monthOfYear == mMonth)
                    view.updateDate(mYear, mMonth, mDay);

            }
        };
        return _date;

    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {

            date_pick.setText(+selectedDay + " / " + (selectedMonth + 1) + " / "
                    + selectedYear);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem item1 = menu.findItem(R.id.action_cart);
        MenuItemCompat.setActionView(item1, R.layout.count);
        // notificationCount1 = (RelativeLayout) MenuItemCompat.getActionView(item1);
        return super.onCreateOptionsMenu(menu);
    }
}

Body:
To stop a user being able to pick a time in the past (I think that's what you're asking for!) just do this:

myDatePicker.setMinDate(System.currentTimeMillis(););


来源: stackexchange

问:
Regex match all strings between 2 characters
I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters
but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

```<code>text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"
</code>```

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.

答:
You forgot to escape the pipe (|), which is now interpreted as the indicator for an alternation

Your regex with the escaped pipe:

```<code>(?<=\|).*?(?=>)
</code>```

Here you can see the result

ContentLicense: CC BY-SA 3.0

Body:
I tried a couple of other links like Regex Match all characters between two strings and Regex get all content between two characters
but they don't seem to fit this use case.

I want to get all the names, potato and tomato. Eg, from | to >.

text = "with <@U0D08NR3|potato> and <@U1698M96|tomato> please"

text.scan((?<=|).*?(?=>)) doesnt seem to work either..

Please guide me regex gods.

Body:
You forgot to escape the pipe (|), which is now interpreted as the indicator for an alternation

Your regex with the escaped pipe:

(?<=\|).*?(?=>)

Here you can see the result


问:
System.Data.ProviderIncompatibleException in Entity Framework
Is there any thing missing in my connection string so that i am getting this error:

An exception of type 'System.Data.ProviderIncompatibleException' occurred in EntityFramework.dll but was not handled in user code Additional information: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

This is my connection String in web.config:

```<code><connectionStrings>
    <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</code>```

答: Check your connection string in *.config file and most probably you are missing the providerName="System.Data.SqlClient". See Entity Framework Config File Settings for more information

Body:
Is there any thing missing in my connection string so that i am getting this error:

An exception of type 'System.Data.ProviderIncompatibleException' occurred in EntityFramework.dll but was not handled in user code Additional information: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.

This is my connection String in web.config:

<connectionStrings>
    <add name="OnlineStoreEntities" connectionString="Data Source=SERVERNAME\SQLEXPRESS;Initial Catalog=MVCOnlineShop;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVCOnlineShop" connectionString="metadata=res://*/Models.ShopModel.csdl|res://*/Models.ShopModel.ssdl|res://*/Models.ShopModel.msl;provider=System.Data.SqlClient;provider connection string="data source=AHMADZAKARIA-PC;initial catalog=MVCOnlineShop;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
  </connectionStrings>


问:
ES6 function parameter validation
I've read a great pattern of handling required function parameters on 2ality.

```<code>function throwIfMissing() {
    throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}
</code>```

Is there any such nice and clean way to throw validation errors?

```<code>function throwIfInvalid(value) {
    const max = 10;
    const min = 5;

    if(value < min || value > max){
        throw new Error(`Value must be between ${min} ${max}`);
    }

    return value;
}

function foo(mustBeValid = throwIfInvalid()) {
    return mustBeValid;
}
</code>```

Of course the throwIfInvalid() function does not work as expected. My question is if there is any trick to make it work.?

答:
This trick is only good for a generalized error message, and cannot be forced to be specific to the function it was checking its parameters, since the parameters were never supplied in the first place.

Now, a lesson:

Consider this situation:

function missingArgument() {
    console.warn('Missing parameter');
}

function foo(bar = missingArgument()){
    return bar.value;
}

console.log( foo() ) // will throw an error since "bar" is not a value
console.log('end');  // never reach here```
</div>
</div>
</p>

<p>The above example will throw an error, but the trick with the <code>missingArgument</code> function isn't very helpful since it doesn't tells you imminently where was the problem at. You can pass a string which will give helpful information:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function missingArgument(name) {
  console.warn('Missing parameter in function:', name);
}

function foo(bar = missingArgument('foo')) {
  return bar.value;
}

console.log(foo()) // will throw an error since "bar" is not a value
console.log('end'); // never reach here</code>```

This can be solved in this manner:

function missingArgument() {
    console.warn('Missing parameter');
}

function foo(bar = missingArgument()){
    if( bar == undefined ) return 0;
    return bar.value;
}

console.log( foo() )
console.log('end');```
</div>
</div>
</p>

<p>Each function obviously does its own thing, so you must know what the function should do with the expected argument and what is the expected output of the function, and then tailor-make your protection at the beginning of it.</p>

<p>The <code>foo</code> function above is expecting an Object and then it tries to access the <code>value</code> key of that object, and since the parameter is <code>undefined</code> it will fail and your whole code chain will stop. This is mostly unwanted and can be avoided.
Above example will only work if the Object has a <code>value</code> key, like so:</p>

```console.log( foo({value:1}) )
```

Title: ES6 function parameter validation

Body:
I've read a great pattern of handling required function parameters on 2ality.

function throwIfMissing() {
    throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}

Is there any such nice and clean way to throw validation errors?

function throwIfInvalid(value) {
    const max = 10;
    const min = 5;

    if(value < min || value > max){
        throw new Error(`Value must be between ${min} ${max}`);
    }

    return value;
}

function foo(mustBeValid = throwIfInvalid()) {
    return mustBeValid;
}

Of course the throwIfInvalid() function does not work as expected. My question is if there is any trick to make it work.?

Body:
This trick is only good for a generalized error message, and cannot be forced to be specific to the function it was checking its parameters, since the parameters were never supplied in the first place.

Now, a lesson:

Consider this situation:

function missingArgument() {
    console.warn('Missing parameter');
}

function foo(bar = missingArgument()){
    return bar.value;
}

console.log( foo() ) // will throw an error since "bar" is not a value
console.log('end');  // never reach here

The above example will throw an error, but the trick with the missingArgument function isn't very helpful since it doesn't tells you imminently where was the problem at. You can pass a string which will give helpful information:

function missingArgument(name) {
  console.warn('Missing parameter in function:', name);
}

function foo(bar = missingArgument('foo')) {
  return bar.value;
}

console.log(foo()) // will throw an error since "bar" is not a value
console.log('end'); // never reach here

This can be solved in this manner:

function missingArgument() {
    console.warn('Missing parameter');
}

function foo(bar = missingArgument()){
    if( bar == undefined ) return 0;
    return bar.value;
}

console.log( foo() )
console.log('end');

Each function obviously does its own thing, so you must know what the function should do with the expected argument and what is the expected output of the function, and then tailor-make your protection at the beginning of it.

The foo function above is expecting an Object and then it tries to access the value key of that object, and since the parameter is undefined it will fail and your whole code chain will stop. This is mostly unwanted and can be avoided.
Above example will only work if the Object has a value key, like so:

console.log( foo({value:1}) )


问:
Remove null attributes and empty children from Node
I have a Node which I want to remove all null attributes and empty children from recursively before I write it to a file.  What I have below works, but it seems like there should be a built in method for this.  Have I missed something?

```<code>Node cleanNode(Node node) {

    // Find null attributes
    def attributesToRemove = []
    for(e in node.attributes()) {
        if(e.value == null) {
            attributesToRemove.add(e.key)
        }
    }

    // Remove null attributes
    for(attribute in attributesToRemove) {
        node.attributes().remove(attribute)
    }

    // Clean this node's children
    for(child in node.children()) {
        if(child instanceof Node) {
            cleanNode(child)
        }
    }

    // If node has no attributes, no children, and no text then discard it by setting it to null
    if(!node.attributes() && !node.children() && !node.text()) {
        node = null
    }

    node
}
</code>```

答:
If the xml contains namespaces the cleanNode method will result in namespace declarations sprayed onto every node.
To avoid this use new XmlParser(false, false), so the code becomes:

```<code>Node root = new XmlParser(false, false).parseText(xml)
cleanNode(root)
println XmlUtil.serialize(root)
</code>```

This way the xml is nice and clean afterwards.

Many thanks to Tim for the original answer!

Body:
I have a Node which I want to remove all null attributes and empty children from recursively before I write it to a file.  What I have below works, but it seems like there should be a built in method for this.  Have I missed something?

Node cleanNode(Node node) {

    // Find null attributes
    def attributesToRemove = []
    for(e in node.attributes()) {
        if(e.value == null) {
            attributesToRemove.add(e.key)
        }
    }

    // Remove null attributes
    for(attribute in attributesToRemove) {
        node.attributes().remove(attribute)
    }

    // Clean this node's children
    for(child in node.children()) {
        if(child instanceof Node) {
            cleanNode(child)
        }
    }

    // If node has no attributes, no children, and no text then discard it by setting it to null
    if(!node.attributes() && !node.children() && !node.text()) {
        node = null
    }

    node
}

Body:
If the xml contains namespaces the cleanNode method will result in namespace declarations sprayed onto every node.
To avoid this use new XmlParser(false, false), so the code becomes:

Node root = new XmlParser(false, false).parseText(xml)
cleanNode(root)
println XmlUtil.serialize(root)

This way the xml is nice and clean afterwards.

Many thanks to Tim for the original answer!


问:
join symbol in javascript
I want to produce

1 • 2

But below code won't work?

```<code>const arr = [1,2]

console.log(arr.join(' - '))

console.log(arr.join(' • ')) // doesn't work
</code>```

答:
Use it directly?

const arr = [1, 2],
      res = arr.join(' • ');

      console.log(res);```

Title: join symbol in javascript

Body:
I want to produce

1 • 2

But below code won't work?

const arr = [1,2]

console.log(arr.join(' - '))

console.log(arr.join(' • ')) // doesn't work


问:
Realm write transaction failing, despite being in transaction
I have this code, which should append messages with a new message:

```<code>func addMessage(_ message: Message) {
    do {
        try Realm().write {
            self.messages.append(message)
        }
    } catch let error {
        print("could not add message due to error:\n\(error)")
    }
}
</code>```

However, I get an exception Cannot modify managed RLMArray outside of a write transaction It doesn't make any sense to me, because I'm already in a write transaction...

答:
You can use let realm = try! Realm() with a custom default configuration by setting a default configuration see here:

```<code>  var config = Realm.Configuration()

  // Set this as the configuration used for the default Realm
  Realm.Configuration.defaultConfiguration = config
</code>```

Body:
I have this code, which should append messages with a new message:

func addMessage(_ message: Message) {
    do {
        try Realm().write {
            self.messages.append(message)
        }
    } catch let error {
        print("could not add message due to error:\n\(error)")
    }
}

However, I get an exception Cannot modify managed RLMArray outside of a write transaction It doesn't make any sense to me, because I'm already in a write transaction...

Body:
You can use let realm = try! Realm() with a custom default configuration by setting a default configuration see here:

  var config = Realm.Configuration()

  // Set this as the configuration used for the default Realm
  Realm.Configuration.defaultConfiguration = config


问:
Copy source files to other TFS
We have a TeamCity/Octopus setup that runs great for several projects.

A new client wants access to the source code during development. Is it possible to copy code from our TFS to an other TFS using TeamCity? It does not need to be real-time. Daily copies are OK.

Not sure if we should use TeamCity for this or if there are possibilities within TFS itself.

答:
You could setup a daily build schedule and use the TFS command line utilities to transfer the files to another server. You'll probably get all kinds of sync issues along the way, unless you always take your own solution as the current situation.

Look at tf.exe, especially the workspace, workfold commands and add, delete, and optionally destroy. Complete the job with a tf checkin.

Process as follows:

Create a workspace on your source TFS server (or use the built-in workspace features in team city): tf workspace /new

Map the folders you want to share: tf workfold /map

Get the files to the machine that's doing the transfer: tf get /recursive

Create a workspace on your target TFS server: tf workspace /new

Map the folders you want to share to tf workfold /map to a new folder that's not mapped to the source TFS server.

WS2 delete the files in the target folder: tf delete * /recursive

WS2 Check in to make sure you won't get any conflict remotely: tf checkin /recursive

WS1 -> WS2 Copy the files from the first workspace to the second: xcopy

WS2 Add all files: tf add * /recursive

WS2 Checkin all files tf checkin * /recursive

WS2 & WS2 Delete the workspace: tf workspace /delete

(Optional) Delete the files in the folders of the deleted workspaces on disk.

PS: if you move to git, this all becomes a lot easier, since the distributed nature of git is kind of meant for scenarios like these.

Title: Copy source files to other TFS

ContentLicense: CC BY-SA 4.0


问:
How do I add a polygon into my Google local business map?
I want to add the same circle on my google place/business listing as in attached image. Please help me out.

Google Local Business Map

答: You need to use Google My Business and define a service area for your business. See also Guidelines for representing your business on Google and beware that your business won't be available in the Maps APIs until this bug is fixed.</p>


问:
jQuery autocomplete not displaying values Cakephp route
I am trying to use jQuery auto complete to display data from my table in Cakephp. I can get auto complete working using tags but I cannot display the data from my table. The function to search for like data in the table in returning correctly but I'm not entirely sure if it passing it to the autocomplete script correctly. I am still quite new to this.

This is my search function in InvoicesController.php

```<code>public function search()
{
    $this->loadComponent('RequestHandler');
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = (strval($result['id']));
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);

    }
}
</code>```

This is the code in my search.ctp

```<code><?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
    var testTags = ['52332', '56346', '5734'];
    var tags = '<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>'
    jQuery('#id').autocomplete({
        source: tags,
        minLength: 1
    });
</script>
</code>```

This is what is being returned by the function and what appears in the autocomplete drop down.

This is what it should look like using the testTags array

What the view looks like in sources.

```<code><div class="input text"><label for="id">Id</label><input type="text" name="id" id="id"/></div>
<script>
    var testTags = ['52332', '56346', '5734'];
    var tags = '/invoices/search'
    jQuery('#id').autocomplete({
        source: testTags,
        minLength: 1
    });
</script>    </div>
</code>```

答:
```<code>    <?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
    var testTags = ['52332', '56346', '5734'];
    var tags = $.post(url:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>');
    jQuery('#id').autocomplete({
        source: tags,
        minLength: 1
    });
</script>
</code>```

Try to use Jquery $.post or $.get to fetch your data with ajax

Body:
I am trying to use jQuery auto complete to display data from my table in Cakephp. I can get auto complete working using tags but I cannot display the data from my table. The function to search for like data in the table in returning correctly but I'm not entirely sure if it passing it to the autocomplete script correctly. I am still quite new to this.

This is my search function in InvoicesController.php

public function search()
{
    $this->loadComponent('RequestHandler');
    if ($this->request->is('ajax'))
    {
        $name = $this->request->query['term'];
        $resultArr = $this->Invoices
    ->find()
    ->where(
        ['Invoices.id LIKE' => ($name . '%')],
        ['Invoices.id' => 'string']
    );

        $resultsArr = [];
        foreach ($resultArr as $result)
        {
             $resultsArr[] = (strval($result['id']));
        }

        $this->set('resultsArr', $resultsArr);
        // This line is what handles converting your array into json
        // To get this to work you must load the request handler
        $this->set('_serialize', ['resultsArr']);

    }
}

This is the code in my search.ctp

<?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

This is what is being returned by the function and what appears in the autocomplete drop down.

This is what it should look like using the testTags array

What the view looks like in sources.

Id<input type="text" name="id" id="id"/>

Body:
    <?php use Cake\Routing\Router; ?>

    <?php echo $this->Form->input('id', ['type' => 'text']); ?>

<script>
    var testTags = ['52332', '56346', '5734'];
    var tags = $.post(url:'<?php echo Router::url(array('controller' => 'Invoices', 'action' => 'search')); ?>');
    jQuery('#id').autocomplete({
        source: tags,
        minLength: 1
    });
</script>

Try to use Jquery $.post or $.get to fetch your data with ajax


问:
How to split a string into command line arguments like the shell in python?
I have command line arguments in a string and I need to split it to feed to argparse.ArgumentParser.parse_args.

I see that the documentation uses string.split() plentifully. However in complex cases, this does not work, such as

```<code>--foo "spaces in brakets"  --bar escaped\ spaces
</code>```

Is there a functionality to do that in python?

(A similar question for java was asked here).

答:
You could use the split_arg_string helper function from the click package:

```<code>import re

def split_arg_string(string):
    """Given an argument string this attempts to split it into small parts."""
    rv = []
    for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
                             r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
                             r'|\S+)\s*', string, re.S):
        arg = match.group().strip()
        if arg[:1] == arg[-1:] and arg[:1] in '"\'':
            arg = arg[1:-1].encode('ascii', 'backslashreplace') \
                .decode('unicode-escape')
        try:
            arg = type(string)(arg)
        except UnicodeError:
            pass
        rv.append(arg)
    return rv
</code>```

For example:

```<code>>>> print split_arg_string('"this is a test" 1 2 "1 \\" 2"')
['this is a test', '1', '2', '1 " 2']
</code>```

The click package is starting to dominate for command-arguments parsing, but I don't think it supports parsing arguments from string (only from argv). The helper function above is used only for bash completion.

Edit: I can nothing but recommend to use the shlex.split() as suggested in the answer by @ShadowRanger. The only reason I'm not deleting this answer is because it provides a little bit faster splitting then the full-blown pure-python tokenizer used in shlex (around 3.5x faster for the example above, 5.9us vs 20.5us). However, this shouldn't be a reason to prefer it over shlex.

Body:
I have command line arguments in a string and I need to split it to feed to argparse.ArgumentParser.parse_args.

I see that the documentation uses string.split() plentifully. However in complex cases, this does not work, such as

--foo "spaces in brakets"  --bar escaped\ spaces

Is there a functionality to do that in python?

(A similar question for java was asked here).

Body:
You could use the split_arg_string helper function from the click package:

import re

def split_arg_string(string):
    """Given an argument string this attempts to split it into small parts."""
    rv = []
    for match in re.finditer(r"('([^'\\]*(?:\\.[^'\\]*)*)'"
                             r'|"([^"\\]*(?:\\.[^"\\]*)*)"'
                             r'|\S+)\s*', string, re.S):
        arg = match.group().strip()
        if arg[:1] == arg[-1:] and arg[:1] in '"\'':
            arg = arg[1:-1].encode('ascii', 'backslashreplace') \
                .decode('unicode-escape')
        try:
            arg = type(string)(arg)
        except UnicodeError:
            pass
        rv.append(arg)
    return rv

For example:

>>> print split_arg_string('"this is a test" 1 2 "1 \\" 2"')
['this is a test', '1', '2', '1 " 2']

The click package is starting to dominate for command-arguments parsing, but I don't think it supports parsing arguments from string (only from argv). The helper function above is used only for bash completion.

Edit: I can nothing but recommend to use the shlex.split() as suggested in the answer by @ShadowRanger. The only reason I'm not deleting this answer is because it provides a little bit faster splitting then the full-blown pure-python tokenizer used in shlex (around 3.5x faster for the example above, 5.9us vs 20.5us). However, this shouldn't be a reason to prefer it over shlex.


问:
pthread win32 version? (Mongoose)
Please tell me what difference between pthread versions: VC2, VCE2 and VSE2? How to choose which of them I must use with Visual C++ Express 2010 for Mongoose webserver library?

Thank you!!!

答:
VCE - MSVC dll with C++ exception handling

VSE - MSVC dll with structured exception handling

VC  - MSVC dll with C cleanup code

Which one you'd want to use with VC++ Express 2010 depends on how you want pthread clean up to be handled.  If you're linking this to the Mongoose webserver (which I'm not familiar with), I think you'll want to use the exception handling model as that code is compiled with.

The pthreads Win32 library goes into a fair bit of detail:

Library naming

Because the library is being built
  using various exception handling
  schemes and compilers - and because
  the library may not work reliably if
  these are mixed in an application,
  each different version of the library
  has it's own name.

Note 1: the incompatibility is really
  between EH implementations of the
  different compilers. It should be
  possible to use the standard C version
  from either compiler with C++
  applications built with a different
  compiler. If you use an EH version of
  the library, then you must use the
  same compiler for the application.
  This is another complication and
  dependency that can be avoided by
  using only the standard C library
  version.

Note 2: if you use a standard C
  pthread*.dll with a C++ application,
  then any functions that you define
  that are intended to be called via
  pthread_cleanup_push() must be
  __cdecl.

Note 3: the intention was to also name
  either the VC or GC version (it should
  be arbitrary) as pthread.dll,
  including pthread.lib and libpthread.a
  as appropriate. This is no longer
  likely to happen.

Note 4: the compatibility number was
  added so that applications can
  differentiate between binary
  incompatible versions of the libs and
  dlls.

In general:   pthread[VG]{SE,CE,C}c.dll
    pthread[VG]{SE,CE,C}c.lib

where:    [VG] indicates the compiler
    V   - MS VC, or     G   - GNU C

{SE,CE,C} indicates the exception
  handling scheme   SE  - Structured EH,
  or    CE  - C++ EH, or    C   - no exceptions
  - uses setjmp/longjmp

c   - DLL compatibility number
  indicating ABI and API
          compatibility with applications built against
          any snapshot with the same compatibility number.
          See 'Version numbering' below.

The name may also be suffixed by a 'd'
  to indicate a debugging version of the
  library. E.g. pthreadVC2d.lib.
  Debugging versions contain additional
  information for debugging (symbols
  etc) and are often not optimised in
  any way (compiled with optimisation
  turned off).

For example:
    pthreadVSE.dll  (MSVC/SEH)
    pthreadGCE.dll  (GNUC/C++ EH)
    pthreadGC.dll   (GNUC/not dependent on
  exceptions)   pthreadVC1.dll  (MSVC/not
  dependent on exceptions - not binary
            compatible with pthreadVC.dll)
    pthreadVC2.dll  (MSVC/not dependent on
  exceptions - not binary           compatible
  with pthreadVC1.dll or pthreadVC.dll)

The GNU library archive file names
  have correspondingly changed to:

libpthreadGCEc.a    libpthreadGCc.a

If you want to see what the differences are for each of these clean up models, search for "__CLEANUP" in the pthreads Win32 source (there are only a few places where the different clean up models come into play).

ContentLicense: CC BY-SA 2.5

Title: pthread win32 version? (Mongoose)


问:
Linq query for below data
```<code>id  vid Amount  Date
a   1   10  Today
a   1   5   Yesterday
b   2   6   Today
b   2   7   Yesterday
</code>```

How to fetch records using linq where amount for today is greater than yesterday for each vid group bi Id and vid?

答:
If I have understood correctly, you have a class that looks like this:

```<code>class Data
{
    public string Id;
    public int Vid;
    public int Amount;
    public DateTime Date;
}
</code>```

And an enumeration of instances of this class, which contains multiple instances that share the same Vid value, but different Amount and Date values. What you want is to get all instances which simultaneously have the greatest Date and Amount values of all other instances with the same Vid. Once you have that, you want to group the results by Id and Vid

In this case, you want the following query:

```<code>var myList = new List<Data>();
var result = myList.SelectMany(d1 => myList.Where(d2 => d2.Vid == d1.Vid && d1.Amount < d2.Amount && d1.Date < d2.Date)).OrderBy(data => data.Vid).ThenBy(data => data.Id).ToList();
</code>```

What we are doing here is the following:

Iterate through all elements in myList.

For each element, find all other elements with the same Vid, but a larger Date and Amount.

Flatten all results into a single collection using SelectMany.

Order the resulting enumeration by Vid, and then by Id.

Convert the result into a list.

Title: Linq query for below data

Body:
id  vid Amount  Date
a   1   10  Today
a   1   5   Yesterday
b   2   6   Today
b   2   7   Yesterday

How to fetch records using linq where amount for today is greater than yesterday for each vid group bi Id and vid?

Body:
If I have understood correctly, you have a class that looks like this:

class Data
{
    public string Id;
    public int Vid;
    public int Amount;
    public DateTime Date;
}

And an enumeration of instances of this class, which contains multiple instances that share the same Vid value, but different Amount and Date values. What you want is to get all instances which simultaneously have the greatest Date and Amount values of all other instances with the same Vid. Once you have that, you want to group the results by Id and Vid

In this case, you want the following query:

var myList = new List<Data>();
var result = myList.SelectMany(d1 => myList.Where(d2 => d2.Vid == d1.Vid && d1.Amount < d2.Amount && d1.Date < d2.Date)).OrderBy(data => data.Vid).ThenBy(data => data.Id).ToList();

What we are doing here is the following:

Iterate through all elements in myList.

For each element, find all other elements with the same Vid, but a larger Date and Amount.

Flatten all results into a single collection using SelectMany.

Order the resulting enumeration by Vid, and then by Id.

Convert the result into a list.


问:
Cmake: check if system include directory
Is it possible with cmake 2.6 (or higher, if not possible in this version) to check whether an include directory is marked as SYSTEM (e.g. compile with the isystem gcc flag, see 2.8 System Headers)?

For example, I get the include directories of the current target with:

```<code>GET_PROPERTY(_target_include_dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES)
</code>```

How do I know which ones are marked as isystem?

Thanks

答:
Looking at the CMake source, whether an include directory added with include_directories is marked as SYSTEM seems to be tracked in CMake internals, and is not available for consumption inside your CMakeLists.txt¹.

However, for the target property INTERFACE_INCLUDE_DIRECTORIES (populated by target_include_directories with either PUBLIC or INTERFACE), there is another target property named INTERFACE_SYSTEM_INCLUDE_DIRECTORIES:

```<code>add_library(testlib test.cc)

target_include_directories(testlib SYSTEM INTERFACE /target_system)

get_property(_system_include_dirs TARGET testlib PROPERTY INTERFACE_SYSTEM_INCLUDE_DIRECTORIES)
message("System: ${_system_include_dirs}")
</code>```

So maybe you can use that instead.

¹ There is mention of a SYSTEM_INCLUDE_DIRECTORIES property available through a generator expression, but I couldn't get it to work.

Body:
Is it possible with cmake 2.6 (or higher, if not possible in this version) to check whether an include directory is marked as SYSTEM (e.g. compile with the isystem gcc flag, see 2.8 System Headers)?

For example, I get the include directories of the current target with:

GET_PROPERTY(_target_include_dirs DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES)

How do I know which ones are marked as isystem?

Thanks

Body:
Looking at the CMake source, whether an include directory added with include_directories is marked as SYSTEM seems to be tracked in CMake internals, and is not available for consumption inside your CMakeLists.txt¹.

However, for the target property INTERFACE_INCLUDE_DIRECTORIES (populated by target_include_directories with either PUBLIC or INTERFACE), there is another target property named INTERFACE_SYSTEM_INCLUDE_DIRECTORIES:

add_library(testlib test.cc)

target_include_directories(testlib SYSTEM INTERFACE /target_system)

get_property(_system_include_dirs TARGET testlib PROPERTY INTERFACE_SYSTEM_INCLUDE_DIRECTORIES)
message("System: ${_system_include_dirs}")

So maybe you can use that instead.

¹ There is mention of a SYSTEM_INCLUDE_DIRECTORIES property available through a generator expression, but I couldn't get it to work.


答:
What I understand from your question is you don't want to select previous time from current time of calender. For your problem to work you can use below code

```<code>datePicker.setMinDate(System.currentTimeMillis() - 1000);
</code>```

Remember :

From the source code the minimum date must be before, not equal to, the current date.So you simply need to subtract enough time from now

Title: How to compare current time with selected time in android

Body:
I have time picker and I don't want to select previous time from it.

It means that if I am selecting time before current time it can't display. I don't want to show time before current time.

public class ProfileDetail extends AppCompatActivity {
    Toolbar toolbar;
    String description, str_requirement, str_date, str_time, str_noofperson, str_address;
    TextView txt_description;
    EditText et_requirment, date_pick, time_set, et_no_of_person, et_address_service;
    Button btn_submit;
    int mYear, mMonth, mDay, mHour, mMinute;
    private Calendar cal;
    DateFormat fmtDateAndTime = DateFormat.getTimeInstance();

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_details);
        Bundle extras = getIntent().getExtras();
        description = extras.getString("description");
        txt_description = (TextView) findViewById(R.id.txtservicedetails);
        toolbar = (Toolbar) findViewById(R.id.toolbarforprofile);
        setSupportActionBar(toolbar);
        cal = Calendar.getInstance();
        mDay = cal.get(Calendar.DAY_OF_MONTH);
        mMonth = cal.get(Calendar.MONTH);
        mYear = cal.get(Calendar.YEAR);
        mHour = cal.get(Calendar.HOUR_OF_DAY);
        mMinute = cal.get(Calendar.MINUTE);
        et_requirment = (EditText) findViewById(R.id.editText_requirement);
        et_no_of_person = (EditText) findViewById(R.id.et_noofperson);
        et_address_service = (EditText) findViewById(R.id.et_serviceaddress);
        time_set = (EditText) findViewById(R.id.et_time);
        date_pick = (EditText) findViewById(R.id.et_dateof_visit);
        btn_submit = (Button) findViewById(R.id.btn_submit);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setTitle("Need-Hlp");
        toolbar.setTitleTextColor(Color.WHITE);
        txt_description.setText(description);
        //date_pick.setInputType(InputType.TYPE_NULL);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intentfromprevious = new Intent(ProfileDetail.this, NavigationDrawer.class);
                intentfromprevious.putExtra("description", description);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intentfromprevious.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivity(intentfromprevious);

            }
        });

        date_pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(0);
            }
        });

        final TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

                cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
                cal.set(Calendar.MINUTE, minute);

                updateLabel();
            }
        };

        time_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get Current Time

                new TimePickerDialog(ProfileDetail.this, t, cal
                        .get(Calendar.HOUR_OF_DAY), cal
                        .get(Calendar.MINUTE), true).show();
            }
        });
        //final TextView textView = (TextView)findViewById(R.id.textview23);

        //////Submit button onclicklistener
        btn_submit.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {

                str_date = date_pick.getText().toString();
                if (et_requirment.getText().toString().equals("")) {
                    et_requirment.setError("Requirement cannot be blank");
                    et_requirment.requestFocus();
                    return;
                }
                if (str_date.isEmpty() || str_date.length() == 0 || str_date.equals("") || str_date == null) {
                    Toast.makeText(ProfileDetail.this, "Date cannot be blank", Toast.LENGTH_SHORT).show();
                    //date_pick.setError("Date cannot be blank");
                    return;

                }

                if (time_set.getText().toString().equals("")) {
                    Toast.makeText(ProfileDetail.this, "Time cannot be blank", Toast.LENGTH_SHORT).show();
                    //time_set.setError("Time cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }

                if (et_no_of_person.getText().toString().toString().equals("")) {
                    et_no_of_person.setError("No of person cannot be blank");
                    //edittext_phone.requestFocus();
                    return;
                }
                if (et_address_service.getText().toString().equals("")) {
                    et_address_service.setError("Address cannot be blank");
                    //edittext_Password.requestFocus();
                    return;
                }

                if (!et_requirment.getText().toString().trim().equals("") && !et_no_of_person.getText().toString().trim().equals("") && !et_address_service.getText().toString().equals("")) {

                    Toast.makeText(ProfileDetail.this, "You Request Submitted", Toast.LENGTH_SHORT).show();
                    Intent intentforlist = new Intent(ProfileDetail.this, NavigationDrawer.class);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intentforlist.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(intentforlist);
                }

            }

        });

    }

    private void updateLabel() {
        Calendar c = Calendar.getInstance();

        String time = "23:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date timeCompare = null;
        Date currentTimes = new Date();
        int comareResult = timeCompare.compareTo(currentTimes);
        try {

            if (comareResult == 0) {
                timeCompare = sdf.parse(time);
                time_set.setText(time);
            }

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

    }

    @Override
    @Deprecated
    protected Dialog onCreateDialog(int id) {
        //return new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay);

        DatePickerDialog _date = new DatePickerDialog(this, datePickerListener, mYear, mMonth, mDay) {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                if (year < mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (monthOfYear < mMonth && year == mYear)
                    view.updateDate(mYear, mMonth, mDay);

                if (dayOfMonth < mDay && year == mYear && monthOfYear == mMonth)
                    view.updateDate(mYear, mMonth, mDay);

            }
        };
        return _date;

    }

    private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int selectedYear,
                              int selectedMonth, int selectedDay) {

            date_pick.setText(+selectedDay + " / " + (selectedMonth + 1) + " / "
                    + selectedYear);
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem item1 = menu.findItem(R.id.action_cart);
        MenuItemCompat.setActionView(item1, R.layout.count);
        // notificationCount1 = (RelativeLayout) MenuItemCompat.getActionView(item1);
        return super.onCreateOptionsMenu(menu);
    }
}

Body:
What I understand from your question is you don't want to select previous time from current time of calender. For your problem to work you can use below code

datePicker.setMinDate(System.currentTimeMillis() - 1000);

Remember :

From the source code the minimum date must be before, not equal to, the current date.So you simply need to subtract enough time from now


问:
How to annotate Django QuerySet with other object using Subquery
In Django version 1.11, Subquery expressions were added. I was hoping to use this feature to select a related model object based on some filters.

This is an example from the documentation:

```<code>from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))
</code>```

I would like to do the same, but instead of just annotating with the "newest_commenter_email" in this scenario, I'd like the whole Comment object saved to a newest_comment annotation, like so:

```<code>from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_comment=Subquery(newest[:1]))
</code>```

However, this results in the following error:

```<code>FieldError: Expression contains mixed types. You must set output_field
</code>```

Is there a way around this?

答:
You ommited values on the subquery, try this:

```<code>Post.objects.annotate(newest_commenter=Subquery(newest.values('author')[:1]))
</code>```

where 'author' is the "commenter" field on Comment model.

Body:
In Django version 1.11, Subquery expressions were added. I was hoping to use this feature to select a related model object based on some filters.

This is an example from the documentation:

from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))

I would like to do the same, but instead of just annotating with the "newest_commenter_email" in this scenario, I'd like the whole Comment object saved to a newest_comment annotation, like so:

from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_comment=Subquery(newest[:1]))

However, this results in the following error:

FieldError: Expression contains mixed types. You must set output_field

Is there a way around this?

Body:
You ommited values on the subquery, try this:

Post.objects.annotate(newest_commenter=Subquery(newest.values('author')[:1]))

where 'author' is the "commenter" field on Comment model.


问:
full-text search condition in sql
```<code> select * from quotestable where contains(RelatedKeyword, 'Benjamin Franklin Quotes')
</code>```

returns an error

```<code> Msg 7630, Level 15, State 3, Line 1
 Syntax error near 'Franklin' in the full-text search condition 'Benjamin Franklin'.
</code>```

I am surprised as to why. It should ideally search for the word but it has returned error message.

答:
Use CONTAINS and CONTAINSTABLE to match words and phrases.

It performs a SQL Server full-text search on full-text indexed
  columns containing character-based data types.Text Search

```<code>select * from quotestable where CONTAINSTABLE(<tablename>, <ColumnName> ,'Benjamin Franklin Quotes')
</code>```

CONTAINS

```<code>select * from quotestable where CONTAINS(<ColumnName> ,'"Benjamin Franklin Quotes"')
</code>```

word

Is a string of characters without spaces or punctuation.

phrase

Is one or more words with spaces between each word.

Phrases should be enclosed in double quotation marks ("").

Title: full-text search condition in sql

Body:
 select * from quotestable where contains(RelatedKeyword, 'Benjamin Franklin Quotes')

returns an error

 Msg 7630, Level 15, State 3, Line 1
 Syntax error near 'Franklin' in the full-text search condition 'Benjamin Franklin'.

I am surprised as to why. It should ideally search for the word but it has returned error message.

Body:
Use CONTAINS and CONTAINSTABLE to match words and phrases.

It performs a SQL Server full-text search on full-text indexed
  columns containing character-based data types.Text Search

select * from quotestable where CONTAINSTABLE(<tablename>, <ColumnName> ,'Benjamin Franklin Quotes')

CONTAINS

select * from quotestable where CONTAINS(<ColumnName> ,'"Benjamin Franklin Quotes"')

word

Is a string of characters without spaces or punctuation.

phrase

Is one or more words with spaces between each word.

Phrases should be enclosed in double quotation marks ("").


问:
what is Varien_Db_Ddl_Table::TYPE_TEXT in mysql/magento
I have seen in magento mysql install or upgrade script where they are adding column by using :

```<code>$installer->getTable('catalog/eav_attribute'),
    'tooltip',
    array(
        'type'      => Varien_Db_Ddl_Table::TYPE_TEXT,
        'nullable'  => true,
        'comment'   => 'Tooltip'
    )
</code>```

I Want to know what is Varien_Db_Ddl_Table::TYPE_TEXT? If I want to add the tooltip column manually in mysql table then what should I use in type section? Is it only 'TEXT'?

答: I had the same doubt in magento 2, later i found the declaration in table.php in \vendor\magento\framework\DB\Ddl\Table.php</p>

Body:
I have seen in magento mysql install or upgrade script where they are adding column by using :

$installer->getTable('catalog/eav_attribute'),
    'tooltip',
    array(
        'type'      => Varien_Db_Ddl_Table::TYPE_TEXT,
        'nullable'  => true,
        'comment'   => 'Tooltip'
    )

I Want to know what is Varien_Db_Ddl_Table::TYPE_TEXT? If I want to add the tooltip column manually in mysql table then what should I use in type section? Is it only 'TEXT'?


问:
Talend - tOralcerow Issue
Team, I'm using the below insert query to insert data into a table. But I'm getting syntax error not sure what I'm missing here,

```<code> insert into employee (emp_id,dept_id,emp_nm,emp_address,insert_date)
 values(@EMP_ID,(select max(dept_id) + 1 as dept_id from
 department),@EMP_NM,NULL,to_char(sysdate(),”DD-MM-YYYY”))
</code>```

Getting error as “tOraclerow - ORA-00936 missing expression” Please help on this issue.

Basically i'm getting the columns in the flow till the tOracelrow component, I need to know what is the coding or procedure on how to access the same in the query written inside the tOraclerow component.

答:
At the place of @EMP_ID, please use your flowname.EMP_ID

for example : row1.EMP_ID

if your column is string than put this variable in quote also like

"insert into employee (emp_id,dept_id,emp_nm,emp_address,insert_date)
 values("+row1.EMP_ID+",(select max(dept_id) + 1 as dept_id from
 department),'"+row1.EMP_ID+"',NULL,to_char(sysdate(),”DD-MM-YYYY”))"

Hope this helps..

Title: Talend - tOralcerow Issue

Body:
Team, I'm using the below insert query to insert data into a table. But I'm getting syntax error not sure what I'm missing here,

 insert into employee (emp_id,dept_id,emp_nm,emp_address,insert_date)
 values(@EMP_ID,(select max(dept_id) + 1 as dept_id from
 department),@EMP_NM,NULL,to_char(sysdate(),”DD-MM-YYYY”))

Getting error as “tOraclerow - ORA-00936 missing expression” Please help on this issue.

Basically i'm getting the columns in the flow till the tOracelrow component, I need to know what is the coding or procedure on how to access the same in the query written inside the tOraclerow component.


问:
How do I force evaluation of a cfif stored in a string?
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

```<code>"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"
</code>```

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

```<code><cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>
</code>```

I also tried

```<code><cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>
</code>```

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?

答:
If you absolutely have to do this, look at the evaluate() function.  This, essentially, fires up a new CF thread, compiles the string passed to it, runs it, and returns the result.

If at all possible, I would try to find a way to move your logic to the actual file being run, not the string from the database.  I assume you are pulling the data based on some string you've already built, so you might consider appending something to it, so you are looking up subjectDotLegal and subjectDocketLegal or something similar.

Remember, evaluate() is slow, ugly, and can be dangerous (it will run anything passed to it!).  If there's a way around it, I suggest you use it.

Body:
I am trying to store coldfusion code in a database to be used for the subject of a cfmail. The code stored is as follows:

"RE: <cfif myData.general.legalName NEQ """">  {{dotlegalname}}<cfelse>{{docketLegalName}}</cfif>,
DOT## {{dot}}, Docket ##(s)   {{docketString}}"

When I retrieve string from the database, I use cfsavecontent to attempt to evaluate it.

<cfsavecontent variable="subject">
 <cfoutput>#myData.email.subject#</cfoutput>
</cfsavecontent>

I also tried

<cfsavecontent variable="subject">
     <cfoutput>#evaluate(myData.email.subject)#</cfoutput>
</cfsavecontent>

And then I replace all the {{ }} with the appropriate values.

However, the subject of the email is stubbornly refusing to contain an evaluated cfif, and is instead showing the cfif as if it were a string.

Any ideas?


问:
Time complexity of a de-duping algorithm
Here is a function for removing duplicates from an array.

function dedupe(arr) {
    var seen = {};
    arr.forEach((e,i)=>{
        if (seen[e]) {
            arr.splice(i, 1);
        }
        seen[e] = true;
    });
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 4]));```
</div>
</div>
</p>

<p>I am interested in the time complexity of this function.</p>

<p>If we assume that <code>Array</code> is backed by a real array, does that the time complexity can be analysed as follows?</p>

<ul>
<li>allocation of <code>seen</code>: O(1)</li>
<li>enumerate all elements: O(n)</li>
<li>removal of a duplicate: O(n) (because re-allocation required item by item?)</li>
<li>return O(1)</li>
</ul>

<p>So is this an O(n^2) algorithm?</p>

<p><strong>Edit:</strong></p>

<p>Corrected for indexing issue.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function dedupe(arr) {
    var seen = {};
    for(let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (seen[e]) {
            arr.splice(i, 1);
            i--; // we have modified the array and need to continue from the current index
        }
        seen[e] = true;
    }
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));</code>```

For those upset by the performance of the above, this is O(N) I think.

I wanted to de-dupe in-place. Use of Set maintains the order across host environments.

function dedupe(arr) {
    var seen = new Set();
    for(let i = 0; i < arr.length; i++) {
        seen.add(arr[i]);
    }
    arr.length = 0; // empty the array
    return arr.concat(...seen.keys());
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));```

答:
My answer, builds a new array. Maybe is O(n).

function dedupe(arr) {
    var result = [];
    var seen = {};
    for(let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (seen[e]) {
            //skip
        } else {
            seen[e] = true;
            result.push(e);
        }

    }
    return result;
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));```

Body:
Here is a function for removing duplicates from an array.

function dedupe(arr) {
    var seen = {};
    arr.forEach((e,i)=>{
        if (seen[e]) {
            arr.splice(i, 1);
        }
        seen[e] = true;
    });
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 4]));

I am interested in the time complexity of this function.

If we assume that Array is backed by a real array, does that the time complexity can be analysed as follows?

allocation of seen: O(1)

enumerate all elements: O(n)

removal of a duplicate: O(n) (because re-allocation required item by item?)

return O(1)

So is this an O(n^2) algorithm?

Edit:

Corrected for indexing issue.

function dedupe(arr) {
    var seen = {};
    for(let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (seen[e]) {
            arr.splice(i, 1);
            i--; // we have modified the array and need to continue from the current index
        }
        seen[e] = true;
    }
    return arr;
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));

For those upset by the performance of the above, this is O(N) I think.

I wanted to de-dupe in-place. Use of Set maintains the order across host environments.

function dedupe(arr) {
    var seen = new Set();
    for(let i = 0; i < arr.length; i++) {
        seen.add(arr[i]);
    }
    arr.length = 0; // empty the array
    return arr.concat(...seen.keys());
}

console.log(dedupe([1, 2, 1, 3, 1, 4, 4, 7, 6, 7, 7, 7, 1, 5]));


问:
How can we use @types/bootbox and @types/jquery?
How can we use @types/bootbox and @types/jquery in angular 4 project?
I did something like this

```<code>npm install @types/bootbox
</code>```

and  in my code I am doing something like this

```<code>import * as bootbox from 'bootbox'.
</code>```

I am getting this Error
@types/bootbox/index.d.ts (96,41): Generic type 'JQuery' requires 2 type argument(s).

答:
Just install both of them (@types/bootbox, @types/jquery) with NPM:</p>

```<code>npm install --save-dev @types/bootbox
npm install --save-dev @types/jquery
</code>```

Body:
How can we use @types/bootbox and @types/jquery in angular 4 project?
I did something like this

npm install @types/bootbox

and  in my code I am doing something like this

import * as bootbox from 'bootbox'.

I am getting this Error
@types/bootbox/index.d.ts (96,41): Generic type 'JQuery' requires 2 type argument(s).

Body:
Just install both of them (@types/bootbox, @types/jquery) with NPM:

npm install --save-dev @types/bootbox
npm install --save-dev @types/jquery


问:
GOOGLE_SIGN_IN_API fails in a release build
When my app is a built as a debug build I can login correctly, but when I build as a signed APK and release in Google Play the same account can't login.

Is there an extra Google API permission that I'm missing?

mGoogleApiClient = new GoogleApiClient.Builder(this)
                  .enableAutoManage(this, this )
                  .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                  .build();

...

GoogleSignInResult result =
  Auth.GoogleSignInApi.getSignInResultFromIntent(data); if
  (!result.isSuccess()) { .. }

答: As I understand, you have provided the debug SHA1 in the Google developer console, then you signed the apk and the SHA1 changed.</p>


问:
How could i make a div with rounded borders and make the fa icons inside it centered?
So i want a div with rounded borders (to make a circle) and inside that i want my fa icons which would be aligned to the middle.

So basically i want a Circle containing an fa icon in the middle just to make it simple.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
    </div>
  </div>
</div></code>```

答:
http://jsfiddle.net/Parthoghsh820/rm7zhLv1/1/

```<code> <span>Please refer the above fiddle</span>
</code>```

[https://codepen.io/ParthoGhosh/pen/mwjpgv

```<code> <span>and the Codepen for your ref</span>
</code>```

Body:
So i want a div with rounded borders (to make a circle) and inside that i want my fa icons which would be aligned to the middle.

So basically i want a Circle containing an fa icon in the middle just to make it simple.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Body:
http://jsfiddle.net/Parthoghsh820/rm7zhLv1/1/

 <span>Please refer the above fiddle</span>

[https://codepen.io/ParthoGhosh/pen/mwjpgv

 <span>and the Codepen for your ref</span>


问:
ES6 function parameter validation
I've read a great pattern of handling required function parameters on 2ality.

```<code>function throwIfMissing() {
    throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}
</code>```

Is there any such nice and clean way to throw validation errors?

```<code>function throwIfInvalid(value) {
    const max = 10;
    const min = 5;

    if(value < min || value > max){
        throw new Error(`Value must be between ${min} ${max}`);
    }

    return value;
}

function foo(mustBeValid = throwIfInvalid()) {
    return mustBeValid;
}
</code>```

Of course the throwIfInvalid() function does not work as expected. My question is if there is any trick to make it work.?

答:
Of course it doesnt work, i think you are misunderstanding how Default Parameters work.

When you write

function foo(mustBeProvided = throwIfMissing())
```

<p>you are assigning the result of <code>throwIfMissing</code> to the parameter <strong>IF AND ONLY IF</strong> the parameter is <code>undefined</code>.</p>

<p>Meaning that if that parameter is provided then <code>throwIfMissing</code> is <strong>not</strong> called at all; it will never execute and will never check for the validity of your parameter.</p>

<p>That's why you can only use this "trick" to react to an undefined parameter, not to validate one.</p>

<p>--</p>

<p><strong>Alternative Solution</strong></p>

<p>Personally i would solve the problem with a simple solution</p>

<pre class="lang-js prettyprint-override"><code>function checkRange(val, min, max) {
    if (val > max || val < min) {
        throw new Error();
    }
}

function foo(val) {
    checkRange(val, 5, 10);
    return val;
}
</code>```

You may argue that this is much less elegant but keep in mind that in this case you can reuse the validator with different values, you don't have to hardcode min and max.

If you are looking for an npm module you can try this one but i wouldn't go that far for a simple validation.

Title: ES6 function parameter validation

Body:
I've read a great pattern of handling required function parameters on 2ality.

function throwIfMissing() {
    throw new Error('Missing parameter');
}
function foo(mustBeProvided = throwIfMissing()) {
    return mustBeProvided;
}

Is there any such nice and clean way to throw validation errors?

function throwIfInvalid(value) {
    const max = 10;
    const min = 5;

    if(value < min || value > max){
        throw new Error(`Value must be between ${min} ${max}`);
    }

    return value;
}

function foo(mustBeValid = throwIfInvalid()) {
    return mustBeValid;
}

Of course the throwIfInvalid() function does not work as expected. My question is if there is any trick to make it work.?

Body:
Of course it doesnt work, i think you are misunderstanding how Default Parameters work.

When you write

function foo(mustBeProvided = throwIfMissing())

you are assigning the result of throwIfMissing to the parameter IF AND ONLY IF the parameter is undefined.

Meaning that if that parameter is provided then throwIfMissing is not called at all; it will never execute and will never check for the validity of your parameter.

That's why you can only use this "trick" to react to an undefined parameter, not to validate one.

--

Alternative Solution

Personally i would solve the problem with a simple solution

function checkRange(val, min, max) {
    if (val > max || val < min) {
        throw new Error();
    }
}

function foo(val) {
    checkRange(val, 5, 10);
    return val;
}

You may argue that this is much less elegant but keep in mind that in this case you can reuse the validator with different values, you don't have to hardcode min and max.

If you are looking for an npm module you can try this one but i wouldn't go that far for a simple validation.


问:
Getting Information from Req.User() into Req.params() in ExpressJS
After people log into my Express app, I'd like to redirect them to a url that reads:

```<code>www.mysite.com/:user
</code>```

What I'm having trouble with is that my req.params object is coming up as an empty object literal when people get re-directed after logging in.

Ideally what I'd like to do is to somehow take the information stored in req.user and pass some of that information into the URL.

So basically I'd like to get from here:

```<code>router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect: '/login', failureFlash: true}));
</code>```

To here:

```<code>router.get('/:user', function(req, res) {
    //stuff
}
</code>```

After logging in the req.user object reads like this:

```<code>{
  username: joesmith@mail.com,
  name: Joe Smith,
  password:  dkei348#$kDL^583L,
  formulas: []
}
</code>```

And the code I'm attempting to use is as follows:

```<code>router.get('/:user', function(req, res) {
var user = req.user.name;
req.params = {
  "user": user
}
</code>```

But this doesn't work because initially req.user.name is undefined if someone isn't already logged in, so I can't get past the console error.

Apparently I don't understand how req.params is generated in enough detail to get around this problem.

Thank you.

答:
You can provide a custom handler, instead of letting Passport do all the redirecting:

```<code>app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      req.flash('error', 'Unable to authenticate user');
      return res.redirect('/login');
    }
    if (! user) {
      return res.redirect('/login');
    }
    req.logIn(user, function(err) {
      if (err) {
        req.flash('error', 'Unable to log in user');
        return res.redirect('/login');
      }
      return res.redirect('/' + user.username);
    });
  })(req, res, next);
});
</code>```

This does mean that each logged-in user gets their "personal" URL, because you're redirecting to /USERNAME. I'm not sure from your question if that's actually your intention.

Body:
After people log into my Express app, I'd like to redirect them to a url that reads:

www.mysite.com/:user

What I'm having trouble with is that my req.params object is coming up as an empty object literal when people get re-directed after logging in.

Ideally what I'd like to do is to somehow take the information stored in req.user and pass some of that information into the URL.

So basically I'd like to get from here:

router.post('/login',
passport.authenticate('local', {successRedirect:'/', failureRedirect: '/login', failureFlash: true}));

To here:

router.get('/:user', function(req, res) {
    //stuff
}

After logging in the req.user object reads like this:

{
  username: joesmith@mail.com,
  name: Joe Smith,
  password:  dkei348#$kDL^583L,
  formulas: []
}

And the code I'm attempting to use is as follows:

router.get('/:user', function(req, res) {
var user = req.user.name;
req.params = {
  "user": user
}

But this doesn't work because initially req.user.name is undefined if someone isn't already logged in, so I can't get past the console error.

Apparently I don't understand how req.params is generated in enough detail to get around this problem.

Thank you.

Body:
You can provide a custom handler, instead of letting Passport do all the redirecting:

app.post('/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      req.flash('error', 'Unable to authenticate user');
      return res.redirect('/login');
    }
    if (! user) {
      return res.redirect('/login');
    }
    req.logIn(user, function(err) {
      if (err) {
        req.flash('error', 'Unable to log in user');
        return res.redirect('/login');
      }
      return res.redirect('/' + user.username);
    });
  })(req, res, next);
});

This does mean that each logged-in user gets their "personal" URL, because you're redirecting to /USERNAME. I'm not sure from your question if that's actually your intention.


答:
One approach would be to use the Javascript Set. You could simply do this:

```<code>const removeDuplicates = array => (new Set(array)).values()
</code>```

This will return an iterator, and not an array, however this can easily be fixed. Also, sets are not yet supported in most browsers. The complexity of this should be O(n).

Another approach more similar to yours (but probably identical to the Set, since I'm gonna guess it's implemented using the same underlying structure) would be like this:

```<code>const removeDuplicates = array =>
    Object.keys(array.reduce((agg, x) => { agg[x] = true; return agg }, {}))
</code>```

The time complexity of this should be O(m+n) where m will be the number of unique items, which will always be <= n, therefore O(n).

Also, the time complexity you worked out seems correct.

Title: Time complexity of a de-duping algorithm

Body:
One approach would be to use the Javascript Set. You could simply do this:

const removeDuplicates = array => (new Set(array)).values()

This will return an iterator, and not an array, however this can easily be fixed. Also, sets are not yet supported in most browsers. The complexity of this should be O(n).

Another approach more similar to yours (but probably identical to the Set, since I'm gonna guess it's implemented using the same underlying structure) would be like this:

const removeDuplicates = array =>
    Object.keys(array.reduce((agg, x) => { agg[x] = true; return agg }, {}))

The time complexity of this should be O(m+n) where m will be the number of unique items, which will always be <= n, therefore O(n).

Also, the time complexity you worked out seems correct.


问:
unity3D high memory usage in debug
i have a scene in my Unity project with 2 2D skinned and animated character. (and some others things...)

When i build in release, the scene take on pc around 500 MB. (all inclusive)
When i launch debug in unity, Unity take 10 GB more memory... (so my computer is nearly memory empty and crash often...)

If i remove that 2 characters, the memory usage for debugging is more "normal".

Is it normal that just with that 2 characters it take so much memory ?
I have less issue with previous version of unity (i'm using Unity 5.6.1f1)

答:
I found out that it was the profiler that is using that huge memory size.

I remove the profiler recording and memory keep under 1.5G in unity / debug and it's clearly better.

But i don't know why the profiler use so much memory in that scene....

Title: unity3D high memory usage in debug


问:
HP ALM - download a resource under a specific folder in the Test Resource module
We are using ALM 12.  We have multiple folders in our Test Resources module, and some of the resources stored in these folders have the same name as in other folders.  I am able to download a resource using the name, but can't figure out how to get a resource under a specific folder.  Anyone know how to download a resource specifying the folder to download it from?

e.g
Folder1
   mysheet.xls
Folder2
   mysheet.xls

I want to download Folder2\mysheet.xls and not Folder1\mysheet.xls

答:
```<code>Option Explicit

Dim objCon, cust, resource
set objCon= CreateObject("TDApiOle80.TDConnection")
objCon.InitConnectionEx "http://YourALMServer:Port/qcbin"
objCon.Login "username", "password"
objCon.Connect "domainName", "projectName"

Set oResourceFolder = objCon.QCResourceFolderFactory
Set oFilter = oResourceFolder.Filter
oFilter.Filter("RFO_NAME") ="abc" \\ abc is your folder name
Set oList = oFilter.NewList()
set oChild = oList.item(1).QCResourceFactory.NewList("")
''assuming that there is only 1 folder with name "abc" in Test Resources section
For i =1 to oChild.count Step 1
 oChild.item(i).DownloadResource "c:\\a", TRUE
''c:\\a is the location where we need to safe the resource
next
set objCon = Nothing
</code>```


问:
VB - Graphs (Series being added)
I have two separate graphs but every time I go back to a different graph. It adds the series again which causes it to break. I've tried adding the series to the Series Collection but then says it cannot find them.</p>

```<code> Private Sub Finances_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ChrPriceChange.ChartAreas("ChartArea").AxisX.ScrollBar.Enabled = True
    ChrPriceChange.ChartAreas("ChartArea").AxisX.IsLabelAutoFit = True
    ChrPriceChange.ChartAreas("ChartArea").AxisX.ScaleView.Size = 4
    ChrRoomProfit.ChartAreas("ChartArea").AxisX.ScrollBar.Enabled = True
    ChrRoomProfit.ChartAreas("ChartArea").AxisX.IsLabelAutoFit = True
    ChrRoomProfit.ChartAreas("ChartArea").AxisX.ScaleView.Size = 6
End Sub

Private Sub CmbType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbType.SelectedIndexChanged
    If CmbType.SelectedItem = "Price Change" Then

        ChrPriceChange.Series.Add("Single Room")
        ChrPriceChange.Series.Add("Double Room")
        ChrPriceChange.Series.Add("Family Room")
        ChrPriceChange.Series.Add("per Adult")
        ChrPriceChange.Series.Add("per Child")
        ChrPriceChange.Visible = True
        ChrRoomProfit.Visible = False

        MyConn.ConnectionString = dataFile
        MyConn.Open()
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Prices] ORDER BY `Last Modified` ASC", MyConn)
        Dim dr As OleDbDataReader = cmd.ExecuteReader
        While dr.Read
            ChrPriceChange.Series("Single Room").Points.AddXY(dr("Last Modified").ToString, dr("Single").ToString)
            If (ChrPriceChange.ChartAreas(0).AxisX.Maximum > ChrPriceChange.ChartAreas(0).AxisX.ScaleView.Size) Then
                ChrPriceChange.ChartAreas(0).AxisX.ScaleView.Scroll(ChrPriceChange.ChartAreas(0).AxisX.Maximum)
            End If
            ChrPriceChange.Series("Double Room").Points.AddXY(dr("Last Modified").ToString, dr("Double").ToString)
            ChrPriceChange.Series("Family Room").Points.AddXY(dr("Last Modified").ToString, dr("Family").ToString)
            ChrPriceChange.Series("per Adult").Points.AddXY(dr("Last Modified").ToString, dr("Adult").ToString)
            ChrPriceChange.Series("per Child").Points.AddXY(dr("Last Modified").ToString, dr("Child").ToString)
        End While
        MyConn.Close()
        cmd.Dispose()
    End If

    If CmbType.SelectedItem = "Room Profit" Then
        ChrRoomProfit.Series.Add("Total Made")

        ChrRoomProfit.Visible = True
        ChrPriceChange.Visible = False

        MyConn.ConnectionString = dataFile
        MyConn.Open()
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [BookingInformation] ORDER BY `Date In` ASC", MyConn)
        Dim dr As OleDbDataReader = cmd.ExecuteReader
        While dr.Read
            ChrRoomProfit.Series("Total Made").Points.AddXY(dr("Date In").ToString, dr("Total").ToString)

            If (ChrRoomProfit.ChartAreas(0).AxisX.Maximum > ChrRoomProfit.ChartAreas(0).AxisX.ScaleView.Size) Then
                ChrRoomProfit.ChartAreas(0).AxisX.ScaleView.Scroll(ChrRoomProfit.ChartAreas(0).AxisX.Maximum)
            End If
        End While
        MyConn.Close()
        cmd.Dispose()
    End If
End Sub
</code>```

答: Realised it was because I didn't have anything to clear it. ChrPriceChange.Series.Clear

Title: VB - Graphs (Series being added)

Body:
I have two separate graphs but every time I go back to a different graph. It adds the series again which causes it to break. I've tried adding the series to the Series Collection but then says it cannot find them.

 Private Sub Finances_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ChrPriceChange.ChartAreas("ChartArea").AxisX.ScrollBar.Enabled = True
    ChrPriceChange.ChartAreas("ChartArea").AxisX.IsLabelAutoFit = True
    ChrPriceChange.ChartAreas("ChartArea").AxisX.ScaleView.Size = 4
    ChrRoomProfit.ChartAreas("ChartArea").AxisX.ScrollBar.Enabled = True
    ChrRoomProfit.ChartAreas("ChartArea").AxisX.IsLabelAutoFit = True
    ChrRoomProfit.ChartAreas("ChartArea").AxisX.ScaleView.Size = 6
End Sub

Private Sub CmbType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbType.SelectedIndexChanged
    If CmbType.SelectedItem = "Price Change" Then

        ChrPriceChange.Series.Add("Single Room")
        ChrPriceChange.Series.Add("Double Room")
        ChrPriceChange.Series.Add("Family Room")
        ChrPriceChange.Series.Add("per Adult")
        ChrPriceChange.Series.Add("per Child")
        ChrPriceChange.Visible = True
        ChrRoomProfit.Visible = False

        MyConn.ConnectionString = dataFile
        MyConn.Open()
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [Prices] ORDER BY `Last Modified` ASC", MyConn)
        Dim dr As OleDbDataReader = cmd.ExecuteReader
        While dr.Read
            ChrPriceChange.Series("Single Room").Points.AddXY(dr("Last Modified").ToString, dr("Single").ToString)
            If (ChrPriceChange.ChartAreas(0).AxisX.Maximum > ChrPriceChange.ChartAreas(0).AxisX.ScaleView.Size) Then
                ChrPriceChange.ChartAreas(0).AxisX.ScaleView.Scroll(ChrPriceChange.ChartAreas(0).AxisX.Maximum)
            End If
            ChrPriceChange.Series("Double Room").Points.AddXY(dr("Last Modified").ToString, dr("Double").ToString)
            ChrPriceChange.Series("Family Room").Points.AddXY(dr("Last Modified").ToString, dr("Family").ToString)
            ChrPriceChange.Series("per Adult").Points.AddXY(dr("Last Modified").ToString, dr("Adult").ToString)
            ChrPriceChange.Series("per Child").Points.AddXY(dr("Last Modified").ToString, dr("Child").ToString)
        End While
        MyConn.Close()
        cmd.Dispose()
    End If

    If CmbType.SelectedItem = "Room Profit" Then
        ChrRoomProfit.Series.Add("Total Made")

        ChrRoomProfit.Visible = True
        ChrPriceChange.Visible = False

        MyConn.ConnectionString = dataFile
        MyConn.Open()
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM [BookingInformation] ORDER BY `Date In` ASC", MyConn)
        Dim dr As OleDbDataReader = cmd.ExecuteReader
        While dr.Read
            ChrRoomProfit.Series("Total Made").Points.AddXY(dr("Date In").ToString, dr("Total").ToString)

            If (ChrRoomProfit.ChartAreas(0).AxisX.Maximum > ChrRoomProfit.ChartAreas(0).AxisX.ScaleView.Size) Then
                ChrRoomProfit.ChartAreas(0).AxisX.ScaleView.Scroll(ChrRoomProfit.ChartAreas(0).AxisX.Maximum)
            End If
        End While
        MyConn.Close()
        cmd.Dispose()
    End If
End Sub


问:
Does Visual Studio Code work with PowerShell in the Command Palette?
With Visual Studio Code (not the traditional Visual Studio IDEs), can you run PowerShell in the Command Palette? I ask because I commonly use it in the full IDE.

I have not seen PowerShell mentioned in the documentation, other than for basic syntax highlighting. I have tried it with no success. Is it unsupported, or is it an optional feature I can configure somehow?

Note: to those voting up the PowerGUI answer, it is not correct as it references the wrong edition of Visual Studio for this question. It is helpful if you are using the full IDE, but not the new editor named: Code.

答:
Open the Debug view, in the View Bar select Debug from the View menu or press Ctrl + Shift + D.

In the Launch Configuration dropdown (shown in the following screenshot), select Add Configuration...

The launch.json configuration will open in the editor, type PowerShell and select the debug configurations you want, as shown in the following screenshot.

Save the launch.json file and select the debug configuration you want from the Launch Configuration dropdown:

Now you can debug PowerShell scripts through VSCode.

The Scripting Guys wrote a comprehensive 2 part blog post on this topic, like everything else they write, it's well worth a read if you're new to VSCode and PowerShell.

https://blogs.technet.microsoft.com/heyscriptingguy/2017/02/06/debugging-powershell-script-in-visual-studio-code-part-1/

https://blogs.technet.microsoft.com/heyscriptingguy/2017/02/13/debugging-powershell-script-in-visual-studio-code-part-2/

EDIT: I am aware that this question is several years old, but I came across it before I found any up to date information on how to set up PowerShell debugging in VSCode