问:
Using decorator on a variable in a function in Python
I would like to use a decorator for validating data in Python.
Normally in Python one uses a decorator on a function, but I would like to use a decorator on a variable, similar to Java:

public class Main {
   public static void main(String[] args) {
      @BoldWrapper
      @ItalicWrapper
      String str = "Hello World";
      // Display Hello World
   }
}

public @interface BoldWrapper {
    public void wrap() default "" + str + "";
}

public @interface ItalicWrapper {
    public void wrap() default "" + str + "";
}
```

<p>So in Python I would have something like:</p>

```if __name__ == '__main__':
    @BoldWrapper
    @ItalicWrapper
    str = "Hello World";
```

答:
only classes and functions/methods definitions may be decorated (functions/methods since Python 2.4, classes since Python 2.6):

from docs about function definition

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition.

and class definition

Classes can also be decorated: just like when decorating functions

so

```<code>@BoldWrapper
@ItalicWrapper
text = "Hello World"
</code>```

will cause SynaxError.

There is no need for this feature, because we can just write function calls

```<code>text = BoldWrapper(ItalicWrapper("Hello World"))
</code>```

P. S.

do not use names of built-ins like str for your objects,

semicolons are redundant in Python

Further reading

functions and methods decorators: PEP-318,

class decorators: PEP-3129,

PythonWiki page

Body:
I would like to use a decorator for validating data in Python.
Normally in Python one uses a decorator on a function, but I would like to use a decorator on a variable, similar to Java:

public class Main {
   public static void main(String[] args) {
      @BoldWrapper
      @ItalicWrapper
      String str = "Hello World";
      // Display Hello World
   }
}

public @interface BoldWrapper {
    public void wrap() default "" + str + "";
}

public @interface ItalicWrapper {
    public void wrap() default "" + str + "";
}

So in Python I would have something like:

if __name__ == '__main__':
    @BoldWrapper
    @ItalicWrapper
    str = "Hello World";

Body:
only classes and functions/methods definitions may be decorated (functions/methods since Python 2.4, classes since Python 2.6):

from docs about function definition

A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition.

and class definition

Classes can also be decorated: just like when decorating functions

so

@BoldWrapper
@ItalicWrapper
text = "Hello World"

will cause SynaxError.

There is no need for this feature, because we can just write function calls

text = BoldWrapper(ItalicWrapper("Hello World"))

P. S.

do not use names of built-ins like str for your objects,

semicolons are redundant in Python

Further reading

functions and methods decorators: PEP-318,

class decorators: PEP-3129,

PythonWiki page


来源: stackexchange

问:
list-style & bullet effect with proper text alignment

.lists li{
        list-style-type: none;
    }
    .lists li:before {
        content: '\00b7';
        font-size: 140px;
        line-height: 60px;
        vertical-align: middle;
        color: #114576;
        /* margin-left: -5.5%; */
    }
    .lists ul{
        padding-top: 2%;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="lists">
 <ul>
  <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra  by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
  <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
  <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
  <li class="text-muted">Students can access the        results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) -  a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>
  <li class="text-muted">These courses are further mapped to the student’s relevant district and assessed interest</li>
  <li class="text-muted">The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)</li>
  <li class="text-muted">SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)</li>
  </ul>
</div></code>```

here i have implemented the code for the designing the paragraph with bullets.but,i am facing some problem like the second line taking top space between two lines as well the text is not appearing in proper alignment as like displayed in image.
some css effects are missing to display the code same as like displayed in image.

答:
You could achieve it with font aweseome as well :

.lists li {
  list-style-type: none;
  padding-left: 2.3em;
  margin-bottom:30px;
}

.lists li:before {
  content: "\f111"; /* Unicode */
  font-family: FontAwesome;
  color: #114576;
  display: inline-block;
  margin-left: -2.3em;
  width: 2.3em;
}

.lists ul {
  list-style: none;
  padding: 0;
  padding-left:3em;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<div class="lists">
  <ul>
    <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
    <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
    <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
  <li class="text-muted">Students can access the        results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) -  a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>

  </ul>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
.lists li{
        list-style-type: none;
    }
    .lists li:before {
        content: '\00b7';
        font-size: 140px;
        line-height: 60px;
        vertical-align: middle;
        color: #114576;
        /* margin-left: -5.5%; */
    }
    .lists ul{
        padding-top: 2%;
    }

In 2016, SAF lent technical support to the Government of Maharashtra  by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling

In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University

In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test

Students can access the        results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) -  a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra

These courses are further mapped to the student’s relevant district and assessed interest

The portal also serves as a rich source of information, with numerous videos and articles on the 7 education fields (Arts, Commerce, Fine Arts, Technical, Health Sciences, Agriculture and Uniform Services)

SAF maintains a dedicated helpline that offers students one-on-one counseling with trained career counselors from the Institute of Vocational Guidance and Selection (IVGS)

here i have implemented the code for the designing the paragraph with bullets.but,i am facing some problem like the second line taking top space between two lines as well the text is not appearing in proper alignment as like displayed in image.
some css effects are missing to display the code same as like displayed in image.

Body:
You could achieve it with font aweseome as well :

.lists li {
  list-style-type: none;
  padding-left: 2.3em;
  margin-bottom:30px;
}

.lists li:before {
  content: "\f111"; /* Unicode */
  font-family: FontAwesome;
  color: #114576;
  display: inline-block;
  margin-left: -2.3em;
  width: 2.3em;
}

