问:
How to repeat event weekly by using selection on multiple days from my application
I am using checkbox for selection of multiple days

```<code>if (monday == 1) {
            chkMonday.setChecked(true);

        }  if (tuesday == 1) {
            chkTuesday.setChecked(true);
        }  if (wednesday == 1) {
            chkWedneday.setChecked(true);
        }  if (thursday == 1) {
            chkThursday.setChecked(true);
        }  if (friday == 1) {
            chkFriday.setChecked(true);
        }  if (saturday == 1) {
            chkSaturday.setChecked(true);
        }  if (sunday == 1) {
            chkSunday.setChecked(true);
        }
</code>```

Now i want to pass multiple repetition days to calendar according to my selection of days from checkbox. For that I am using if..else if condition like this

```<code>  values.put(CalendarContract.Reminders.TITLE, "Routine Custom");
        values.put(CalendarContract.Reminders.DTSTART, millisecondsTimesEveryday);
        values.put(CalendarContract.Reminders.HAS_ALARM, true);
        if (chkMonday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=MO");//UNTIL=1924885800000
        }else   if (chkTuesday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TU");
        } else if (chkWedneday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=WE");
        } else if (chkThursday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TH");
        } else if (chkFriday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=FR");
        } else if (chkSaturday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SA");
        } else if (chkSunday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SU");
        }
        values.put(CalendarContract.Reminders.DTEND, EndtimeInMilliseconds);
</code>```

But in calendar there is only first selected day for repetition. How to set all selected day to the repetition days in remindar?

答:
Your Checking the Conditions Using If-else,But the problem with this approach is that once the first condition gets true,it breaks out and never bother to check the other conditions,The solution to your issue would be iterating through the entire data set which u need to create before checking boolean states of the checkboxes,I would rather take help of the Hashmap to store the boolean states of the check boxes,i would store the week name and pair up with a boolean state along with it and this continues for all the days of the week

```<code>//Create a Hashmap
 HashMap<String,Boolean> dayOfWeek = new HashMap<>();
if (monday == 1) {
            chkMonday.setChecked(true);
       dayOfWeek.put("Monday",true);

        }  if (tuesday == 1) {
            chkTuesday.setChecked(true);
     dayOfWeek.put("Tuesday",true);//pairing an unique string with a boolean value depending on whether it is checked or not
        }  if (wednesday == 1) {
            chkWedneday.setChecked(true);
        dayOfWeek.put("Wedneday",true);//pairing continues for all days similarly
        }  if (thursday == 1) {
            chkThursday.setChecked(true);
       dayOfWeek.put("Thursday",true);
        }  if (friday == 1) {
            chkFriday.setChecked(true);
       dayOfWeek.put("Friday",true);
        }  if (saturday == 1) {
            chkSaturday.setChecked(true);
       dayOfWeek.put("Saturday",true);
        }  if (sunday == 1) {
            chkSunday.setChecked(true);
       dayOfWeek.put("Sunday",true);
        }
</code>```

create values as usually

```<code>values.put(CalendarContract.Reminders.TITLE, "Routine Custom");
        values.put(CalendarContract.Reminders.DTSTART, millisecondsTimesEveryday);
        values.put(CalendarContract.Reminders.HAS_ALARM, true);
</code>```

//Now you need to Iterate through the hashmap to insert reminders for all the checked days:

```<code>Iterator it =  dayOfWeek.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry)it.next();
                System.out.println(pair.getKey() + " = " + pair.getValue());
               if (pair.getValue()==true){
               if (pair.getKey().toString().equalsIgnoreCase("Monday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=MO");//UNTIL=1924885800000
        }else   if (pair.getKey().toString().equalsIgnoreCase("Tuesday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TU");
        } else if (pair.getKey().toString().equalsIgnoreCase("Wednesday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=WE");
        } else if (pair.getKey().toString().equalsIgnoreCase("Thursday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TH");
        } else if (pair.getKey().toString().equalsIgnoreCase("Friday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=FR");
        } else if (pair.getKey().toString().equalsIgnoreCase("Saturday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SA");
        } else if (pair.getKey().toString().equalsIgnoreCase("Sunday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SU");
        }
    }
            }
values.put(CalendarContract.Reminders.DTEND, EndtimeInMilliseconds);
</code>```

Using this u would be able to iterate through the entire data set (Hashmap in this case) to insert reminders for all the days which are checked

Body:
I am using checkbox for selection of multiple days

if (monday == 1) {
            chkMonday.setChecked(true);

        }  if (tuesday == 1) {
            chkTuesday.setChecked(true);
        }  if (wednesday == 1) {
            chkWedneday.setChecked(true);
        }  if (thursday == 1) {
            chkThursday.setChecked(true);
        }  if (friday == 1) {
            chkFriday.setChecked(true);
        }  if (saturday == 1) {
            chkSaturday.setChecked(true);
        }  if (sunday == 1) {
            chkSunday.setChecked(true);
        }

Now i want to pass multiple repetition days to calendar according to my selection of days from checkbox. For that I am using if..else if condition like this

  values.put(CalendarContract.Reminders.TITLE, "Routine Custom");
        values.put(CalendarContract.Reminders.DTSTART, millisecondsTimesEveryday);
        values.put(CalendarContract.Reminders.HAS_ALARM, true);
        if (chkMonday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=MO");//UNTIL=1924885800000
        }else   if (chkTuesday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TU");
        } else if (chkWedneday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=WE");
        } else if (chkThursday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TH");
        } else if (chkFriday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=FR");
        } else if (chkSaturday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SA");
        } else if (chkSunday.isChecked()) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SU");
        }
        values.put(CalendarContract.Reminders.DTEND, EndtimeInMilliseconds);

But in calendar there is only first selected day for repetition. How to set all selected day to the repetition days in remindar?

Body:
Your Checking the Conditions Using If-else,But the problem with this approach is that once the first condition gets true,it breaks out and never bother to check the other conditions,The solution to your issue would be iterating through the entire data set which u need to create before checking boolean states of the checkboxes,I would rather take help of the Hashmap to store the boolean states of the check boxes,i would store the week name and pair up with a boolean state along with it and this continues for all the days of the week

//Create a Hashmap
 HashMap<String,Boolean> dayOfWeek = new HashMap<>();
if (monday == 1) {
            chkMonday.setChecked(true);
       dayOfWeek.put("Monday",true);

        }  if (tuesday == 1) {
            chkTuesday.setChecked(true);
     dayOfWeek.put("Tuesday",true);//pairing an unique string with a boolean value depending on whether it is checked or not
        }  if (wednesday == 1) {
            chkWedneday.setChecked(true);
        dayOfWeek.put("Wedneday",true);//pairing continues for all days similarly
        }  if (thursday == 1) {
            chkThursday.setChecked(true);
       dayOfWeek.put("Thursday",true);
        }  if (friday == 1) {
            chkFriday.setChecked(true);
       dayOfWeek.put("Friday",true);
        }  if (saturday == 1) {
            chkSaturday.setChecked(true);
       dayOfWeek.put("Saturday",true);
        }  if (sunday == 1) {
            chkSunday.setChecked(true);
       dayOfWeek.put("Sunday",true);
        }

create values as usually

values.put(CalendarContract.Reminders.TITLE, "Routine Custom");
        values.put(CalendarContract.Reminders.DTSTART, millisecondsTimesEveryday);
        values.put(CalendarContract.Reminders.HAS_ALARM, true);

//Now you need to Iterate through the hashmap to insert reminders for all the checked days:

Iterator it =  dayOfWeek.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry pair = (Map.Entry)it.next();
                System.out.println(pair.getKey() + " = " + pair.getValue());
               if (pair.getValue()==true){
               if (pair.getKey().toString().equalsIgnoreCase("Monday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=MO");//UNTIL=1924885800000
        }else   if (pair.getKey().toString().equalsIgnoreCase("Tuesday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TU");
        } else if (pair.getKey().toString().equalsIgnoreCase("Wednesday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=WE");
        } else if (pair.getKey().toString().equalsIgnoreCase("Thursday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TH");
        } else if (pair.getKey().toString().equalsIgnoreCase("Friday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=FR");
        } else if (pair.getKey().toString().equalsIgnoreCase("Saturday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SA");
        } else if (pair.getKey().toString().equalsIgnoreCase("Sunday")) {
            values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SU");
        }
    }
            }
values.put(CalendarContract.Reminders.DTEND, EndtimeInMilliseconds);

Using this u would be able to iterate through the entire data set (Hashmap in this case) to insert reminders for all the days which are checked


来源: stackexchange

问:
Bypass a Java error
Is there a way that I can bypass an error message in Java ?
What if I get an error, but there is no viable way to change my program ? What if I suspect that I might get an error from a block of code, but I don't know when or if it will happen ? There's been a lot of times where I had to let something be in my code, but produced an error. For example, converting a string into a float with parseFloat().

Anyway to do this ?

答:
Yes you can handle runtime errors in Java.

Exception Handling

There are two ways to handle Exceptions.

Throw out and ignore -

When an Exception occur inside a code of program simply throw it out and ignore that an exception occur(i.e.declare the methods as throws Exception).

Example:

```<code>void method()throws IOException{

 }
</code>```

Catch and handle -

If a code snippet is generating an Exception place it inside a try block. Then mention the way to handle the Exception inside the catch block.

Example for catch and handle:

```<code>try{
  double a= parseDouble("12.4a");
}catch(NumberFormatException e){
  System.out.println("cannot format");
}
</code>```

Here try to convert 12.4a to double and store in a. Since 12.4a contains character a NumberFormatException will occur. you can handle it. In above code I just print a text. But you get printStackTrace:

```<code>e.printStackTrace;
</code>```

You can add finally after catch block. read Orcale doc.

ContentLicense: CC BY-SA 3.0

Title: Bypass a Java error

Body:
Yes you can handle runtime errors in Java.

Exception Handling

There are two ways to handle Exceptions.

