问:
C: why does pointer address set to null in function, have a non-null address in main?
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

```<code>//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...
</code>```

答:
Most of the comments have picked up the various problems. See my comments inline with your original code, and a rewritten example below (using a list rather than tree for simplicity):

```<code>//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); //here returns (nil) as expected
        // Its not actually expected - the compiler happens to
        // set it to null but it is actually undefined - you
        // have not yet set t->top to any address (through malloc)
        // or explicitly assigned it as NULL
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t; //This line creates the tree
                    // as a locally allocated variable
                    // of type org_tree. The declaration
                    // allocates it though it is yet
                    // to be assigned.

        //CreateTree(&t);   //this is not required.
                            // It would be if your tree head
                            // was a pointer but it is not

        printf("%p\n", t.top); //**here returns a memory location
        // Through undefined behaviour. Even when you called
        // CreateTree, you reassigned it (t=temp) which
        // creates a memory hole (the original address
        // assigned by declaration is lost)

        t.top = NULL; //**if I add this, then if below works.
        // Because it is now assigned.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
        }
</code>```

And this is a re-written version which addresses the pointer issues by example (though noting that it's not the most elegant way to approach lists and trees - but will hopefully be useful for explanation). The immediately obvious opportunity is to combine CreateEmployee() and AddNodeToList():

```<code>#include <stdio.h>
#include <stdlib.h>

//There's many more elegant ways to do this, though this
//version extends your approach to provide understanding

// This is also simplified as a linked list, unsorted
// rather than a tree - again just to look at the pointer
// concepts;

// To use a tree a recursive walk is best to avoid complex
// procedural structures plus logic to determine left / right
// branches etc.

typedef struct employee {
    char mgr[20], st1[20], st2[20], st3[20], st4[20];
    struct employee *next_node;
} employee;

//struct for org chart list
typedef struct org_list {
    struct employee *top;
} org_list;

//create org list
org_list *CreateList(void)  // must return it
{
    org_list *temp;
    temp = malloc(sizeof(org_list));
    //t = temp;

    temp->top = NULL; //needs to be explicit

    printf("%p\n", temp->top); //should be NULL

    return temp; //send back the address in the heap
}

//create employee
employee *CreateEmployee(employee *emp) {
    emp = malloc(sizeof(employee));
    emp->next_node = NULL;
    return emp;
}

int AddNodeToList(org_list* list_head, employee* e) {

    if (list_head->top == NULL) { //special case - empty list
        list_head->top = e;
        return 1; //all done
    } else {
        employee* temp_ptr;         //temporary pointer to walk the list
        temp_ptr = list_head->top;

        while (temp_ptr->next_node != NULL) {
            temp_ptr = temp_ptr->next_node;
        }
        // temp_ptr now points to the last node in the list
        // add the employee

        temp_ptr->next_node = e;
        return 1;
    }
}

//main program
int main(void) {
    FILE *file;
    file = fopen("employee.list", "r");
    printf("file opened\n");    //not necessarily - check (file != NULL)

    org_list *t;    //This line creates _a pointer to_ the list

    t = CreateList();   //you need an address to come back
    // The other way is to use a pointer to a pointer but this
    // gets confusing

    printf("%p\n", t->top); // This is now NULL
    // Note you haven't yet added an employee - just the head

    //t.top = NULL; //already done

    char mgr[20], st1[20], st2[20], st3[20], st4[20];

    while (fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4) != EOF) {
        employee *m;    // this doesn't malloc or assign the underlying struct

        // this does
        m = CreateEmployee(m);

        if (m != NULL) {
            // copy the scanned strings into m->mgr m->st1 etc using strncpy

        }
        // but m is still not added to the list yet!
        AddNodeToList(t, m);
    }
}
</code>```

Body:
I am a beginner in C. I am working on an assignment to create a tree data structure. I have an if in main where I check if top is NULL before doing some action. Within my function to create the top pointer, it returns NULL right after being created (as expected, I haven't pointed it at anything yet). However when execution goes back to main, it returns an address even though I haven't assigned it one. So, my if doesn't work like I want it to.

I have noticed, if I set top to NULL from within main, then it sticks.

My question is, why does the address of top change from NULL to something else when execution returns to main? Have I done something in my code to unknowingly give point top to an unintended address?

//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); **here returns (nil) as expected
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t;

        CreateTree(&t);
        printf("%p\n", t.top) **here returns a memory location

        t.top = NULL **if I add this, then if below works.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
         }
         ...

Body:
Most of the comments have picked up the various problems. See my comments inline with your original code, and a rewritten example below (using a list rather than tree for simplicity):

//struct for org chart tree
    typedef struct org_tree{
        struct employee *top;
    } org_tree;

//create org tree
    void CreateTree(org_tree *t)
    {
        org_tree *temp;
        temp = malloc(sizeof(org_tree));
        t = temp;
        printf("%p\n", t->top); //here returns (nil) as expected
        // Its not actually expected - the compiler happens to
        // set it to null but it is actually undefined - you
        // have not yet set t->top to any address (through malloc)
        // or explicitly assigned it as NULL
    }

//main program
    int main(void)
    {
        FILE *file;
        file = fopen("employee.list", "r");
        printf("file opened\n");
        org_tree t; //This line creates the tree
                    // as a locally allocated variable
                    // of type org_tree. The declaration
                    // allocates it though it is yet
                    // to be assigned.

        //CreateTree(&t);   //this is not required.
                            // It would be if your tree head
                            // was a pointer but it is not

        printf("%p\n", t.top); //**here returns a memory location
        // Through undefined behaviour. Even when you called
        // CreateTree, you reassigned it (t=temp) which
        // creates a memory hole (the original address
        // assigned by declaration is lost)

        t.top = NULL; //**if I add this, then if below works.
        // Because it is now assigned.

        char mgr[20], st1[20], st2[20], st3[20], st4[20];

        while(fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4)!=EOF)
        {
            employee *m;
            if (t.top !=NULL) **this if not working like I want it to because NULL doesn't "stick" unless set in main.
            {
             ///remaining code not relevant to question//
            }
        }

And this is a re-written version which addresses the pointer issues by example (though noting that it's not the most elegant way to approach lists and trees - but will hopefully be useful for explanation). The immediately obvious opportunity is to combine CreateEmployee() and AddNodeToList():

#include <stdio.h>
#include <stdlib.h>

//There's many more elegant ways to do this, though this
//version extends your approach to provide understanding

// This is also simplified as a linked list, unsorted
// rather than a tree - again just to look at the pointer
// concepts;

// To use a tree a recursive walk is best to avoid complex
// procedural structures plus logic to determine left / right
// branches etc.

typedef struct employee {
    char mgr[20], st1[20], st2[20], st3[20], st4[20];
    struct employee *next_node;
} employee;

//struct for org chart list
typedef struct org_list {
    struct employee *top;
} org_list;

//create org list
org_list *CreateList(void)  // must return it
{
    org_list *temp;
    temp = malloc(sizeof(org_list));
    //t = temp;

    temp->top = NULL; //needs to be explicit

    printf("%p\n", temp->top); //should be NULL

    return temp; //send back the address in the heap
}

//create employee
employee *CreateEmployee(employee *emp) {
    emp = malloc(sizeof(employee));
    emp->next_node = NULL;
    return emp;
}

int AddNodeToList(org_list* list_head, employee* e) {

    if (list_head->top == NULL) { //special case - empty list
        list_head->top = e;
        return 1; //all done
    } else {
        employee* temp_ptr;         //temporary pointer to walk the list
        temp_ptr = list_head->top;

        while (temp_ptr->next_node != NULL) {
            temp_ptr = temp_ptr->next_node;
        }
        // temp_ptr now points to the last node in the list
        // add the employee

        temp_ptr->next_node = e;
        return 1;
    }
}

//main program
int main(void) {
    FILE *file;
    file = fopen("employee.list", "r");
    printf("file opened\n");    //not necessarily - check (file != NULL)

    org_list *t;    //This line creates _a pointer to_ the list

    t = CreateList();   //you need an address to come back
    // The other way is to use a pointer to a pointer but this
    // gets confusing

    printf("%p\n", t->top); // This is now NULL
    // Note you haven't yet added an employee - just the head

    //t.top = NULL; //already done

    char mgr[20], st1[20], st2[20], st3[20], st4[20];

    while (fscanf(file, "%s %s %s %s %s\n", mgr, st1, st2, st3, st4) != EOF) {
        employee *m;    // this doesn't malloc or assign the underlying struct

        // this does
        m = CreateEmployee(m);

        if (m != NULL) {
            // copy the scanned strings into m->mgr m->st1 etc using strncpy

        }
        // but m is still not added to the list yet!
        AddNodeToList(t, m);
    }
}


来源: stackexchange

问:
Using something other than a Frame for Window.Current.Content
I am trying to create a top level navigation control in UWP. So far I was thinking of replacing the Window.Current.Content with my top level navigation control instead of a Frame. (My Control wraps a frame)

It works but now while deployed to a phone the status bar and virtual buttons overlap my content.

Has anyone had any success not using a Frame as their window's content?

答:
I haven't changed my content to other controls but it seems even using Frame you will get the same behavior on phone. To control this you may need to caculate the height of the status bar and virtual button then do some modification to change your UI to fit the content.<br>
By the way, I have no idea why you need to use your control replce the frame. Using Frame you can still put your control on your frame and then keep the navigation history. </p>

ContentLicense: CC BY-SA 3.0

Body:
I haven't changed my content to other controls but it seems even using Frame you will get the same behavior on phone. To control this you may need to caculate the height of the status bar and virtual button then do some modification to change your UI to fit the content.

By the way, I have no idea why you need to use your control replce the frame. Using Frame you can still put your control on your frame and then keep the navigation history.


问:
casperjs / Filling and submitting a form on facebook error
I'm trying to scrap basic informations from facebook profiles. My final goal is to get for example the age of someone (if the information is accessible on facebook of course) by using casperjs.

So I installed Casper.js.
I started by filling my password and mail to get access to the search field in a second time.

But :

ReferenceError: Can't find variable: casper

phantomjs://code/scrapin.js:1 in global code
    :0 in injectJs
    phantomjs://code/bootstrap.js:456
  Hint: you may want to use the casperjs test command.

phantomjs://code/bootstrap.js:148 in onPhantomError

Here is my code:

```<code>     casper.start('https://www.facebook.com/', function() {

    this.fill('form[id="login-form"]', {
        'username': 'my mail adress',
        'password': 'my fb password'
    }, true);
    });

casper.then(function() {
    this.echo(this.getTitle());
});

casper.run();
</code>```

I precise that Casper.js is working on my computer, it worked for other tasks.

I'm sure it's a basic mistake, I'm totally a beginner on javascript!
Please excuse my bad english, I do my best ;)

Thank you!

答:
On top of your script, add this line,

```<code>var casper = require('casper').create();
</code>```

Then when you want to run the script, run it using the following,

```<code>casperjs myPreciousScript.js
</code>```

Body:
I'm trying to scrap basic informations from facebook profiles. My final goal is to get for example the age of someone (if the information is accessible on facebook of course) by using casperjs.

So I installed Casper.js.
I started by filling my password and mail to get access to the search field in a second time.

But :

ReferenceError: Can't find variable: casper

phantomjs://code/scrapin.js:1 in global code
    :0 in injectJs
    phantomjs://code/bootstrap.js:456
  Hint: you may want to use the casperjs test command.

phantomjs://code/bootstrap.js:148 in onPhantomError

Here is my code:

     casper.start('https://www.facebook.com/', function() {

    this.fill('form[id="login-form"]', {
        'username': 'my mail adress',
        'password': 'my fb password'
    }, true);
    });

casper.then(function() {
    this.echo(this.getTitle());
});

casper.run();

I precise that Casper.js is working on my computer, it worked for other tasks.

I'm sure it's a basic mistake, I'm totally a beginner on javascript!
Please excuse my bad english, I do my best ;)

