问:
Mysql Select Empty Cells not showing [WHERE part]
I'm doing a software for payment control as a freelance, but I have a few issues about mysql.
I have a table that works as a log, called "Bitacora". In the table I have a column named idCliente, that it is the id of a person in its own table, because I have another table named "Cliente" with a column named "idCliente" so when i do the select I expect to show the name of the client.

The example below shows how the table "Bitacora" works with 3 rows.

```<code>idBitacora, tipoBitacora, **idCliente**, idPago, idPagoVario, fecha, razon

'1', '1', **'6',** '-1', '-1', '2017-05-06 21:52:53', ''

'2', '1', **'7',** '-1', '-1', '2017-05-06 21:53:01', ''

'3', '1', **'-1',** '-1', '-1', '2017-05-06 22:19:33', ''
</code>```

So I made a select query

```<code>> SELECT **IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso** , IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;
</code>```

The bold above its a conditional to know what kind of log it is.

```<code>> SELECT IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso , **IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente** FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;
</code>```

And the bold above its a conditional I made to make sure that if there is no client in cliente.idCliente the row can still show up, but in my results the one with the bitacora.idCliente that doesnt appear in Cliente (-1) doesnt show, so with the example of the first table shown, the query only return

```<code>> Cliente Agregado |Mark
> Cliente Agregado |Zack
</code>```

But I want to get

```<code>> Cliente Agregado |Mark
>
> Cliente Agregado |Zack
>
> Cliente Agregado |(nothing)
</code>```

And I have tried, but still can't get what I want, I think its because the WHERE part. But still cant figure it out, after days, I think a need some help please.

答:
You're using the wrong construct. You should be using case… else. That doesn't mean you can't continue as you are, but you'd be better with:

```<code>case
  when bitacora.tipoBitacora = 2 then 'Cliente Borrado'
  when bitacora.tipoBitacora = 3 then 'Cliente Editado'
  else 'nothing'
end as `my_column`
</code>```

Body:
I'm doing a software for payment control as a freelance, but I have a few issues about mysql.
I have a table that works as a log, called "Bitacora". In the table I have a column named idCliente, that it is the id of a person in its own table, because I have another table named "Cliente" with a column named "idCliente" so when i do the select I expect to show the name of the client.

The example below shows how the table "Bitacora" works with 3 rows.

idBitacora, tipoBitacora, **idCliente**, idPago, idPagoVario, fecha, razon

'1', '1', **'6',** '-1', '-1', '2017-05-06 21:52:53', ''

'2', '1', **'7',** '-1', '-1', '2017-05-06 21:53:01', ''

'3', '1', **'-1',** '-1', '-1', '2017-05-06 22:19:33', ''

So I made a select query

> SELECT **IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso** , IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;

The bold above its a conditional to know what kind of log it is.

> SELECT IF(bitacora.tipoBitacora = 1, 'Cliente Agregado',
> IF(bitacora.tipoBitacora = 2, 'Cliente Borrado',
> IF(bitacora.tipoBitacora = 3, 'Cliente Editado',
> IF(bitacora.tipoBitacora = 4, 'Pago Mensual', IF(bitacora.tipoBitacora
> = 5, 'Pago Vario', IF(bitacora.tipoBitacora = 6, 'Intento Clave Fallida', 'Desconocido')))))) AS Suceso , **IF(bitacora.idCliente =
> -1, '', cliente.idCliente) as idCliente** FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;

And the bold above its a conditional I made to make sure that if there is no client in cliente.idCliente the row can still show up, but in my results the one with the bitacora.idCliente that doesnt appear in Cliente (-1) doesnt show, so with the example of the first table shown, the query only return

> Cliente Agregado |Mark
> Cliente Agregado |Zack

But I want to get

> Cliente Agregado |Mark
>
> Cliente Agregado |Zack
>
> Cliente Agregado |(nothing)

And I have tried, but still can't get what I want, I think its because the WHERE part. But still cant figure it out, after days, I think a need some help please.

Body:
You're using the wrong construct. You should be using case… else. That doesn't mean you can't continue as you are, but you'd be better with:

case
  when bitacora.tipoBitacora = 2 then 'Cliente Borrado'
  when bitacora.tipoBitacora = 3 then 'Cliente Editado'
  else 'nothing'
end as `my_column`


来源: stackexchange

问:
Django - run a function every x seconds
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is -

```<code>def shut_down(request):
  # Do some stuff
  while True:
    result = some_fn()
    if result:
      break
    time.sleep(2)

  return True
</code>```

While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it.

This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True)

EDIT -

Reading Oz123's response gave me an idea which seems to work. Here's what I did -

```<code>def shut_down(params):
    # Do some stuff
    # Offload the blocking job to a new thread

    t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
    t.setDaemon(True)
    t.start()

    return True

def some_fn(id):
    while True:
        # Do the job, get result in res
        # If the job is done, return. Or sleep the thread for 2 seconds before trying again.

        if res:
            return
        else:
            time.sleep(2)
</code>```

This does the job for me. It's simple but I don't know how efficient multithreading is in conjunction with Django.

If anyone can point out pitfalls of this, criticism is appreciated.

答:
I recommend you use Celery's task management. You can refer this to set up this app (package if you're from javaScript background).

Once set, you can alter the code to:

```<code>@app.task
def check_shut_down():
    if not some_fun():
        # add task that'll run again after 2 secs
        check_shut_down.delay((), countdown=3)
    else:
        # task completed; do something to notify yourself
        return True
</code>```

ContentLicense: CC BY-SA 3.0

Title: Django - run a function every x seconds

Body:
I'm working on a Django app. I have an API endpoint, which if requested, must carry out a function that must be repeated a few times (until a certain condition is true). How I'm dealing with it right now is -

def shut_down(request):
  # Do some stuff
  while True:
    result = some_fn()
    if result:
      break
    time.sleep(2)

  return True

While I know that this is a terrible approach and that I shouldn't be blocking for 2 seconds, I can't figure out how to get around it.

This works, after say a wait of 4 seconds. But I'd like something that keeps the loop running in the background, and stop once some_fn returns True. (Also, it is certain that some_fn will return True)

EDIT -

Reading Oz123's response gave me an idea which seems to work. Here's what I did -

def shut_down(params):
    # Do some stuff
    # Offload the blocking job to a new thread

    t = threading.Thread(target=some_fn, args=(id, ), kwargs={})
    t.setDaemon(True)
    t.start()

    return True

def some_fn(id):
    while True:
        # Do the job, get result in res
        # If the job is done, return. Or sleep the thread for 2 seconds before trying again.

        if res:
            return
        else:
            time.sleep(2)

This does the job for me. It's simple but I don't know how efficient multithreading is in conjunction with Django.

If anyone can point out pitfalls of this, criticism is appreciated.

Body:
I recommend you use Celery's task management. You can refer this to set up this app (package if you're from javaScript background).

Once set, you can alter the code to:

@app.task
def check_shut_down():
    if not some_fun():
        # add task that'll run again after 2 secs
        check_shut_down.delay((), countdown=3)
    else:
        # task completed; do something to notify yourself
        return True


问:
Excel get Day Name gives an Error
So I have been stuck at this weird error with excel 2010. I have the following data at cell A4 which is a reference to another cell B1, which is a start date entered by user, and I am trying to  get day name by using the formula
=CHOOSE(WEEKDAY(B4),"Su","Mo","Tu","We","Th","Fr","Sa"), yet it gives an error with no real clues. Also I have tried

```<code>=Text(B4, "dddd")
</code>```

and it gives an error as well.

Any ideas?

答: The issue is that, depending on regional settings, you should use semicolon ; instead of comma , as separator in formulas.

Title: Excel get Day Name gives an Error

Body:
So I have been stuck at this weird error with excel 2010. I have the following data at cell A4 which is a reference to another cell B1, which is a start date entered by user, and I am trying to  get day name by using the formula
=CHOOSE(WEEKDAY(B4),"Su","Mo","Tu","We","Th","Fr","Sa"), yet it gives an error with no real clues. Also I have tried

=Text(B4, "dddd")

and it gives an error as well.

Any ideas?


问:
Strip Html Tags In Ionic?
Using ionic 3 I have fetched some data from wordpress api and am then displaying the same on app UI. Everything seems to work fine except the HTML tags included in the content. The html tags are printed too. I have referred to some resources that suggested the following code :-

```<code>`var app = angular.module('myHDApp', []);

    app.filter('removeHTMLTags', function() {

    return function(text) {

        return  text ? String(text).replace(/<[^>]+>/gm, '') : '';

};

});
</code>```

I have implemented the above function in my .ts code but it does not seems to work for me as I still get the HTML tags in the content.

答:
What you have found is for ionic v1. In ionic 3, you have to create a pipe first.

In your cli,

```<code>ionic g pipe removehtmltags
</code>```

You can find your newly created pipe under src/pipes. Now in your removehtmltags.ts,

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'removehtmltag',
})
export class RemovehtmltagPipe implements PipeTransform {
  /**
   * Takes a value and makes it lowercase.
   */
  transform(value: string) {
           if(value){
               var result = value.replace(/<\/?[^>]+>/gi, ""); //removing html tag using regex pattern
              return result;
           }
           else{}

  }
}
</code>```