Throw out and ignore -

When an Exception occur inside a code of program simply throw it out and ignore that an exception occur(i.e.declare the methods as throws Exception).

Example:

void method()throws IOException{

 }

Catch and handle -

If a code snippet is generating an Exception place it inside a try block. Then mention the way to handle the Exception inside the catch block.

Example for catch and handle:

try{
  double a= parseDouble("12.4a");
}catch(NumberFormatException e){
  System.out.println("cannot format");
}

Here try to convert 12.4a to double and store in a. Since 12.4a contains character a NumberFormatException will occur. you can handle it. In above code I just print a text. But you get printStackTrace:

e.printStackTrace;

You can add finally after catch block. read Orcale doc.


问:
How can place a imageButton inside a textfield?
How can i create a text field with a button at the left side like whatsapp's smiley button and i also want my text to start after the button.

答:
Set icon by drawableLeft of EditText and to perform click on that icon write down below code.</p>

```<code> editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getRawX() <= (back.getCompoundDrawables()[0].getBounds().width())) {
                    // Your Code
                    return true;
                }
                return false;
            }
        });
</code>```

Body:
Set icon by drawableLeft of EditText and to perform click on that icon write down below code.

 editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getRawX() <= (back.getCompoundDrawables()[0].getBounds().width())) {
                    // Your Code
                    return true;
                }
                return false;
            }
        });


问:
PHP: Manipulating existing array
I have an existing array $cars[]. Here's how I created the array $cars[]

```<code>$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );
</code>```

As you can see, the indices of the array $cars[] is not in order. What I need to do is insert an array element in the array $cars[] when needed, to make it in order. I need to make the array $cars[] like this:

```<code>$cars = array("1" => "Toyota",
              "2"=> "NULL",
              "3"=> "NULL",
              "4"=> "NULL",
              "5" => "BMW",
              "6"=> "NULL",
              "7" => "Volvo",
              "8"=> "NULL",
               .
               .
               .
              "31"=> "NULL",
              "32"=> "Porsche"
               .
               .
               .
              "48"=> "NULL"  );
</code>```

A total of 48 cars. Thank you guys!

答:
This piece of code will help you

```<code>$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );
for($i=min(array_keys($cars));$i<=max(array_keys($cars));$i++){
    if(!isset($cars[$i])){
        $cars[$i]="NULL";
    }
}
ksort($cars);
</code>```

If you want to start with index 1 everytime, you can change "min(array_keys($cars))" in for loop with "1"

Title: PHP: Manipulating existing array

Body:
I have an existing array $cars[]. Here's how I created the array $cars[]

$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );

As you can see, the indices of the array $cars[] is not in order. What I need to do is insert an array element in the array $cars[] when needed, to make it in order. I need to make the array $cars[] like this:

$cars = array("1" => "Toyota",
              "2"=> "NULL",
              "3"=> "NULL",
              "4"=> "NULL",
              "5" => "BMW",
              "6"=> "NULL",
              "7" => "Volvo",
              "8"=> "NULL",
               .
               .
               .
              "31"=> "NULL",
              "32"=> "Porsche"
               .
               .
               .
              "48"=> "NULL"  );

A total of 48 cars. Thank you guys!

Body:
This piece of code will help you

$cars = array("1" => "Toyota",
              "5" => "BMW",
              "7" => "Volvo",
              "32"=> "Porsche" );
for($i=min(array_keys($cars));$i<=max(array_keys($cars));$i++){
    if(!isset($cars[$i])){
        $cars[$i]="NULL";
    }
}
ksort($cars);

If you want to start with index 1 everytime, you can change "min(array_keys($cars))" in for loop with "1"


问:
How to completely hide the status bar in iOS using Cordova?
I want to have no status bar for the Cordova app I am developing. I am nearly there, the status bar doesn't show on the splash screen. However on the first page that loads you see a flash of the status bar, before it gets hidden.

I have checked the "hide status bar" checkbox in Xcode.

I have added the cordova-plugin-statusbar plugin, and on the deviceready callback, I'm calling StatusBar.hide().

However when the splash image disappears and the first page is being rendered there is a flash of status bar prior to the page being display. It is only for a split second but looks awful.

Anybody know how the status bar can be hidden completely, without flashing up before being hidden?

答:
This way worked to me:

On your mac or VM xcode, select TARGETS->Your app

Then on INFO menu, on CUSTOM iOS TARGET PROPERTIES, add this NEW properties:

Statusbar is initially hidden -> Then set the value to YES.

View controller-based status bar appearance -> Then set the value to NO

Build and you should have no statusbar.

printscreen: http://prntscr.com/fg0jtf


问:
strtotime on incorrect dates
I found something odd about strtotime().

On dates that do not exist it returns the day after.

```<code>$d30= strtotime("2017-06-30");
Echo $d30 ."\n";
Echo date("Y-m-d", $d30)."\n\n";  // 2017-06-30

$d31= strtotime("2017-06-31");
Echo $d31 ."\n";
Echo date("Y-m-d", $d31)."\n\n";  // 2017-07-01

$d32= strtotime("2017-06-32");
Echo $d32 ."\n";
Echo date("Y-m-d", $d32);         // 1970-01-01
</code>```

https://3v4l.org/AjMAE

I understand the last one. It returns nothing as it's an error.

But why does the second one return first of July?

Is it a meant to be functional, in case you make a mistake it will "correct you"? Or is it a true bug in strtotime()?

答:
As day 31 of a month is possible strtotime() will correct the date for you. If you try it with February (2017-02-31) it will correct to 2017-03-03. This is what you found.

So, what it essentially does is:

get the date

check if the date is in a valid range (days per
month)

if not valid count days into the next month

This behaviour is implemented into the strtotime function itself.

There was a great comment on the documentation page about this, but I am no longer able to find it. This comment provides some extra information (be sure to check the link in the comment).

Title: strtotime on incorrect dates

Body:
I found something odd about strtotime().

On dates that do not exist it returns the day after.

$d30= strtotime("2017-06-30");
Echo $d30 ."\n";
Echo date("Y-m-d", $d30)."\n\n";  // 2017-06-30

$d31= strtotime("2017-06-31");
Echo $d31 ."\n";
Echo date("Y-m-d", $d31)."\n\n";  // 2017-07-01

$d32= strtotime("2017-06-32");
Echo $d32 ."\n";
Echo date("Y-m-d", $d32);         // 1970-01-01

https://3v4l.org/AjMAE

I understand the last one. It returns nothing as it's an error.

But why does the second one return first of July?

Is it a meant to be functional, in case you make a mistake it will "correct you"? Or is it a true bug in strtotime()?


问:
Required Framework vs Static Library
Building Modern Frameworks says every app has its own copy of a custom framework. Now that Xcode supports iOS frameworks, is it still true that frameworks are static libraries but just more convenient? If that's true, then why choose the static library template? Otherwise, should I convert all my required custom frameworks to static libraries once Swift supports static libraries?