.lists ul {
  list-style: none;
  padding: 0;
  padding-left:3em;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<div class="lists">
  <ul>
    <li class="text-muted">In 2016, SAF lent technical support to the Government of Maharashtra by assisting them with test interpretation, as well as the development of the Maha Mitra Career Portal and the setup of the student helpline for counseling</li>
    <li class="text-muted">In 2017, we have entered the next stage of development with a unique 7-field interest test, developed in collaboration with the Department of Psychology at the Savitribai Phule Pune University</li>
    <li class="text-muted">In the last 2 years, more than 32 lakh grade 10 students from over 22000 State Board schools, as well as students appearing externally for the grade 10 exam, have taken the interest test</li>
  <li class="text-muted">Students can access the        results of the interest test on the Maha Career Mitra Portal (www.mahacareermitra.in) -  a special portal developed by SAF which lists 83,000 government approved higher educational options available in Maharashtra</li>

  </ul>
</div>


问:
Left JOIN on DATE field not working in SQL
This is an Order Management System scenario.

I have a [SalesHistory] Table with following fields:

    ItemMasterID varchar(60)

    Qty int

    OrderDate DateTime

(Omitted non relevant fields)

Executing following query on SalesHistory:

```<code>select Cast(OrderDate as Date) 'OrderDate',Sum(Qty) 'Qty'  from SalesHistory
where itemmasterid= '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
Group by ItemMasterId ,Cast(OrderDate as DAte)
order by OrderDate desc
</code>```

I get the following results (As expected)

As you can see, for the month of 04 there are only 4 records.

What I expect is that all the days of a month be displayed on the left side (Date column) with zeros on the right side (Qty column) if there is no record for that particular date

Here is what I tried:

I created a table [Date_Ref] with field:

    Day DateTime

Then I filled it up with all days of month 04 using the following procedure:

```<code>declare @SD Date = convert(Date,'04/01/2017',101)
declare @ED Date = convert(Date,'04/30/2017',101)
declare @DatePeriod Date = @SD
while (@DatePeriod <= @ED)
begin
    insert into Date_Ref (Day) values (@DatePeriod)
    set @DatePeriod = DATEADD(DD, 1,@DatePeriod)
end
</code>```

Now the Date_Ref table is filled with expected records:

```<code>select Day 'Date' from Date_Ref
</code>```

I tried using LEFT JOIN on this and SalesHistory table expecting to get the result I mentioned above:

```<code>select Cast(d.Day as Date) 'Date',ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join
SalesHistory as s on Cast(s.OrderDate as date) = cast(d.Date_Period as date)
where
s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
</code>```

and I got his result:

Clearly this is not what I EXPECTED.!! I excepected something like:

```<code>+-------------+----+
| Date        | Qty|
+-------------+----+
| 2017-04-01  |   0|
| 2017-04-02  |   0|
| 2017-04-03  |   0|
| 2017-04-04  |   0|
| 2017-04-05  |   0|
| 2017-04-06  |   0|
| 2017-04-07  |   0|
| 2017-04-08  |   0|
| 2017-04-09  |   0|
| 2017-04-10  |   1|
| 2017-04-11  |   1|
....
....
</code>```

Why is the LEFT JOIN behaving like an INNER JOIN? Or is this how SQL returns when you join on DateTime field?

Note:

I also tried removing the Cast.

I also tried all the joins LEFT RIGHT OUTER INNER.

I also tried switching positions of SalesHistory and Date_Ref tables in the query.

Is it that I am doing something wrong? Or is there another approach to this?

Thankyou

Sorry for the lengthy question!! I just had to describe the exact steps what I did

答:
Condition s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008' shoult belongs to left join:

```<code>select Cast(d.Day as Date) 'Date',ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join SalesHistory as s on
    Cast(s.OrderDate as date) = cast(d.Date_Period as date)
    and s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
</code>```

Body:
This is an Order Management System scenario.

I have a [SalesHistory] Table with following fields:

    ItemMasterID varchar(60)

    Qty int

    OrderDate DateTime

(Omitted non relevant fields)

Executing following query on SalesHistory:

select Cast(OrderDate as Date) 'OrderDate',Sum(Qty) 'Qty'  from SalesHistory
where itemmasterid= '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'
Group by ItemMasterId ,Cast(OrderDate as DAte)
order by OrderDate desc

I get the following results (As expected)

As you can see, for the month of 04 there are only 4 records.

What I expect is that all the days of a month be displayed on the left side (Date column) with zeros on the right side (Qty column) if there is no record for that particular date

Here is what I tried:

I created a table [Date_Ref] with field:

    Day DateTime

Then I filled it up with all days of month 04 using the following procedure:

declare @SD Date = convert(Date,'04/01/2017',101)
declare @ED Date = convert(Date,'04/30/2017',101)
declare @DatePeriod Date = @SD
while (@DatePeriod <= @ED)
begin
    insert into Date_Ref (Day) values (@DatePeriod)
    set @DatePeriod = DATEADD(DD, 1,@DatePeriod)
end

Now the Date_Ref table is filled with expected records:

select Day 'Date' from Date_Ref

I tried using LEFT JOIN on this and SalesHistory table expecting to get the result I mentioned above:

select Cast(d.Day as Date) 'Date',ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join
SalesHistory as s on Cast(s.OrderDate as date) = cast(d.Date_Period as date)
where
s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'

and I got his result:

Clearly this is not what I EXPECTED.!! I excepected something like:

+-------------+----+
| Date        | Qty|
+-------------+----+
| 2017-04-01  |   0|
| 2017-04-02  |   0|
| 2017-04-03  |   0|
| 2017-04-04  |   0|
| 2017-04-05  |   0|
| 2017-04-06  |   0|
| 2017-04-07  |   0|
| 2017-04-08  |   0|
| 2017-04-09  |   0|
| 2017-04-10  |   1|
| 2017-04-11  |   1|
....
....

Why is the LEFT JOIN behaving like an INNER JOIN? Or is this how SQL returns when you join on DateTime field?

Note:

I also tried removing the Cast.

I also tried all the joins LEFT RIGHT OUTER INNER.

I also tried switching positions of SalesHistory and Date_Ref tables in the query.

Is it that I am doing something wrong? Or is there another approach to this?

Thankyou

Sorry for the lengthy question!! I just had to describe the exact steps what I did

Body:
Condition s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008' shoult belongs to left join:

select Cast(d.Day as Date) 'Date',ISNULL (s.Qty,0) 'Qty'
from date_Ref as d
left join SalesHistory as s on
    Cast(s.OrderDate as date) = cast(d.Date_Period as date)
    and s.itemmasterid = '001FCB08-B72E-4D1A-91D6-C3D8A8CF7008'


问:
How to run HTML based sql query from MultilineTextBox?
I have a multiline textbox from which I am updating my sql store procedure. In my store procedure I'm sending email(Html Formated) to user via SQL Job.
Problem is when I try to put below code in my textbox my submit button is stop working and perform no action.

```<code>Set @link = ' <br> URL: <a href=abc.com/default4.aspx> abc.com/default4.aspx</a> <br> ' -- For Test
</code>```

I'm also tried to put validateRequest="false" in my page directive but nothing happened.

Sorry here I mentioned one thing more that when I remove
 tag from above code my submit button works fine. But when I put only
 in my ASP.Net Textbox submit button again perform no action on submit.

How can I able to insert HTML Tags in ASP.Net Textbox.

Also I found below links regarding to my question but these links not works for me.

Allow HTML tags in TextBox control

ASP.Net Text with LineBreak from Multi-Line-TextBox to save in a database

ASP.NET Replacing Line Break with HTML br not working

答:
You should put HTML attribute values in double quotes;

```<code><a href="abc.com/default4.aspx">
        ^                     ^
</code>```

Also br tags should be self closed;

```<code><br/>
   ^
</code>```

Also, I don't fully understand what you mean by 'I have a multiline textbox from which I am updating my sql store procedure', but if you are having users type SQL code into a textbox this is usually a terrible idea... You should consider having them just type the URL and having this inserted into the SQL in a safe manner....

Body:
I have a multiline textbox from which I am updating my sql store procedure. In my store procedure I'm sending email(Html Formated) to user via SQL Job.
Problem is when I try to put below code in my textbox my submit button is stop working and perform no action.

Set @link = '
 URL:  abc.com/default4.aspx
 ' -- For Test

I'm also tried to put validateRequest="false" in my page directive but nothing happened.

Sorry here I mentioned one thing more that when I remove
 tag from above code my submit button works fine. But when I put only
 in my ASP.Net Textbox submit button again perform no action on submit.

How can I able to insert HTML Tags in ASP.Net Textbox.

Also I found below links regarding to my question but these links not works for me.

Allow HTML tags in TextBox control

ASP.Net Text with LineBreak from Multi-Line-TextBox to save in a database

ASP.NET Replacing Line Break with HTML br not working

Body:
You should put HTML attribute values in double quotes;

<a href="abc.com/default4.aspx">
        ^                     ^

Also br tags should be self closed;

<br/>
   ^

Also, I don't fully understand what you mean by 'I have a multiline textbox from which I am updating my sql store procedure', but if you are having users type SQL code into a textbox this is usually a terrible idea... You should consider having them just type the URL and having this inserted into the SQL in a safe manner....


问:
How to pass an argument to kafka-console-consumer
I am trying to read a message of size 3mb using kafka-console-consumer by running the command:

```<code>/bin/kafka-console-consumer --zookeeper myzookeeper:2181 --topic Topic1
</code>```

However, I am getting exception:

```<code>2017-06-05 17:16:13,046] ERROR Error processing message, terminating consumer process:  (kafka.tools.ConsoleConsumer$)
kafka.common.MessageSizeTooLargeException: Found a message larger than the maximum fetch size of this consumer on topic Topic1 partition 9 at fetch offset 5. Increase the fetch size, or decrease the maximum message size the broker will allow.
    at kafka.consumer.ConsumerIterator.makeNext(ConsumerIterator.scala:90)
    at kafka.consumer.ConsumerIterator.makeNext(ConsumerIterator.scala:33)
    at kafka.utils.IteratorTemplate.maybeComputeNext(IteratorTemplate.scala:64)
    at kafka.utils.IteratorTemplate.hasNext(IteratorTemplate.scala:56)
    at kafka.consumer.OldConsumer.receive(BaseConsumer.scala:89)
    at kafka.tools.ConsoleConsumer$.process(ConsoleConsumer.scala:110)
    at kafka.tools.ConsoleConsumer$.run(ConsoleConsumer.scala:70)
    at kafka.tools.ConsoleConsumer$.main(ConsoleConsumer.scala:48)
    at kafka.tools.ConsoleConsumer.main(ConsoleConsumer.scala)
Processed a total of 0 messages
</code>```

Now i am trying to run the command:

```<code>/bin/kafka-console-consumer --zookeeper myzookeeper:2181 --topic Topic1 --args max.partitiion.fetch.bytes=10485760
</code>```

But getting error:

```<code>args is not a recognized option
</code>```

How can I pass the param args to kafka-console-consumer?

答: Try to specify consumer properties in a file and supply it with --consumer.config parameter.

Body:
I am trying to read a message of size 3mb using kafka-console-consumer by running the command:

/bin/kafka-console-consumer --zookeeper myzookeeper:2181 --topic Topic1

However, I am getting exception:

2017-06-05 17:16:13,046] ERROR Error processing message, terminating consumer process:  (kafka.tools.ConsoleConsumer$)
kafka.common.MessageSizeTooLargeException: Found a message larger than the maximum fetch size of this consumer on topic Topic1 partition 9 at fetch offset 5. Increase the fetch size, or decrease the maximum message size the broker will allow.
    at kafka.consumer.ConsumerIterator.makeNext(ConsumerIterator.scala:90)
    at kafka.consumer.ConsumerIterator.makeNext(ConsumerIterator.scala:33)
    at kafka.utils.IteratorTemplate.maybeComputeNext(IteratorTemplate.scala:64)
    at kafka.utils.IteratorTemplate.hasNext(IteratorTemplate.scala:56)
    at kafka.consumer.OldConsumer.receive(BaseConsumer.scala:89)
    at kafka.tools.ConsoleConsumer$.process(ConsoleConsumer.scala:110)
    at kafka.tools.ConsoleConsumer$.run(ConsoleConsumer.scala:70)
    at kafka.tools.ConsoleConsumer$.main(ConsoleConsumer.scala:48)
    at kafka.tools.ConsoleConsumer.main(ConsoleConsumer.scala)
Processed a total of 0 messages

Now i am trying to run the command:

/bin/kafka-console-consumer --zookeeper myzookeeper:2181 --topic Topic1 --args max.partitiion.fetch.bytes=10485760

But getting error:

args is not a recognized option

How can I pass the param args to kafka-console-consumer?


问:
Query SQL LDAP import
I am doing an ldap import into a DB, the specific area of interest is the date created attribute.

Currently as per screenshot, this is in a long string and I would like to pick it apart so it displays in a date/time format. enter image description here

The format I would like is DD-MM-YYYY all of the other information can be excluded.

答:
Why export, ldap is a database, you can search this

On-topic:
In openldap this the field: createTimestamp, and it is presented in the following format
(20170531094335Z) -> 2017 05 31 09:43:35 Zulu time (utc)

The timestamp has the following format: YYYYMMDDHHMMSST. T is the time zone which is usually 'Z' (Zulu Time Zone = UTC/GMT)

Title: Query SQL LDAP import


问:
LINQ & Lambda Expressions equivalent of SQL In
Is there a lambda equivalent of IN?  I will like to select all the funds with ids either 4, 5 or 6.  One way of writing it is:

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();

However, that quickly becomes unmanageable if I need it to match say 100 different fundIds.  Can I do something like:

List
  fundHistoricalPrices =
  lionContext.FundHistoricalPrices.Where(fhp
  => fhp.Fund.FundId in(5,6,7)).ToList();

答:
No, the only similar operator i'm aware of is the Contains() function.