You can now use this pipe in your html files like this,

```<code><p>{{yourData | removehtmltag}}</p>
</code>```

Title: Strip Html Tags In Ionic?

Body:
Using ionic 3 I have fetched some data from wordpress api and am then displaying the same on app UI. Everything seems to work fine except the HTML tags included in the content. The html tags are printed too. I have referred to some resources that suggested the following code :-

`var app = angular.module('myHDApp', []);

    app.filter('removeHTMLTags', function() {

    return function(text) {

        return  text ? String(text).replace(/<[^>]+>/gm, '') : '';

};

});

I have implemented the above function in my .ts code but it does not seems to work for me as I still get the HTML tags in the content.

Body:
What you have found is for ionic v1. In ionic 3, you have to create a pipe first.

In your cli,

ionic g pipe removehtmltags

You can find your newly created pipe under src/pipes. Now in your removehtmltags.ts,

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'removehtmltag',
})
export class RemovehtmltagPipe implements PipeTransform {
  /**
   * Takes a value and makes it lowercase.
   */
  transform(value: string) {
           if(value){
               var result = value.replace(/<\/?[^>]+>/gi, ""); //removing html tag using regex pattern
              return result;
           }
           else{}

  }
}

You can now use this pipe in your html files like this,

<p>{{yourData | removehtmltag}}</p>


问:
Problem logging out user on chat applet
I wish for users of a Java chat applet to be automatically logged out when closing the browser window.

I currently use the following:

```<code>public void destroy() {
    sendLogoutMessage();
}
</code>```

However this only works 3/4 of the time (probably due to network delays).

The chat applet pings the server and logs them out after 90 seconds (this allows them to reconnect due to any internet problems) - so they do get removed eventually, however I would like a way to better catch the close event.

答:
I think that your code does not work in 100% cases because it is called in destroy method that does not wait and closes everything including network connections being opened. So, sometimes if network is slow the applet together with its output streams is killed before it sends the logout message to server.

If my theory is correct you can probably check it.

Try to see whether you get logout command in server logs (in case of failure). I believe that you will find that command did not arrive.

Open java console on client side. You will probably get IOException or SocketException. I hope that examining of the exception may give you an idea how to improve the solution.

Additionally I'd suggest the following.

Add servlet session listener on server side and logout automatically when session is expired.

Decrease time-to-live of HTTP session to reasonable number. Default value for JBoss is 20 minutes, so make it 1 minute.

Implement keep-alive mechanims from your applet. It may be very simple. Just perform HTTP GET every 30 seconds to special URL that does nothing. This will keep your session alive.

This solution should be an addition to your existing solution that works 3/4 of the times.

I hope this helps. Good luck.

ContentLicense: CC BY-SA 2.5

Title: Problem logging out user on chat applet

Body:
I wish for users of a Java chat applet to be automatically logged out when closing the browser window.

I currently use the following:

public void destroy() {
    sendLogoutMessage();
}

However this only works 3/4 of the time (probably due to network delays).

The chat applet pings the server and logs them out after 90 seconds (this allows them to reconnect due to any internet problems) - so they do get removed eventually, however I would like a way to better catch the close event.


答:
```<code>You can use this query
SELECT
(
CASE
when bitacora.tipoBitacora = 1 THEN 'Cliente Agregado'
when bitacora.tipoBitacora = 2 THEN 'Cliente Borrado'
when bitacora.tipoBitacora = 3 THEN 'Cliente Editado'
when bitacora.tipoBitacora = 4 THEN 'Pago Mensual'
when bitacora.tipoBitacora = 5 THEN 'Pago Vario'
when bitacora.tipoBitacora = 6 THEN 'Intento Clave Fallida'
ELSE 'Desconocido'
END
)AS Suceso,
(
CASE
WHEN bitacora.idCliente = -1 THEN cliente.idCliente
ELSE 'nothing'
END
) AS idCliente
FROM bitacora, cliente where cliente.idCliente=bitacora.idCliente ;
</code>```

Title: Mysql Select Empty Cells not showing [WHERE part]


问:
components load before call angularjs
I am working on angular js components there are two components that will called when their respective button is clicked

Issue: when the page loads both components are initialized , but in real they should be initialized when I click on the respective component
example:

index.html

```<code>    <div class='breadcrumbs'>
   <div class='inner'>
      <ul class='cf' style="    margin-top: 0px;">
         <li ng-click="WizardsViewerCtrl.createFirst()">

         </li>
         <li ng-click="WizardsViewerCtrl.createSecond()">
         <span>Arrange Questions</span> </a>

         </li>

      </ul>
   </div>
</div>

      <div ng-show="viewFirstRoute">
         <first-component></first-component>
      </div>
      <div ng-show="viewSecondRoute">
         <second-component></second-component>

      </div>
</code>```

index.js

```<code>$scope.viewFirstRoute=false;
$scope.viewSecondRoute=false;

function createFirst() {

    $scope.viewFirstRoute=true;
    $scope.viewSecondRoute=false;

}

function createSecond() {
   $scope.viewFirstRoute=false;
    $scope.viewSecondRoute=true;

}
</code>```

problem is when this page index.html is loaded ,both components are initialized

first.component.js

```<code>angular
.module('AOTC')
.component('firstComponent', {
        templateUrl: 'first.html',
        controllerAs: 'firstCtrl',
        controller:(function ($scope) {
            console.log("first component loaded");//it prints while index.html is loaded even i didn't clicked on this component
           })});
</code>```

second.component.js

```<code>angular
.module('AOTC')
.component('secondComponent', {
        templateUrl: 'second.html',
        controllerAs: 'secondCtrl',
        controller:(function ($scope) {
            console.log("second component loaded");//it prints while index.html is loaded even i didn't clicked on second component
           })});
</code>```

summarizing: two components on same route must be initialized when I click on the respective component , but behavior noticed components are loaded as soon as route is loaded it doesn't care about the click, see comments in the JS file

答:
Use ng-if instead of ng-show. it should fix the issue.

```<code><div ng-if="viewFirstRoute">
         <first-component></first-component>
 </div>
 <div ng-if="viewSecondRoute">
     <second-component></second-component>
  </div>
</code>```

ng-show: it will add component to DOM but set its display property to none.

  ng-if: Will add or remove component from DOM conditionally.

Title: components load before call angularjs

Body:
I am working on angular js components there are two components that will called when their respective button is clicked

Issue: when the page loads both components are initialized , but in real they should be initialized when I click on the respective component
example:

index.html

         Arrange Questions

         <first-component></first-component>

         <second-component></second-component>

index.js

$scope.viewFirstRoute=false;
$scope.viewSecondRoute=false;

function createFirst() {

    $scope.viewFirstRoute=true;
    $scope.viewSecondRoute=false;

}

function createSecond() {
   $scope.viewFirstRoute=false;
    $scope.viewSecondRoute=true;

}

problem is when this page index.html is loaded ,both components are initialized

first.component.js

angular
.module('AOTC')
.component('firstComponent', {
        templateUrl: 'first.html',
        controllerAs: 'firstCtrl',
        controller:(function ($scope) {
            console.log("first component loaded");//it prints while index.html is loaded even i didn't clicked on this component
           })});

second.component.js

angular
.module('AOTC')
.component('secondComponent', {
        templateUrl: 'second.html',
        controllerAs: 'secondCtrl',
        controller:(function ($scope) {
            console.log("second component loaded");//it prints while index.html is loaded even i didn't clicked on second component
           })});

summarizing: two components on same route must be initialized when I click on the respective component , but behavior noticed components are loaded as soon as route is loaded it doesn't care about the click, see comments in the JS file

Body:
Use ng-if instead of ng-show. it should fix the issue.

<div ng-if="viewFirstRoute">
         <first-component></first-component>
 </div>
 <div ng-if="viewSecondRoute">
     <second-component></second-component>
  </div>

ng-show: it will add component to DOM but set its display property to none.

  ng-if: Will add or remove component from DOM conditionally.


问:
Laravel - change specific tr bgcolor in views using controller based on parameter
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

```<code>public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}
</code>```

walks.blade.php

```<code><tr class="{{ $highlightClass }}">
</code>```

It didn't work.. :(

Here's the image of table in my views:

enter image description here

答:
Just pass with function:</p>

```<code>public function table_row(){
    $highlightClass = "";

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }

   return View::make('walks')
                        ->with('highlightClass', $highlightClass)
}
</code>```

Body:
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}

walks.blade.php

It didn't work.. :(

Here's the image of table in my views:

enter image description here

Body:
Just pass with function:

public function table_row(){
    $highlightClass = "";

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }

   return View::make('walks')
                        ->with('highlightClass', $highlightClass)
}


问:
App won't start on Google Repository 55 with any firebase-messaging version
When I start up my application, it will immediately crash before the main activity starts with the following stack trace:

```<code>ca.uwaterloo.foodwithfriends E/AndroidRuntime: FATAL EXCEPTION: main