答:
The use of dynamic frameworks is exclusively for swift from iOS 8 and later, i.e (you can't submit a build with iOS 7 and a dynamic framework)

If you want support for iOS 7 and before you can use a static library and objc

A dynamic framework and a static library are different things, a framework is a bundle where you have a directory and can include resources, views, classes, and also libraries

A static library is only executable code

Also you use the code in a static library inside your own code, in the case of a framework he use the code and handle the way it runs and what do

This link could help you
http://www.knowstack.com/framework-vs-library-cocoa-ios/

Title: Required Framework vs Static Library


问:
SQL Server: Group By based on one column and get columns based on other column
My data:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes
</code>```

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

```<code>ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
</code>```

How do I select all values that satisfy above rule?

答:
try this without group by and having cluase,</p>

```<code>create table #t(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10))
insert into #t
    select 'A','Hi','Yes' union all
    select 'A','Hello',NULL union all
    select 'B','Hola','Yes' union all
    select 'B','Hola','Yes' union all
    select 'B','Hi',NULL union all
    select 'C','ABCD','Yes'

    ;With CTE as
    (
    select *
    ,ROW_NUMBER()over(partition by ColumnA order by ColumnA)rn
    from #t
    where ColumnC is null or ColumnC='Yes'
    )
    select * from cte c
    where exists(select columnA from cte c1
    where c.ColumnA=c1.ColumnA and rn>1)

    drop table #t
</code>```

Body:
My data:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL
C                          ABCD                Yes

My SQL should be able to do following:

Group by Column A

Select only those groups of A that contain Yes and Null both in the result of a

Expected Result is:

ColumnA                 Column B            ColumnC
A                          Hi                  Yes
A                          Hello               NULL
B                          Hola                Yes
B                          Hola                Yes
B                          Hi                  NULL

How do I select all values that satisfy above rule?

Body:
try this without group by and having cluase,

create table #t(ColumnA varchar(10),ColumnB varchar(10),ColumnC varchar(10))
insert into #t
    select 'A','Hi','Yes' union all
    select 'A','Hello',NULL union all
    select 'B','Hola','Yes' union all
    select 'B','Hola','Yes' union all
    select 'B','Hi',NULL union all
    select 'C','ABCD','Yes'

    ;With CTE as
    (
    select *
    ,ROW_NUMBER()over(partition by ColumnA order by ColumnA)rn
    from #t
    where ColumnC is null or ColumnC='Yes'
    )
    select * from cte c
    where exists(select columnA from cte c1
    where c.ColumnA=c1.ColumnA and rn>1)

    drop table #t


问:
I have a h1, and a h3 that I can't vertically center in Foundation 6
I've tried to everything to vertically center my h1 and h3 tag in Foundation 6. I've tried the transform translate, flexbox, and tried multiple examples here on stack over flow, and nothing works. When I use absolute positioning to center the content the, the headings get in the way of the top-bar nav on smaller screens, id there anyway to fix this issue, and Could some give me a hand with this? The h1 tag, and the h3 tag are located in line 48, and 49 of my codepen.
Codepen link</p>

```<code><!doctype html>
<html class="no-js" lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
    <div class="off-canvas-wrapper">
            <div class="off-canvas position-left" id="offCanvas" data-off-canvas data-transition="overlap">
                <!-- Close button -->
            <button class="close-button" aria-label="Close menu" type="button" data-close>
        <span aria-hidden="true">×</span>
            </button>
            <ul class="vertical menu">
              <li><a href="#">Home</a></li>
              <li><a href="#">About</a></li>
              <li><a href="#">References</a></li>
              <li><a href="#">Contact</a></li>
            </ul>
            </div><!-- off-canvas menu -->
            <div class="off-canvas-content" data-off-canvas-content>
            <!-- Your page content lives here -->
            <div class="hero-image">
                <div class="expanded header-intro row">
              <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button><!-- Button to open off-canvas menu -->
              <div class="title-bar" data-responsive-toggle="menu" data-hide-for="medium"><!--top bar navigation -->
              <button class="menu-icon" type="button" data-toggle></button>
              <div class="title-bar-title">Menu</div>
              </div>
              <div class="top-bar show-for-small-only" id="menu">
                <div class="top-bar-left">
                <ul class="dropdown vertical menu" data-dropdown-menu>
                    <li class="menu-text">Foundation Framework</li>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Reference</a></li>
                    <li><a href="#">About</a></li>
                </ul>
                </div>
              </div>
                </div>
                <div class="row">
            <div class="small-12 text-center columns">
              <h1>Foundation</h1> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
              <h3>Foundation For Sites</h3> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
            </div>
                </div>
            </div><!-- Eno of hero-image section -->
            </div><!-- off-canvas-content-->
        </div><!-- off-canvas wrapper-->
    <script src="js/vendor/jquery.js"></script>
    <script src="js/vendor/what-input.js"></script>
    <script src="js/vendor/foundation.js"></script>
    <script src="js/app.js"></script>
  </body>
</html>
</code>```

答:
I suppose you're using flex-grid, so you can just add align-middle class to you row. This will add align-items: center; attribute, and align your columns' content vertically in the center.

.row {
  max-width: 960px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-flow: row wrap;

  height: 200px;
}

.align-middle {
  align-items: center;
}

.column, .columns {
  flex: 1 1 0px;
  padding-left: 20px;
  padding-right: 20px;
  min-width: initial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row align-middle">
            <div class="small-12 text-center columns">
              <h1>Foundation</h1> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
              <h3>Foundation For Sites</h3> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
            </div>
                </div></code>```

Body:
I've tried to everything to vertically center my h1 and h3 tag in Foundation 6. I've tried the transform translate, flexbox, and tried multiple examples here on stack over flow, and nothing works. When I use absolute positioning to center the content the, the headings get in the way of the top-bar nav on smaller screens, id there anyway to fix this issue, and Could some give me a hand with this? The h1 tag, and the h3 tag are located in line 48, and 49 of my codepen.
Codepen link

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">

            <button class="close-button" aria-label="Close menu" type="button" data-close>
        ×
            </button>

Home

About

References

Contact

              <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button>

              <button class="menu-icon" type="button" data-toggle></button>

Menu

Foundation Framework

Home

About

Reference

About

Foundation

Foundation For Sites

Body:
I suppose you're using flex-grid, so you can just add align-middle class to you row. This will add align-items: center; attribute, and align your columns' content vertically in the center.

.row {
  max-width: 960px;
  margin-left: auto;
  margin-right: auto;
  display: flex;
  flex-flow: row wrap;

  height: 200px;
}

.align-middle {
  align-items: center;
}

.column, .columns {
  flex: 1 1 0px;
  padding-left: 20px;
  padding-right: 20px;
  min-width: initial;
}

<div class="row align-middle">
            <div class="small-12 text-center columns">
              <h1>Foundation</h1> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
              <h3>Foundation For Sites</h3> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
            </div>
                </div>


问:
How many variables are too much for a class?
I want to see if anyone has a better design for a class (class as in OOP) I am writing. We have a script that puts shared folder stats in a CSV file. I am reading that in and putting it in a Share class.

My boss wants to know information like:

Total Number of Files

Total Size of Files

Number of Office Files

Size of Office Files

Number of Exe Files

Size of Exe Files

etc ....

I have a class with variables like $numOfficeFiles, $sizeOfficeFiles, etc. with a ton of get/set methods. Isn't there a better way to do this? What is the general rule if you have a class with a lot of variables/properties?

I think of this as a language agnostic question, but if it matters, I am using PHP.

答:
I always try to think of a Class as being the "name of my container" or the "name of the task" that I am going to compute. Methods in the Class are "actions" part of the task.

In this case seems like you can start grouping things together, for example you are repeating the number and the size actions many times. Why not create a super class that other classes inherit from, for example:

```<code>class NameOfSuperClass {
    public $type;
    function __construct($type) {
        $this->type = $type;
        $this->getNumber();
        $this->getSize();
    }
    public function getNumber() {
        // do something with the type and the number
    }
    public function getSize() {
        // do something with the type and the size
    }
}

Class OfficeFiles extends NameOfSuperClass {
    function __construct() {
        $this->_super("office");
    }
}
</code>```

I'm not sure if this is right in PHP, but you get my point. Things will start to look a lot cleaner and better to manage.

OwnerDisplayName: Ben

LastEditorDisplayName: mmyers

Body:
I always try to think of a Class as being the "name of my container" or the "name of the task" that I am going to compute. Methods in the Class are "actions" part of the task.

In this case seems like you can start grouping things together, for example you are repeating the number and the size actions many times. Why not create a super class that other classes inherit from, for example:

class NameOfSuperClass {
    public $type;
    function __construct($type) {
        $this->type = $type;
        $this->getNumber();
        $this->getSize();
    }
    public function getNumber() {
        // do something with the type and the number
    }
    public function getSize() {
        // do something with the type and the size
    }
}

Class OfficeFiles extends NameOfSuperClass {
    function __construct() {
        $this->_super("office");
    }
}

I'm not sure if this is right in PHP, but you get my point. Things will start to look a lot cleaner and better to manage.

OwnerDisplayName: sktrdie

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: sktrdie


问:
Calculates b/w two row
Can any one Help me Please I want to Calculate 2 or more row Record see Below Query.

```<code>SELECT docs_DocCode, SUM(invd_Qty) AS Total_IN
FROM   dbo.SI_InventoryDetail

WHERE  (docs_DocCode = 'D.C') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'IOB') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'GRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'PRN') AND (itm_ItemCode = '0101050000083')
GROUP BY docs_DocCode
</code>```

ABove Query Give me Result as below

```<code>dics_doccode   Total
D.C            328.00000000
GRN            205.00000000
IOB             96.00000000
SAI             66.00000000
SAO             51.00000000
SRN             14.00000000
STI            150.00000000
STO            150.00000000
</code>```

Now i want To ADD (D.C+STI+SAI) - (GRN+STI+SAI+IOB) = One Value

And i am using SQL SERVER 2000

Thankx

答:
```<code>SELECT SUM(CASE
             WHEN docs_DocCode IN ('D.C', 'STI', 'SAI') THEN invd_Qty
             WHEN docs_DocCode IN ('GRN', 'STI', 'SAI', 'IOB') THEN -1 * invd_Qty
             ELSE 0
           END) AS One_Value
....
</code>```

Note that invd_Qty that do not belong to any from 'D.C', 'STI', 'SAI', 'GRN', 'STI', 'SAI', 'IOB' will not be added.

PS: (D.C+STI+SAI) - (GRN+STI+SAI+IOB) - I've emphasized the pointless (??) parts. It is equal to D.C. - (SAI + IOB)

Title: Calculates b/w two row

Body:
Can any one Help me Please I want to Calculate 2 or more row Record see Below Query.

SELECT docs_DocCode, SUM(invd_Qty) AS Total_IN
FROM   dbo.SI_InventoryDetail

WHERE  (docs_DocCode = 'D.C') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAO') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'IOB') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'GRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'STI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SAI') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'SRN') AND (itm_ItemCode = '0101050000083') OR
       (docs_DocCode = 'PRN') AND (itm_ItemCode = '0101050000083')
GROUP BY docs_DocCode

ABove Query Give me Result as below

dics_doccode   Total
D.C            328.00000000
GRN            205.00000000
IOB             96.00000000
SAI             66.00000000
SAO             51.00000000
SRN             14.00000000
STI            150.00000000
STO            150.00000000

Now i want To ADD (D.C+STI+SAI) - (GRN+STI+SAI+IOB) = One Value

And i am using SQL SERVER 2000

Thankx

Body:
SELECT SUM(CASE
             WHEN docs_DocCode IN ('D.C', 'STI', 'SAI') THEN invd_Qty
             WHEN docs_DocCode IN ('GRN', 'STI', 'SAI', 'IOB') THEN -1 * invd_Qty
             ELSE 0
           END) AS One_Value
....

Note that invd_Qty that do not belong to any from 'D.C', 'STI', 'SAI', 'GRN', 'STI', 'SAI', 'IOB' will not be added.

PS: (D.C+STI+SAI) - (GRN+STI+SAI+IOB) - I've emphasized the pointless (??) parts. It is equal to D.C. - (SAI + IOB)


问:
Should I close the channel/connection after every publish?
I am using amqplib in Node.js, and I am not clear about the best practices in my code.

Basically, my current code calls the amqp.connect() when the Node server starts up, and then uses a different channel for each producer and each consumer, never actually closing any of them. I'd like to know if that makes any sense, or should I create the channel, publish and close it every time I want to publish a message. And what about the connection? Is that a "good practice" to connect once, and then keep it open for the lifetime of my server?

On the Consumer side - can I use a single connection and a single channel to listen on multiple queues?

Thank you for any clarifications