Thank you!

Body:
On top of your script, add this line,

var casper = require('casper').create();

Then when you want to run the script, run it using the following,

casperjs myPreciousScript.js


问:
netbeans sql's statment using Like operator
I am trying to pass value from Jcombobox and I used Like Operator in order to retrieve data from Database ..
I need to retrieve all data related to a chosen month from combobox </p>

```<code>String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '?%'";
try {
    ps = con.prepareStatement(sql);
    ps.setString(1, cmb.getSelectedItem().toString());
    rs = ps.executeQuery();
    table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, e.getMessage());
}
</code>```

答:
```<code>String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '"+cmb.getText().toString()+"%'";
</code>```

Use this format.
this will help more...

Body:
I am trying to pass value from Jcombobox and I used Like Operator in order to retrieve data from Database ..
I need to retrieve all data related to a chosen month from combobox

String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '?%'";
try {
    ps = con.prepareStatement(sql);
    ps.setString(1, cmb.getSelectedItem().toString());
    rs = ps.executeQuery();
    table_PatuentReg.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
    JOptionPane.showMessageDialog(null, e.getMessage());
}

Body:
String sql = "SELECT * FROM Treatment WHERE Treatment_Date LIKE '"+cmb.getText().toString()+"%'";

Use this format.
this will help more...


问:
Component is part of the declaration of 2 modules
I try to build an ionic 2 app.
When I try the app in the browser with ionic serve or launch it on an emulator everything works fine.

But when I try to build it every time the error

```<code>ionic-app-script tast: "build"
Error Type AddEvent in "PATH"/add.event.ts is part of the declarations of 2 modules: AppModule in "PATH"/app.modules.ts and AddEvent in "PATH"/add-event.module.ts.
Please consider moving AddEvent in "PATH"/add-event.ts to a higher module that imports AppModule in "PATH"/app.module.ts and AddEventModule.
You can also create a new NgModule that exports and includes AddEvent then import that NgModule in AppModule and AddEventModule
</code>```

my AppModule is

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { AngularFireModule } from 'angularfire2';
import { MyApp } from './app.component';
import { Eventdata } from '../providers/eventdata';
import { AuthProvider } from '../providers/auth-provider';
import { HttpModule } from '@angular/http';

import { HomePage } from '../pages/home/home';
import { Login } from '../pages/login/login';
import { Register } from '../pages/register/register';
import { AddEvent } from '../pages/add-event/add-event';
import { EventDetails } from '../pages/event-details/event-details';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    Login,
    Register,
    AddEvent,
    EventDetails

  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    AngularFireModule.initializeApp(config)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    Login,
    Register,
    AddEvent,
    EventDetails
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}, Eventdata, AuthProvider
  ]
})
export class AppModule {}
```
<p>and my add-event.module.ts is</p>
<pre class="lang-ts prettyprint-override"><code>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { AddEvent } from './add-event';

@NgModule({
  declarations: [
    AddEvent,
  ],
  imports: [
    IonicPageModule.forChild(AddEvent),
  ],
  exports: [
    AddEvent
  ]
})
export class AddEventModule {}
</code>```

I understand that I have to remove one of the declarations, but I don't know how.

If I remove the declaration from AppModule I get an Error that the Login Page is not found, while running ionic serve

答:
IN Angular 4. This error is considered as ng serve run time cache issue.

case:1 this error will occur, once you import the component in one module and again import in sub modules will occur.

case:2 Import one Component in wrong place and removed and replaced in Correct module, That time it consider as ng serve cache issue. Need to Stop the project and start -do again ng serve, It will work as expected.

ContentLicense: CC BY-SA 4.0

Body:
I try to build an ionic 2 app.
When I try the app in the browser with ionic serve or launch it on an emulator everything works fine.

But when I try to build it every time the error

ionic-app-script tast: "build"
Error Type AddEvent in "PATH"/add.event.ts is part of the declarations of 2 modules: AppModule in "PATH"/app.modules.ts and AddEvent in "PATH"/add-event.module.ts.
Please consider moving AddEvent in "PATH"/add-event.ts to a higher module that imports AppModule in "PATH"/app.module.ts and AddEventModule.
You can also create a new NgModule that exports and includes AddEvent then import that NgModule in AppModule and AddEventModule

my AppModule is

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { AngularFireModule } from 'angularfire2';
import { MyApp } from './app.component';
import { Eventdata } from '../providers/eventdata';
import { AuthProvider } from '../providers/auth-provider';
import { HttpModule } from '@angular/http';

import { HomePage } from '../pages/home/home';
import { Login } from '../pages/login/login';
import { Register } from '../pages/register/register';
import { AddEvent } from '../pages/add-event/add-event';
import { EventDetails } from '../pages/event-details/event-details';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    Login,
    Register,
    AddEvent,
    EventDetails

  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule,
    AngularFireModule.initializeApp(config)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    Login,
    Register,
    AddEvent,
    EventDetails
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}, Eventdata, AuthProvider
  ]
})
export class AppModule {}

and my add-event.module.ts is

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { AddEvent } from './add-event';

@NgModule({
  declarations: [
    AddEvent,
  ],
  imports: [
    IonicPageModule.forChild(AddEvent),
  ],
  exports: [
    AddEvent
  ]
})
export class AddEventModule {}

I understand that I have to remove one of the declarations, but I don't know how.

If I remove the declaration from AppModule I get an Error that the Login Page is not found, while running ionic serve


问:
Angular2, How to get the current active component selector to use it as class globally for css styling
I want to apply styling for each component, what i am looking is I want to get the current component selector name and pass it as class name like this

```<code><div [class]="component-slector-name">
<router-outlet></router-outlet>
</div>
</code>```

so that for every active component I get its selector and set it to div tag for custom css styling..

Does anyone know how to do this ??
Thanks in advance for time and support.

答:
There are different ways to achieve it.

Here is one option:

*.html

  <router-outlet (activate)="onActivated($event)"></router-outlet>

```

<p><strong>*.ts</strong></p>

<pre class="lang-typescript prettyprint-override"><code>activeSelector: string;

constructor(private resolver: ComponentFactoryResolver) {}

onActivated(component) {
  this.activeSelector =
        this.resolver.resolveComponentFactory(component.constructor).selector;
}
</code>```

Body:
I want to apply styling for each component, what i am looking is I want to get the current component selector name and pass it as class name like this

<router-outlet></router-outlet>

so that for every active component I get its selector and set it to div tag for custom css styling..

Does anyone know how to do this ??
Thanks in advance for time and support.

Body:
There are different ways to achieve it.

Here is one option:

*.html

<div [class]="activeSelector">
  <router-outlet (activate)="onActivated($event)"></router-outlet>
</div>

*.ts

activeSelector: string;

constructor(private resolver: ComponentFactoryResolver) {}

onActivated(component) {
  this.activeSelector =
        this.resolver.resolveComponentFactory(component.constructor).selector;
}


问:
Android Pass Bitmap to Native in 2.1 and lower
It's extremely easy to get the Bitmap data in the NDK when working with Android 2.2, but with 2.1 and lower, the AndroidBitmap_lockPixels function is not available. I've been searching for the past few hours, but nothing has worked.

How can I access the pixel data of a bitmap without using that function?

答:
Create an IntBuffer in your Java code and pass the array down to your native library:

```<code>// this is called from native code
buffer = IntBuffer.allocate(width*height);
return buffer.array();
</code>```

Use GetIntArrayElements to get an jint* and write to the array:

```<code>jint * arr = env->GetIntArrayElements((jintArray)bufferArray, NULL);
</code>```

Write to the array and when finished, release:

```<code>env->ReleaseIntArrayElements((jintArray)bufferArray, arr, 0);
</code>```