Process: ca.uwaterloo.foodwithfriends, PID: 20134

java.lang.NoSuchMethodError: No static method zzcL(Ljava/lang/String;)Z in
    class Lcom/google/android/gms/common/util/zzt; or its super classes
(declaration of 'com.google.android.gms.common.util.zzt' appears in /data/app/ca.uwaterloo.foodwithfriends-1/base.apk)
at com.google.firebase.FirebaseOptions.<init>(Unknown Source)
at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5262)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4847)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4787)
at android.app.ActivityThread.access$1600(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1452)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method).java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

This stack trace started appearing after I upgraded my firebase libraries in my build.gradle file to 11.0.2 due to an issue receiving messages. This required an update to Google Repository 55. Since then reverting to previous versions of firebase-messaging and google play services has been ineffective, including reverting to the exact same revision but with Google Repository 55 as was starting but not receiving messages earlier today.

The following code block is my build.gradle file for my app trying to run the current versions of firebase and of google play services.

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "ca.uwaterloo.foodwithfriends"
    minSdkVersion 19
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

defaultConfig {
    jackOptions {
        enabled true
    }
}
dexOptions {

}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

repositories {
mavenCentral()
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('libs/foodwithfriends-common.jar')

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:25.3.1'
compile 'com.google.android.gms:play-services-maps:11.0.2'
compile 'com.google.android.gms:play-services-location:11.0.2'
compile 'com.google.android.gms:play-services-places:11.0.2'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
compile 'com.android.support:support-v4:25.3.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.github.pwittchen:infinitescroll:0.0.1'
compile 'com.github.clans:fab:1.6.4'
compile 'com.stripe:stripe-android:4.1.1'
compile 'com.google.firebase:firebase-core:11.0.2'
compile 'com.google.firebase:firebase-messaging:11.0.2'
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile 'com.google.dexmaker:dexmaker-mockito:1.1'
androidTestCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
}
apply plugin: 'com.google.gms.google-services'
</code>```

This block is of the project build.gradle file.

```<code>// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

The working setup earlier today was Google Repository 54, with google play services in project at 3, google play services at app as 10.2.6, and firebase at version 10.0.1. Google Repository 55 with google play services in project at 3, google play services at app as 10.2.6, and firebase at version 10.0.1 does not work. I updated due to the receiving messages issue which I read could be because of non compatible versions between all these dependencies.

edit - Possible duplicate question had an answer that there are incompatible dependencies that may be exposed by running gradlew dependencies. I did this and the result did not seem to include a different version for any google-play-services or firebase dependency. See below:

```<code>+--- com.android.support:appcompat-v7:25.3.1
|    +--- com.android.support:support-annotations:25.3.1
|    +--- com.android.support:support-v4:25.3.1
|    |    +--- com.android.support:support-compat:25.3.1
|    |    |    \--- com.android.support:support-annotations:25.3.1
|    |    +--- com.android.support:support-media-compat:25.3.1
|    |    |    +--- com.android.support:support-annotations:25.3.1
|    |    |    \--- com.android.support:support-compat:25.3.1 (*)
|    |    +--- com.android.support:support-core-utils:25.3.1
|    |    |    +--- com.android.support:support-annotations:25.3.1
|    |    |    \--- com.android.support:support-compat:25.3.1 (*)
|    |    +--- com.android.support:support-core-ui:25.3.1
|    |    |    +--- com.android.support:support-annotations:25.3.1
|    |    |    \--- com.android.support:support-compat:25.3.1 (*)
|    |    \--- com.android.support:support-fragment:25.3.1
|    |         +--- com.android.support:support-compat:25.3.1 (*)
|    |         +--- com.android.support:support-media-compat:25.3.1 (*)
|    |         +--- com.android.support:support-core-ui:25.3.1 (*)
|    |         \--- com.android.support:support-core-utils:25.3.1 (*)
|    +--- com.android.support:support-vector-drawable:25.3.1
|    |    +--- com.android.support:support-annotations:25.3.1
|    |    \--- com.android.support:support-compat:25.3.1 (*)
|    \--- com.android.support:animated-vector-drawable:25.3.1
|         \--- com.android.support:support-vector-drawable:25.3.1 (*)
+--- com.android.support.constraint:constraint-layout:1.0.2
|    \--- com.android.support.constraint:constraint-layout-solver:1.0.2
+--- com.android.support:design:25.3.1
|    +--- com.android.support:support-v4:25.3.1 (*)
|    +--- com.android.support:appcompat-v7:25.3.1 (*)
|    +--- com.android.support:recyclerview-v7:25.3.1
|    |    +--- com.android.support:support-annotations:25.3.1
|    |    +--- com.android.support:support-compat:25.3.1 (*)
|    |    \--- com.android.support:support-core-ui:25.3.1 (*)
|    \--- com.android.support:transition:25.3.1
|         +--- com.android.support:support-annotations:25.3.1
|         \--- com.android.support:support-v4:25.3.1 (*)
+--- com.google.android.gms:play-services-maps:11.0.2
|    +--- com.google.android.gms:play-services-base:[11.0.2] -> 11.0.2
|    |    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2
|    |    |    \--- com.android.support:support-v4:25.2.0 -> 25.3.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2
|    |         \--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|    \--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
+--- com.google.android.gms:play-services-location:11.0.2
|    +--- com.google.android.gms:play-services-base:[11.0.2] -> 11.0.2 (*)
|    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
+--- com.google.android.gms:play-services-places:11.0.2
|    +--- com.google.android.gms:play-services-base:[11.0.2] -> 11.0.2 (*)
|    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|    +--- com.google.android.gms:play-services-maps:[11.0.2] -> 11.0.2 (*)
|    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
+--- com.android.volley:volley:1.0.0
+--- com.google.code.gson:gson:2.7
+--- com.facebook.android:facebook-android-sdk:[4,5) -> 4.24.0
|    +--- com.android.support:support-v4:25.3.1 (*)
|    +--- com.android.support:appcompat-v7:25.3.1 (*)
|    +--- com.android.support:cardview-v7:25.3.1
|    |    \--- com.android.support:support-annotations:25.3.1
|    +--- com.android.support:customtabs:25.3.1
|    |    +--- com.android.support:support-compat:25.3.1 (*)
|    |    \--- com.android.support:support-annotations:25.3.1
|    \--- com.parse.bolts:bolts-android:1.4.0
|         +--- com.parse.bolts:bolts-tasks:1.4.0
|         \--- com.parse.bolts:bolts-applinks:1.4.0
|              \--- com.parse.bolts:bolts-tasks:1.4.0
+--- com.github.bumptech.glide:glide:4.0.0-RC0
|    +--- com.github.bumptech.glide:gifdecoder:4.0.0-RC0
|    |    \--- com.android.support:support-annotations:25.3.1
|    +--- com.github.bumptech.glide:disklrucache:4.0.0-RC0
|    \--- com.github.bumptech.glide:annotations:4.0.0-RC0
+--- com.android.support:support-v4:25.3.1 (*)
+--- de.hdodenhof:circleimageview:2.1.0
+--- com.github.pwittchen:infinitescroll:0.0.1
|    \--- com.android.support:recyclerview-v7:23.1.1 -> 25.3.1 (*)
+--- com.github.clans:fab:1.6.4
+--- com.stripe:stripe-android:4.1.1
|    +--- com.android.support:support-annotations:25.3.1
|    +--- com.android.support:support-v4:25.3.1 (*)
|    \--- com.android.support:appcompat-v7:25.3.1 (*)
+--- com.google.firebase:firebase-core:11.0.2
|    \--- com.google.firebase:firebase-analytics:[11.0.2] -> 11.0.2
|         +--- com.google.firebase:firebase-analytics-impl:[11.0.2] -> 11.0.2
|         |    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         |    +--- com.google.firebase:firebase-iid:[11.0.2] -> 11.0.2
|         |    |    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         |    |    \--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2
|         |    |         +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         |    |         \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
|         |    +--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2 (*)
|         |    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
|         +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         \--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2 (*)
\--- com.google.firebase:firebase-messaging:11.0.2
     +--- com.google.firebase:firebase-iid:[11.0.2] -> 11.0.2 (*)
     +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
     \--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2 (*)
</code>```

答:
This can happen when you have Firebase (or Google Play) deps   using different versions.

Run ./gradlew dependencies to check the full list of dependencies.

If the dependencies are OK, but the problem persists, try ./gradlew clean and build again.

Gradle could be using some cached code, and not the declared list of deps.

Body:
When I start up my application, it will immediately crash before the main activity starts with the following stack trace:

ca.uwaterloo.foodwithfriends E/AndroidRuntime: FATAL EXCEPTION: main

Process: ca.uwaterloo.foodwithfriends, PID: 20134

java.lang.NoSuchMethodError: No static method zzcL(Ljava/lang/String;)Z in
    class Lcom/google/android/gms/common/util/zzt; or its super classes
(declaration of 'com.google.android.gms.common.util.zzt' appears in /data/app/ca.uwaterloo.foodwithfriends-1/base.apk)
at com.google.firebase.FirebaseOptions.<init>(Unknown Source)
at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5262)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4847)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4787)
at android.app.ActivityThread.access$1600(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1452)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method).java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

This stack trace started appearing after I upgraded my firebase libraries in my build.gradle file to 11.0.2 due to an issue receiving messages. This required an update to Google Repository 55. Since then reverting to previous versions of firebase-messaging and google play services has been ineffective, including reverting to the exact same revision but with Google Repository 55 as was starting but not receiving messages earlier today.

The following code block is my build.gradle file for my app trying to run the current versions of firebase and of google play services.

apply plugin: 'com.android.application'

android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "ca.uwaterloo.foodwithfriends"
    minSdkVersion 19
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

defaultConfig {
    jackOptions {
        enabled true
    }
}
dexOptions {

}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
}