答:
In general, it's not a good practice to open and close connections and channels per message. Connections are long lived and it takes resources to keep opening and closing them. For channels, they share the TCP connection with the connection so they are more lightweight, but they will still consume memory and definitely should not be left open after done using them.

It is recommended to have a channel per thread, and a channel per consumer. But for publishing it is totally ok to use the same channel. But keep in mind that depending on the operations, the protocol might kill the channel in certain situations (e.g. queue existence check), so prepare for that. There is also soft (configurable) and hard (usually 65535) limits on the maximum number of channels on many of the client implementations.

So to sum up, depending on your use case use one to a few connections, open channels when you need them and share them when it makes sense, but remember to close them when done.

The rabbitmq documentation explains the nature of the connections and channels (end of the document). And the accepted answer on this question has good information on the subject.


问:
Pagination in thumbnail PHP
I am trying to create a page that shows thumbnails from my database. However i want to create a pagination in case i want to update my database. Only the first 3 table should show in page 1 and so on...

Here is my script in thumbnail

```<code><?php
    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $link = mysqli_connect("localhost", "root", "", "test");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Attempt select query execution
    $sql = "SELECT * FROM news limit 3";
    if($result = mysqli_query($link, $sql)){
        if( mysqli_num_rows($result) > 0 ){

            echo "<div class=\"container\">";
            echo "<table>";
            echo "<tr>";
            echo "</tr>";
            while($row=mysqli_fetch_array($result)){

                echo "<div class=\"col-md-4\">";
                echo "<div class=\"thumbnail\">";
                echo "<img alt=\"News\" src=\"images/{$row["image"]}\">";
                echo "<div class=\"caption\">";
                echo "<b><h4>{$row["title"]}</b></h4>";
                echo "<p>{$row["caption"]}</p>";
                echo "<p align=\"right\">";
                echo "<a class=\"btn btn-primary\" href=\"{$row["newsupdate"]}\">Read More</a>";
                echo "</p>";
                echo "</div>";
                echo "</div>";
                echo "</div>";
                echo "</div>";
            }
            echo "</table>";

            // Free result set
            mysqli_free_result($result);
        } else{
            echo "No records matching your query were found.";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    // Close connection
    mysqli_close($link);
?>

<ul class="pagination">
  <li><a href="#">1</a></li>
  <li><a href="#">2</a></li>
  <li><a href="#">3</a></li>
  <li><a href="#">4</a></li>
  <li><a href="#">5</a></li>
</ul>
</code>```

答:
Do you want to paginate the tables that are appearing as a result not?

I think is a good option use the pagination of Bootstrap or Jquery:

https://www.uno-de-piera.com/paginacion-original-con-jquery-y-php/
https://esimakin.github.io/twbs-pagination/

You can configure the items shows per page, the style, etc.

Title: Pagination in thumbnail PHP

Body:
I am trying to create a page that shows thumbnails from my database. However i want to create a pagination in case i want to update my database. Only the first 3 table should show in page 1 and so on...

Here is my script in thumbnail

<?php
    /* Attempt MySQL server connection. Assuming you are running MySQL
    server with default setting (user 'root' with no password) */
    $link = mysqli_connect("localhost", "root", "", "test");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }

    // Attempt select query execution
    $sql = "SELECT * FROM news limit 3";
    if($result = mysqli_query($link, $sql)){
        if( mysqli_num_rows($result) > 0 ){

            echo "
";
            echo "
";
            echo "
";
            echo "
";
            while($row=mysqli_fetch_array($result)){

                echo "
";
                echo "
";
                echo "";
                echo "
";
                echo "
{$row["title"]}
";
                echo "
{$row["caption"]}
";
                echo "
";
                echo "Read More";
                echo "
";
                echo "
";
                echo "
";
                echo "
";
                echo "
";
            }
            echo "
";

            // Free result set
            mysqli_free_result($result);
        } else{
            echo "No records matching your query were found.";
        }
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
    }

    // Close connection
    mysqli_close($link);
?>

1

2

3

4

5


问:
.htaccess exception rules not working
These are my current rules in .htaccess. Basically, I want to redirect my entire site from domain1.com to domain2.com except for the following conditions:

all files/pages inside /offers folder

the page at /page/company-a

When I access www.domain1.com/page/company-a, I am redirected to domain2.com/index.php instead.

Any advice appreciated.

```<code>RewriteCond %{REQUEST_URI} !^/offers
RewriteCond %{REQUEST_URI} !^/page/company-a

RewriteCond %{HTTP_HOST}  ^www\.domain1\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain2.com/$1 [L,R=301]

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]
</code>```

答:
Use THE_REQUEST variable instead of REQUEST_URI. THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules.

```<code>RewriteEngine On

RewriteCond %{THE_REQUEST} !\s/+(offers|page/company-a) [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?domain1\.com$ [NC]
RewriteRule ^ http://www.domain2.com%{REQUEST_URI} [L,R=301,NE]

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]
</code>```

Make sure to clear your browser cache while testing.

Title: .htaccess exception rules not working

Body:
These are my current rules in .htaccess. Basically, I want to redirect my entire site from domain1.com to domain2.com except for the following conditions:

all files/pages inside /offers folder

the page at /page/company-a

When I access www.domain1.com/page/company-a, I am redirected to domain2.com/index.php instead.

Any advice appreciated.

RewriteCond %{REQUEST_URI} !^/offers
RewriteCond %{REQUEST_URI} !^/page/company-a

RewriteCond %{HTTP_HOST}  ^www\.domain1\.com$ [NC]
RewriteRule ^(.*)$ http://www.domain2.com/$1 [L,R=301]

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

Body:
Use THE_REQUEST variable instead of REQUEST_URI. THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules.

RewriteEngine On

RewriteCond %{THE_REQUEST} !\s/+(offers|page/company-a) [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?domain1\.com$ [NC]
RewriteRule ^ http://www.domain2.com%{REQUEST_URI} [L,R=301,NE]

# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

Make sure to clear your browser cache while testing.


问:
Angular2 how to change background color when drag & drop
I have a drag and drop container written in Angular 2 typescript. I want to change the background color of the drag & drop container while I am dragging a file into the container.

Typescript:

```<code>@HostListener('dragover', ['$event']) public onDragOver(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('dragleave', ['$event']) public onDragLeave(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('drop', ['$event']) public onDrop(evt){
 evt.preventDefault();
 evt.stopPropagation();
 let files = evt.dataTransfer.files;
 let valid_files : Array<File> = [];
 let invalid_files : Array<File> = [];
 if(files.length > 0){
   forEach(files, (file: File) =>{
     let ext = file.name.split('.')[file.name.split('.').length - 1];
     if(this.allowed_extensions.lastIndexOf(ext) != -1){
       valid_files.push(file);
     }else{
       invalid_files.push(file);
     }
   });
   this.filesChangeEmiter.emit(valid_files);
   this.filesInvalidEmiter.emit(invalid_files);
 }
}
</code>```

HTML:

```<code><div class="dropzone" (filesChangeEmiter)="onFilesChange($event)"
    (filesInvalidEmiter)="onFileInvalids($event)">
   <div class="centered">Drop your file here!</div>
</div>
</code>```

I tired to use HostBinding to change the background color, but it doesn't work. How can I detect dragging state and change its CSS?

答:
You can simply specify [ngStyle] in your tag as below.

Define one variable in component for back color like:

```<code>let backColor:string="transparent";
</code>```

Set above variable value in your drop event and use as below.

(1) Inline CSS with [ngStyle] like

(2) Return style from component like

```<code> private setStyles(): any {
    let styles = {
        'background-color': this.backColor
    };
    return styles;
}
</code>```

Body:
I have a drag and drop container written in Angular 2 typescript. I want to change the background color of the drag & drop container while I am dragging a file into the container.

Typescript:

@HostListener('dragover', ['$event']) public onDragOver(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('dragleave', ['$event']) public onDragLeave(evt){
 evt.preventDefault();
 evt.stopPropagation();
}

@HostListener('drop', ['$event']) public onDrop(evt){
 evt.preventDefault();
 evt.stopPropagation();
 let files = evt.dataTransfer.files;
 let valid_files : Array<File> = [];
 let invalid_files : Array<File> = [];
 if(files.length > 0){
   forEach(files, (file: File) =>{
     let ext = file.name.split('.')[file.name.split('.').length - 1];
     if(this.allowed_extensions.lastIndexOf(ext) != -1){
       valid_files.push(file);
     }else{
       invalid_files.push(file);
     }
   });
   this.filesChangeEmiter.emit(valid_files);
   this.filesInvalidEmiter.emit(invalid_files);
 }
}

HTML:

Drop your file here!

I tired to use HostBinding to change the background color, but it doesn't work. How can I detect dragging state and change its CSS?

Body:
You can simply specify [ngStyle] in your tag as below.

Define one variable in component for back color like:

let backColor:string="transparent";

Set above variable value in your drop event and use as below.

(1) Inline CSS with [ngStyle] like

(2) Return style from component like

 private setStyles(): any {
    let styles = {
        'background-color': this.backColor
    };
    return styles;
}


问:
App_Code Folder, ignore compile errors?
I am making use of the app code folder to write on the fly macros using a web UI, this is working well when there are no compilation errors on the macros but as soon as i save a type the whole application goes down and is not recoverable until i manually fix the error over ftp for example.

Is there a way i can have the compiler skip the building of the App_Code.dll if there are errors?

I am using ASP.NEt MVC if that is at all relevent.

答:
I received an answer to this in a comment, a more consistent way to do what i am trying to achieve was to use the CSScript library which allow on the fly dynamic compilation of C Sharp code from either a file location or an input string. This avoids having to compile it into the main assembly at build time. Its faster and safer and provides more flexibility than using the App_Code folder.

As a side note a hybrid approach could also be achieved where you could use CSScript to compile any script before saving it to the App_Code folder, this would avoid cases where you would save code with errors into the App_Code folder.

Title: App_Code Folder, ignore compile errors?


问:
Custom font not working in lollipop
Is there any way to use geomanist(custom) font in android lollipop.

But it works in all other version.

Here is my code

In MyApplication class

```<code>    FontsOverride.setDefaultFont(this, "DEFAULT", "geomanist-lightnew.ttf");
    FontsOverride.setDefaultFont(this, "MONOSPACE", "geomanist-lightnew.ttf");
    FontsOverride.setDefaultFont(this, "SERIF", "geomanist-lightnew.ttf");
    FontsOverride.setDefaultFont(this, "SANS_SERIF", "geomanist-lightnew.ttf");
</code>```

```<code>public final class FontsOverride {

public static void setDefaultFont(Context context,
                                  String staticTypefaceFieldName, String fontAssetName) {
    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
                                  final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}

}
</code>```

Thanks

答:
I use this Library and it works superbly on all devices

Step:-

1) Add this line in your gradle compile 'com.github.balrampandey19:FontOnText:0.0.1'

2) Add your font in asset folder like this