ANother was is to construct your query dynamically by using the predicate builder out of the LINQkit: http://www.albahari.com/nutshell/predicatebuilder.aspx

Example

```<code>int[] fundIds = new int[] { 5,6,7};

var predicate = PredicateBuilder.False<FundHistoricalPrice>();

foreach (int  id in fundIds)
{
    int tmp = id;
    predicate = predicate.Or (fhp => fhp.Fund.FundId == tmp);
}

var query = lionContext.FundHistoricalPrices.Where (predicate);
</code>```

Body:
No, the only similar operator i'm aware of is the Contains() function.

ANother was is to construct your query dynamically by using the predicate builder out of the LINQkit: http://www.albahari.com/nutshell/predicatebuilder.aspx

Example

int[] fundIds = new int[] { 5,6,7};

var predicate = PredicateBuilder.False<FundHistoricalPrice>();

foreach (int  id in fundIds)
{
    int tmp = id;
    predicate = predicate.Or (fhp => fhp.Fund.FundId == tmp);
}

var query = lionContext.FundHistoricalPrices.Where (predicate);

ContentLicense: CC BY-SA 2.5


问:
How to hide a bar button item for certain users
I have a settings bar button item (set as left bar button item). I only want to display it if the user is logged in.

I thought I could use the following for anonymous users

```<code>navigationItem.leftBarButtonItem = nil
</code>```

But then how would I show it as soon as they logged in?

答:
I have more that 2 menuitems and remove/add menuitem is an overhead. This code snippet worked for me.</p>

```<code>func showMenuItem(){

    menuItemQuit.customView?.isHidden = false
    menuItemQuit.plainView.isHidden = false
}

func hideMenuItem(){

    menuItemQuit.customView?.isHidden = true
    menuItemQuit.plainView.isHidden = true
}
</code>```

Body:
I have a settings bar button item (set as left bar button item). I only want to display it if the user is logged in.

I thought I could use the following for anonymous users

navigationItem.leftBarButtonItem = nil

But then how would I show it as soon as they logged in?

Body:
I have more that 2 menuitems and remove/add menuitem is an overhead. This code snippet worked for me.

func showMenuItem(){

    menuItemQuit.customView?.isHidden = false
    menuItemQuit.plainView.isHidden = false
}

func hideMenuItem(){

    menuItemQuit.customView?.isHidden = true
    menuItemQuit.plainView.isHidden = true
}


问:
moment-timezones.js, how to convert date in spesific timezone to utc, disregarding my local timezone?
my system uses timezone UTC+03:00 ,

im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc

```<code>const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York")
  .tz("Z").toDate();
</code>```

doesnt work correctly

how am i even suppose to convert to utc time?

-----------edit---------------

i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:

```<code>moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York").tz("Africa/Accra")
</code>```

but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!

is there a way to set the utc offset to 0 in momentjs-timezones?

答:
Short answer is that you cannot.

The .toDate() method of the Moment library returns a native Date object. Such objects do not keep memory of any specific time zone (that's one of the reasons to use Moment in the first place), they just keep track of the exact time moment represented and merely pick a time zone when formatting to string, which is either UTC or the browser's time zone (not an arbitrary one).

The long answer is that you're probably getting correct results but are printing them with a method that uses the browser's time zone.

Body:
my system uses timezone UTC+03:00 ,

im trying to get a date in string format, represented by NY timezone,
and convert it to a Date object in utc

const dateInNY = moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York")
  .tz("Z").toDate();

doesnt work correctly

how am i even suppose to convert to utc time?

-----------edit---------------

i got it to work, using the timezone "Africa/Accra" , where UTC offset is 0, and ther is no daylight savings time:

moment.tz(xlsxDate, "M/D/YYYY h:mm a",  "America/New_York").tz("Africa/Accra")

but this solution is a bad workaround, and if the government of Accra decide to change the time laws, will stop working!

is there a way to set the utc offset to 0 in momentjs-timezones?


问:
Express + Node application deployed to Azure can't connect to CosmosDB/DocumentDB
I created an app using Nodejs, express and DocumentDB and deployed it to Azure(App Service\Web App). Everything is working fine except it is not connecting to DocumentDB. It works fine in my local environment.

I am new to this environment so not sure what additional information can be provided.

Only difference between my local environment and azure is that I added following web.config because site was not starting

答: According to your description, it seems that you enabled IP Access Control in the Azure portal. If this is the case, then you'll need to add your current IP to allowed IPs list. See Azure Cosmos DB firewall support.</p>


问:
Using post handler inside a while loop
I am trying to use  handler.postdelayed inside a while(true) loop so every 5 seconds it will send a specific value using a button
but when i press the button it just hang without any respond it doesn't crash neither send
how can i use the post delayed inside the loop ?

```<code> btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                while(true) {
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                                DatabaseReference childRoot = rootRoomName.push();
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("Name", username);
                                map.put("message", Response1);
                                childRoot.updateChildren(map);

                        }
                    }, 5000);
                }
            }
        });
</code>```

答:
This is wrong. You are killing the app with a while(true) loop. Instead, you should call postDelayed from inside the run() method at the end, so that it schedules itself every time after its execution. Something like this:</p>

```<code>handler = new Handler();

runnable = new Runnable() {
    @Override
    public void run() {
        handler.postDelayed(this, 5000);
    }
}

handler.post(runnable);
</code>```

Title: Using post handler inside a while loop

Body:
I am trying to use  handler.postdelayed inside a while(true) loop so every 5 seconds it will send a specific value using a button
but when i press the button it just hang without any respond it doesn't crash neither send
how can i use the post delayed inside the loop ?

 btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                while(true) {
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                                DatabaseReference childRoot = rootRoomName.push();
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("Name", username);
                                map.put("message", Response1);
                                childRoot.updateChildren(map);

                        }
                    }, 5000);
                }
            }
        });

Body:
This is wrong. You are killing the app with a while(true) loop. Instead, you should call postDelayed from inside the run() method at the end, so that it schedules itself every time after its execution. Something like this:

handler = new Handler();

runnable = new Runnable() {
    @Override
    public void run() {
        handler.postDelayed(this, 5000);
    }
}

handler.post(runnable);


问:
Out of memory error in EA
When i try to generate the relationship matrix in EA we are getting the "out of memory" dialog is getting show up every time.What might be the reasons for this issue.

答:
There are too many reasons to guess and I've never encountered this. Here are a few things you can do:

Run the Project Integrity Check and see if it solves the issue.

Look into %appdata%\...sparx...\dberror.txt to find out if some DB SQL error is related.

Turn off all MDGs to see if one of them might be the cause.

Try a transfer to an empty schema and see if the copy has the same issue.

Contact Sparx support if the error persists.

I guess that "install more memory" is not really what you want to hear ;-)

Title: Out of memory error in EA


问:
Regex for values between -10 and 10 up to 1 decimal place
I have a c# web application that has a control in that I would like to add a regular expression to, but as I'm useless with regular expressions I was hoping someone would be able to help me!

I would like a regex that will accept all values between -10 and 10 and allow up to 1 optional decimal place.

Successful Inputs

```<code>1
-2.1
3.7
-4
5.8
10
-10
</code>```

Unsuccessful Inputs

```<code>10.1
-10.1
3.14159265359
-3.14159265359 and so on
</code>```

I already have a somewhat similar regex in my application ^(0(\.\d{1,4})?|1(\.0{1,4})?)$. This only accepts positive and negative values to 4dp, I've had a go at changing it (see below) but I'm unsure of how to include the -10 to 10 range.

```<code>^(0(\.\d{1,1})?|1(\.0{1,1})?)$
</code>```

Thanks in advance

答:
You may use

```<code>^-?(?:10(?:\.0)?|[0-9](?:\.[0-9])?)$
</code>```

See the regex demo

If you do not want to match 10 with 0 in the fractional part, remove (?:\.0)?.

Details:

^ - start of string

-? - 1 or 0 - symbols

(?:10(?:\.0)?|[0-9](?:\.[0-9])?) - 2 alternatives:

10(?:\.0)? - 10 optionally followed with .0

| - or

[0-9](?:\.[0-9])? - any 1 digit from 0 to 9 followed with an optional sequence of . and any 1 digit

$ - end of string.

Body:
I have a c# web application that has a control in that I would like to add a regular expression to, but as I'm useless with regular expressions I was hoping someone would be able to help me!

I would like a regex that will accept all values between -10 and 10 and allow up to 1 optional decimal place.

Successful Inputs

1
-2.1
3.7
-4
5.8
10
-10

Unsuccessful Inputs

10.1
-10.1
3.14159265359
-3.14159265359 and so on

I already have a somewhat similar regex in my application ^(0(\.\d{1,4})?|1(\.0{1,4})?)$. This only accepts positive and negative values to 4dp, I've had a go at changing it (see below) but I'm unsure of how to include the -10 to 10 range.

^(0(\.\d{1,1})?|1(\.0{1,1})?)$

Thanks in advance

Body:
You may use

^-?(?:10(?:\.0)?|[0-9](?:\.[0-9])?)$

See the regex demo

If you do not want to match 10 with 0 in the fractional part, remove (?:\.0)?.

Details:

^ - start of string

-? - 1 or 0 - symbols

(?:10(?:\.0)?|[0-9](?:\.[0-9])?) - 2 alternatives:

10(?:\.0)? - 10 optionally followed with .0

| - or

[0-9](?:\.[0-9])? - any 1 digit from 0 to 9 followed with an optional sequence of . and any 1 digit

$ - end of string.


问:
Verify certificate against Java certificate store via CLI
How can I verify an X509 (or DER-formatted) certificate against the Java certificate store via the command line?

I've looked into using the keytool utility, but it looks like it only handles import/export/display functionality (no verification).