repositories {
mavenCentral()
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile files('libs/foodwithfriends-common.jar')

androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
{
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:design:25.3.1'
compile 'com.google.android.gms:play-services-maps:11.0.2'
compile 'com.google.android.gms:play-services-location:11.0.2'
compile 'com.google.android.gms:play-services-places:11.0.2'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.code.gson:gson:2.7'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
compile 'com.android.support:support-v4:25.3.1'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.github.pwittchen:infinitescroll:0.0.1'
compile 'com.github.clans:fab:1.6.4'
compile 'com.stripe:stripe-android:4.1.1'
compile 'com.google.firebase:firebase-core:11.0.2'
compile 'com.google.firebase:firebase-messaging:11.0.2'
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile 'com.google.dexmaker:dexmaker-mockito:1.1'
androidTestCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
}
apply plugin: 'com.google.gms.google-services'

This block is of the project build.gradle file.

// Top-level build file where you can add configuration options common to
all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.3'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

The working setup earlier today was Google Repository 54, with google play services in project at 3, google play services at app as 10.2.6, and firebase at version 10.0.1. Google Repository 55 with google play services in project at 3, google play services at app as 10.2.6, and firebase at version 10.0.1 does not work. I updated due to the receiving messages issue which I read could be because of non compatible versions between all these dependencies.

edit - Possible duplicate question had an answer that there are incompatible dependencies that may be exposed by running gradlew dependencies. I did this and the result did not seem to include a different version for any google-play-services or firebase dependency. See below:

+--- com.android.support:appcompat-v7:25.3.1
|    +--- com.android.support:support-annotations:25.3.1
|    +--- com.android.support:support-v4:25.3.1
|    |    +--- com.android.support:support-compat:25.3.1
|    |    |    \--- com.android.support:support-annotations:25.3.1
|    |    +--- com.android.support:support-media-compat:25.3.1
|    |    |    +--- com.android.support:support-annotations:25.3.1
|    |    |    \--- com.android.support:support-compat:25.3.1 (*)
|    |    +--- com.android.support:support-core-utils:25.3.1
|    |    |    +--- com.android.support:support-annotations:25.3.1
|    |    |    \--- com.android.support:support-compat:25.3.1 (*)
|    |    +--- com.android.support:support-core-ui:25.3.1
|    |    |    +--- com.android.support:support-annotations:25.3.1
|    |    |    \--- com.android.support:support-compat:25.3.1 (*)
|    |    \--- com.android.support:support-fragment:25.3.1
|    |         +--- com.android.support:support-compat:25.3.1 (*)
|    |         +--- com.android.support:support-media-compat:25.3.1 (*)
|    |         +--- com.android.support:support-core-ui:25.3.1 (*)
|    |         \--- com.android.support:support-core-utils:25.3.1 (*)
|    +--- com.android.support:support-vector-drawable:25.3.1
|    |    +--- com.android.support:support-annotations:25.3.1
|    |    \--- com.android.support:support-compat:25.3.1 (*)
|    \--- com.android.support:animated-vector-drawable:25.3.1
|         \--- com.android.support:support-vector-drawable:25.3.1 (*)
+--- com.android.support.constraint:constraint-layout:1.0.2
|    \--- com.android.support.constraint:constraint-layout-solver:1.0.2
+--- com.android.support:design:25.3.1
|    +--- com.android.support:support-v4:25.3.1 (*)
|    +--- com.android.support:appcompat-v7:25.3.1 (*)
|    +--- com.android.support:recyclerview-v7:25.3.1
|    |    +--- com.android.support:support-annotations:25.3.1
|    |    +--- com.android.support:support-compat:25.3.1 (*)
|    |    \--- com.android.support:support-core-ui:25.3.1 (*)
|    \--- com.android.support:transition:25.3.1
|         +--- com.android.support:support-annotations:25.3.1
|         \--- com.android.support:support-v4:25.3.1 (*)
+--- com.google.android.gms:play-services-maps:11.0.2
|    +--- com.google.android.gms:play-services-base:[11.0.2] -> 11.0.2
|    |    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2
|    |    |    \--- com.android.support:support-v4:25.2.0 -> 25.3.1 (*)
|    |    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2
|    |         \--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|    \--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
+--- com.google.android.gms:play-services-location:11.0.2
|    +--- com.google.android.gms:play-services-base:[11.0.2] -> 11.0.2 (*)
|    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
+--- com.google.android.gms:play-services-places:11.0.2
|    +--- com.google.android.gms:play-services-base:[11.0.2] -> 11.0.2 (*)
|    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|    +--- com.google.android.gms:play-services-maps:[11.0.2] -> 11.0.2 (*)
|    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
+--- com.android.volley:volley:1.0.0
+--- com.google.code.gson:gson:2.7
+--- com.facebook.android:facebook-android-sdk:[4,5) -> 4.24.0
|    +--- com.android.support:support-v4:25.3.1 (*)
|    +--- com.android.support:appcompat-v7:25.3.1 (*)
|    +--- com.android.support:cardview-v7:25.3.1
|    |    \--- com.android.support:support-annotations:25.3.1
|    +--- com.android.support:customtabs:25.3.1
|    |    +--- com.android.support:support-compat:25.3.1 (*)
|    |    \--- com.android.support:support-annotations:25.3.1
|    \--- com.parse.bolts:bolts-android:1.4.0
|         +--- com.parse.bolts:bolts-tasks:1.4.0
|         \--- com.parse.bolts:bolts-applinks:1.4.0
|              \--- com.parse.bolts:bolts-tasks:1.4.0
+--- com.github.bumptech.glide:glide:4.0.0-RC0
|    +--- com.github.bumptech.glide:gifdecoder:4.0.0-RC0
|    |    \--- com.android.support:support-annotations:25.3.1
|    +--- com.github.bumptech.glide:disklrucache:4.0.0-RC0
|    \--- com.github.bumptech.glide:annotations:4.0.0-RC0
+--- com.android.support:support-v4:25.3.1 (*)
+--- de.hdodenhof:circleimageview:2.1.0
+--- com.github.pwittchen:infinitescroll:0.0.1
|    \--- com.android.support:recyclerview-v7:23.1.1 -> 25.3.1 (*)
+--- com.github.clans:fab:1.6.4
+--- com.stripe:stripe-android:4.1.1
|    +--- com.android.support:support-annotations:25.3.1
|    +--- com.android.support:support-v4:25.3.1 (*)
|    \--- com.android.support:appcompat-v7:25.3.1 (*)
+--- com.google.firebase:firebase-core:11.0.2
|    \--- com.google.firebase:firebase-analytics:[11.0.2] -> 11.0.2
|         +--- com.google.firebase:firebase-analytics-impl:[11.0.2] -> 11.0.2
|         |    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         |    +--- com.google.firebase:firebase-iid:[11.0.2] -> 11.0.2
|         |    |    +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         |    |    \--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2
|         |    |         +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         |    |         \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
|         |    +--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2 (*)
|         |    \--- com.google.android.gms:play-services-tasks:[11.0.2] -> 11.0.2 (*)
|         +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
|         \--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2 (*)
\--- com.google.firebase:firebase-messaging:11.0.2
     +--- com.google.firebase:firebase-iid:[11.0.2] -> 11.0.2 (*)
     +--- com.google.android.gms:play-services-basement:[11.0.2] -> 11.0.2 (*)
     \--- com.google.firebase:firebase-common:[11.0.2] -> 11.0.2 (*)


问:
Logging time in Db wrt to clients TimeZone
I have an web application which logs all the activities perform by the client with the userid and time when the event was performed. As of now the application logs the time dat is of the DB server. my application supports different time zone so i want to capture the time of the client machine which invokes an event and store that time in db rather than the Db server timezone.

Structure of table
Columns: UserID, EventId, Time (this value needs to be the client machine time rather than the DB server value)

My question is how do i get to record the client machine time zone and not the dbserver time zone.

I hope i was clear enough.
Thanks in advance

答:
Your issue here is getting the time zone of the client browser, but unfortunately there isn't a foolproof way of doing this. There are a number of options though:

I. Ask the user

As part of your "User Preferences" section, you give the user an option to set their preferred time zone.

II. Take a guess

Using the HTTP_ACCEPT_LANGUAGE header, you can infer a country. Obviously if the setting is just "en" or "fr" or "es" then your guess will be just that, if there's a country preference as well, e.g. "en-US" or "en-GB" or "fr-FR" then your guess will be closer. You'll still need a "User Preferences" box to handle the edge cases.

III. Use Javascript

Javascript has a getTimezoneOffset() function that will give you the offset from GMT for the client browser. The following shows an example of using this function:

How can I obtain the local time in jQuery?

Hope this helps.


问:
Android studio action bar not showing in new activity
style.xml

<resources>

答:
Add this in your styles.xml

```<code>    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/grey_400</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
</code>```

And in your Manifest add this in every Activity

```<code><activity
        android:name=".YourActivity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme" />
</code>```

Body:
style.xml

<resources>

Body:
Add this in your styles.xml

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/grey_400</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

And in your Manifest add this in every Activity

<activity
        android:name=".YourActivity"
        android:label="@string/title_activity_main2"
        android:theme="@style/AppTheme" />


问:
How to add a custom option(Dowload Image) with other share options in android
Is it possible to add a custom option(For eg. Download Image) with other share option(shown in attached image) in intent chooser?

答:
Refer this answer: Link

Sample Code:
Github Project


问:
returning data in console.log with angular but not displaying on HTML page
I am new to angular and I am developing a Web application. I am getting data in console.log but not able to display it on HTML page. table is displaying blank value.

Here is my HTML page:

```<code><div class="bs-example" data-example-id="panel-without-body-with-table">
    <div class="panel panel-default">
        <div class="panel-heading">Account list</div>
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>AWS Account</th>
                    <th>VPC</th>
                    <th>Subnet</th>
                    <th>Instance Type</th>
                    <th>Port</th>
                    <th></th>

                </tr>
            </thead>
            <tbody>
           <!-- {% raw %}-->
                 <tr ng-repeat="Account in Accounts ">
                <!--{% for account in myaccounts %}track by $index-->
                <tr>

                    <th scope="row">// $index+1 //</th>
                    <td> // Account.name // </td>
                    <td>// Account.vpc //</td>
                    <td>// Account.subnet //</td>
                    <td>// Account.instance_type //</td>

                    <td><span style="cursor:pointer;" ng-click="editAccount(Account.id)" class="glyphicon glyphicon-pencil" aria-hidden="true"></span></td>
                </tr>
               <!--{% endfor %}-->
              <!-- {% endraw %}-->
            </tbody>
        </table>
    </div>
</div>
</code>```

Here is my Angular controller:

```<code>angular.module('pushButtonAdmin', [])

 .config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
  })

  .controller('adminCtrl', function($scope, $http) {

                $scope.info = {};

                $scope.showAdd = true;

                $scope.showAddPopUp = function(){
                    $scope.showAdd = true;
                    $scope.info = {};
                    //$('#addPopUp').modal('show');
                }

                $scope.test = function(){
                    console.log("sfasd");
                }

                $scope.showlist = function(){
                    $http({
                        method: 'POST',
                        url: '/getAccountList',
                    }).then(function(response) {
                        $scope.Accounts = response.data;
                        console.log('mm',$scope.Accounts);
                    }, function(error) {
                        console.log(error);
                    });
                }

                $scope.showlist();
            });
</code>```

答:
```<code><div class="bs-example" data-example-id="panel-without-body-with-table">
    <div class="panel panel-default">
        <div class="panel-heading">Account list</div>
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">AWS Account</th>
                    <th scope="col">VPC</th>
                    <th scope="col">Subnet</th>
                    <th scope="col">Instance Type</th>
                    <th scope="col">Port</th>
                    <th scope="col"></th>
                </tr>
            </thead>
            <tbody>
           <!-- {% raw %}-->
                <!--{% for account in myaccounts %}track by $index-->
                <tr ng-repeat="Account in Accounts track by $index">

                    <th scope="row">{{$index+1//</th>
                    <td> //Account.name//</td>
                    <td>//Account.vpc//</td>
                    <td>//Account.subnet//</td>
                    <td>//Account.instance_type//</td>
                    <td></td>
                    <td><span style="cursor:pointer;" ng-click="editAccount(Account.id)" class="glyphicon glyphicon-pencil" aria-hidden="true"></span></td>
                </tr>
               <!--{% endfor %}-->
              <!-- {% endraw %}-->
            </tbody>
        </table>
    </div>
</div>
</code>```

Body:
I am new to angular and I am developing a Web application. I am getting data in console.log but not able to display it on HTML page. table is displaying blank value.

Here is my HTML page:

Account list

                    #
                    AWS Account
                    VPC
                    Subnet
                    Instance Type
                    Port

                    // $index+1 //
                     // Account.name //
                    // Account.vpc //
                    // Account.subnet //
                    // Account.instance_type //

Here is my Angular controller:

angular.module('pushButtonAdmin', [])

 .config(function($interpolateProvider) {
    $interpolateProvider.startSymbol('//');
    $interpolateProvider.endSymbol('//');
  })

  .controller('adminCtrl', function($scope, $http) {

                $scope.info = {};

                $scope.showAdd = true;

                $scope.showAddPopUp = function(){
                    $scope.showAdd = true;
                    $scope.info = {};
                    //$('#addPopUp').modal('show');
                }

                $scope.test = function(){
                    console.log("sfasd");
                }

                $scope.showlist = function(){
                    $http({
                        method: 'POST',
                        url: '/getAccountList',
                    }).then(function(response) {
                        $scope.Accounts = response.data;
                        console.log('mm',$scope.Accounts);
                    }, function(error) {
                        console.log(error);
                    });
                }

                $scope.showlist();
            });


问:
Highlighting search terms in an MS Word document
We have a project where we need to provide search over a collection of Word documents through a web-based interface. The client would like for the search terms to be highlighted when a user opens a document.

Is there a way to do this directly in Word when opening a document? The only alternative we can come up with is to convert the Word documents to HTML and display that.

Just for background, we're currently using Windows SharePoint Services for document searching.

答:
You could do that using Word's Highlight feature. However, to use the feature you will have to use Word automation on either server-side or client-side.

A script in VBA for highlighting a search term could look like this:

```<code>Sub Highlight(oDoc As Word.Document, term As String)

    With oDoc.Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Highlight = True
        .Text = term
        .Replacement.Text = term
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With

End Sub
</code>```

The script does a search-and-replace and applies highlighting to the found text. If you have any questions on how to automate Word best, e.g. in a server environment, don't hesitate to ask.

OwnerDisplayName: DylanW

Body:
You could do that using Word's Highlight feature. However, to use the feature you will have to use Word automation on either server-side or client-side.

A script in VBA for highlighting a search term could look like this:

Sub Highlight(oDoc As Word.Document, term As String)

    With oDoc.Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Highlight = True
        .Text = term
        .Replacement.Text = term
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With

End Sub

The script does a search-and-replace and applies highlighting to the found text. If you have any questions on how to automate Word best, e.g. in a server environment, don't hesitate to ask.

OwnerDisplayName: divo


问:
What's the safest way to iterate through the keys of a Perl hash?
If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys?  I have heard that using each may in some way have unintended side effects.  So, is that true, and is one of the two following methods best, or is there a better way?

```<code># Method 1
while (my ($key, $value) = each(%hash)) {
    # Something
}

# Method 2
foreach my $key (keys(%hash)) {
    # Something
}
</code>```

答:
I woudl say:

Use whatever's easiest to read/understand for most people (so keys, usually, I'd argue)

Use whatever you decide consistently throught the whole code base.

This give 2 major advantages:

It's easier to spot "common" code so you can re-factor into functions/methiods.

It's easier for future developers to maintain.

I don't think it's more expensive to use keys over each, so no need for two different constructs for the same thing in your code.

Body:
If I have a Perl hash with a bunch of (key, value) pairs, what is the preferred method of iterating through all the keys?  I have heard that using each may in some way have unintended side effects.  So, is that true, and is one of the two following methods best, or is there a better way?

# Method 1
while (my ($key, $value) = each(%hash)) {
    # Something
}

# Method 2
foreach my $key (keys(%hash)) {
    # Something
}

LastEditorDisplayName: brian d foy


问:
Align vertical text next to the image
I'm trying to create exactly like what is shown in the picture below. So far, it's not looking good for me.