Notify the Java code that the array has been updated and use Canvas.drawBitmap() to draw the IntBuffer:

```<code>canvas.drawBitmap(buffer.array(), ....);
</code>```

To draw to a Bitmap, initialize the canvas with the bitmap

```<code>... new Canvas(bitmap)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Create an IntBuffer in your Java code and pass the array down to your native library:

// this is called from native code
buffer = IntBuffer.allocate(width*height);
return buffer.array();

Use GetIntArrayElements to get an jint* and write to the array:

jint * arr = env->GetIntArrayElements((jintArray)bufferArray, NULL);

Write to the array and when finished, release:

env->ReleaseIntArrayElements((jintArray)bufferArray, arr, 0);

Notify the Java code that the array has been updated and use Canvas.drawBitmap() to draw the IntBuffer:

canvas.drawBitmap(buffer.array(), ....);

To draw to a Bitmap, initialize the canvas with the bitmap

... new Canvas(bitmap)


问:
how to ignore builtin xslt rules
I have this xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<lib>
    <books xmlns="http://www.books.com/SRK">
        <name>English</name>
    </books>
    <cats>
        <cat>cat1</cat>
        <cat>cat2</cat>
    </cats>
</lib>
</code>```

and this xslt:

```<code><xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="//cats/*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="node()"/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>
</code>```

the expected out is to not have english in output but first it  write english and then what I need.
I mean currently output is :

```<code>English<cat>cat1</cat>
<cat>cat2</cat>
</code>```

but I don't want it contain English.

答:
You can apply your template only to cats section. like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes"/>
    <xsl:template match="node()|@*">
           <xsl:apply-templates select="//cats"/>
    </xsl:template>
    <xsl:template match="cats">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>