EDIT:  It looks as though keytool can be used for verification, but only if an import is attempted.  I suppose a better way of asking this questions is whether or not a more passive approach (as in: not modifying the keystore) is available.  Thanks!

答:
This page could be oversimplifying:

http://java.sun.com/docs/books/tutorial/security/toolfilex/rstep1.html

But it doesn't look like even import with keytool does a true verification of a certificate.  I'm not seeing any description of verifying the signature of the incoming certificate against the signature of another trusted certificate.

jarsigner will verify a signature on a signed jar, but doesn't do anything to verify the signature on the certificate used to sign the jar.

I'm afraid you'd either have to write a tool to do the verfication, or look for a commercial tool that does it.  I would think that some of the PKI tool kits would have a certificate verification tool that would do this.

OwnerDisplayName: Brian

LastEditorDisplayName: Brian

OwnerDisplayName: bethlakshmi


问:
Autocreate object when property is called
Im wondering if there is a way to autocreate object if a property is called. An example:

```<code><?php
  echo $myObj->myProperty
?>
</code>```

This code will of course fail because i did not initiate $myObj before reading the property.
What im looking for is a way to automaticly initiate $myObj based on "myObj".

Something like:

```<code><?php
class myObj {
  public myProperty = 'BlaBla';
}
echo $myObj->myProperty; //outputs BlaBla instead of failing
?>
</code>```

I know about __autoload($classname) but that only works of initiating classcode with i.e. an include(), so that is not what im after.

答:
Just to close this question, this is what i ended up doing:

```<code>preg_match_all("/\\\$(.*?)->/si", $code, $matches);
</code>```

I loop trough the code i get from database looking for any references to objects like

```<code>$xxxx->
</code>```

Then i loop trough the references and create the objects

```<code>            foreach($matches[1] as $key=>$value) {
            $$value = Connector::loadConnector($value);
        }
</code>```

Where the "loadConnector is:

```<code>    public function loadConnector($connector, $params = NULL) {
    require_once $connector. ".php";
    $c_name = $connector;
    return new $c_name($params);
}
</code>```

This is of course based on my file structure and it also needs some errorhandling, but so far it looks like it solves my problem :)

BR/Sune

Body:
Im wondering if there is a way to autocreate object if a property is called. An example:

<?php
  echo $myObj->myProperty
?>

This code will of course fail because i did not initiate $myObj before reading the property.
What im looking for is a way to automaticly initiate $myObj based on "myObj".

Something like:

<?php
class myObj {
  public myProperty = 'BlaBla';
}
echo $myObj->myProperty; //outputs BlaBla instead of failing
?>

I know about __autoload($classname) but that only works of initiating classcode with i.e. an include(), so that is not what im after.

Body:
Just to close this question, this is what i ended up doing:

preg_match_all("/\\\$(.*?)->/si", $code, $matches);

I loop trough the code i get from database looking for any references to objects like

$xxxx->

Then i loop trough the references and create the objects

            foreach($matches[1] as $key=>$value) {
            $$value = Connector::loadConnector($value);
        }

Where the "loadConnector is:

    public function loadConnector($connector, $params = NULL) {
    require_once $connector. ".php";
    $c_name = $connector;
    return new $c_name($params);
}

This is of course based on my file structure and it also needs some errorhandling, but so far it looks like it solves my problem :)

BR/Sune


问:
Remove a string from another string in javascript
I am trying to remove a String from another String.

```<code>var text = "This is a string";
</code>```

I want to remove the word "is" so I will have

```<code>text = "This a string";
</code>```

How do I go about that?

答:
You should try with split() and filter() function

var text = "This is a string";
var res = text.split(" ").filter(a=> a != 'is').join(" ")
console.log(res)```
</div>
</div>
</p>

<p><strong>or</strong> Regex <code>/\s+is/g</code></p>

<p><strong>Demo and Explanation</strong> </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>var text = "This is a string";
var res = text.replace(/\s+is/g ,'')
console.log(res)</code>```

Body:
I am trying to remove a String from another String.

var text = "This is a string";

I want to remove the word "is" so I will have

text = "This a string";

How do I go about that?

Body:
You should try with split() and filter() function

var text = "This is a string";
var res = text.split(" ").filter(a=> a != 'is').join(" ")
console.log(res)

or Regex /\s+is/g

Demo and Explanation

var text = "This is a string";
var res = text.replace(/\s+is/g ,'')
console.log(res)


答:
You have used an infinite while loop which will not terminate normally. I don't think you need while here, just configure handler as you need.</p>

```<code>btnsend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    DatabaseReference childRoot = rootRoomName.push();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("Name", username);
                    map.put("message", Response1);
                    childRoot.updateChildren(map);
                }
            }, 5000);
        }
    });
</code>```

Title: Using post handler inside a while loop

Body:
You have used an infinite while loop which will not terminate normally. I don't think you need while here, just configure handler as you need.

btnsend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    DatabaseReference childRoot = rootRoomName.push();
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("Name", username);
                    map.put("message", Response1);
                    childRoot.updateChildren(map);
                }
            }, 5000);
        }
    });


问:
Neo4J, cypher: Unidirectional query from specified node
I have done some googling and tried several things myself but I have not yet found a solution. I'm rather new to graph databases, Neo4j and cypher.

Attached is an image which I hope will make it easier to explain. The graph has Block (pink), Input (green), Output(blue) and Property (red) nodes and the relationship types are PART_OF, connectsTo, hasInPort and hasOutPort.

I wish to retrieve all nodes from block_3, going in the direction of the [:connectsTo] relations. So what I expect back are blocks 3, 2, 4, and 5 with all their input, output and property nodes. Block_3's input should also be included.

I think I still lack understanding of quite how the queries work. I would really appreciate it if someone could tell me exactly what the query should look like and then give an explanation of the different parts of the query.

答:
The general approach is to find the relationship/direction pattern needed to reach all the desired :Block nodes from your starting :Block node, and once you have all those :Block nodes, match to their :Input, :Output, and :Property nodes.

The biggest complication here is the conflicting relationship directions with respect to the pattern you want to follow. :hasOutPort and :connectsTo are both outgoing, which is good, but the :hasInPort relationship points in the opposite direction.

This is a problem because variable-length relationships using multiple relationship types, which is the ideal tool to solve this traversal, can only specify a single direction for all relationships involved...if we let it be any direction instead (by omitting the arrow on the relationship) then it would match to incoming :connectsTo relationships, which is not what you want.

Option 1: Change relationship type/direction

One easy modeling fix would be to change the relationship between :Input nodes and :Block nodes.

Instead of what you have currently:

```<code>(:Block)-[:hasInPort]->(:Input)
</code>```

You could instead use this:

```<code>(:Block)<-[:inPortFor]-(:Input)
</code>```

If you made this change, then the path you want all goes in the same direction, and the query becomes easy:

```<code>// match from starting node to all :Block nodes along desired relationships
MATCH (:Block{name:'block_3'})-[:hasOutPort|:connectsTo|:inPortFor*0..]->(block:Block)
// use pattern comprehension to get lists of :Properties, :Input, and :Output nodes per :Block
WITH block, [(block)-[:PART_OF]->(prop) | prop] as properties,
 [(block)-[:hasOutPort]->(output) | output] as outputs,
 [(block)<-[:inPortFor]-(input) | input] as inputs
RETURN block, properties, outputs, inputs
</code>```

If you can't or won't change the relationship direction/type between :Input and :Block nodes, then you can't take this approach (the first variable-length match) and need a different approach.

Option 2: APOC Procedures

APOC Procedures is a plugin for Neo4j with a good number of very useful procedures and functions. One of these is a path expander which allows specification of expansion along different relationships, with the ability to declare which direction to follow for each separate relationship type. Using this, as well as a termination label filter (so you only get matches to :Block nodes), we can replace the first match.

```<code>// match from starting node to all :Block nodes along desired relationships
MATCH (start:Block{name:'block_3'})
CALL apoc.path.subgraphNodes(start, {labelFilter:'/Block',
 relationshipFilter:'hasOutPort>|connectsTo>|<hasInPort'}) YIELD node as block
// use pattern comprehension to get lists of :Properties, :Input, and :Output nodes per :Block
WITH block, [(block)-[:PART_OF]->(prop) | prop] as properties,
 [(block)-[:hasOutPort]->(output) | output] as outputs,
 [(block)-[:hasInPort]->(input) | input] as inputs
RETURN block, properties, outputs, inputs
</code>```

Body:
The general approach is to find the relationship/direction pattern needed to reach all the desired :Block nodes from your starting :Block node, and once you have all those :Block nodes, match to their :Input, :Output, and :Property nodes.

The biggest complication here is the conflicting relationship directions with respect to the pattern you want to follow. :hasOutPort and :connectsTo are both outgoing, which is good, but the :hasInPort relationship points in the opposite direction.

This is a problem because variable-length relationships using multiple relationship types, which is the ideal tool to solve this traversal, can only specify a single direction for all relationships involved...if we let it be any direction instead (by omitting the arrow on the relationship) then it would match to incoming :connectsTo relationships, which is not what you want.

Option 1: Change relationship type/direction

One easy modeling fix would be to change the relationship between :Input nodes and :Block nodes.

Instead of what you have currently:

(:Block)-[:hasInPort]->(:Input)

You could instead use this:

(:Block)<-[:inPortFor]-(:Input)

If you made this change, then the path you want all goes in the same direction, and the query becomes easy:

// match from starting node to all :Block nodes along desired relationships
MATCH (:Block{name:'block_3'})-[:hasOutPort|:connectsTo|:inPortFor*0..]->(block:Block)
// use pattern comprehension to get lists of :Properties, :Input, and :Output nodes per :Block
WITH block, [(block)-[:PART_OF]->(prop) | prop] as properties,
 [(block)-[:hasOutPort]->(output) | output] as outputs,
 [(block)<-[:inPortFor]-(input) | input] as inputs