Here's the JSFiddle: https://jsfiddle.net/6o3nz6g9/

HTML:

```<code><h1>This is Sparta!</h1>
<div class="container">
<div class="row">
    <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
    <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
  <div class="col-xs-4">
        <div class="services__text">Title Text Here</div>
        <img src="https://image.ibb.co/hccDVF/sample.jpg" class="img-responsive" alt=""/>
    </div>
</div>
</div>
</code>```

CSS:

```<code>.services__text {
    -ms-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -ms-transform-origin: right top 0;
    -moz-transform-origin: right top 0;
    -webkit-transform-origin: right top 0;
    transform-origin: right top 0;
    padding: 10px;
    float: left;
}
</code>```

How do I do to get this desired effect? FYI: I'm working on Bootstrap framework.

答:
Add following css properties in your code for class .service_text

```<code>top:20px;  left:-126px;  position:absolute;
</code>```

And add a class to your class="col-xs-4" as class="col-xs-4 parent"
And for parent add following css. position: relative;    padding-left: 8px;

This will give exactly same result. And if you want further explanation i would love to help you on that

Title: Align vertical text next to the image

Body:
I'm trying to create exactly like what is shown in the picture below. So far, it's not looking good for me.

Here's the JSFiddle: https://jsfiddle.net/6o3nz6g9/

HTML:

This is Sparta!

Title Text Here

Title Text Here

Title Text Here

CSS:

.services__text {
    -ms-transform: rotate(-90deg);
    -moz-transform: rotate(-90deg);
    -webkit-transform: rotate(-90deg);
    transform: rotate(-90deg);
    -ms-transform-origin: right top 0;
    -moz-transform-origin: right top 0;
    -webkit-transform-origin: right top 0;
    transform-origin: right top 0;
    padding: 10px;
    float: left;
}

How do I do to get this desired effect? FYI: I'm working on Bootstrap framework.

Body:
Add following css properties in your code for class .service_text

top:20px;  left:-126px;  position:absolute;

And add a class to your class="col-xs-4" as class="col-xs-4 parent"
And for parent add following css. position: relative;    padding-left: 8px;

This will give exactly same result. And if you want further explanation i would love to help you on that


问:
Access frame via "relative=up" with Selenium & Ruby
Recently I've used command "selectFrame > relative=up" in Selenium IDE to switch between nested frames. Since i've decided to rewrite all code in Selenium and Ruby, i can't find this command analog for mentioned language.

I can't select frame by name because it different after any reload. Other frame attributes are:

```<code>iframe id="ext-comp-1465" name="ext-comp-1465" frameborder="0" src="/5005700001V96Ub/e?retURL=%2F5005700001V96Ub&isdtp=vw&cancelURL=%2F5005700001V96Ub&nonce=a37ade0829c6d08539a765cd370dff0766cd596851439e853d68a60e9d7c28d0&sfdcIFrameOrigin=https%3A%2F%2F*************.com" class=" x-border-panel" style="left: 0px; top: 0px; width: 329px; height: 641px;"></iframe
</code>```

Please advise how i can get to this frame using "relative=up" option  or other frame attributes. Thanks in advance.

答:
Try the following,

```<code>driver.switch_to.frame "ext-comp-1465"
</code>```

or

```<code>driver.switch_to.frame driver.find_element(id: 'ext-comp-1465')
</code>```

or

```<code>driver.switch_to.frame driver.find_element(name: 'ext-comp-1465')
</code>```

or

```<code>driver.switch_to.frame driver.find_element(xpath: '//iframe[starts-with(@id,"ext-comp-"] ')
</code>```

Body:
Recently I've used command "selectFrame > relative=up" in Selenium IDE to switch between nested frames. Since i've decided to rewrite all code in Selenium and Ruby, i can't find this command analog for mentioned language.

I can't select frame by name because it different after any reload. Other frame attributes are:

iframe id="ext-comp-1465" name="ext-comp-1465" frameborder="0" src="/5005700001V96Ub/e?retURL=%2F5005700001V96Ub&isdtp=vw&cancelURL=%2F5005700001V96Ub&nonce=a37ade0829c6d08539a765cd370dff0766cd596851439e853d68a60e9d7c28d0&sfdcIFrameOrigin=https%3A%2F%2F*************.com" class=" x-border-panel" style="left: 0px; top: 0px; width: 329px; height: 641px;"></iframe

Please advise how i can get to this frame using "relative=up" option  or other frame attributes. Thanks in advance.

Body:
Try the following,

driver.switch_to.frame "ext-comp-1465"

or

driver.switch_to.frame driver.find_element(id: 'ext-comp-1465')

or

driver.switch_to.frame driver.find_element(name: 'ext-comp-1465')

or

driver.switch_to.frame driver.find_element(xpath: '//iframe[starts-with(@id,"ext-comp-"] ')


问:
Add UIView rounding logic inside UIView class
I have a custom UIView and I add it to my ViewController like this:

```<code>let myCustomView = Bundle.main.loadNibNamed("MyCustomView", owner: nil, options: nil) as! MyCustomView
myCustomView.layer.cornerRadius = 10
myCustomView.layer.masksToBounds = true
</code>```

I round the corners of the view. But I am wondering, is there a way to move this logic of rounding the corners inside the MyCustomView class?

答:
You can do something like this in your UIView subclass:

```<code>class RoundedView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
    }

}
</code>```

Also if you want to pass a custom value instead of '10' in the cornerRadius property, you can try to implement a convenience init by looking here:

Override Init method of UIView in Swift

Body:
I have a custom UIView and I add it to my ViewController like this:

let myCustomView = Bundle.main.loadNibNamed("MyCustomView", owner: nil, options: nil) as! MyCustomView
myCustomView.layer.cornerRadius = 10
myCustomView.layer.masksToBounds = true

I round the corners of the view. But I am wondering, is there a way to move this logic of rounding the corners inside the MyCustomView class?

Body:
You can do something like this in your UIView subclass:

class RoundedView: UIView {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.layer.cornerRadius = 10
        self.layer.masksToBounds = true
    }

}

Also if you want to pass a custom value instead of '10' in the cornerRadius property, you can try to implement a convenience init by looking here:

Override Init method of UIView in Swift


问:
What's the magic of arrays in C#
```<code>int[] a = new int[5];
string[] b = new string[1];
</code>```

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

答:
Arrays are special to CLR. They're allocated with 'newarr' instruction, and elements are accessed with 'ldelem*' and 'stelem*' instructions, not via System.Array methods;

see http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.newarr.aspx

You can check out ildasm output to see how arrays are represented.

So, to answer your question - no new type declaration is generated for any particular array.

Title: What's the magic of arrays in C#

Body:
int[] a = new int[5];
string[] b = new string[1];

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?


问:
passport.deserializeUser never call
please help me with passportjs local strategy. When I try loggin, my passport flow is : serialize, Success auth and redirect to '/' where req.user is undefined. In passport flow deserialize is call after every serialize, but in my never. I dont know where is the bug, thanks for help.

Require:

```<code>    var express = require('express');
    var bodyParser = require('body-parser');
    var objection = require('objection');
    var Model = objection.Model;
    var Knex = require('knex');
    var bcrypt = require('bcrypt');
    var expressValidator = require('express-validator');
    var passport = require('passport');
    var cookieParser = require('cookie-parser');
    var session = require('express-session');
    var LocalStrategy = require('passport-local').Strategy;
    var api = express();
</code>```

Strategy middleware:

```<code>passport.use(new LocalStrategy(
        async function (username, password, done) {
            var user = await User.findOne(username);
            if (!user) {
                return done(null, false, {message: 'Incorrect username.'});
            }
            if (!bcrypt.compareSync(password, user.password)) {
                return done(null, false, {message: 'Incorrect password.'});
            } else {
                return done(null, user);
            }
        }
    ));
</code>```

Serialize an Deserialize method:

```<code>    passport.serializeUser(function (user, done) {
        console.log("serialialize");
        done(null,user.id);
    });

    passport.deserializeUser(async function (id, done) {
        console.log("deserialialize");
        let user = await User.findById(id);
        if (user) {
            done(null, user);
        }
    });
</code>```

Middlewares:

```<code>    api.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        next();
    });

    api.use(bodyParser.json());
    api.use(expressValidator());
    api.use(cookieParser()); // required before session.
    api.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: false}));
    api.use(passport.initialize());
    api.use(passport.session());
</code>```

DB configurations:

```<code>    var knex = Knex({
        client: 'pg',
        connection: {
            user: 'marossmrek',
            password: '12345',
            database: 'ita-js'
        }
    });

    Model.knex(knex);

    class Base extends Model {

        static get tableName() {
            return this.name.toLowerCase();
        }

        static async findById(id) {

            return await this.query().where({id: id}).limit(1).first();
        }
    }

    class User extends Base {

        static async findOne(username) {
            return await this.query().where({username: username}).limit(1).first();
        }
    }
</code>```