</code>```

Title: how to ignore builtin xslt rules

Body:
I have this xml:

<?xml version="1.0" encoding="UTF-8"?>
<lib>
    <books xmlns="http://www.books.com/SRK">
        <name>English</name>
    </books>
    <cats>
        <cat>cat1</cat>
        <cat>cat2</cat>
    </cats>
</lib>

and this xslt:

<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="//cats/*">
        <xsl:element name="{local-name()}">
            <xsl:apply-templates select="node()"/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>

the expected out is to not have english in output but first it  write english and then what I need.
I mean currently output is :

English<cat>cat1</cat>
<cat>cat2</cat>

but I don't want it contain English.

Body:
You can apply your template only to cats section. like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes"/>
    <xsl:template match="node()|@*">
           <xsl:apply-templates select="//cats"/>
    </xsl:template>
    <xsl:template match="cats">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>


问:
Checking if array element is empty with for loop in bash
Can you please provide a sample code for checking if array element is empty using for loop?

None of this worked for me:

```<code>declare -a f=( 'file' )
for ((i=0; ${f[$i]}; i++); do echo "i: $i"; done
for ((i=0; `test -n "${f[$i]}"`; i++); do echo "i: $i"; done
</code>```

What I wanted is to keep this braces-like for style and iterate over array, following solution worked for me:

```<code>for((i=0; i < ${#f[@]}; i++))
</code>```

Does any other syntax available?

答:
This might work</p>

```<code>for i in ${f[@]}
do
   if [ -z "$f[$i]" ]
   then
       #do whatever you want
   fi
done
</code>```

Body:
Can you please provide a sample code for checking if array element is empty using for loop?

None of this worked for me:

declare -a f=( 'file' )
for ((i=0; ${f[$i]}; i++); do echo "i: $i"; done
for ((i=0; `test -n "${f[$i]}"`; i++); do echo "i: $i"; done

What I wanted is to keep this braces-like for style and iterate over array, following solution worked for me:

for((i=0; i < ${#f[@]}; i++))

Does any other syntax available?

Body:
This might work

for i in ${f[@]}
do
   if [ -z "$f[$i]" ]
   then
       #do whatever you want
   fi
done


问:
Creating voice command synonyms in GRXML
I've created a voice controlled UWP application in C++/CX (for Hololens, if that matters). A very simple one, mostly according to some samples, this is the speech recognition event handler:

```<code>void MyAppMain::HasSpoken(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
{
    if (args->Result->Confidence == SpeechRecognitionConfidence::Medium
        || args->Result->Confidence == SpeechRecognitionConfidence::High)
    {
        process_voice_command(args->Result->Text);
    }
}
</code>```

Everything works so far, the recognition result is in args->Result->Text variable. Now, I only need to support a very limited set of voice commands and simply ignore everything else, but within that limited set of commands I want some variability. It seems, the last example on this page is exactly about that. So I made the following grammar file based on that:

```<code><grammar version="1.0" xml:lang="en-US" root="nextCommands" xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="nextCommands">
    <item>
      <one-of>
        <item>next</item>
        <item>go</item>
        <item>advance</item>
      </one-of>
      <tag>out="next";</tag>
    </item>
  </rule>

</grammar>
</code>```

What I want with it is that when I say either "next", "go" or "advance", the recognition engine just returns "next", so it is in the args->Result->Text above. What it actually does for me right now is limiting the set of recognized words to those three, but it simply returns the word I say, without converting it to "next". Looks like it either ignores the <tag> element, or I have to retrieve its content in a different way in my C++/CX program. Or <tag> doesn't work the way I think it does. What shall I change to make it work?

答:
Or  doesn't work the way I think it does

A tag is a legal rule expansion,Tags do not affect the legal word patterns defined by the grammars or the process of recognizing speech or other input given a grammar. Details please check Tags section of Speech Recognition Grammar Specification.

What I want with it is that when I say either "next", "go" or "advance", the recognition engine just returns "next"

Speech recognition converts words spoken by the user into text for form input.  Constraints, or grammars, define the spoken words and phrases that can be matched by the speech recognizer. The grammar you used is for defining the match worlds. If you want "next","go" or "advance" to execute the same command, you could deal with them when you handle the text result. For example,

```<code>// Start recognition.
Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeWithUIAsync();
// Do something with the recognition result.
if (speechRecognitionResult.Text == "go" || speechRecognitionResult.Text == "next" || speechRecognitionResult.Text == "advance")
{

}
</code>```

Details please reference the Scenario_SRGSConstraint of the official sample which contains the method HandleRecognitionResult.

Body:
I've created a voice controlled UWP application in C++/CX (for Hololens, if that matters). A very simple one, mostly according to some samples, this is the speech recognition event handler:

void MyAppMain::HasSpoken(SpeechContinuousRecognitionSession ^sender, SpeechContinuousRecognitionResultGeneratedEventArgs ^args)
{
    if (args->Result->Confidence == SpeechRecognitionConfidence::Medium
        || args->Result->Confidence == SpeechRecognitionConfidence::High)
    {
        process_voice_command(args->Result->Text);
    }
}

Everything works so far, the recognition result is in args->Result->Text variable. Now, I only need to support a very limited set of voice commands and simply ignore everything else, but within that limited set of commands I want some variability. It seems, the last example on this page is exactly about that. So I made the following grammar file based on that:

<grammar version="1.0" xml:lang="en-US" root="nextCommands" xmlns="http://www.w3.org/2001/06/grammar" tag-format="semantics/1.0">

  <rule id="nextCommands">
    <item>
      <one-of>
        <item>next</item>
        <item>go</item>
        <item>advance</item>
      </one-of>
      <tag>out="next";</tag>
    </item>
  </rule>

</grammar>

What I want with it is that when I say either "next", "go" or "advance", the recognition engine just returns "next", so it is in the args->Result->Text above. What it actually does for me right now is limiting the set of recognized words to those three, but it simply returns the word I say, without converting it to "next". Looks like it either ignores the <tag> element, or I have to retrieve its content in a different way in my C++/CX program. Or <tag> doesn't work the way I think it does. What shall I change to make it work?

Body:
Or  doesn't work the way I think it does

A tag is a legal rule expansion,Tags do not affect the legal word patterns defined by the grammars or the process of recognizing speech or other input given a grammar. Details please check Tags section of Speech Recognition Grammar Specification.

What I want with it is that when I say either "next", "go" or "advance", the recognition engine just returns "next"

Speech recognition converts words spoken by the user into text for form input.  Constraints, or grammars, define the spoken words and phrases that can be matched by the speech recognizer. The grammar you used is for defining the match worlds. If you want "next","go" or "advance" to execute the same command, you could deal with them when you handle the text result. For example,

// Start recognition.
Windows.Media.SpeechRecognition.SpeechRecognitionResult speechRecognitionResult = await speechRecognizer.RecognizeWithUIAsync();
// Do something with the recognition result.
if (speechRecognitionResult.Text == "go" || speechRecognitionResult.Text == "next" || speechRecognitionResult.Text == "advance")
{

}

Details please reference the Scenario_SRGSConstraint of the official sample which contains the method HandleRecognitionResult.


问:
Transform a text case in to UpperCase Using JavaFX CSS
Any one can help me to Change the Case in JavaFX project I'm trying to find solution by browse, But i can't Please find the below code I'm trying but it can't get the result

```<code>.text {
    -fx-font-family: "Arial";
    -fx-font-size: 24;
    -fx-text-fill: #263248;
    -fx-padding: 10 20 10 20;
    -fx-cursor: hand;
    -fx-text-transform: uppercase; /* this property is not working */
}
</code>```

Any help would really be appreciated! Thanks!

答:
Unfortunately, there's no CSS property that handles text transformation in JavaFX (currently none, see the JavaFX CSS Reference). But you can actually do it in Java with just a single line of code!

For an instance, you have a Label node which has an ID named label.

```<code><Label fx:id="label" text="Hello!" />
</code>```

In this case, you can reference the node by its ID and set its text toUpperCase() with a controller class.

```<code>// Reference to the node you wish
// to transform texts to uppercase.
@FXML private Label label;

@Override
// Assuming you have Initializable class implemented.
public void initialize(URL arg0, ResourceBundle arg1) {

  // Get the current text value of the node.
  String text = label.getText();

  // Then update the text into whatever case you like.
  label.setText(text.toUpperCase());

}
</code>```

OR

Simply straight from a Java code (one straight line of code).

```<code>Label label = new Label("Hello!".toUpperCase());
</code>```

Body:
Any one can help me to Change the Case in JavaFX project I'm trying to find solution by browse, But i can't Please find the below code I'm trying but it can't get the result

.text {
    -fx-font-family: "Arial";
    -fx-font-size: 24;
    -fx-text-fill: #263248;
    -fx-padding: 10 20 10 20;
    -fx-cursor: hand;
    -fx-text-transform: uppercase; /* this property is not working */
}

Any help would really be appreciated! Thanks!

Body:
Unfortunately, there's no CSS property that handles text transformation in JavaFX (currently none, see the JavaFX CSS Reference). But you can actually do it in Java with just a single line of code!

For an instance, you have a Label node which has an ID named label.

<Label fx:id="label" text="Hello!" />

In this case, you can reference the node by its ID and set its text toUpperCase() with a controller class.

// Reference to the node you wish
// to transform texts to uppercase.
@FXML private Label label;

@Override
// Assuming you have Initializable class implemented.
public void initialize(URL arg0, ResourceBundle arg1) {

  // Get the current text value of the node.
  String text = label.getText();

  // Then update the text into whatever case you like.
  label.setText(text.toUpperCase());

}

OR

Simply straight from a Java code (one straight line of code).

Label label = new Label("Hello!".toUpperCase());


问:
How to hide specific div when clicked outside the element having same class in multiple div
I have the following code snippet where I want to hide specific div having same class name. I have multiple divs having same class name and event need to be triggered outside the actionLinks class. But I am little bit confused how to do this. can you guide me?

$(document).on("click", ".actionLinks", function() {
  $('.mainAction').hide();
  $(this).prev('.mainAction').show();
});

$(document).not(".actionLinks").on("click", function() {
  $('.mainAction').hide();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link one
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link two
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link three
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link four
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link five
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link six
</div>
<div class="mainAction" style="display: none;">
  Action 1
  Action 2
  Action 3
</div>
<div class="actionLinks">
  Link seven
</div>

<p>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p></code>```

答:
Instead of $(document).not(".actionLinks").on(...), you can do the same action in following way,

```<code>$(':not(div.actionLinks)').click(function(){
    $('div.mainAction').hide();
});
</code>```

Body:
I have the following code snippet where I want to hide specific div having same class name. I have multiple divs having same class name and event need to be triggered outside the actionLinks class. But I am little bit confused how to do this. can you guide me?

$(document).on("click", ".actionLinks", function() {
  $('.mainAction').hide();
  $(this).prev('.mainAction').show();
});

$(document).not(".actionLinks").on("click", function() {
  $('.mainAction').hide();
});

  Action 1
  Action 2
  Action 3

  Link one

  Action 1
  Action 2
  Action 3

  Link two

  Action 1
  Action 2
  Action 3

  Link three

  Action 1
  Action 2
  Action 3

  Link four

  Action 1
  Action 2
  Action 3

  Link five

  Action 1
  Action 2
  Action 3

  Link six

  Action 1
  Action 2
  Action 3

  Link seven

  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
  in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Body:
Instead of $(document).not(".actionLinks").on(...), you can do the same action in following way,

$(':not(div.actionLinks)').click(function(){
    $('div.mainAction').hide();
});


问:
Create string - all listed element for multiple fields grouping using MS Access SQL
For MSACCESS query, I have a table with 3 fields as following:

```<code>ID1 ID2 ID3
101 1001 1
102 1001 1
101 1002 1
102 1003 2
102 1004 3
103 1004 3
104 1004 4
</code>```

I would like to create a string with all recorded ID1 for each ID2, my desired output is following:

```<code>ID2 ID3 output
1001 1 101-102
1002 1 101
1003 2 102
1004 3 102-103
1004 4 104
</code>```

There are 2 possible ID1 value for ID2=1001, which is 101 and 102. Thus the desired string is 101-102 (assume no duplication by considering both fields ID1, ID2)

My attempt
Based on @Erik suggestion, i tried below while have error message on type mismatch.

```<code>Select T.[ID2] + T.[ID3]
  , GetList("Select [ID 1] From tblCEPAlert As T1 Where T1.[ID2] + T1.[ID3]  = " & T.[ID2] + T.[ID3],"",", ") as output
From tblCEPAlert AS T
Group By T.[ID2] + T.[ID3];
</code>```

答:
Refer the Link, Concatenate many rows into a single text string?

Hope it useful to to you, Try this:

```<code>DECLARE @Tab TABLE(ID1 VARCHAR(100), ID2 INT)
INSERT INTO @Tab VALUES(101,1001),(102,1001),(101,1002),(102,1003),(102,1004),(103,1004),(104,1004)

Select Main.ID2,
       Left(Main.[Outs],Len(Main.[Outs])-1) As "Students"
From
    (
        Select distinct ST2.ID2,
            (
                Select ST1.ID1 + '-' AS [text()]
                From @Tab ST1
                Where ST1.ID2 = ST2.ID2
                ORDER BY ST1.ID2
                For XML PATH ('')
            ) [Outs]
        From @Tab ST2
    ) [Main]
</code>```

For MS-ACCESS Can you read this answer  ConcatRelated(), hope it was the one you need...

Combine values from related rows into a single concatenated string value

Body:
For MSACCESS query, I have a table with 3 fields as following:

ID1 ID2 ID3
101 1001 1
102 1001 1
101 1002 1
102 1003 2
102 1004 3
103 1004 3
104 1004 4

I would like to create a string with all recorded ID1 for each ID2, my desired output is following:

ID2 ID3 output
1001 1 101-102
1002 1 101
1003 2 102
1004 3 102-103
1004 4 104

There are 2 possible ID1 value for ID2=1001, which is 101 and 102. Thus the desired string is 101-102 (assume no duplication by considering both fields ID1, ID2)

My attempt
Based on @Erik suggestion, i tried below while have error message on type mismatch.

Select T.[ID2] + T.[ID3]
  , GetList("Select [ID 1] From tblCEPAlert As T1 Where T1.[ID2] + T1.[ID3]  = " & T.[ID2] + T.[ID3],"",", ") as output
From tblCEPAlert AS T
Group By T.[ID2] + T.[ID3];

Body:
Refer the Link, Concatenate many rows into a single text string?

Hope it useful to to you, Try this:

DECLARE @Tab TABLE(ID1 VARCHAR(100), ID2 INT)
INSERT INTO @Tab VALUES(101,1001),(102,1001),(101,1002),(102,1003),(102,1004),(103,1004),(104,1004)

Select Main.ID2,
       Left(Main.[Outs],Len(Main.[Outs])-1) As "Students"
From
    (
        Select distinct ST2.ID2,
            (
                Select ST1.ID1 + '-' AS [text()]
                From @Tab ST1
                Where ST1.ID2 = ST2.ID2
                ORDER BY ST1.ID2
                For XML PATH ('')
            ) [Outs]
        From @Tab ST2
    ) [Main]

For MS-ACCESS Can you read this answer  ConcatRelated(), hope it was the one you need...

Combine values from related rows into a single concatenated string value


问:
KeyError: "Couldn't find field google.protobuf.DescriptorProto.ExtensionRange.options"
How should I fix this error?</p>

```<code>Mon Nov 13 00:37:49 :~$  /Users/mona/anaconda/bin/pip  install --upgrade tensorflow tensorflow-tensorboard
Collecting tensorflow
  Downloading tensorflow-1.4.0-cp36-cp36m-macosx_10_11_x86_64.whl (39.3MB)
    100% |████████████████████████████████| 39.3MB 28kB/s
Collecting tensorflow-tensorboard
  Downloading tensorflow_tensorboard-0.1.8-py3-none-any.whl (1.6MB)
    100% |████████████████████████████████| 1.6MB 560kB/s
Collecting wheel>=0.26 (from tensorflow)
  Downloading wheel-0.30.0-py2.py3-none-any.whl (49kB)
    100% |████████████████████████████████| 51kB 604kB/s
Collecting protobuf>=3.3.0 (from tensorflow)
  Downloading protobuf-3.4.0-py2.py3-none-any.whl (375kB)
    100% |████████████████████████████████| 378kB 57kB/s
Collecting numpy>=1.12.1 (from tensorflow)
  Downloading numpy-1.13.3-cp36-cp36m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
    100% |████████████████████████████████| 4.6MB 200kB/s
Collecting enum34>=1.1.6 (from tensorflow)
  Downloading enum34-1.1.6-py3-none-any.whl
Collecting six>=1.10.0 (from tensorflow)
  Using cached six-1.11.0-py2.py3-none-any.whl
Requirement already up-to-date: werkzeug>=0.11.10 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Requirement already up-to-date: bleach==1.5.0 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Requirement already up-to-date: markdown>=2.6.8 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Requirement already up-to-date: html5lib==0.9999999 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Collecting setuptools (from protobuf>=3.3.0->tensorflow)
  Downloading setuptools-36.7.1-py2.py3-none-any.whl (482kB)
    100% |████████████████████████████████| 491kB 883kB/s
Installing collected packages: wheel, six, setuptools, protobuf, numpy, tensorflow-tensorboard, enum34, tensorflow
  Found existing installation: wheel 0.29.0
    Uninstalling wheel-0.29.0:
      Successfully uninstalled wheel-0.29.0
  Found existing installation: six 1.10.0
    Uninstalling six-1.10.0:
      Successfully uninstalled six-1.10.0
  Found existing installation: setuptools 36.5.0.post20170921
    Uninstalling setuptools-36.5.0.post20170921:
      Successfully uninstalled setuptools-36.5.0.post20170921
  Found existing installation: protobuf 3.3.2
    Uninstalling protobuf-3.3.2:
      Successfully uninstalled protobuf-3.3.2
  Found existing installation: numpy 1.12.1
    Uninstalling numpy-1.12.1:
      Successfully uninstalled numpy-1.12.1
  Found existing installation: tensorflow 1.1.0
    Uninstalling tensorflow-1.1.0:
      Successfully uninstalled tensorflow-1.1.0
Successfully installed enum34-1.1.6 numpy-1.13.3 protobuf-3.4.0 setuptools-36.7.1 six-1.11.0 tensorflow-1.4.0 tensorflow-tensorboard-0.1.8 wheel-0.30.0
Mon Nov 13 00:40:10 :~$ tensorboard --logdir=/var/folders/bk/2b2d879912bgnl5s768s7crh0000gn/T/tmpzy0cj6xc
Traceback (most recent call last):
  File "/Users/mona/anaconda/bin/tensorboard", line 7, in <module>
    from tensorboard.main import main
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorboard/main.py", line 29, in <module>
    import tensorflow as tf
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 52, in <module>
    from tensorflow.core.framework.graph_pb2 import *
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/core/framework/graph_pb2.py", line 10, in <module>
    from google.protobuf import descriptor_pb2
  File "/Users/mona/anaconda/lib/python3.6/site-packages/google/protobuf/descriptor_pb2.py", line 409, in <module>
    options=None),
  File "/Users/mona/anaconda/lib/python3.6/site-packages/google/protobuf/descriptor.py", line 501, in __new__
    return _message.default_pool.FindFieldByName(full_name)
KeyError: "Couldn't find field google.protobuf.DescriptorProto.ExtensionRange.options"
Mon Nov 13 00:40:22 :~$
</code>```

答:
A related bug report on Google protobuf can be found here, you may want to check it out. There's a bug report on GitHub tensorflow here. The solution may be to run

```<code>pip install tensorflow tensorflow-tensorboard --upgrade --force-reinstall
</code>```

Can you try that?

Body:
How should I fix this error?

Mon Nov 13 00:37:49 :~$  /Users/mona/anaconda/bin/pip  install --upgrade tensorflow tensorflow-tensorboard
Collecting tensorflow
  Downloading tensorflow-1.4.0-cp36-cp36m-macosx_10_11_x86_64.whl (39.3MB)
    100% |████████████████████████████████| 39.3MB 28kB/s
Collecting tensorflow-tensorboard
  Downloading tensorflow_tensorboard-0.1.8-py3-none-any.whl (1.6MB)
    100% |████████████████████████████████| 1.6MB 560kB/s
Collecting wheel>=0.26 (from tensorflow)
  Downloading wheel-0.30.0-py2.py3-none-any.whl (49kB)
    100% |████████████████████████████████| 51kB 604kB/s
Collecting protobuf>=3.3.0 (from tensorflow)
  Downloading protobuf-3.4.0-py2.py3-none-any.whl (375kB)
    100% |████████████████████████████████| 378kB 57kB/s
Collecting numpy>=1.12.1 (from tensorflow)
  Downloading numpy-1.13.3-cp36-cp36m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
    100% |████████████████████████████████| 4.6MB 200kB/s
Collecting enum34>=1.1.6 (from tensorflow)
  Downloading enum34-1.1.6-py3-none-any.whl
Collecting six>=1.10.0 (from tensorflow)
  Using cached six-1.11.0-py2.py3-none-any.whl
Requirement already up-to-date: werkzeug>=0.11.10 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Requirement already up-to-date: bleach==1.5.0 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Requirement already up-to-date: markdown>=2.6.8 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Requirement already up-to-date: html5lib==0.9999999 in ./anaconda/lib/python3.6/site-packages (from tensorflow-tensorboard)
Collecting setuptools (from protobuf>=3.3.0->tensorflow)
  Downloading setuptools-36.7.1-py2.py3-none-any.whl (482kB)
    100% |████████████████████████████████| 491kB 883kB/s
Installing collected packages: wheel, six, setuptools, protobuf, numpy, tensorflow-tensorboard, enum34, tensorflow
  Found existing installation: wheel 0.29.0
    Uninstalling wheel-0.29.0:
      Successfully uninstalled wheel-0.29.0
  Found existing installation: six 1.10.0
    Uninstalling six-1.10.0:
      Successfully uninstalled six-1.10.0
  Found existing installation: setuptools 36.5.0.post20170921
    Uninstalling setuptools-36.5.0.post20170921:
      Successfully uninstalled setuptools-36.5.0.post20170921
  Found existing installation: protobuf 3.3.2
    Uninstalling protobuf-3.3.2:
      Successfully uninstalled protobuf-3.3.2
  Found existing installation: numpy 1.12.1
    Uninstalling numpy-1.12.1:
      Successfully uninstalled numpy-1.12.1
  Found existing installation: tensorflow 1.1.0
    Uninstalling tensorflow-1.1.0:
      Successfully uninstalled tensorflow-1.1.0
Successfully installed enum34-1.1.6 numpy-1.13.3 protobuf-3.4.0 setuptools-36.7.1 six-1.11.0 tensorflow-1.4.0 tensorflow-tensorboard-0.1.8 wheel-0.30.0
Mon Nov 13 00:40:10 :~$ tensorboard --logdir=/var/folders/bk/2b2d879912bgnl5s768s7crh0000gn/T/tmpzy0cj6xc
Traceback (most recent call last):
  File "/Users/mona/anaconda/bin/tensorboard", line 7, in <module>
    from tensorboard.main import main
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorboard/main.py", line 29, in <module>
    import tensorflow as tf
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 52, in <module>
    from tensorflow.core.framework.graph_pb2 import *
  File "/Users/mona/anaconda/lib/python3.6/site-packages/tensorflow/core/framework/graph_pb2.py", line 10, in <module>
    from google.protobuf import descriptor_pb2
  File "/Users/mona/anaconda/lib/python3.6/site-packages/google/protobuf/descriptor_pb2.py", line 409, in <module>
    options=None),
  File "/Users/mona/anaconda/lib/python3.6/site-packages/google/protobuf/descriptor.py", line 501, in __new__
    return _message.default_pool.FindFieldByName(full_name)
KeyError: "Couldn't find field google.protobuf.DescriptorProto.ExtensionRange.options"
Mon Nov 13 00:40:22 :~$

Body:
A related bug report on Google protobuf can be found here, you may want to check it out. There's a bug report on GitHub tensorflow here. The solution may be to run

pip install tensorflow tensorflow-tensorboard --upgrade --force-reinstall

Can you try that?


问:
Windows Phone 7 Frame Rate Performance
Reading Jeff Willcox on frame rate counters, I realized my application rarely hit the 60 fps. I'm not satisfied with the global performance of my app (compared to its iPhone counterpart), but the numbers seems weird to me.

When the app is doing nothing, even just after launch, it's even sometimes at 0 fps. And the higher I hit is 50 fps.

Overall, my application is not blazing fast, but not really slow. So how can I interpret the numbers ? How can I spot the issue that makes my app have a bad fps ?

答:
Jeff Wilcox notes in his post that:

Frame rate counters may be 0 when there is no animation being updated on the thread at any particular moment. You can add a very simple, continually animating and repeating, animation to your application during development & testing if you want to ensure that there is always some frame rate value available.

So the 0fps reading seems not be an issue since no screen updates need to be rendered.

Title: Windows Phone 7 Frame Rate Performance


问:
Accessing the scope inside the $timeout in angularjs
I have a directive  in AngularJS, with $timeout in link function.

.directive('setValueInColorSelectionBlock', function($timeout) {
    return {
        restrict:'A',
        scope:{
            setValueInColorSelectionBlock:"=setValueInColorSelectionBlock"
        },
        link:function(scope, element, attrs) {
           //able to access the scope
             $timeout(function() {
               //not able to access the scope
            });
        }
    };
});```
</div>
</div>
</p>

<p>My html :</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-html lang-html prettyprint-override"><code><div class="container-fluid" set-value-in-color-selection-block="$tbCtrl.containers"></code>```

this in $time out access the window object. I am not able to access scope inside the $timeout.

How do we access the scope?

答:
Similar to @Charlie H's answer for closure. You can try this, Wrap your $timeout with a function with parameter and user that parameter into $timeout function.

```<code>function(eleScope){ // wrapper function with eleScope as parameter
           $timeout(function() {
               console.log(eleScope); // access eleScope paramter
        })(scope); // pass scope to closure function
    }
}
</code>```

Body:
I have a directive  in AngularJS, with $timeout in link function.

.directive('setValueInColorSelectionBlock', function($timeout) {
    return {
        restrict:'A',
        scope:{
            setValueInColorSelectionBlock:"=setValueInColorSelectionBlock"
        },
        link:function(scope, element, attrs) {
           //able to access the scope
             $timeout(function() {
               //not able to access the scope
            });
        }
    };
});

My html :

this in $time out access the window object. I am not able to access scope inside the $timeout.

How do we access the scope?

Body:
Similar to @Charlie H's answer for closure. You can try this, Wrap your $timeout with a function with parameter and user that parameter into $timeout function.

function(eleScope){ // wrapper function with eleScope as parameter
           $timeout(function() {
               console.log(eleScope); // access eleScope paramter
        })(scope); // pass scope to closure function
    }
}


问:
string concatenate for global variable
I have fetched the value from database using query and trace the variable using foreach.  I want to get the mail id append with the variable $cc_test.

Initially the variable is empty. for first iteration test@sample.com 2nd iteration test1@sample.com and for 3rd test2@sample.com.

Finally I want to get test@sample.com,test1@sample.com,test2@sample.com, but now I get 'test2@sample.com,test2@sample.com'.

$cc_check is an indexed array print_r($cc_test) in for loop prints test@sample.com for 1st and test1@sample.com for 2nd and so on.

```<code>$cc_check=asset_status_tracker::where('request_id','=',$data['id'])->where('status_before','!=',null)->get();
$cc_test=''; //dump requestor mail id
foreach($cc_check as $cc_inner){
    $cc_mail=$cc_inner->changed_by;
    print_r($cc_mail);
    $cc_test=users::where('id','=',$cc_mail)->first()->mail;
    $cc_test=$cc_test.','.$cc_test;
    //print_r($cc_test);
}
print_r($cc_test); //test@sample.com,test1@sample.com,test2@sample.com
</code>```

答:
If I understand you, you don't need a counter, you just need to concatenate all of the values using commas as glue.

You can do this without excess commas or iterating conditions by running implode() after the loop is finished.

Save the emails in an array, and implode the array to generate a string of comma-separated values.

Code:

```<code>$emails=[];
foreach($cc_check as $cc_inner){
    $emails[]=users::where('id','=',$cc_inner->changed_by)->first()->mail;
}
$email_string=implode(',',$emails);
echo $email_string;
</code>```

Title: string concatenate for global variable

Body:
I have fetched the value from database using query and trace the variable using foreach.  I want to get the mail id append with the variable $cc_test.

Initially the variable is empty. for first iteration test@sample.com 2nd iteration test1@sample.com and for 3rd test2@sample.com.

Finally I want to get test@sample.com,test1@sample.com,test2@sample.com, but now I get 'test2@sample.com,test2@sample.com'.

$cc_check is an indexed array print_r($cc_test) in for loop prints test@sample.com for 1st and test1@sample.com for 2nd and so on.

$cc_check=asset_status_tracker::where('request_id','=',$data['id'])->where('status_before','!=',null)->get();
$cc_test=''; //dump requestor mail id
foreach($cc_check as $cc_inner){
    $cc_mail=$cc_inner->changed_by;
    print_r($cc_mail);
    $cc_test=users::where('id','=',$cc_mail)->first()->mail;
    $cc_test=$cc_test.','.$cc_test;
    //print_r($cc_test);
}
print_r($cc_test); //test@sample.com,test1@sample.com,test2@sample.com

Body:
If I understand you, you don't need a counter, you just need to concatenate all of the values using commas as glue.

You can do this without excess commas or iterating conditions by running implode() after the loop is finished.

Save the emails in an array, and implode the array to generate a string of comma-separated values.

Code:

$emails=[];
foreach($cc_check as $cc_inner){
    $emails[]=users::where('id','=',$cc_inner->changed_by)->first()->mail;
}
$email_string=implode(',',$emails);
echo $email_string;


问:
Does it make diffrence in speed efficiency of code if we assign property of object to another variable and then use it?
I wonder does it make difference if I use another variable to access the property of object once and for all or access the data that I want , from the object each time :

data = {position: [{X:12},{Y:4}] ,name : 'Smth'}

is there any diffrent between the following method :

```<code>const X = data.position[0].X
for(...){
 ...do somthing with X
 }
</code>```

or

```<code>for(...){
 ...do somthing with data.position[0].X
 }
</code>```

答:
Yes, some different is exist. Every time when you call property js interpreter try to find calling property (or method) at prototype hierarchy.

Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk.

If you use variable to cache some data it will be faster than you use direct access.
There is some great benchmark to test it.

Body:
I wonder does it make difference if I use another variable to access the property of object once and for all or access the data that I want , from the object each time :

data = {position: [{X:12},{Y:4}] ,name : 'Smth'}

is there any diffrent between the following method :

const X = data.position[0].X
for(...){
 ...do somthing with X
 }

or

for(...){
 ...do somthing with data.position[0].X
 }


问:
Unable to get existing Hive tables from HiveContext using Spark
I am trying to get databases or table details of Hive from spark using HiveContext. But I am unable to point to existing Hive Database as shown below:
Spark Version: 2.2.0
Hive Version : 2.3.0

Using below script in Spark Shell to connect to existing Hive Server(127.0.0.1 used below is my machine ip address):

```<code>scala> val hc = new org.apache.spark.sql.hive.HiveContext(sc)
warning: there was one deprecation warning; re-run with -deprecation for details
hc: org.apache.spark.sql.hive.HiveContext = org.apache.spark.sql.hive.HiveContext@6dde913e

scala> hc.setConf("hive.metastore.uris","thrift://127.0.0.1:9083")

scala> val df = hc.sql("show databases")
df: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val dfTables = hc.sql("show tables");
dfTables: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> dfTables.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+
</code>```

As shown above I am unable to get the existing Hive databases and tables available. HiveContext is pointing to new database(default) and no tables available.
Below are my hive db listed:

```<code>hive> show databases;
OK
default
mydbbackup
Time taken: 7.593 seconds, Fetched: 2 row(s)
hive> use mydbbackup;
OK
Time taken: 0.021 seconds
hive> show tables;
OK
customers
customerspart
customerspart1
Time taken: 0.194 seconds, Fetched: 3 row(s)
hive>
</code>```

Below is my hive-site.xml:

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/home/hduser/apache-hive-2.3.0-bin/metastore_db;create=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/user/hive/warehouse</value>
<description>location of default database for the warehouse</description>
</property>
<property>
<name>hive.metastore.uris</name>
<value/>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.PersistenceManagerFactoryClass</name>
<value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
<description>class implementing the jdo persistence</description>
</property>
</configuration>
```

<p>Below is my spark conf Directory:</p>

```total 40
drwxr-xr-x  2 root root 4096 Nov 12 20:22 ./
drwxr-xr-x 12 root root 4096 Nov  9 22:57 ../
-rw-r--r--  1 root root  996 Nov  9 22:57 docker.properties.template
-rw-r--r--  1 root root 1105 Nov  9 22:57 fairscheduler.xml.template
-rw-r--r--  1 root root 2025 Nov  9 22:57 log4j.properties.template
-rw-r--r--  1 root root 7313 Nov  9 22:57 metrics.properties.template
-rw-r--r--  1 root root  865 Nov  9 22:57 slaves.template
-rw-r--r--  1 root root 1292 Nov  9 22:57 spark-defaults.conf.template
-rwxr-xr-x  1 root root 3699 Nov  9 22:57 spark-env.sh.template*
```

Do I need to modify any thing to point to existing Hive server rather than creating new. Kindly help me on the same.

答:
Start your spark shell as is shown below: </p>

```<code>./spark-shell --driver-java-options
"-Dhive.metastore.uris=thrift://localhost:9083"
</code>```

Body:
I am trying to get databases or table details of Hive from spark using HiveContext. But I am unable to point to existing Hive Database as shown below:
Spark Version: 2.2.0
Hive Version : 2.3.0

Using below script in Spark Shell to connect to existing Hive Server(127.0.0.1 used below is my machine ip address):

scala> val hc = new org.apache.spark.sql.hive.HiveContext(sc)
warning: there was one deprecation warning; re-run with -deprecation for details
hc: org.apache.spark.sql.hive.HiveContext = org.apache.spark.sql.hive.HiveContext@6dde913e

scala> hc.setConf("hive.metastore.uris","thrift://127.0.0.1:9083")

scala> val df = hc.sql("show databases")
df: org.apache.spark.sql.DataFrame = [databaseName: string]

scala> df.show
+------------+
|databaseName|
+------------+
|     default|
+------------+

scala> val dfTables = hc.sql("show tables");
dfTables: org.apache.spark.sql.DataFrame = [database: string, tableName: string ... 1 more field]

scala> dfTables.show
+--------+---------+-----------+
|database|tableName|isTemporary|
+--------+---------+-----------+
+--------+---------+-----------+

As shown above I am unable to get the existing Hive databases and tables available. HiveContext is pointing to new database(default) and no tables available.
Below are my hive db listed:

hive> show databases;
OK
default
mydbbackup
Time taken: 7.593 seconds, Fetched: 2 row(s)
hive> use mydbbackup;
OK
Time taken: 0.021 seconds
hive> show tables;
OK
customers
customerspart
customerspart1
Time taken: 0.194 seconds, Fetched: 3 row(s)
hive>

Below is my hive-site.xml:

<configuration>
<property>
<name>javax.jdo.option.ConnectionURL</name>
<value>jdbc:derby:;databaseName=/home/hduser/apache-hive-2.3.0-bin/metastore_db;create=true</value>
<description>
JDBC connect string for a JDBC metastore.
To use SSL to encrypt/authenticate the connection, provide database-specific SSL flag in the connection URL.
For example, jdbc:postgresql://myhost/db?ssl=true for postgres database.
</description>
</property>
<property>
<name>hive.metastore.warehouse.dir</name>
<value>/user/hive/warehouse</value>
<description>location of default database for the warehouse</description>
</property>
<property>
<name>hive.metastore.uris</name>
<value/>
<description>Thrift URI for the remote metastore. Used by metastore client to connect to remote metastore.</description>
</property>
<property>
<name>javax.jdo.option.ConnectionDriverName</name>
<value>org.apache.derby.jdbc.EmbeddedDriver</value>
<description>Driver class name for a JDBC metastore</description>
</property>
<property>
<name>javax.jdo.PersistenceManagerFactoryClass</name>
<value>org.datanucleus.api.jdo.JDOPersistenceManagerFactory</value>
<description>class implementing the jdo persistence</description>
</property>
</configuration>

Below is my spark conf Directory:

total 40
drwxr-xr-x  2 root root 4096 Nov 12 20:22 ./
drwxr-xr-x 12 root root 4096 Nov  9 22:57 ../
-rw-r--r--  1 root root  996 Nov  9 22:57 docker.properties.template
-rw-r--r--  1 root root 1105 Nov  9 22:57 fairscheduler.xml.template
-rw-r--r--  1 root root 2025 Nov  9 22:57 log4j.properties.template
-rw-r--r--  1 root root 7313 Nov  9 22:57 metrics.properties.template
-rw-r--r--  1 root root  865 Nov  9 22:57 slaves.template
-rw-r--r--  1 root root 1292 Nov  9 22:57 spark-defaults.conf.template
-rwxr-xr-x  1 root root 3699 Nov  9 22:57 spark-env.sh.template*

Do I need to modify any thing to point to existing Hive server rather than creating new. Kindly help me on the same.

Body:
Start your spark shell as is shown below:

./spark-shell --driver-java-options
"-Dhive.metastore.uris=thrift://localhost:9083"


问:
I need to extract data from "Request" tab
My Request Tab (In "View Result Tree" listener)

```<code>GET https://example.com/index.html

GET data:

[no cookies]

Request Headers:
Connection: keep-alive
Upgrade-Insecure-Requests: 1

Accept-Language: en-US,en;q=0.8

Authorization: Basic ZGVtb2FhY29lQGdtYWlsLmNvbTpVbmlzeXMqMTIz
</code>```

I need value of "Authorization", How can I get it?

答:
You can add Regular Expression Extractor as Post Processor of request to get Authorization Header using: Field to check Request Headers and with Regular expression to get value:

```<code>Authorization: (.*)
</code>```

Use Template $1$ and Match No. 1 to get the first value.

Body:
My Request Tab (In "View Result Tree" listener)

GET https://example.com/index.html

GET data:

[no cookies]

Request Headers:
Connection: keep-alive
Upgrade-Insecure-Requests: 1

Accept-Language: en-US,en;q=0.8

Authorization: Basic ZGVtb2FhY29lQGdtYWlsLmNvbTpVbmlzeXMqMTIz

I need value of "Authorization", How can I get it?

Body:
You can add Regular Expression Extractor as Post Processor of request to get Authorization Header using: Field to check Request Headers and with Regular expression to get value:

Authorization: (.*)

Use Template $1$ and Match No. 1 to get the first value.


问:
Python acting strange when trying to call wget with encoding for Japanese
I'm creating a python script that uses bash to do a wget on a list of Japanese words contained in a file. I would just use curl but this had encoding problems. With wget it does download the html, but it dumps it in the current directory with poetic titles such as:

```<code>   試%E8%A1%8C%E9%8C%AF誤
</code>```

I want it to put the html into pretty-sounding places like "output/混合.txt". It does create these pretty-sounding files, but with nothing in them.

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

with open("words") as f:
    for line in f:
        text = unicode(line, "utf-8")
        os.system("wget \'https://kotobank.jp/word/" + line.strip() + "'> output/" + line.strip() + ".txt")
        #print("wget \'https://kotobank.jp/word/" + line.strip() + "'>> output/out.txt")
</code>```

And the file "words" is as follows:

```<code>追究
花器
陶磁器
枯渇
風合い
繊維
混合
アボード
受け継い
試行錯誤
硬質
</code>```

答:
Use -O file option instead of redirecting the output:

```<code>os.system("wget \'https://kotobank.jp/word/" + line.strip() + "' -O " + line.strip() + ".txt"
</code>```

See wget documentation for more information.

Body:
I'm creating a python script that uses bash to do a wget on a list of Japanese words contained in a file. I would just use curl but this had encoding problems. With wget it does download the html, but it dumps it in the current directory with poetic titles such as:

   試%E8%A1%8C%E9%8C%AF誤

I want it to put the html into pretty-sounding places like "output/混合.txt". It does create these pretty-sounding files, but with nothing in them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os

with open("words") as f:
    for line in f:
        text = unicode(line, "utf-8")
        os.system("wget \'https://kotobank.jp/word/" + line.strip() + "'> output/" + line.strip() + ".txt")
        #print("wget \'https://kotobank.jp/word/" + line.strip() + "'>> output/out.txt")

And the file "words" is as follows:

追究
花器
陶磁器
枯渇
風合い
繊維
混合
アボード
受け継い
試行錯誤
硬質

Body:
Use -O file option instead of redirecting the output:

os.system("wget \'https://kotobank.jp/word/" + line.strip() + "' -O " + line.strip() + ".txt"

See wget documentation for more information.


问:
Apache mod_rewrite clashing with wordpress rule
I have a page outside of the Wordpress installing but located in the root directory at v1.html

I've tried a few different mod_rewrite rules but they all seem to clash with the WordPress .htaccess rules. How can I keep my wordpress installation in tact but also have /v1.html renamed to /v1 without 404ing

```<code>    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    </IfModule>

    # END WordPress
</code>```

答:
Add your rule before the WordPress block and use the [L] to stop on your rule when it matches. This way it doesn't trickle into the WordPress rules.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^v1/?$ /v1.html [L]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```

Body:
I have a page outside of the Wordpress installing but located in the root directory at v1.html

I've tried a few different mod_rewrite rules but they all seem to clash with the WordPress .htaccess rules. How can I keep my wordpress installation in tact but also have /v1.html renamed to /v1 without 404ing

    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    </IfModule>

    # END WordPress


问:
getting distinct count on join of two tables
I have 2 tables where primary key of first table is used as foreign key for second table. In first table primary key is having unique values but in second table as foreign key it is having duplicate values as well. Now i want count from both the tables at same time and using left join for that.
I have tried the following query :-

```<code> select distinct count(c.joined) as joined,
    count(t.JobReqID),t.Country from txrecruitment as t
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid
    where t.status='open'
    group by t.Country
</code>```

The count value of count(t.JobReqID) is not giving count of distinct JobReqId which i want. The result of count is counting the multiple instances of 2nd table also which i want to remove.
What should be the right way to do this. Any help is welcomed!!

答:
Because our distinct is not placed in the correct location. Use Distinct Inside the Count.</p>

```<code> select count(distinct  c.joined) as joined,
    count(DISTINCT t.JobReqID),t.Country from txrecruitment as t
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid
    where t.status='open'
    group by t.Country
</code>```

Body:
I have 2 tables where primary key of first table is used as foreign key for second table. In first table primary key is having unique values but in second table as foreign key it is having duplicate values as well. Now i want count from both the tables at same time and using left join for that.
I have tried the following query :-

 select distinct count(c.joined) as joined,
    count(t.JobReqID),t.Country from txrecruitment as t
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid
    where t.status='open'
    group by t.Country

The count value of count(t.JobReqID) is not giving count of distinct JobReqId which i want. The result of count is counting the multiple instances of 2nd table also which i want to remove.
What should be the right way to do this. Any help is welcomed!!

Body:
Because our distinct is not placed in the correct location. Use Distinct Inside the Count.

 select count(distinct  c.joined) as joined,
    count(DISTINCT t.JobReqID),t.Country from txrecruitment as t
    left join CandidateDetails as c on t.JobReqID=c.Jobreqid
    where t.status='open'
    group by t.Country


问:
Spring 4, @Resource annotated field is null
I have class AnnotatedCollectionInjection with @Resource annotated fields:

```<code>package LearnBook.part0.s9;

import LearnBook.Common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

@Service("injectedAnnotatedCollection")
public class AnnotatedCollectionInjection {

    @Resource(name = "map")
    private Map<String, String> map;

    @Resource(name = "props")
    private Properties props;

    @Resource(name = "set")
    private Set<Integer> set;

    @Resource(name = "list")
    private List<Long> list;

    @Override
    public String toString() {
        return "CollectionInjection{\n" +
            "map=" + map +
            ", \nprops=" + props +
            ", \nset=" + set +
            ", \nlist=" + list +
            "\n}";
    }

    public static void main(String ...args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "META-INF/spring/learnbook/part0/s9/a1.xml"
        );
        System.out.println(ctx.getBean("injectedAnnotatedCollection"));
    }
}
</code>```

Spring configuration (a1.xml) is here:

<?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:context="http://www.springframework.org/schema/context"
   xmlns:util="http://www.springframework.org/schema/util"
   xmlns:c="http://www.springframework.org/schema/c"
   xsi:schemaLocation="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/util
   http://www.springframework.org/schema/util/spring-util.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="LearnBook.part0.s9"/>

    <util:map id="map" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
        <entry key="someValue" value="is value"/>
        <entry key-ref="someKeyValue" value-ref="someStringValue"/>
    </util:map>

    <util:properties id="props">
        <prop key="one">two</prop>
        <prop key="DA">DO</prop>
    </util:properties>

    <util:list id="list" value-type="java.lang.Long">
        <ref bean="someLongValue"/>
        <value>2000</value>
    </util:list>

    <util:set id="set" value-type="java.lang.Integer">
        <ref bean="someIntValue"/>
        <value>200</value>
    </util:set>

    <bean id="someStringValue"
          class="java.lang.String"
          c:_0="Some string value"/>

    <bean id="someKeyValue"
          class="java.lang.String"
          c:_0="Some key value"/>

    <bean id="someLongValue"
          class="java.lang.Long"
          c:_0="25"/>

    <bean id="someIntValue"
          class="java.lang.Integer"
          c:_0="7"/>
</beans>
```

<p>But field is null, why?:  </p>

```CollectionInjection{
map=null,
props=null,
set=null,
list=null
}
```

<p>If i create setter and move annotation to it, i haven't get changes (map field also is null):</p>

```private Map<String, String> map;

@Resource(name = "map")
public void setMap(Map<String, String> map) {
    this.map = map;
}
```

答:
Your configuration looks fine as long as the file is present in the class path given META-INF/spring/learnbook/part0/s9/a1.xml.

Just ran the test by lowering the package name as learnBook.part0.s9, <context:component-scan base-package="learnBook.part0.s9"/> and with FileSystemXmlApplicationContext instead of ClassPathXmlApplicationContext

```<code> public static void main(String ...args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext(
                "C://fullyQualifiedPathTo//a1.xml"
        );
        System.out.println(ctx.getBean("injectedAnnotatedCollection"));
    }
</code>```

Received the output successfully.

```<code>CollectionInjection{
map={someValue=is value, Some key value=Some string value},
props={one=two, DA=DO},
set=[7, 200],
list=[25, 2000]
}
</code>```

Body:
I have class AnnotatedCollectionInjection with @Resource annotated fields:

package LearnBook.part0.s9;

import LearnBook.Common;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

@Service("injectedAnnotatedCollection")
public class AnnotatedCollectionInjection {

    @Resource(name = "map")
    private Map<String, String> map;

    @Resource(name = "props")
    private Properties props;

    @Resource(name = "set")
    private Set<Integer> set;

    @Resource(name = "list")
    private List<Long> list;

    @Override
    public String toString() {
        return "CollectionInjection{\n" +
            "map=" + map +
            ", \nprops=" + props +
            ", \nset=" + set +
            ", \nlist=" + list +
            "\n}";
    }

    public static void main(String ...args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
                "META-INF/spring/learnbook/part0/s9/a1.xml"
        );
        System.out.println(ctx.getBean("injectedAnnotatedCollection"));
    }
}

Spring configuration (a1.xml) is here:

<?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:context="http://www.springframework.org/schema/context"
   xmlns:util="http://www.springframework.org/schema/util"
   xmlns:c="http://www.springframework.org/schema/c"
   xsi:schemaLocation="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/util
   http://www.springframework.org/schema/util/spring-util.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="LearnBook.part0.s9"/>

    <util:map id="map" map-class="java.util.HashMap" key-type="java.lang.String" value-type="java.lang.String">
        <entry key="someValue" value="is value"/>
        <entry key-ref="someKeyValue" value-ref="someStringValue"/>
    </util:map>

    <util:properties id="props">
        <prop key="one">two</prop>
        <prop key="DA">DO</prop>
    </util:properties>

    <util:list id="list" value-type="java.lang.Long">
        <ref bean="someLongValue"/>
        <value>2000</value>
    </util:list>

    <util:set id="set" value-type="java.lang.Integer">
        <ref bean="someIntValue"/>
        <value>200</value>
    </util:set>

    <bean id="someStringValue"
          class="java.lang.String"
          c:_0="Some string value"/>

    <bean id="someKeyValue"
          class="java.lang.String"
          c:_0="Some key value"/>

    <bean id="someLongValue"
          class="java.lang.Long"
          c:_0="25"/>

    <bean id="someIntValue"
          class="java.lang.Integer"
          c:_0="7"/>
</beans>

But field is null, why?:

CollectionInjection{
map=null,
props=null,
set=null,
list=null
}

If i create setter and move annotation to it, i haven't get changes (map field also is null):

private Map<String, String> map;

@Resource(name = "map")
public void setMap(Map<String, String> map) {
    this.map = map;
}

Body:
Your configuration looks fine as long as the file is present in the class path given META-INF/spring/learnbook/part0/s9/a1.xml.

Just ran the test by lowering the package name as learnBook.part0.s9, <context:component-scan base-package="learnBook.part0.s9"/> and with FileSystemXmlApplicationContext instead of ClassPathXmlApplicationContext

 public static void main(String ...args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext(
                "C://fullyQualifiedPathTo//a1.xml"
        );
        System.out.println(ctx.getBean("injectedAnnotatedCollection"));
    }

Received the output successfully.

CollectionInjection{
map={someValue=is value, Some key value=Some string value},
props={one=two, DA=DO},
set=[7, 200],
list=[25, 2000]
}


答:
You could use STUFF() function in your T-SQL Script which could help you :

```<code>SELECT DISTINCT
        T.ID2,
        [output] = STUFF(
                      (select  '-'+CONVERT(VARCHAR, ID1) from <table> where ID2 = T.ID2 FOR XML PATH('')),
                       1, 1, '')
FROM <table> T
</code>```

Result :

```<code>ID2     output
1001    101-102
1002    101
1003    102
1004    102-103-104
</code>```

Title: Create string - all listed element for multiple fields grouping using MS Access SQL

Body:
For MSACCESS query, I have a table with 3 fields as following:

ID1 ID2 ID3
101 1001 1
102 1001 1
101 1002 1
102 1003 2
102 1004 3
103 1004 3
104 1004 4

I would like to create a string with all recorded ID1 for each ID2, my desired output is following:

ID2 ID3 output
1001 1 101-102
1002 1 101
1003 2 102
1004 3 102-103
1004 4 104

There are 2 possible ID1 value for ID2=1001, which is 101 and 102. Thus the desired string is 101-102 (assume no duplication by considering both fields ID1, ID2)

My attempt
Based on @Erik suggestion, i tried below while have error message on type mismatch.

Select T.[ID2] + T.[ID3]
  , GetList("Select [ID 1] From tblCEPAlert As T1 Where T1.[ID2] + T1.[ID3]  = " & T.[ID2] + T.[ID3],"",", ") as output
From tblCEPAlert AS T
Group By T.[ID2] + T.[ID3];

Body:
You could use STUFF() function in your T-SQL Script which could help you :

SELECT DISTINCT
        T.ID2,
        [output] = STUFF(
                      (select  '-'+CONVERT(VARCHAR, ID1) from <table> where ID2 = T.ID2 FOR XML PATH('')),
                       1, 1, '')
FROM <table> T

Result :

ID2     output
1001    101-102
1002    101
1003    102
1004    102-103-104


问:
Bootstrap Navbar fixed on top, Container centered vertically
My page is very simple : it is made of a navbar, and two panels.

I am trying to get my navbar fixed on top, and the two panels vertically centered (for any screen size or browsers).

These two panels are placed in a container.

I have been unsuccessful in vertically centering the container so far.

Here is what I have now :

Here is what I want to achieve :

Here is my code :

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <nav class="navbar transparent navbar-static-top">

    <div class="navbar-header">
      <p>Welcome</p>
    </div>

  </nav>

  <div class="container d-flex h-100">

    <div class="row justify-content-center align-self-center">

      <!-- 1st panel -->
      <div class="col-md-4 mb-4" id="panel">

        <div class="panel panel-default1">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel body -->
        </div>
        <!-- panel-default1-->
      </div>
      <!-- col md 4 -->

      <!-- 2nd panel -->

      <div class="col-md-8 col-md-8" id="panel2">

        <div class="panel panel-default2">

          <div class="panel-body">

            <p>Blablabla</p>

          </div>
          <!-- panel-body -->

        </div>
        <!-- panel-default2-->

      </div>
      <!-- col md 8 -->

    </div>
    <!-- row -->

  </div>
  <!-- container-->

</body></code>```

As you can see from the HTML, I have tried to use Bootstrap's flexbox on container and row, without success.

Please advise a working solution to vertically center my container, except the navbar.

答:
You should be able to just use col-4 and col-8 for columns inside row inside container
see here

see example

Edit:
to align them vertically you should be able to just add align-items-center class on a row, without additional css.
Updated example

Body:
My page is very simple : it is made of a navbar, and two panels.

I am trying to get my navbar fixed on top, and the two panels vertically centered (for any screen size or browsers).

These two panels are placed in a container.

I have been unsuccessful in vertically centering the container so far.

Here is what I have now :

Here is what I want to achieve :

Here is my code :

html {
  overflow: hidden;
  height: 100%;
}

body {
  overflow: hidden;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.panel-default1 {
  padding-top: 8px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  overflow: hidden;
  margin: 0 auto;
  position: relative;
}

.panel-default2 {
  padding-top: 10px;
  padding-right: -15px;
  border-radius: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.10);
  height: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}

Welcome

Blablabla

Blablabla

As you can see from the HTML, I have tried to use Bootstrap's flexbox on container and row, without success.

Please advise a working solution to vertically center my container, except the navbar.


问:
ArrayList Relation in java
so i still learn about arraylist stuff in java,
lets say i have two arraylist

```<code>name = [John,Mark,David,Luke,Dame]
thingsTheyHave = [ball,racquet,golfStick,laptop,personalComputer,shoes,shirt,chair,table,phone]
</code>```

my question, how to create these 2 arraylist become something like this :

```<code>john : Ball , golfStick
mark : Laptop,personalComputer
david : racquet,shoes
luke : shirt, chair
dame  : table,phone
</code>```

what method do i have to use ? thanks in advance !

答:
Maybe you can use java.util.Map.

```<code>Map<String, List<String>> equipmentMap = new HashMap();
equipmentMap.put("John", Arrays.asList("Ball", "golfStick"));
</code>```

And then you can get things that John have like this:

```<code>equipmentMap.get("John");
</code>```

Title: ArrayList Relation in java

Body:
so i still learn about arraylist stuff in java,
lets say i have two arraylist

name = [John,Mark,David,Luke,Dame]
thingsTheyHave = [ball,racquet,golfStick,laptop,personalComputer,shoes,shirt,chair,table,phone]

my question, how to create these 2 arraylist become something like this :

john : Ball , golfStick
mark : Laptop,personalComputer
david : racquet,shoes
luke : shirt, chair
dame  : table,phone

what method do i have to use ? thanks in advance !

Body:
Maybe you can use java.util.Map.

Map<String, List<String>> equipmentMap = new HashMap();
equipmentMap.put("John", Arrays.asList("Ball", "golfStick"));

And then you can get things that John have like this:

equipmentMap.get("John");


问:
Graphs in .NET CF
I'm looking for a decent free control, library, or tutorial that allow graphing on .NET CF... I'm currently using v2.0 but can probably upgrade to 3.5.

I will also want to be able to save the graph as an image.

答:
Two years ago i did nearly the same search and found several one, but nothing really excited me. Here are my old result:

Mooseworks Trend Graph Control

MindFusion PocketChart

Steema TeeChart

QCChart2D CF Charting Tools

QCRTGraph CF - Real-Time Graphics Tools

Maybe one or all of them released new versions in the meantime with better performance, but better check it for yourself.

Title: Graphs in .NET CF