RETURN block, properties, outputs, inputs

If you can't or won't change the relationship direction/type between :Input and :Block nodes, then you can't take this approach (the first variable-length match) and need a different approach.

Option 2: APOC Procedures

APOC Procedures is a plugin for Neo4j with a good number of very useful procedures and functions. One of these is a path expander which allows specification of expansion along different relationships, with the ability to declare which direction to follow for each separate relationship type. Using this, as well as a termination label filter (so you only get matches to :Block nodes), we can replace the first match.

// match from starting node to all :Block nodes along desired relationships
MATCH (start:Block{name:'block_3'})
CALL apoc.path.subgraphNodes(start, {labelFilter:'/Block',
 relationshipFilter:'hasOutPort>|connectsTo>|<hasInPort'}) YIELD node as block
// use pattern comprehension to get lists of :Properties, :Input, and :Output nodes per :Block
WITH block, [(block)-[:PART_OF]->(prop) | prop] as properties,
 [(block)-[:hasOutPort]->(output) | output] as outputs,
 [(block)-[:hasInPort]->(input) | input] as inputs
RETURN block, properties, outputs, inputs


问:
How to sort dates of string?
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

```<code>func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }
</code>```

Please guide me where I am doing wrong ?

答:
```<code>extension String  {

func date(format: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    let date = dateFormatter.date(from: self)
    return date
}

}
extension Date {
func string(format: String) -> String {
    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = format
    return dateFormatterPrint.string(from: self) as String
}
}
var datesSting = ["2017-07-06","2017-08-07","2017-07-07"]

let soteddates  = datesSting.map { (obj) -> Date in
    return obj.date(format: "yyyy-MM-DD")!
}

let sorteedStings = soteddates.sorted { (obj1, obj2) -> Bool in
    return obj1.compare(obj2) == ComparisonResult.orderedAscending
}.map { (obj) -> String in
   return obj.string(format:  "yyyy-MM-DD")
}

print(sorteedStings)
</code>```

Title: How to sort dates of string?

Body:
I have an array of date as 2017-07-06,2017-06-07,2017-07-07. I want to sort these dates in ascending order. So 2017-06-07 will come first. But it is not happening at all. I am using below code for this:

func sortDates(array:NSMutableArray)->[String]  {

        var strArray:[String] = []
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd"// yyyy-MM-dd"
        var convertedArray: [Date] = []
        for dat in array {
            let date = dateFormatter.date(from: dat as! String)
            convertedArray.append(date!)
        }
        let arrDates = convertedArray.sorted(by: { $0.compare($1) == .orderedAscending })
        for value in arrDates {
            let formatter = DateFormatter()
            // initially set the format based on your datepicker date
            formatter.dateFormat = "yyyy-MM-dd"
            let myString = formatter.string(from: value)
            // convert your string to date
            let yourDate = formatter.date(from: myString)
            if yourDate != nil {
                //then again set the date format whhich type of output you need
                formatter.dateFormat = "yyyy-MM-dd"
                // again convert your date to string
                let myStringafd = formatter.string(from: yourDate!)
                strArray.append(myStringafd)
            }
        }
        return strArray
    }

Please guide me where I am doing wrong ?


问:
Check if a String is valid UTF-8 encoded in Java
How can I check if a string is in valid UTF-8 format?</p>

答:
The following post is taken from the official Java tutorials available at: https://docs.oracle.com/javase/tutorial/i18n/text/string.html.

The StringConverter program starts by creating a String containing
  Unicode characters:

```<code>String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
</code>```

When printed, the String named original appears as:

```<code>AêñüC
</code>```

To convert the String object to UTF-8, invoke the getBytes method and
  specify the appropriate encoding identifier as a parameter. The
  getBytes method returns an array of bytes in UTF-8 format. To create a
  String object from an array of non-Unicode bytes, invoke the String
  constructor with the encoding parameter. The code that makes these
  calls is enclosed in a try block, in case the specified encoding is
  unsupported:

```<code>try {
    byte[] utf8Bytes = original.getBytes("UTF8");
    byte[] defaultBytes = original.getBytes();

    String roundTrip = new String(utf8Bytes, "UTF8");
    System.out.println("roundTrip = " + roundTrip);
    System.out.println();
    printBytes(utf8Bytes, "utf8Bytes");
    System.out.println();
    printBytes(defaultBytes, "defaultBytes");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}
</code>```

The StringConverter program prints out the values in the utf8Bytes and
  defaultBytes arrays to demonstrate an important point: The length of
  the converted text might not be the same as the length of the source
  text. Some Unicode characters translate into single bytes, others into
  pairs or triplets of bytes.
       The printBytes method displays the byte arrays by invoking the byteToHex method, which is defined in the source file,
  UnicodeFormatter.java. Here is the printBytes method:

```<code>public static void printBytes(byte[] array, String name) {
    for (int k = 0; k < array.length; k++) {
        System.out.println(name + "[" + k + "] = " + "0x" +
            UnicodeFormatter.byteToHex(array[k]));
    }
}
</code>```

The output of the printBytes method follows. Note that only the first
  and last bytes, the A and C characters, are the same in both arrays:

```<code>utf8Bytes[0] = 0x41
utf8Bytes[1] = 0xc3
utf8Bytes[2] = 0xaa
utf8Bytes[3] = 0xc3
utf8Bytes[4] = 0xb1
utf8Bytes[5] = 0xc3
utf8Bytes[6] = 0xbc
utf8Bytes[7] = 0x43
defaultBytes[0] = 0x41
defaultBytes[1] = 0xea
defaultBytes[2] = 0xf1
defaultBytes[3] = 0xfc
defaultBytes[4] = 0x43
</code>```

Body:
The following post is taken from the official Java tutorials available at: https://docs.oracle.com/javase/tutorial/i18n/text/string.html.

The StringConverter program starts by creating a String containing
  Unicode characters:

String original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");

When printed, the String named original appears as:

AêñüC

To convert the String object to UTF-8, invoke the getBytes method and
  specify the appropriate encoding identifier as a parameter. The
  getBytes method returns an array of bytes in UTF-8 format. To create a
  String object from an array of non-Unicode bytes, invoke the String
  constructor with the encoding parameter. The code that makes these
  calls is enclosed in a try block, in case the specified encoding is
  unsupported:

try {
    byte[] utf8Bytes = original.getBytes("UTF8");
    byte[] defaultBytes = original.getBytes();

    String roundTrip = new String(utf8Bytes, "UTF8");
    System.out.println("roundTrip = " + roundTrip);
    System.out.println();
    printBytes(utf8Bytes, "utf8Bytes");
    System.out.println();
    printBytes(defaultBytes, "defaultBytes");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

The StringConverter program prints out the values in the utf8Bytes and
  defaultBytes arrays to demonstrate an important point: The length of
  the converted text might not be the same as the length of the source
  text. Some Unicode characters translate into single bytes, others into
  pairs or triplets of bytes.
       The printBytes method displays the byte arrays by invoking the byteToHex method, which is defined in the source file,
  UnicodeFormatter.java. Here is the printBytes method:

public static void printBytes(byte[] array, String name) {
    for (int k = 0; k < array.length; k++) {
        System.out.println(name + "[" + k + "] = " + "0x" +
            UnicodeFormatter.byteToHex(array[k]));
    }
}

The output of the printBytes method follows. Note that only the first
  and last bytes, the A and C characters, are the same in both arrays:

utf8Bytes[0] = 0x41
utf8Bytes[1] = 0xc3
utf8Bytes[2] = 0xaa
utf8Bytes[3] = 0xc3
utf8Bytes[4] = 0xb1
utf8Bytes[5] = 0xc3
utf8Bytes[6] = 0xbc
utf8Bytes[7] = 0x43
defaultBytes[0] = 0x41
defaultBytes[1] = 0xea
defaultBytes[2] = 0xf1
defaultBytes[3] = 0xfc
defaultBytes[4] = 0x43


问:
Display an error message next to the input field if input field is blank
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

```<code><form name="user_details" method="post" onsubmit="return checkform()">
    <table id="form_table">
        <tr>
            <td class="form_cell"><label for="first_name">First Name:</label></td>
            <td class="form_cell"><input type="text" id="first_name">*</td>
            <td id="error_first_name">The first name field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="surname">Surname:</label></td>
            <td class="form_cell"><input type="text" id="surname">*</td>
            <td id="error_surname">The surname field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="address">Address:</label></td>
            <td class="form_cell"><input type="text" id="address">*</td>
            <td id="error_address">The address field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="city">City:</label></td>
            <td class="form_cell"><input type="text" id="city">*</td>
            <td id="error_city">The city field needs to contain at least one character.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="post_code">Post Code:</label></td>
            <td class="form_cell"><input type="text" id="post_code">*</td>
            <td id="error_post_code">The post code field needs to contain a number.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="email">Email:</label></td>
            <td class="form_cell"><input type="email" id="email">*</td>
            <td id="error_email">The email field needs to contain an email address.</td>
        </tr>
        <tr>
            <td class="form_cell"><label for="phone_number">Phone Number:</label></td>
            <td class="form_cell"><input type="text" id="phone_number"></td>
        </tr>
    </table>
        <input type="submit"><input type=reset>
    </form>
</code>```

My JavaScript:

```<code>function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}
</code>```

}

My CSS:

```<code>#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}
</code>```

答:
You have several issues in your code and you can improve it in many factors, see below.

You don't close the function checkform() properly, you're missing a closing bracket.

You want to return ok from the function no matter what, so you should omit the else block, for example:

```<code>function checkform() {
    var ok = true,
    [ omitted for brevity ]
    else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
        document.getElementById("first_name").style.borderColor = "red";
        ok = false;
    }

    return ok;
}
</code>```

You probably want to check all the errors at form submit. Currently what your code does is look for errors in each field and when it encounters one it will display the error message and stop looking for other errors. To change it you should give up else if in favor of just series of if, like so:

```<code>function checkform() {
    var ok = true,
    [ omitted for brevity ]

    if (document.getElementById("first_name").value == "") {
        document.getElementById("first_name").style.borderColor = "red";
        $("#error_first_name").show();
        ok = false;
    } // See here - it will check each field no matter what
    if (document.getElementById("surname").value == "") {
        document.getElementById("surname").style.borderColor = "red";
        $("#error_surname").show();
        ok = false;
    }
    return ok;
}
</code>```

You are not resetting field style if the error is gone. For example - user tries to submit an empty form, so all fields signal an error. Then the user fills just first name and submits, but the error is still shown, because you never reset it. You could add an else to each check and act accordingly.

You should use === for string comparison (see this answer)

I see you are using jQuery, you should not mix "bare" js (like document.getElementById with jQuery code, because it makes the code messy. With jQuery you can get value of a field like so: $('<css selector here>').val(), for example $('#first_name').val() and you can change styles, by doing $('<css selector>').css('<property', '<value>')

You should not mix presentation and code (like setting styles) instead add and remove a css class and style it in your stylesheet. You can add class with jQuery like so: $('<css selector').addClass('<you class name') and remove it analogically $('<css selector').removeClass('<you class name')

You should attach your event handlers (like onsubmit) in your script file, so you don't clutter your HTML with event handlers and JS with a lot of functions called only from HTML. This improves readability of your code. You can attach your event handler in jQuery like so:

```<code>$(function() { // This wait's for document.ready.
    // It's required to attach event in script
    // because scripts are ran before browser parses HTML
    $('#formId').submit(function() {
        return false; // This gets called on form submit
    });
});
</code>```

I've created a plunker that demonstrates all of my points

For more information you should see jQuery website and other questions at stackoverflow.

Body:
I am new to JavaScript and am a bit stuck...

I have a form and am trying to generate error messages next to input fields that are blank or do not contain the correct information.

Unfortunately is doesn't do anything...
Thanks for your help!!

My HTML:

<form name="user_details" method="post" onsubmit="return checkform()">

            First Name:
            <input type="text" id="first_name">*
            The first name field needs to contain at least one character.

            Surname:
            <input type="text" id="surname">*
            The surname field needs to contain at least one character.

            Address:
            <input type="text" id="address">*
            The address field needs to contain at least one character.

            City:
            <input type="text" id="city">*
            The city field needs to contain at least one character.

            Post Code:
            <input type="text" id="post_code">*
            The post code field needs to contain a number.

            Email:
            <input type="email" id="email">*
            The email field needs to contain an email address.

            Phone Number:
            <input type="text" id="phone_number">

        <input type="submit"><input type=reset>
    </form>

My JavaScript:

function checkform() {
var ok = true,
    first_name,
    surname,
    address,
    city,
    post_code,
    email;

if (document.getElementById("first_name").value == "") {
    document.getElementById("first_name").style.borderColor = "red";
    $("#error_first_name").show();
    ok = false;
}

else if (document.getElementById("surname").value == "") {
    document.getElementById("surname").style.borderColor = "red";
    $("#error_surname").show();
    ok = false;
}

else if (document.getElementById("address").value == "") {
    document.getElementById("address").style.borderColor = "red";
    $("#error_address").show();
    ok = false;
}

else if (document.getElementById("city").value == "") {
    document.getElementById("city").style.borderColor = "red";
    $("#error_city").show();
    ok = false;
}

else if (document.getElementById("post_code").value == "") {
    document.getElementById("post_code").style.borderColor = "red";
    $("#error_post_code").show();
    ok = false;
}

else if (document.getElementById("email").value == "") {
    document.getElementById("email").style.borderColor = "red";
    $("#error_email").show();
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("first_name").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("surname").value)) {
    document.getElementById("surname").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z]+$/.test(document.getElementById("address").value)) {
    document.getElementById("address").style.borderColor = "red";
    ok = false;
}

else if (!/^[A-Za-z][0-9]+$/.test(document.getElementById("city").value)) {
    document.getElementById("city").style.borderColor = "red";
    ok = false;
}

else if (!/^[0-9]+$/.test(document.getElementById("post_code").value)) {
    document.getElementById("post_code").style.borderColor = "red";
    ok = false;
}

else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
    document.getElementById("first_name").style.borderColor = "red";
    ok = false;
}

else {
    return ok;
}

}

My CSS:

#error_first_name {
display: none;
}

#error_surname {
display: none;
}

#error_address {
display: none;
}

#error_city {
display: none;
}

#error_post_code {
display: none;
}

#error_email {
display: none;
}

Body:
You have several issues in your code and you can improve it in many factors, see below.

You don't close the function checkform() properly, you're missing a closing bracket.

You want to return ok from the function no matter what, so you should omit the else block, for example:

function checkform() {
    var ok = true,
    [ omitted for brevity ]
    else if (!/\S+@\S+/.test(document.getElementById("email").value)) {
        document.getElementById("first_name").style.borderColor = "red";
        ok = false;
    }

    return ok;
}

You probably want to check all the errors at form submit. Currently what your code does is look for errors in each field and when it encounters one it will display the error message and stop looking for other errors. To change it you should give up else if in favor of just series of if, like so:

function checkform() {
    var ok = true,
    [ omitted for brevity ]

    if (document.getElementById("first_name").value == "") {
        document.getElementById("first_name").style.borderColor = "red";
        $("#error_first_name").show();
        ok = false;
    } // See here - it will check each field no matter what
    if (document.getElementById("surname").value == "") {
        document.getElementById("surname").style.borderColor = "red";
        $("#error_surname").show();
        ok = false;
    }
    return ok;
}

You are not resetting field style if the error is gone. For example - user tries to submit an empty form, so all fields signal an error. Then the user fills just first name and submits, but the error is still shown, because you never reset it. You could add an else to each check and act accordingly.

You should use === for string comparison (see this answer)