3) Then replace your view in xml with

```<code><com.balram.library.FotTextView
                    android:id="@+id/vno_tv"
                    .
                    .
                    android:textSize="14sp"
                    app:font="regular.ttf" />
</code>```

this line is important to set custom font you want app:font="regular.ttf"

You can do same for Buttons Edittext

OR

If you want to use same "Font" through whole application you can follow this Guide here

Title: Custom font not working in lollipop

Body:
Is there any way to use geomanist(custom) font in android lollipop.

But it works in all other version.

Here is my code

In MyApplication class

    FontsOverride.setDefaultFont(this, "DEFAULT", "geomanist-lightnew.ttf");
    FontsOverride.setDefaultFont(this, "MONOSPACE", "geomanist-lightnew.ttf");
    FontsOverride.setDefaultFont(this, "SERIF", "geomanist-lightnew.ttf");
    FontsOverride.setDefaultFont(this, "SANS_SERIF", "geomanist-lightnew.ttf");

public final class FontsOverride {

public static void setDefaultFont(Context context,
                                  String staticTypefaceFieldName, String fontAssetName) {
    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
                                  final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

}

}

Thanks

Body:
I use this Library and it works superbly on all devices

Step:-

1) Add this line in your gradle compile 'com.github.balrampandey19:FontOnText:0.0.1'

2) Add your font in asset folder like this

3) Then replace your view in xml with

<com.balram.library.FotTextView
                    android:id="@+id/vno_tv"
                    .
                    .
                    android:textSize="14sp"
                    app:font="regular.ttf" />

this line is important to set custom font you want app:font="regular.ttf"

You can do same for Buttons Edittext

OR

If you want to use same "Font" through whole application you can follow this Guide here


问:
How do I round a double to two decimal places in Java?
This is what I did to round a double to 2 decimal places:

```<code>amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}
</code>```

This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0!  What I want is both rounding as well as formatting to 2 decimal places.

答:
First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.

```<code>private static DecimalFormat df2 = new DecimalFormat("#.00");
</code>```

Now, apply the format to your double value:

```<code>double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12
</code>```

Note in case of double input = 32.1;

Then the output would be 32.10 and so on.

Body:
This is what I did to round a double to 2 decimal places:

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}

This works great if the amount = 25.3569 or something like that, but if the amount = 25.00 or the amount = 25.0, then I get 25.0!  What I want is both rounding as well as formatting to 2 decimal places.

Body:
First declare a object of DecimalFormat class. Note the argument inside the DecimalFormat is #.00 which means exactly 2 decimal places of rounding off.

private static DecimalFormat df2 = new DecimalFormat("#.00");

Now, apply the format to your double value:

double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12

Note in case of double input = 32.1;

Then the output would be 32.10 and so on.


答:
The root cause of the problem is badly written font files, so it
makes sense that the solution is to re-encode the offending font. You can use a online converting tool such as
http://www.freefontconverter.com/.

Another Alternative is using a library for custom fonts like https://github.com/chrisjenx/Calligraphy

```<code>dependencies {
            compile 'uk.co.chrisjenx:calligraphy:2.2.0'
        }
</code>```

Title: Custom font not working in lollipop

Body:
The root cause of the problem is badly written font files, so it
makes sense that the solution is to re-encode the offending font. You can use a online converting tool such as
http://www.freefontconverter.com/.

Another Alternative is using a library for custom fonts like https://github.com/chrisjenx/Calligraphy

dependencies {
            compile 'uk.co.chrisjenx:calligraphy:2.2.0'
        }


问:
Maximum sum subarray returning wrong output
Algorithm looks correct, not able to figure out where the mistake is. Code returns from 8 to 10 is max subarray with total of 32. But actual answer is 8 to 11 with total of 43.  </p>

```<code>import sys
import math

def maxtuple(lss,rss):
  if lss[2] > rss[2]:
      return lss
  else:
      return rss

def crosssubarray(A, start, mid, end):
  ls=rs=-sys.maxsize
  maxleft=0
  maxright=0
  sum = 0;
  for i in reversed(range(start, mid)):
    sum = sum + A[i]
    print(i)
    if sum > ls:
        ls = sum
        maxleft = i
  sum = 0
  for i in range(mid+1, end):
    sum = sum+ A[i]
    if sum > rs:
        rs = sum
        maxright = i
  return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
  if start == end:
    return (start,end,A[start])
  else:
    mid = (start+end)/2
    lss = maxsubarray(A, start, mid)
    rss = maxsubarray(A, mid+1, end)
    css = crosssubarray(A, start, mid, end)
    maxsub = maxtuple(lss,rss)
    maxall = maxtuple(maxsub, css)
    return maxall`enter code here`

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))
</code>```

答:
The problem is that range(start, mid) produces start,start+1,..,mid-1 but does not include mid.

This means that your crosssubarray does not include the middle value.

Instead try:

```<code>for i in reversed(range(start, mid+1)):
</code>```

Body:
Algorithm looks correct, not able to figure out where the mistake is. Code returns from 8 to 10 is max subarray with total of 32. But actual answer is 8 to 11 with total of 43.

import sys
import math

def maxtuple(lss,rss):
  if lss[2] > rss[2]:
      return lss
  else:
      return rss

def crosssubarray(A, start, mid, end):
  ls=rs=-sys.maxsize
  maxleft=0
  maxright=0
  sum = 0;
  for i in reversed(range(start, mid)):
    sum = sum + A[i]
    print(i)
    if sum > ls:
        ls = sum
        maxleft = i
  sum = 0
  for i in range(mid+1, end):
    sum = sum+ A[i]
    if sum > rs:
        rs = sum
        maxright = i
  return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
  if start == end:
    return (start,end,A[start])
  else:
    mid = (start+end)/2
    lss = maxsubarray(A, start, mid)
    rss = maxsubarray(A, mid+1, end)
    css = crosssubarray(A, start, mid, end)
    maxsub = maxtuple(lss,rss)
    maxall = maxtuple(maxsub, css)
    return maxall`enter code here`

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))

Body:
The problem is that range(start, mid) produces start,start+1,..,mid-1 but does not include mid.

This means that your crosssubarray does not include the middle value.

Instead try:

for i in reversed(range(start, mid+1)):


问:
Call an existing odoo 9 pos popup
In version 9.0c of odoo, specifically in the point of sale.

How can I call an existing popup? I understand that the way to do this process is very different with version 8.0c.

In 8.0c i use: self.pos_widget.screen_selector.show_popup("popup_name");

In 9.0 how i can call click_username?

答:
You can call base popup like this in odoo v9.

```<code> this.gui.show_popup('confirm',{});
</code>```

In the second argument, you can specify the title, body etc.

eg.

```<code>        this.gui.show_popup('confirm',{
            'title': _t('Destroy Current Order ?'),
            'body': _t('You will lose any data associated with the current order'),
            confirm: function(){
                self.pos.delete_current_order();
            },
        });
</code>```

Title: Call an existing odoo 9 pos popup

Body:
You can call base popup like this in odoo v9.

 this.gui.show_popup('confirm',{});

In the second argument, you can specify the title, body etc.

eg.

        this.gui.show_popup('confirm',{
            'title': _t('Destroy Current Order ?'),
            'body': _t('You will lose any data associated with the current order'),
            confirm: function(){
                self.pos.delete_current_order();
            },
        });


问:
Override open variable for class in Swift and SpriteKit for use in XCode's ActionEditor
I'm trying to make small platformer game, just in learning purposes. I've tried to animate character with array of SKTextures like this:

```<code>let animation: SKAction = SKAction.animate(
    with: frames.map {
        let texture : SKTexture = SKTexture(imageNamed: $0)
        texture.filteringMode = SKTextureFilteringMode.nearest

        return texture
    },
    timePerFrame: 0.15
)
</code>```

frames variable is array of SKTextures. I've used map to set filtering mode for each texture. This works fine and dandy, but than i've discovered that i can create animations (actions) in ActionEditor in XCode with AnimateWithTextures action. And here lies my problem. This is much more efficient, but i can't change filtering mode for textures in animation in ActionEditor. I've looked into SKTexture class and saw this:

```<code>open class SKTexture : NSObject, NSCopying, NSCoding {
    ...
    /**
    The filtering mode the texture should use when not drawn at native size. Defaults to SKTextureFilteringLinear.
    */
    open var filteringMode: SKTextureFilteringMode
    ...
}
</code>```

If i'm not mistaken open means that i can override variable, but i don't know how. I want to set default value of filteringMode to SKTextureFilteringMode.nearest for all SKTextures so ActionEditor will use textures with texture filtering set to nearest neighbor.

Also if you know how to set filtering mode for textures in specific action – i would like to know how to do it too. Thanks

答:
Unfortunately you can't override a variable without subclassing it, that is to do something like

```<code>class MyTexture: SKTexture {
</code>```

from there, you could override the variable:

```<code>  override var filteringMode: SKTextureFilteringMode {
    get {
      return .nearest
    }
    set {
    }
  }
</code>```