User login routes:

```<code>    api.post('/login',
        passport.authenticate('local', { failureRedirect: '/login' }),
        function(req, res) {
            console.log('Success auth');
            res.redirect('/');
        });

    api.get('/logout', (req, res) => {
        req.logout();
        res.end();
    });

    api.get('/', (req,res)=> {
        console.log("After redirect: " +req.user);
        res.end();
    });

    api.listen(5000, () => {
        console.log("I listen on port 5000");
    });
</code>```

答:
If you serialize whole user, then deserialize whole user object not just the id.</p>

```<code>passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});
</code>```

Title: passport.deserializeUser never call

Body:
please help me with passportjs local strategy. When I try loggin, my passport flow is : serialize, Success auth and redirect to '/' where req.user is undefined. In passport flow deserialize is call after every serialize, but in my never. I dont know where is the bug, thanks for help.

Require:

    var express = require('express');
    var bodyParser = require('body-parser');
    var objection = require('objection');
    var Model = objection.Model;
    var Knex = require('knex');
    var bcrypt = require('bcrypt');
    var expressValidator = require('express-validator');
    var passport = require('passport');
    var cookieParser = require('cookie-parser');
    var session = require('express-session');
    var LocalStrategy = require('passport-local').Strategy;
    var api = express();

Strategy middleware:

passport.use(new LocalStrategy(
        async function (username, password, done) {
            var user = await User.findOne(username);
            if (!user) {
                return done(null, false, {message: 'Incorrect username.'});
            }
            if (!bcrypt.compareSync(password, user.password)) {
                return done(null, false, {message: 'Incorrect password.'});
            } else {
                return done(null, user);
            }
        }
    ));

Serialize an Deserialize method:

    passport.serializeUser(function (user, done) {
        console.log("serialialize");
        done(null,user.id);
    });

    passport.deserializeUser(async function (id, done) {
        console.log("deserialialize");
        let user = await User.findById(id);
        if (user) {
            done(null, user);
        }
    });

Middlewares:

    api.use((req, res, next) => {
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
        next();
    });

    api.use(bodyParser.json());
    api.use(expressValidator());
    api.use(cookieParser()); // required before session.
    api.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: false}));
    api.use(passport.initialize());
    api.use(passport.session());

DB configurations:

    var knex = Knex({
        client: 'pg',
        connection: {
            user: 'marossmrek',
            password: '12345',
            database: 'ita-js'
        }
    });

    Model.knex(knex);

    class Base extends Model {

        static get tableName() {
            return this.name.toLowerCase();
        }

        static async findById(id) {

            return await this.query().where({id: id}).limit(1).first();
        }
    }

    class User extends Base {

        static async findOne(username) {
            return await this.query().where({username: username}).limit(1).first();
        }
    }

User login routes:

    api.post('/login',
        passport.authenticate('local', { failureRedirect: '/login' }),
        function(req, res) {
            console.log('Success auth');
            res.redirect('/');
        });

    api.get('/logout', (req, res) => {
        req.logout();
        res.end();
    });

    api.get('/', (req,res)=> {
        console.log("After redirect: " +req.user);
        res.end();
    });

    api.listen(5000, () => {
        console.log("I listen on port 5000");
    });

Body:
If you serialize whole user, then deserialize whole user object not just the id.

passport.serializeUser(function (user, done) {
    done(null, user);
});

passport.deserializeUser(function (user, done) {
    done(null, user);
});


问:
Can't set response cookies inside promise ExpressJS
So I have an app.post leading to this file:

'use strict';

function login(req, res, next) {
    console.log("This line is executed");
    makePromise().then(function(result){
        res.cookie("key", "val");
        console.log("This line isn't executed");
        res.send("Ok");
    });
    next();
}

function makePromise() {
    return new Promise(function (resolve, reject) {
        resolve("Done");
    });
}