I see you are using jQuery, you should not mix "bare" js (like document.getElementById with jQuery code, because it makes the code messy. With jQuery you can get value of a field like so: $('<css selector here>').val(), for example $('#first_name').val() and you can change styles, by doing $('<css selector>').css('<property', '<value>')

You should not mix presentation and code (like setting styles) instead add and remove a css class and style it in your stylesheet. You can add class with jQuery like so: $('<css selector').addClass('<you class name') and remove it analogically $('<css selector').removeClass('<you class name')

You should attach your event handlers (like onsubmit) in your script file, so you don't clutter your HTML with event handlers and JS with a lot of functions called only from HTML. This improves readability of your code. You can attach your event handler in jQuery like so:

$(function() { // This wait's for document.ready.
    // It's required to attach event in script
    // because scripts are ran before browser parses HTML
    $('#formId').submit(function() {
        return false; // This gets called on form submit
    });
});

I've created a plunker that demonstrates all of my points

For more information you should see jQuery website and other questions at stackoverflow.


问:
How to install OpenCV for python
HI! I'm trying to install opencv and use it with python, but when I compile it I get no errors but I can't import cv module from python:

```<code>patrick:release patrick$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv
</code>```

The code I used to compile it is this:

```<code>cd opencv
mkdir release
cd release
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON
make
sudo make install
</code>```

how can I get it working with python?

答: I found here a way to install opencv for python: http://recursive-design.com/blog/2010/12/14/face-detection-with-osx-and-python/ :)</p>

Title: How to install OpenCV for python

Body:
HI! I'm trying to install opencv and use it with python, but when I compile it I get no errors but I can't import cv module from python:

patrick:release patrick$ python
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named cv

The code I used to compile it is this:

cd opencv
mkdir release
cd release
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON
make
sudo make install

how can I get it working with python?


问:
AppCompatSpinner vs android.widget.Spinner for app with min SDK version 14
I am developing application with minimum SDK version 14 Ice-cream sandwitch and targeted version is Android Marshmallow.

DO I need to use AppCompatSpinner or normal spinner will work on ICS devices with all material look and feel?

答:
If you look at the AppCompatSpinner page, you will see the folowing line.

This will automatically be used when you use Spinner in your layouts. You should only need to manually use this class when writing custom views.

So you don't have to choose between Spinners and AppCompatSpinners.


问:
MySQL-Can we use range for text which has numbers?
In the table 'DailyStatus' one the column value text is like 'taskRead2017ww23.3','taskWrite2017ww45.5', etc

That means all the column values has year and work week as string.

How can I get the data if we want as work week ranges.?

For ex. I want all records in the ranges between 2017ww23.3 to 2017ww25.4

I tried with RLIKE and '|' but i need to pass every single work week value to the query like below

```<code>select *
  from dailystatus
 where taskname rlike '.*(*ww23.3 |*ww23.4 | *ww23.3 | .......|25.4 )'
</code>```

The above method seems very difficult if the range increases.

Is there any optimized way to achieve this?

答:
How about if you do it like this:</p>

```<code>declare @tb table(sam varchar(50))
insert into @tb

select 'taskRead2017ww23.3' union all
select 'taskRead2017ww23.4' union all
select 'taskRead2017ww23.5' union all
select 'taskRead2017ww23.6' union all
select 'taskRead2017ww23.7'

select CAST(replace(replace(sam,'ww',''),'taskRead','') as numeric(18,2)) from @tb
where CAST(replace(replace(sam,'ww',''),'taskRead','') as numeric(18,2))>= 201723.3
and CAST(replace(replace(sam,'ww',''),'taskRead','') as numeric(18,2))<= 201723.5
</code>```

Body:
In the table 'DailyStatus' one the column value text is like 'taskRead2017ww23.3','taskWrite2017ww45.5', etc

That means all the column values has year and work week as string.

How can I get the data if we want as work week ranges.?

For ex. I want all records in the ranges between 2017ww23.3 to 2017ww25.4

I tried with RLIKE and '|' but i need to pass every single work week value to the query like below

select *
  from dailystatus
 where taskname rlike '.*(*ww23.3 |*ww23.4 | *ww23.3 | .......|25.4 )'

The above method seems very difficult if the range increases.

Is there any optimized way to achieve this?

Body:
How about if you do it like this:

declare @tb table(sam varchar(50))
insert into @tb

select 'taskRead2017ww23.3' union all
select 'taskRead2017ww23.4' union all
select 'taskRead2017ww23.5' union all
select 'taskRead2017ww23.6' union all
select 'taskRead2017ww23.7'

select CAST(replace(replace(sam,'ww',''),'taskRead','') as numeric(18,2)) from @tb
where CAST(replace(replace(sam,'ww',''),'taskRead','') as numeric(18,2))>= 201723.3
and CAST(replace(replace(sam,'ww',''),'taskRead','') as numeric(18,2))<= 201723.5


问:
How to set Data Model value on Custom TableView UILabel in Objective C
I am new in iOS and I am facing problem regarding to set Data Model on UIlabel

I used like this code to change

In ConnectiondidFinishLoading

```<code> AuditTextBoxarray=[[NSMutableArray alloc] init];
            for(int i=0;i<idarray.count;i++)
            {
                DataModel *model = [DataModel new];
                model.AuditTextBoxString = @"";
                [AuditTextBoxarray addObject:model];
            }
</code>```

In cellforrowatindexpath

```<code> cell.lblAuditTextBox.text=[NSString stringWithFormat:@"%@",[AuditTextBoxarray objectAtIndex:indexPath.row ]];
</code>```

On Button Click

```<code>   NSString *String=textView1.text;
   DataModel *model = [AuditTextBoxarray objectAtIndex:index];
   model.AuditTextBoxString = String;
</code>```

But I am not able to set value of data model in tableview:

How can I set Data Model value to uilabel? I am doing something wrong, but what I am not getting.

DataModel.h

```<code>@interface DataModel : NSObject
@property(nonatomic, strong)NSString *strSelected;
@property(nonatomic,strong)NSString *TextViewvalue;
@property(nonatomic,strong)NSString *RateViewValue;
@property(nonatomic,strong)NSString *Popupvalue;
@property(nonatomic,strong)NSString *SurveySelected;
@property(nonatomic,strong)NSString *AuditTextBoxString;
</code>```

DataModule.m

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

@implementation DataModel

@end
</code>```

I used DataModule to change Button colour and set it on the table view like this

In ConnectionDidFinishLoading

```<code>    for (int i =0; i<idarray.count; i++)
    {
        DataModel *model = [DataModel new];
        model.strSelected = @"";
        [arrData addObject:model];

    }
</code>```

Button Click

```<code>sender.backgroundColor = [UIColor redColor];
DataModel *model = [arrData objectAtIndex:sender.tag];
model.strSelected = @"P";
</code>```

cellforrowatindexoath

```<code> //background color change on button
    DataModel *model = [arrData objectAtIndex:indexPath.row];
    if([model.strSelected isEqualToString:@"P"])
    {
        cell.passbtn.backgroundColor = [UIColor redColor];
    }
</code>```

Now I am trying to add text on uilabel frok data model.

答:
I just change code from

```<code>cell.lblAuditTextBox.text=[NSString stringWithFormat:@"%@",[AuditTextBoxarray objectAtIndex:indexPath.row ]];
</code>```

To

```<code>DataModel *model = [AuditTextBoxarray objectAtIndex:indexPath.row];
cell.lblAuditTextBox.text=model.AuditTextBoxString
</code>```

Body:
I am new in iOS and I am facing problem regarding to set Data Model on UIlabel

I used like this code to change

In ConnectiondidFinishLoading

 AuditTextBoxarray=[[NSMutableArray alloc] init];
            for(int i=0;i<idarray.count;i++)
            {
                DataModel *model = [DataModel new];
                model.AuditTextBoxString = @"";
                [AuditTextBoxarray addObject:model];
            }

In cellforrowatindexpath

 cell.lblAuditTextBox.text=[NSString stringWithFormat:@"%@",[AuditTextBoxarray objectAtIndex:indexPath.row ]];

On Button Click

   NSString *String=textView1.text;
   DataModel *model = [AuditTextBoxarray objectAtIndex:index];
   model.AuditTextBoxString = String;

But I am not able to set value of data model in tableview:

How can I set Data Model value to uilabel? I am doing something wrong, but what I am not getting.

DataModel.h

@interface DataModel : NSObject
@property(nonatomic, strong)NSString *strSelected;
@property(nonatomic,strong)NSString *TextViewvalue;
@property(nonatomic,strong)NSString *RateViewValue;
@property(nonatomic,strong)NSString *Popupvalue;
@property(nonatomic,strong)NSString *SurveySelected;
@property(nonatomic,strong)NSString *AuditTextBoxString;

DataModule.m

#import "DataModel.h"

@implementation DataModel

@end

I used DataModule to change Button colour and set it on the table view like this

In ConnectionDidFinishLoading

    for (int i =0; i<idarray.count; i++)
    {
        DataModel *model = [DataModel new];
        model.strSelected = @"";
        [arrData addObject:model];

    }

Button Click

sender.backgroundColor = [UIColor redColor];
DataModel *model = [arrData objectAtIndex:sender.tag];
model.strSelected = @"P";

cellforrowatindexoath

 //background color change on button
    DataModel *model = [arrData objectAtIndex:indexPath.row];
    if([model.strSelected isEqualToString:@"P"])
    {
        cell.passbtn.backgroundColor = [UIColor redColor];
    }

Now I am trying to add text on uilabel frok data model.

Body:
I just change code from

cell.lblAuditTextBox.text=[NSString stringWithFormat:@"%@",[AuditTextBoxarray objectAtIndex:indexPath.row ]];

To

DataModel *model = [AuditTextBoxarray objectAtIndex:indexPath.row];
cell.lblAuditTextBox.text=model.AuditTextBoxString


问:
Android application is hanged and showing black screen for 5-6 seconds when checking if a server port is open or not using ThreadPoolExecutor
I need to run a service if a server port is open. I am doing this by using below method.

```<code>public Future<Boolean> ifPortIsOpenThenStartIridiumService(final Context context, final String device_mac, final String device_imei, final String input_mobile) {
    return Executors.newFixedThreadPool(20).submit(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try {
                String SERVER_IP = "IP Address";
                int SERVER_PORT = Server_port;
                int DURATION = 1000;

                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), DURATION);
                socket.close();

                Log.d(TAG, "Port is Open");

                runIridiumService(context, device_mac, device_imei, input_mobile);

                return true;
            } catch (Exception ex) {
                Log.d(TAG, "Port is not Open");
                CustomToast.showToast(context, "No Internet Access.", "If in flight, please switch to \"Aeroplane Mode\" and connect to the airline's Wi-Fi network.", 1);

                return false;
            }
        }
    });
}
</code>```

Above code is working but when I run this method the application is getting hanged and black screen is shown for 5-6 seconds.
I found below message on Logcat.

W/ActivityManager: Launch timeout has expired, giving up wake lock!

After that service is started and application is working well. How can I get rid of this problem?
Thanks in advance.

答:
After some study, as far as I understood,

Android application is hanged and showing black screen for 5-6 seconds  Because,

Future -

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

So, it waits until operation is finished. You can get more info from here.

newFixedThreadPool -

At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available.

Get more info from here.

The possible solution of your problem is to use ScheduledExecutorService.

Before that you can check Future is completed or not using

if (YOUR_FUTURE.isDone()){
     result = (String) YOUR_FUTURE.get();
}

to avoid unwanted or extra loop.

Body:
I need to run a service if a server port is open. I am doing this by using below method.

public Future<Boolean> ifPortIsOpenThenStartIridiumService(final Context context, final String device_mac, final String device_imei, final String input_mobile) {
    return Executors.newFixedThreadPool(20).submit(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            try {
                String SERVER_IP = "IP Address";
                int SERVER_PORT = Server_port;
                int DURATION = 1000;

                Socket socket = new Socket();
                socket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), DURATION);
                socket.close();

                Log.d(TAG, "Port is Open");

                runIridiumService(context, device_mac, device_imei, input_mobile);

                return true;
            } catch (Exception ex) {
                Log.d(TAG, "Port is not Open");
                CustomToast.showToast(context, "No Internet Access.", "If in flight, please switch to \"Aeroplane Mode\" and connect to the airline's Wi-Fi network.", 1);

                return false;
            }
        }
    });
}

Above code is working but when I run this method the application is getting hanged and black screen is shown for 5-6 seconds.
I found below message on Logcat.

W/ActivityManager: Launch timeout has expired, giving up wake lock!

After that service is started and application is working well. How can I get rid of this problem?
Thanks in advance.


问:
Is it good practice to unit test properties?
I'm still getting to grips with the whole TDD concept. Should I be writing tests for properties? Should one only write tests on properties containing sufficient logic? Any thoughts or examples on this would be great.</p>

答: Writing a test for public getter of a private field will not give you much if this getter does nothing except returning your private field. But if it does contain some logic (or just something that can fail, like converting your private Int32 field to Byte), testing such property starts to make sense.</p>


问:
How write join with Entity Framework
Here is my select in SQL:

```<code>select *
from FactorItems fi
inner join tblparts p on p.PartsID = fi.PartRef
</code>```

So as I use * to get all columns from my join.

But with this code:

```<code>var FactorItem = (from FI in context.FactorItems
                  join P in context.tblparts on FI.PartRef equals P.PartsID
                  where (FI.FactorRef == FactorID)
                  select FI);