That should work, but now you can't change the filtering mode, ever (without going through a bunch of hooplah).

So the more apt way would be to set the default value via the initializer, but SKTexture has no public designated initializers, so that option is out of the window.

So your best bet is going to be the convenience init extension by Arie, or just make a plain function that returns a new texture:

```<code>func nearestTexture(imageNamed name: String) -> SKTexture {
   let newTex = SKTexture(imageNamed: name)
   newTex.filteringMode = .nearest
   return newTex
}

let texture: SKTexture = nearestTexture(imageNamed: "lol")
</code>```

Body:
I'm trying to make small platformer game, just in learning purposes. I've tried to animate character with array of SKTextures like this:

let animation: SKAction = SKAction.animate(
    with: frames.map {
        let texture : SKTexture = SKTexture(imageNamed: $0)
        texture.filteringMode = SKTextureFilteringMode.nearest

        return texture
    },
    timePerFrame: 0.15
)

frames variable is array of SKTextures. I've used map to set filtering mode for each texture. This works fine and dandy, but than i've discovered that i can create animations (actions) in ActionEditor in XCode with AnimateWithTextures action. And here lies my problem. This is much more efficient, but i can't change filtering mode for textures in animation in ActionEditor. I've looked into SKTexture class and saw this:

open class SKTexture : NSObject, NSCopying, NSCoding {
    ...
    /**
    The filtering mode the texture should use when not drawn at native size. Defaults to SKTextureFilteringLinear.
    */
    open var filteringMode: SKTextureFilteringMode
    ...
}

If i'm not mistaken open means that i can override variable, but i don't know how. I want to set default value of filteringMode to SKTextureFilteringMode.nearest for all SKTextures so ActionEditor will use textures with texture filtering set to nearest neighbor.

Also if you know how to set filtering mode for textures in specific action – i would like to know how to do it too. Thanks

Body:
Unfortunately you can't override a variable without subclassing it, that is to do something like

class MyTexture: SKTexture {

from there, you could override the variable:

  override var filteringMode: SKTextureFilteringMode {
    get {
      return .nearest
    }
    set {
    }
  }

That should work, but now you can't change the filtering mode, ever (without going through a bunch of hooplah).

So the more apt way would be to set the default value via the initializer, but SKTexture has no public designated initializers, so that option is out of the window.

So your best bet is going to be the convenience init extension by Arie, or just make a plain function that returns a new texture:

func nearestTexture(imageNamed name: String) -> SKTexture {
   let newTex = SKTexture(imageNamed: name)
   newTex.filteringMode = .nearest
   return newTex
}

let texture: SKTexture = nearestTexture(imageNamed: "lol")


问:
How to redirect from spring controller?
I have a MainRedirectController and all requests and responses will redirect from this controller. How can I send request parameter from mainRedirect method to page1 method and send response parameter from page1 method to mainRedirect method?

```<code>public class MainRedirectController{

  public ModelAndView mainRedirect(HttpServletRequest request, HttpServletResponse response) {
    String page = ServletRequestUtils.getStringParameter(request, "page", null);
    if(page.equals("page1")){
       //redirect request to page1 controller and
       //return reponse coming from page1 controller
    }else if(....){
       ...
    }

  }
}

public class Page1Controller{

  public ModelAndView page1(HttpServletRequest request, HttpServletResponse response) {
     response.getOutputStream().print("{\"completed\": \"1\"}");
     response.getOutputStream().flush();
     return null;
  }
}
</code>```

答:
You need to return "redirect:" view to that page.
Just use it as constructor parameter:

```<code>if(page.equals("page1")){
   return new ModelAndView("redirect:/page1MappingValue")
}
</code>```

page1MappingValue here is the address to your page1 depending on the mapping.

You can read more about redirects here:

http://www.baeldung.com/spring-redirect-and-forward

Also if you need to get a response just inside the method and you don't need return it directly, you can use RestTemplate-s:

https://spring.io/guides/gs/consuming-rest/

It will allow you to get a response and use it on the back-end inside your logic.

Title: How to redirect from spring controller?

Body:
I have a MainRedirectController and all requests and responses will redirect from this controller. How can I send request parameter from mainRedirect method to page1 method and send response parameter from page1 method to mainRedirect method?

public class MainRedirectController{

  public ModelAndView mainRedirect(HttpServletRequest request, HttpServletResponse response) {
    String page = ServletRequestUtils.getStringParameter(request, "page", null);
    if(page.equals("page1")){
       //redirect request to page1 controller and
       //return reponse coming from page1 controller
    }else if(....){
       ...
    }

  }
}

public class Page1Controller{