module.exports = login;```

But when I request the url it only executes the first console.log line and then returns 404 without sending the cookie or executing the rest of the code. This doesn't happen when I try setting the cookie outside the promise.

FYI: Obviously this isn't the code I'm actually trying to achieve but a sample that includes the relevant part for my problem. In my code I have to find something in my database in order to send to cookie so I have to use promise unless someone can help me find a better way.

Thanks,
Gur.

答:
You're calling next() BEFORE you call res.send().  You want to only call one of those.  If you're sending a response, then don't call next() at all because calling next() tells Express to continue routing with other handlers (ultimately ending up with a 404 handler if no handler is found that actually handles it).

So, remove the call to next() and make sure nothing else is also trying to send a response for the request:

```<code>function login(req, res, next) {
    console.log("This line is executed");
    makePromise().then(function(result){
        res.cookie("key", "val");
        console.log("This line will execute after your promise resolves");
        res.send("Ok");
    }).catch(function(err) {
        console.log("Got error: ", err);
        res.status(500).send("Error");
    });
}
</code>```

And, remember that promises always resolve asynchronously (on some future tick).  That's why your call to next() was happening before your promise called its .then() handler.

Body:
So I have an app.post leading to this file:

'use strict';

function login(req, res, next) {
    console.log("This line is executed");
    makePromise().then(function(result){
        res.cookie("key", "val");
        console.log("This line isn't executed");
        res.send("Ok");
    });
    next();
}

function makePromise() {
    return new Promise(function (resolve, reject) {
        resolve("Done");
    });
}

module.exports = login;

But when I request the url it only executes the first console.log line and then returns 404 without sending the cookie or executing the rest of the code. This doesn't happen when I try setting the cookie outside the promise.

FYI: Obviously this isn't the code I'm actually trying to achieve but a sample that includes the relevant part for my problem. In my code I have to find something in my database in order to send to cookie so I have to use promise unless someone can help me find a better way.

Thanks,
Gur.

Body:
You're calling next() BEFORE you call res.send().  You want to only call one of those.  If you're sending a response, then don't call next() at all because calling next() tells Express to continue routing with other handlers (ultimately ending up with a 404 handler if no handler is found that actually handles it).

So, remove the call to next() and make sure nothing else is also trying to send a response for the request:

function login(req, res, next) {
    console.log("This line is executed");
    makePromise().then(function(result){
        res.cookie("key", "val");
        console.log("This line will execute after your promise resolves");
        res.send("Ok");
    }).catch(function(err) {
        console.log("Got error: ", err);
        res.status(500).send("Error");
    });
}

And, remember that promises always resolve asynchronously (on some future tick).  That's why your call to next() was happening before your promise called its .then() handler.


问:
PHP script only executing from command line when command is run from script's directory
I am trying to run this script from the command line:

```<code>#!/usr/local/bin/php
<?php
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
$txt = "Success \n";
fwrite($myfile, $txt);
fclose($myfile);
?>
</code>```

And it works, but only when I cd into the directory of the script and run:

```<code>/usr/local/bin/php test_script.php
</code>```

This also works:

```<code>/usr/local/bin/php /home/<username>/public_html/test_script.php
</code>```

but not when I leave the directory.

答:
A more formal answer to the original question:

Your file (test_script.php) needs to be made executable to be able to be run from anywhere. This can be done with chmod:

```<code>chmod 755 test_script.php
</code>```

and results in the file being able to be run by invoking.

```<code>./test_script.php
</code>```

And now, drumroll please, you should be able to run the file by invoking it like this:

```<code>./path/to/test_script.php
</code>```

That dot at the front of the path should allow you to run the script as an executable without doing anything else.

Hope it helps/works!

(If it doesn't work comment and I'll boot up my Linux machine and try to replicate it!)

EDIT

Ok, that's weird that it doesn't work! Shoot! Is the PHP CLI (command line interface) installed on your Linux server? If so I would encourage you to try:

```<code>php /path/to/your/test_script.php
</code>```

Hope that second suggestion helps!

EDIT 2

Aha moment number 2!!

I believe your php should be installed here: /usr/bin/php, having it in the local folder will not allow you to properly invoke it from another directory!

To download yourself a new installation of php, run

sudo apt-get install php5 libapache2-mod-php5

You will also have to change your script header to #!/usr/bin/php.

This was a good source for this third edit! I really hope it helps!

Body:
I am trying to run this script from the command line:

#!/usr/local/bin/php
<?php
$myfile = fopen("cc.log", "a") or die("Unable to open file!");
$txt = "Success \n";
fwrite($myfile, $txt);
fclose($myfile);
?>

And it works, but only when I cd into the directory of the script and run:

/usr/local/bin/php test_script.php

This also works:

/usr/local/bin/php /home/<username>/public_html/test_script.php

but not when I leave the directory.

Body:
A more formal answer to the original question:

Your file (test_script.php) needs to be made executable to be able to be run from anywhere. This can be done with chmod:

chmod 755 test_script.php

and results in the file being able to be run by invoking.

./test_script.php

And now, drumroll please, you should be able to run the file by invoking it like this:

./path/to/test_script.php

That dot at the front of the path should allow you to run the script as an executable without doing anything else.

Hope it helps/works!

(If it doesn't work comment and I'll boot up my Linux machine and try to replicate it!)

EDIT

Ok, that's weird that it doesn't work! Shoot! Is the PHP CLI (command line interface) installed on your Linux server? If so I would encourage you to try:

php /path/to/your/test_script.php

Hope that second suggestion helps!

EDIT 2

Aha moment number 2!!

I believe your php should be installed here: /usr/bin/php, having it in the local folder will not allow you to properly invoke it from another directory!

To download yourself a new installation of php, run

sudo apt-get install php5 libapache2-mod-php5

You will also have to change your script header to #!/usr/bin/php.

This was a good source for this third edit! I really hope it helps!


问:
How can I group by date time column without taking time into consideration
I have a bunch of product orders and I'm trying to group by the date and sum the quantity for that date. How can I group by the month/day/year without taking the time part into consideration?

3/8/2010 7:42:00 should be grouped with 3/8/2010 4:15:00

答:
Here is the example works fine in oracle</p>

```<code>select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');
</code>```

Body:
Here is the example works fine in oracle

select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');


问:
Specify generic type parameter in Scala
I'm new to Scala and have generic method written in Java:

```<code>public interface Context{
    <T> Optional<T> get(String parameterName);
}
</code>```

and Scala class:

```<code>class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}
</code>```

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?

答:
val str:  Optional[String] = ctx.get("str") should do it.

And so should val str = ctx.get[String]("str")

Title: Specify generic type parameter in Scala

Body:
I'm new to Scala and have generic method written in Java:

public interface Context{
    <T> Optional<T> get(String parameterName);
}

and Scala class:

class Mcls(ctx: Context){
    val str = ctx.[Optional[String]]get("str").get //error
}

Is there a way to specify generic type parameter shorted then asInstanceOf[Optional[String]] in Scala?


问:
Insufficient permissions for device in Android Studio Workspace running in openSUSE 13.2
I have a rooted Motorola Defy+ running a Cyanogenmod v11 custom ROM (nightly build) created by Quarx. Using Android Studio Workspace,(ASW) v.1.1.0, when I try and debug on this device, I get

```<code>????????????[null]
</code>```

listed in the Choose Device window, with the Logcat window showing

```<code>insufficient permissions for device
</code>```

I would really like to use this device and ROM for debugging purposes.

When I enter lsusb from the command line I get,

```<code>Bus 002 Device 002: ID 22b8:431d Motorola PCS
</code>```

This is the correct device id for Motorola units. I have installed 51-android.rules and 71-android.rules in /etc/udev/rules.d/ with the correct Motorola ids in these files.

I've also tried Revoke USB debugging authority, from Developer Options on the device, with no luck.

I have not tried running ASW as root hoping that there might be another option; is there?

Update: I was able to get in and access ADB by

```<code>uvachem-gsmith2:/home/greg/Android/Sdk/platform-tools # ./adb
</code>```

I then did a kill server, did an SU to root user and restarted the server. I then tried to connect to the device from Android Studio. Got a message on the device about accepting the RSA key from the PC, said "Yes" and then was able to deploy the app to the device. So back to my original question, Is there another way to access this device without logging in as root? It seems as if there is a permission issue on the phone file system that is preventing this...

Update #2 The core problem here was a permission thing. Even though running ADB as root will allow access to the rooted Android device, a better solution is to change permissions in the udev file for this device...resetting 664 to 666, (see answer below). This allows the PC to access the file system on the device.

答:
I have face the same problem and i have resolved this by
Adding the path of your_android_sdk_path to the environment variable  like

```<code>sudo export $PATH:/your_android_sdk_path/platform-tools/adb
</code>```

its your wish how you want to add this to your account or system wide by editing these file  ~/.bashrc file or ~/.profile
or
/etc/profile, /etc/bash.bashrc, or /etc/environment if u want to add to system wide access.

and then create the link of that in bin

```<code>sudo ln -s /your_android_sdk_path/platform-tools/adb /bin/adb
</code>```

if you have used adb devices or any command then first kill the server like

```<code>adb kill-server
</code>```

then start the server like

```<code>adb start-server
adb devices
</code>```

now you can see your devices are listed properly without an issue

Body:
I have a rooted Motorola Defy+ running a Cyanogenmod v11 custom ROM (nightly build) created by Quarx. Using Android Studio Workspace,(ASW) v.1.1.0, when I try and debug on this device, I get

????????????[null]

listed in the Choose Device window, with the Logcat window showing

insufficient permissions for device

I would really like to use this device and ROM for debugging purposes.

When I enter lsusb from the command line I get,

Bus 002 Device 002: ID 22b8:431d Motorola PCS

This is the correct device id for Motorola units. I have installed 51-android.rules and 71-android.rules in /etc/udev/rules.d/ with the correct Motorola ids in these files.

I've also tried Revoke USB debugging authority, from Developer Options on the device, with no luck.

I have not tried running ASW as root hoping that there might be another option; is there?

Update: I was able to get in and access ADB by

uvachem-gsmith2:/home/greg/Android/Sdk/platform-tools # ./adb

I then did a kill server, did an SU to root user and restarted the server. I then tried to connect to the device from Android Studio. Got a message on the device about accepting the RSA key from the PC, said "Yes" and then was able to deploy the app to the device. So back to my original question, Is there another way to access this device without logging in as root? It seems as if there is a permission issue on the phone file system that is preventing this...

Update #2 The core problem here was a permission thing. Even though running ADB as root will allow access to the rooted Android device, a better solution is to change permissions in the udev file for this device...resetting 664 to 666, (see answer below). This allows the PC to access the file system on the device.

Body:
I have face the same problem and i have resolved this by
Adding the path of your_android_sdk_path to the environment variable  like

sudo export $PATH:/your_android_sdk_path/platform-tools/adb

its your wish how you want to add this to your account or system wide by editing these file  ~/.bashrc file or ~/.profile
or
/etc/profile, /etc/bash.bashrc, or /etc/environment if u want to add to system wide access.

and then create the link of that in bin

sudo ln -s /your_android_sdk_path/platform-tools/adb /bin/adb

if you have used adb devices or any command then first kill the server like

adb kill-server

then start the server like

adb start-server
adb devices

now you can see your devices are listed properly without an issue


问:
How to append an pre-filled textarea content using fillIn
I have a textarea which is already filled in with value using fillIn function. But now I want to append the same textarea with another character '@'. But when I tried using fillIn again; it rewrites the textarea. How can I append the text. I need it to be in two step process.

HTML:

<textarea data-test-id='descriptor'></textarea>```
</div>
</div>
</p>

<p>Test:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>test('testing-fillIn', async function(assert){
await fillIn(testSelector('descriptor'), 'First text ');
await fillIn(testSelector('descriptor'), '@');
});</code>```

The output should be : First text @

答:
test('testing-fillIn', async function(assert){
await fillIn(testSelector('descriptor'), 'First text ');
var textVal =document.getElementById('textArea').val();
await fillIn(testSelector('descriptor'), textVal+'@');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="textArea" data-test-id='descriptor'></textarea></code>```

Body:
I have a textarea which is already filled in with value using fillIn function. But now I want to append the same textarea with another character '@'. But when I tried using fillIn again; it rewrites the textarea. How can I append the text. I need it to be in two step process.

HTML:

<textarea data-test-id='descriptor'></textarea>

Test:

test('testing-fillIn', async function(assert){
await fillIn(testSelector('descriptor'), 'First text ');
await fillIn(testSelector('descriptor'), '@');
});

The output should be : First text @

Body:
test('testing-fillIn', async function(assert){
await fillIn(testSelector('descriptor'), 'First text ');
var textVal =document.getElementById('textArea').val();
await fillIn(testSelector('descriptor'), textVal+'@');
});

<textarea id="textArea" data-test-id='descriptor'></textarea>


问:
The matching wildcard is strict, but no declaration can be found for element 'context:component-scan
I am getting the following errors while trying my first spring project:

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'context:component-scan
```

<p>Here is the <code>applicationContext.xml</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

        <context:component-scan base-package="com.xyz" />

</beans>
</code>```

What is causing the error?

答:
It's too late but somewhat may useful to others

The matching wildcard is strict, but no declaration can be found for
  element 'context:component-scan

which Means you have Missed some Declarations or The Required Declarations Not Found in Your XML

In my case i forgot to add the follwoing

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-4.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

After Adding this the Problem Gone away

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am getting the following errors while trying my first spring project:

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

Here is the applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

        <context:component-scan base-package="com.xyz" />

</beans>

What is causing the error?

Body:
It's too late but somewhat may useful to others

The matching wildcard is strict, but no declaration can be found for
  element 'context:component-scan

which Means you have Missed some Declarations or The Required Declarations Not Found in Your XML

In my case i forgot to add the follwoing

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-aop-4.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

After Adding this the Problem Gone away

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">