</code>```

I just get data which is in FI. I want to get all data - so what code do I need for that?

答:
With that Linq to Sql code, you can return all data creating a new object:</p>

```<code>var FactorItem = (from FI in context.FactorItems
                                  join P in context.tblparts on FI.PartRef equals P.PartsID
                                  where (FI.FactorRef == FactorID)
                                  select new {FI,P};
</code>```

ContentLicense: CC BY-SA 4.0

Title: How write join with Entity Framework

Body:
Here is my select in SQL:

select *
from FactorItems fi
inner join tblparts p on p.PartsID = fi.PartRef

So as I use * to get all columns from my join.

But with this code:

var FactorItem = (from FI in context.FactorItems
                  join P in context.tblparts on FI.PartRef equals P.PartsID
                  where (FI.FactorRef == FactorID)
                  select FI);

I just get data which is in FI. I want to get all data - so what code do I need for that?

Body:
With that Linq to Sql code, you can return all data creating a new object:

var FactorItem = (from FI in context.FactorItems
                                  join P in context.tblparts on FI.PartRef equals P.PartsID
                                  where (FI.FactorRef == FactorID)
                                  select new {FI,P};


问:
How print out the contents of a HashMap<String, String> in ascending order based on its values?
I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys).

But the order when I print it out is seemingly random.

What's the best way to print it out in ascending value order?

```<code>Map<String, String> codes = new HashMap<String, String>();

codes.put("A1", "Aania");
codes.put("X1", "Abatha");
codes.put("C1", "Acathan");
codes.put("S1", "Adreenas");
</code>```

In other words, the example above should print out as this:

```<code>A1, Aania
X1, Abatha
C1, Acathan
S1, Adreenas
</code>```

答:
the simplest and shortest code i think is this:</p>

```<code>public void listPrinter(LinkedHashMap<String, String> caseList) {

    for(Entry entry:caseList.entrySet()) {
        System.out.println("K: \t"+entry.getKey()+", V: \t"+entry.getValue());
    }
}
</code>```

Body:
I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys).

But the order when I print it out is seemingly random.

What's the best way to print it out in ascending value order?

Map<String, String> codes = new HashMap<String, String>();

codes.put("A1", "Aania");
codes.put("X1", "Abatha");
codes.put("C1", "Acathan");
codes.put("S1", "Adreenas");

In other words, the example above should print out as this:

A1, Aania
X1, Abatha
C1, Acathan
S1, Adreenas

Body:
the simplest and shortest code i think is this:

public void listPrinter(LinkedHashMap<String, String> caseList) {

    for(Entry entry:caseList.entrySet()) {
        System.out.println("K: \t"+entry.getKey()+", V: \t"+entry.getValue());
    }
}


问:
How to add an element in this ArrayList?
i've been trying to  make this work but how can I add a fourth element
in this ArrayList "hourCounts"?  </p>

```<code>public class HourCounts {

    private String[] hourCounts = {"One","Two","Three"};
    public hourCounts() {
      hourCount[3] = new String ("Four") ; // how do I write the code to add a
                                           // new element that says "Four"?
    }

    public void countHours() {
      int hour = 0;
       while(hour < hourCounts.length) {
          System.out.println(hour + ": " + hourCounts[hour]);
          hour++;
       }
    }
}
</code>```

答:
The following example of using ArrayList should help you:

```<code>List<String> hourCounts = private List<String> hourCounts
                           = new ArrayList<>Arrays.asList("One", "Two", "Three"));
public hourCounts() {
    hourCount.add(new String ("Four"));
}
</code>```

ArrayList is one of the most popular implementations of List. List is something different than an Array ([]).

Arrays are fixed length. Lists are flexible. Thus, when you know the amount of elements to store, you should use an array. (e.g. String[]). If you don't know the size or you know that size will change from time to time (by adding and removing elements) it's recommended to use a List.

Also, remember that in Java, Strings aren't char[]. In fact, they store an array of chars in a certain field, but it's different from C or Python.

Body:
i've been trying to  make this work but how can I add a fourth element
in this ArrayList "hourCounts"?

public class HourCounts {

    private String[] hourCounts = {"One","Two","Three"};
    public hourCounts() {
      hourCount[3] = new String ("Four") ; // how do I write the code to add a
                                           // new element that says "Four"?
    }

    public void countHours() {
      int hour = 0;
       while(hour < hourCounts.length) {
          System.out.println(hour + ": " + hourCounts[hour]);
          hour++;
       }
    }
}

Body:
The following example of using ArrayList should help you:

List<String> hourCounts = private List<String> hourCounts
                           = new ArrayList<>Arrays.asList("One", "Two", "Three"));
public hourCounts() {
    hourCount.add(new String ("Four"));
}

ArrayList is one of the most popular implementations of List. List is something different than an Array ([]).

Arrays are fixed length. Lists are flexible. Thus, when you know the amount of elements to store, you should use an array. (e.g. String[]). If you don't know the size or you know that size will change from time to time (by adding and removing elements) it's recommended to use a List.

Also, remember that in Java, Strings aren't char[]. In fact, they store an array of chars in a certain field, but it's different from C or Python.


问:
Create an unordered map from a vector of structs
Say I have a class that can easily express key-value semantics:

```<code>template <class T1, class T2>
struct data_t{
    T1 m1;
    T2 m2;
};
</code>```

What would be the most efficient way to create an unordered map out of a vector of such structs?

My approach

I tried to define a conversion operator for my class

```<code>operator std::pair<T1, T2> () { return {m1, m2};  } // typo noted by PasserBy
</code>```

But this doesn't seem to work

```<code>std::vector<data_t> v;
std::unordered_map<T1, T2> um(v.begin(), v.end()); // compilation error
</code>```

My particular use case has a pointer type T1 and a value type T2 so I suppose there wouldn't be a need to define hash functions (?). Also the reason I'm trying to do it through a conversion operator is to be able to add elements to that unordered map in the same fashion:

```<code>um.insert(itn, ite); // insert from a range of the source vector
</code>```

答:
I would just use transform:</p>

```<code>unordered_map<int, double> um;
transform(begin(v), end(v), inserter(um, end(um)), [](const auto& data) {
    return make_pair(data.m1, data.m2);
});
</code>```

Body:
Say I have a class that can easily express key-value semantics:

template <class T1, class T2>
struct data_t{
    T1 m1;
    T2 m2;
};

What would be the most efficient way to create an unordered map out of a vector of such structs?

My approach

I tried to define a conversion operator for my class

operator std::pair<T1, T2> () { return {m1, m2};  } // typo noted by PasserBy

But this doesn't seem to work

std::vector<data_t> v;
std::unordered_map<T1, T2> um(v.begin(), v.end()); // compilation error

My particular use case has a pointer type T1 and a value type T2 so I suppose there wouldn't be a need to define hash functions (?). Also the reason I'm trying to do it through a conversion operator is to be able to add elements to that unordered map in the same fashion:

um.insert(itn, ite); // insert from a range of the source vector

Body:
I would just use transform:

unordered_map<int, double> um;
transform(begin(v), end(v), inserter(um, end(um)), [](const auto& data) {
    return make_pair(data.m1, data.m2);
});


问:
angular $resource delete won't send body to express.js server
hye,

i am building an app with angular.js and node.js (Express.js) on the server side.

for some reason i am having a problem handling a delete request. no body is getting to the server side.

this is my angular.js resource code:

```<code>$scope.deleteProject = function(projectName){
    var postData = {username: 'name', projectName: projectName};
    Project.deleteProject.delete({}, postData,
        function(res){
            alert('Project Deleted');
        },
        function(err){
            alert(err.data);
    });
}
</code>```

on the server side i have this:

```<code>var deleteProject = function(req, res){
    console.log(req.body);
    console.log(req.params);
    if (req.body.projectName){
        //do something
        return res.send(200);
    }
    else
        return res.send(400, 'no project name was specified');
}
</code>```

now for some reason there is no body at all!! it is empty.
i have defined the route as app.delete.

if i change the route in node.js to post and in angular.js to save it works fine.

what am i missing here (banging my head).

thanks.

答:
If you want to use the $resource object instead of $http you need to add hasBody and headers as follow:

```<code>delete:  {
    method: 'DELETE',
    hasBody: true,
    headers: {"Content-Type": "application/json;charset=UTF-8"}
  }
</code>```

Worked for me

Body:
hye,

i am building an app with angular.js and node.js (Express.js) on the server side.

for some reason i am having a problem handling a delete request. no body is getting to the server side.

this is my angular.js resource code:

$scope.deleteProject = function(projectName){
    var postData = {username: 'name', projectName: projectName};
    Project.deleteProject.delete({}, postData,
        function(res){
            alert('Project Deleted');
        },
        function(err){
            alert(err.data);
    });
}

on the server side i have this:

var deleteProject = function(req, res){
    console.log(req.body);
    console.log(req.params);
    if (req.body.projectName){
        //do something
        return res.send(200);
    }
    else
        return res.send(400, 'no project name was specified');
}

now for some reason there is no body at all!! it is empty.
i have defined the route as app.delete.

if i change the route in node.js to post and in angular.js to save it works fine.

what am i missing here (banging my head).

thanks.

Body:
If you want to use the $resource object instead of $http you need to add hasBody and headers as follow:

delete:  {
    method: 'DELETE',
    hasBody: true,
    headers: {"Content-Type": "application/json;charset=UTF-8"}
  }

Worked for me