  public ModelAndView page1(HttpServletRequest request, HttpServletResponse response) {
     response.getOutputStream().print("{\"completed\": \"1\"}");
     response.getOutputStream().flush();
     return null;
  }
}

Body:
You need to return "redirect:" view to that page.
Just use it as constructor parameter:

if(page.equals("page1")){
   return new ModelAndView("redirect:/page1MappingValue")
}

page1MappingValue here is the address to your page1 depending on the mapping.

You can read more about redirects here:

http://www.baeldung.com/spring-redirect-and-forward

Also if you need to get a response just inside the method and you don't need return it directly, you can use RestTemplate-s:

https://spring.io/guides/gs/consuming-rest/

It will allow you to get a response and use it on the back-end inside your logic.


问:
UINavigation Problem
I want to navigate a class on a button click option in a View Controller class. Please give the way to do this. I am using the given following code to do this on a button click. </p>

```<code>- (void)buttonAction {
  Status *status = [[Status alloc] init];
  [self.navigationController pushViewController:status animated:YES];
}

// Status is a UIViewController subclass
</code>```

答:
```<code>(void)buttonAction
{
  Status *status = [[Status alloc]init];//this is not proper
  [self.navigationController pushViewController:status animated:YES];
}
</code>```

you must use

```<code>(void)buttonAction
{
  Status *status = [[Status alloc]initWithNibName:@"YourNib" bundle:nil];
  [self.navigationController pushViewController:status animated:YES];
  [status release];
}
</code>```

here your nib is the name of xib which you want to display.

Edit:

now you application is view based so

(void)buttonAction
    {
      so make object of appDelegate class(suppos objApp)
      now,

```<code>  Status *status = [[Status alloc]initWithNibName:@"YourNib" bundle:nil];
  [objApp.window addSubview:status.view];
  [status release];
}
</code>```

Title: UINavigation Problem

Body:
I want to navigate a class on a button click option in a View Controller class. Please give the way to do this. I am using the given following code to do this on a button click.

- (void)buttonAction {
  Status *status = [[Status alloc] init];
  [self.navigationController pushViewController:status animated:YES];
}

// Status is a UIViewController subclass

Body:
(void)buttonAction
{
  Status *status = [[Status alloc]init];//this is not proper
  [self.navigationController pushViewController:status animated:YES];
}

you must use

(void)buttonAction
{
  Status *status = [[Status alloc]initWithNibName:@"YourNib" bundle:nil];
  [self.navigationController pushViewController:status animated:YES];
  [status release];
}

here your nib is the name of xib which you want to display.

Edit:

now you application is view based so

(void)buttonAction
    {
      so make object of appDelegate class(suppos objApp)
      now,

  Status *status = [[Status alloc]initWithNibName:@"YourNib" bundle:nil];
  [objApp.window addSubview:status.view];
  [status release];
}


问:
Module '...node_modules/ionic-angular/index"' has no exported member 'Page'
i followed the instcructions of this tutorial:
https://www.thepolyglotdeveloper.com/2016/02/add-barcode-scanning-functionality-to-your-ionic-2-app/
However, starting the app, I get the error message:

Typescript Error
  'Module "Path/node_modules/ionic-angular/index"'
  has no exported member 'Page'.

My Code is:

```<code>import {Page, Platform, Alert, NavController} from 'ionic-angular';

@Page({
    templateUrl: 'build/pages/home/home.html'
})

export class HomePage {
static get parameters() {
    return [[Platform], [NavController]];
}

constructor(platform, navController) {
    this.platform = platform;
    this.navController = navController;
}

scan() {
    this.platform.ready().then(() => {
        cordova.plugins.barcodeScanner.scan((result) => {
            this.nav.present(Alert.create({
                title: "Scan Results",
                subTitle: result.text,
                buttons: ["Close"]
            }));
        }, (error) => {
            this.nav.present(Alert.create({
                title: "Attention!",
                subTitle: error,
                buttons: ["Close"]
            }));
        });
    });
}
}
</code>```

I have absolutely no Idea what to do. I am also new in Ionic, therefore I do not know what to do.

答:
Use @Component instead of @Page.
@Page is now deprecated

Checkout https://forum.ionicframework.com/t/difference-between-page-and-component/55287

Body:
i followed the instcructions of this tutorial:
https://www.thepolyglotdeveloper.com/2016/02/add-barcode-scanning-functionality-to-your-ionic-2-app/
However, starting the app, I get the error message:

Typescript Error
  'Module "Path/node_modules/ionic-angular/index"'
  has no exported member 'Page'.

My Code is:

import {Page, Platform, Alert, NavController} from 'ionic-angular';

@Page({
    templateUrl: 'build/pages/home/home.html'
})

export class HomePage {
static get parameters() {
    return [[Platform], [NavController]];
}

constructor(platform, navController) {
    this.platform = platform;
    this.navController = navController;
}

scan() {
    this.platform.ready().then(() => {
        cordova.plugins.barcodeScanner.scan((result) => {
            this.nav.present(Alert.create({
                title: "Scan Results",
                subTitle: result.text,
                buttons: ["Close"]
            }));
        }, (error) => {
            this.nav.present(Alert.create({
                title: "Attention!",
                subTitle: error,
                buttons: ["Close"]
            }));
        });
    });
}
}

I have absolutely no Idea what to do. I am also new in Ionic, therefore I do not know what to do.


问:
Android Error: This class should be public [Instantiatable]
I'm facing some trouble with android studio, my coding is fine, and it worked when I run to device, but somehow its error when I generate signed APK

here are the error messages:

```<code>Error:(25) Error: This class should be public (com.myapp.SoundLevelView) [Instantiatable]
</code>```

heres my coding :

```<code>public SoundLevelView(Context context, AttributeSet attrs) {
            super(context, attrs);

            mGreen  = context.getResources().getDrawable(
                    R.drawable.greenbar);
            mRed    = context.getResources().getDrawable(
                    R.drawable.redbar);

            mWidth  = mGreen.getIntrinsicWidth();
            setMinimumWidth(mWidth*10);

            mHeight = mGreen.getIntrinsicHeight();
            setMinimumHeight(mHeight);

            //Used to paint canvas background color
            mBackgroundPaint = new Paint();
            mBackgroundPaint.setColor(Color.BLACK);

        }
</code>```

I try to disable Lint from Android Preferences and add

```<code>lintOptions {
        abortOnError false
    }
</code>```

to my grade. inside android tag. but its seems not work either.
anybody facing the same problem as me?

Note: I try to Invalidated Cache and Restart too, but not working

答:
Try this :</p>

```<code>public class SoundLevelView(Context context, AttributeSet attrs) {
            super(context, attrs);

            mGreen  = context.getResources().getDrawable(
                    R.drawable.greenbar);
            mRed    = context.getResources().getDrawable(
                    R.drawable.redbar);

            mWidth  = mGreen.getIntrinsicWidth();
            setMinimumWidth(mWidth*10);

            mHeight = mGreen.getIntrinsicHeight();
            setMinimumHeight(mHeight);

            //Used to paint canvas background color
            mBackgroundPaint = new Paint();
            mBackgroundPaint.setColor(Color.BLACK);

        }
</code>```

Body:
I'm facing some trouble with android studio, my coding is fine, and it worked when I run to device, but somehow its error when I generate signed APK

here are the error messages:

Error:(25) Error: This class should be public (com.myapp.SoundLevelView) [Instantiatable]

heres my coding :

public SoundLevelView(Context context, AttributeSet attrs) {
            super(context, attrs);

            mGreen  = context.getResources().getDrawable(
                    R.drawable.greenbar);
            mRed    = context.getResources().getDrawable(
                    R.drawable.redbar);

            mWidth  = mGreen.getIntrinsicWidth();
            setMinimumWidth(mWidth*10);

            mHeight = mGreen.getIntrinsicHeight();
            setMinimumHeight(mHeight);

            //Used to paint canvas background color
            mBackgroundPaint = new Paint();
            mBackgroundPaint.setColor(Color.BLACK);

        }

I try to disable Lint from Android Preferences and add

lintOptions {
        abortOnError false
    }

to my grade. inside android tag. but its seems not work either.
anybody facing the same problem as me?

Note: I try to Invalidated Cache and Restart too, but not working

Body:
Try this :

public class SoundLevelView(Context context, AttributeSet attrs) {
            super(context, attrs);

            mGreen  = context.getResources().getDrawable(
                    R.drawable.greenbar);
            mRed    = context.getResources().getDrawable(
                    R.drawable.redbar);

            mWidth  = mGreen.getIntrinsicWidth();
            setMinimumWidth(mWidth*10);

            mHeight = mGreen.getIntrinsicHeight();
            setMinimumHeight(mHeight);

            //Used to paint canvas background color
            mBackgroundPaint = new Paint();
            mBackgroundPaint.setColor(Color.BLACK);

        }


问:
Can I use same Admob Account for different Google play developers account?
currently I am having One Google play account for games and apps.I am planning to create new google play account which will consist of only games and my old account will hold the apps.But I want to use single admob account for both google play accounts,so that revenue generated by both games and apps will be at same place.

In short,Can I use same Admob Account for different Google play developers account?
is it legal?

答:
absolutely yes!

it's okay to use multi google play accounts with one Admob account.


问:
how to count number of trimester using weeks
i want to display trimester in my app and i don't know how to display please help me how to do.and here is my code for week display.
Thank you

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

```<code>    sharedpreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);

    Bundle b = getIntent().getExtras();

    txt_date = (TextView) findViewById(R.id.Date_Value);
    txt_week = (TextView) findViewById(R.id.Week_Value);
    txt_baby = (TextView) findViewById(R.id.Baby_Value);
    txt_mother = (TextView) findViewById(R.id.Mother_Value);
    txt_tremester = (TextView) findViewById(R.id.Tremester_Value);

    txt_baby.setText(b.getCharSequence("baby_name"));
    txt_mother.setText(b.getCharSequence("mother_name"));
    txt_tremester.setText(b.getCharSequence("tremester"));

    img_week = (ImageView) findViewById(R.id.image_week);
    img_slide = (ImageView) findViewById(R.id.image_slide);
    img_BMI = (ImageView) findViewById(R.id.image_BMI);
    img_setting = (ImageView) findViewById(R.id.image_setting);
    //img_week = (ImageView) findViewById(R.id.image_week);

    String dob = sharedpreferences.getString("dob", null);

    final Calendar c = Calendar.getInstance();
    year  = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day   = c.get(Calendar.DAY_OF_MONTH);

    txt_date.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(year).append("-").append(month + 1).append("-").append(day));

    String current_dob = txt_date.getText().toString();

    StringTokenizer current_tokens = new StringTokenizer(current_dob, "-");
    current_year = current_tokens.nextToken();
    current_month = current_tokens.nextToken();
    current_date = current_tokens.nextToken();

    System.out.println("year==>"+Integer.parseInt(current_year));
    System.out.println("month==>"+Integer.parseInt(current_month));
    System.out.println("date==>"+Integer.parseInt(current_date));

    StringTokenizer tokens = new StringTokenizer(dob, "-");
    selected_year = tokens.nextToken();
    selected_month = tokens.nextToken();
    selected_date = tokens.nextToken();

    System.out.println("year==>"+Integer.parseInt(selected_year));
    System.out.println("month==>"+Integer.parseInt(selected_month));
    System.out.println("date==>"+Integer.parseInt(selected_date));

    getNoOfWeek();

    if(test == true)
    {
        txt_week.setText(String.valueOf(week));
    }
    else
    {
        txt_week.setText(" ");
    }
    img_week.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
 }

private void getNoOfWeek() {

    Calendar date1 = Calendar.getInstance();
    Calendar date2 = Calendar.getInstance();

    date1.clear();
    date1.set(Integer.parseInt(selected_year),Integer.parseInt(selected_month),Integer.parseInt(selected_date)); // set date 1 (yyyy,mm,dd)
    System.out.println("Selected Date==>>"+date1);

    date2.clear();
    date2.set(Integer.parseInt(current_year),Integer.parseInt(current_month),Integer.parseInt(current_date));
    System.out.println("Current Date==>>"+date2);

    long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
    float dayCount = (float) diff / (24 * 60 * 60 * 1000);
    week = (int) (dayCount / 7);

    if(week <= 0)
    {
        Toast.makeText(this, "Sry System Error", Toast.LENGTH_SHORT).show();
        System.out.println("Week==>>"+week);
        test=false;
    }
    else
    {
        Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
        System.out.println("Week==>>"+week);
        test=true;
    }
    System.out.println("Week==>>"+week);

}
</code>```

答:
try this code,it's work properly</p>

```<code>   if (week >= 0 && week <= 12) {
            trimester = 1;
            System.out.print("trimester ==> 1" + trimester);
            txt_tremester.setText(String.valueOf(trimester));
        } else if (week >= 13 && week <= 27) {
            trimester = 2;
            System.out.print("trimester ==> 2" + trimester);
            txt_tremester.setText(String.valueOf(trimester));
        } else if (week >= 28 && week <= 42) {
            trimester = 3;
            System.out.print("trimester ==>3" + trimester);
            txt_tremester.setText(String.valueOf(trimester));
        }
</code>```

Body:
i want to display trimester in my app and i don't know how to display please help me how to do.and here is my code for week display.
Thank you

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

    sharedpreferences = getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);

    Bundle b = getIntent().getExtras();

    txt_date = (TextView) findViewById(R.id.Date_Value);
    txt_week = (TextView) findViewById(R.id.Week_Value);
    txt_baby = (TextView) findViewById(R.id.Baby_Value);
    txt_mother = (TextView) findViewById(R.id.Mother_Value);
    txt_tremester = (TextView) findViewById(R.id.Tremester_Value);

    txt_baby.setText(b.getCharSequence("baby_name"));
    txt_mother.setText(b.getCharSequence("mother_name"));
    txt_tremester.setText(b.getCharSequence("tremester"));

    img_week = (ImageView) findViewById(R.id.image_week);
    img_slide = (ImageView) findViewById(R.id.image_slide);
    img_BMI = (ImageView) findViewById(R.id.image_BMI);
    img_setting = (ImageView) findViewById(R.id.image_setting);
    //img_week = (ImageView) findViewById(R.id.image_week);

    String dob = sharedpreferences.getString("dob", null);

    final Calendar c = Calendar.getInstance();
    year  = c.get(Calendar.YEAR);
    month = c.get(Calendar.MONTH);
    day   = c.get(Calendar.DAY_OF_MONTH);

    txt_date.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(year).append("-").append(month + 1).append("-").append(day));

    String current_dob = txt_date.getText().toString();

    StringTokenizer current_tokens = new StringTokenizer(current_dob, "-");
    current_year = current_tokens.nextToken();
    current_month = current_tokens.nextToken();
    current_date = current_tokens.nextToken();

    System.out.println("year==>"+Integer.parseInt(current_year));
    System.out.println("month==>"+Integer.parseInt(current_month));
    System.out.println("date==>"+Integer.parseInt(current_date));

    StringTokenizer tokens = new StringTokenizer(dob, "-");
    selected_year = tokens.nextToken();
    selected_month = tokens.nextToken();
    selected_date = tokens.nextToken();

    System.out.println("year==>"+Integer.parseInt(selected_year));
    System.out.println("month==>"+Integer.parseInt(selected_month));
    System.out.println("date==>"+Integer.parseInt(selected_date));

    getNoOfWeek();

    if(test == true)
    {
        txt_week.setText(String.valueOf(week));
    }
    else
    {
        txt_week.setText(" ");
    }
    img_week.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
 }

private void getNoOfWeek() {

    Calendar date1 = Calendar.getInstance();
    Calendar date2 = Calendar.getInstance();

    date1.clear();
    date1.set(Integer.parseInt(selected_year),Integer.parseInt(selected_month),Integer.parseInt(selected_date)); // set date 1 (yyyy,mm,dd)
    System.out.println("Selected Date==>>"+date1);

    date2.clear();
    date2.set(Integer.parseInt(current_year),Integer.parseInt(current_month),Integer.parseInt(current_date));
    System.out.println("Current Date==>>"+date2);

    long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
    float dayCount = (float) diff / (24 * 60 * 60 * 1000);
    week = (int) (dayCount / 7);

    if(week <= 0)
    {
        Toast.makeText(this, "Sry System Error", Toast.LENGTH_SHORT).show();
        System.out.println("Week==>>"+week);
        test=false;
    }
    else
    {
        Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
        System.out.println("Week==>>"+week);
        test=true;
    }
    System.out.println("Week==>>"+week);

}

Body:
try this code,it's work properly

   if (week >= 0 && week <= 12) {
            trimester = 1;
            System.out.print("trimester ==> 1" + trimester);
            txt_tremester.setText(String.valueOf(trimester));
        } else if (week >= 13 && week <= 27) {
            trimester = 2;
            System.out.print("trimester ==> 2" + trimester);
            txt_tremester.setText(String.valueOf(trimester));
        } else if (week >= 28 && week <= 42) {
            trimester = 3;
            System.out.print("trimester ==>3" + trimester);
            txt_tremester.setText(String.valueOf(trimester));
        }


问:
Access current route name from a controller or component
I needs to apply an "active" class to a bootstrap tab depending on the current route name.  The route object contains "routeName" but how to I access this from a controller or component?</p>

答:
Using insights from @maharaja-santhir's answer, one can think of setting the routeName property on the target controller to use, e.g., in the target's template. This way there's no need for defining the logic in multiple locations and hence code-reusability. Here's an example of how to accomplish that:

```<code>// app/routes/application.js
export default Ember.Route.extend({
    ...

    actions: {
        willTransition(transition) {
            let targetController = this.controllerFor(transition.targetName);
            set(targetController, 'currentRouteName', transition.targetName);
            return true;
        }
    }
});
</code>```

Defining this willTransition action in the application route allows for propagating the current route name to anywhere in the application. Note that the target controller will retain the currentRouteName property setting even after navigating away to another route. This requires manual cleanup, if needed, but it might be acceptable depending on your implementation and use case.

Body:
Using insights from @maharaja-santhir's answer, one can think of setting the routeName property on the target controller to use, e.g., in the target's template. This way there's no need for defining the logic in multiple locations and hence code-reusability. Here's an example of how to accomplish that:

// app/routes/application.js
export default Ember.Route.extend({
    ...

    actions: {
        willTransition(transition) {
            let targetController = this.controllerFor(transition.targetName);
            set(targetController, 'currentRouteName', transition.targetName);
            return true;
        }
    }
});

Defining this willTransition action in the application route allows for propagating the current route name to anywhere in the application. Note that the target controller will retain the currentRouteName property setting even after navigating away to another route. This requires manual cleanup, if needed, but it might be acceptable depending on your implementation and use case.


问:
how can i track users without cookies
ok... im looking to have a good round of brainstorming here...

say i was google... the adword/adsense/analytics division. i would be getting a little worried about the future, when users start to disable cookies (or at least delete them on a regular basis), use private browsing, roam on multiple devices. how could google alternatively track users without the benefits of cookies?

some ideas to get started (please elaborate on these and any others):

-track users using some other persistent local/client side storage

-use user-agent string fingerprinting

-test cache response - if user 304's an image, they were here

-track mac address

-any random/out of the box ideas?

答:
If your site requires user tracking, then I would have it fail to work if cookies are disabled. Then focus your time and effort on making it a fantastic site for the vast majority of your visitors, and don't worry about the ones who, for whatever reason, have made the explicit decision to disable cookies.

(Made this a CW answer because this is a subjective question that's likely to be closed.)

Title: how can i track users without cookies


问:
Tree Hierarchy in Oracle
I just came across this question from 'HackerRank'.
The BST table contains two columns, N and P. N stands for Node, P stands for Parent:

```<code> N  P
-- --
 1  2
 3  2
 6  8
 9  8
 2  5
 8  5
 5  null
</code>```

Sample Output should be:

1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf
```

<p>What I have tried is : </p>

```select     N,
           case
               when level = 3 then 'leaf'
               when level = 2 then 'inner'
               else 'root'
           end
from       BST
start with P is NULL
connect by P = prior N
order by   N;
```

Although it gives the correct result, I  am not happy with the code as it hardcodes the name (whether it should be leaf, inner or root). Also this code will fail when there are multiple hierarchies in the tree.

Can someone please suggest any other elegant way of writing the same code so that it does not fail for multiple hierarchy?

答:
Oracle provides a pseudocolumn  CONNECT_BY_ISLEAF to test for leafiness. The test for root is the same as the START WITH clause. Anything else is inner. So this should do you

```<code>select N ,
    case
        when CONNECT_BY_ISLEAF =  1 then 'leaf'
        WHEN P is NULL then 'root'
        else 'inner'
    end
from BST
start with P is NULL
connect by P = prior  N
order  by N;
</code>```

Title: Tree Hierarchy in Oracle

Body:
I just came across this question from 'HackerRank'.
The BST table contains two columns, N and P. N stands for Node, P stands for Parent:

 N  P
-- --
 1  2
 3  2
 6  8
 9  8
 2  5
 8  5
 5  null

Sample Output should be:

1 leaf
2 inner
3 leaf
5 root
6 leaf
8 inner
9 leaf

What I have tried is :

select     N,
           case
               when level = 3 then 'leaf'
               when level = 2 then 'inner'
               else 'root'
           end
from       BST
start with P is NULL
connect by P = prior N
order by   N;

Although it gives the correct result, I  am not happy with the code as it hardcodes the name (whether it should be leaf, inner or root). Also this code will fail when there are multiple hierarchies in the tree.

Can someone please suggest any other elegant way of writing the same code so that it does not fail for multiple hierarchy?

Body:
Oracle provides a pseudocolumn  CONNECT_BY_ISLEAF to test for leafiness. The test for root is the same as the START WITH clause. Anything else is inner. So this should do you

select N ,
    case
        when CONNECT_BY_ISLEAF =  1 then 'leaf'
        WHEN P is NULL then 'root'
        else 'inner'
    end
from BST
start with P is NULL
connect by P = prior  N
order  by N;


问:
Right alignment of ionic icons
I want to right align ion icon by default they are appearing in left side. How can i do this? Can anybody help me?</p>

```<code><div class="bar bar-footer no-line ">
    <i class="icon ion-ios-navigate-outline icon"></i>
    <i class="icon ion-document-text icon "></i>
</div>
</code>```

答:
This is because .bar has a display:flex property as per ionic.css

So a justify-content: flex-end; should work for you.

Note the flex-right class i added to the bar-footer.

See the following snippet:

.flex-right {
  justify-content: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.3.2/css/ionic.min.css" rel="stylesheet" />
<div class="bar bar-footer no-line flex-right">
  <i class="icon ion-ios-navigate-outline icon"></i>
  <i class="icon ion-document-text icon"></i>
</div></code>```

Title: Right alignment of ionic icons

Body:
This is because .bar has a display:flex property as per ionic.css

So a justify-content: flex-end; should work for you.

Note the flex-right class i added to the bar-footer.

See the following snippet:

.flex-right {
  justify-content: flex-end;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/ionic/1.3.2/css/ionic.min.css" rel="stylesheet" />
<div class="bar bar-footer no-line flex-right">
  <i class="icon ion-ios-navigate-outline icon"></i>
  <i class="icon ion-document-text icon"></i>
</div>


问:
How to get last modified timestamp of an external file?
How to get last modified timestamp of an external file?

I'm trying to use using xhr.getResponseHeader("Last-Modified"), and I am getting the pervious modified time, but not the recent modified timestamp.
e.g: Fri, 02 Jun 2017 04:39:18 GMT whereas I should get today's date.

答:
You can use get response as a Blob, pass Blob to File constructor to get .lastModifiedDate property value

```<code>fetch("/path/to/file")
.then(response => response.blob())
.then(blob => {
  const file = new File([blob], blob.name);
  console.log(file.lastModifiedDate, file.lastModified);
});
</code>```

Body:
You can use get response as a Blob, pass Blob to File constructor to get .lastModifiedDate property value

fetch("/path/to/file")
.then(response => response.blob())
.then(blob => {
  const file = new File([blob], blob.name);
  console.log(file.lastModifiedDate, file.lastModified);
});


问:
how to debug python click cli application?
I have built a cli application using the click library in python. There is no documentation on how to debug commands. </p>

<p>Without click, its easy to just debug python files in IDE, but when we use click, the commands need to be run through console_scripts setup in setup.py. </p>

答:
If you are looking to debug the modules/classes that are executed after click command functions.

An affordable solution is to create a script that simulates the flow that is performed after executing the command.

Then by placing debug points in the required lines you can achieve the debug functionality.

This is what I figured to do after a brief web search.

Body:
I have built a cli application using the click library in python. There is no documentation on how to debug commands.

Without click, its easy to just debug python files in IDE, but when we use click, the commands need to be run through console_scripts setup in setup.py.