问:
Uncaught ReferenceError: React is not defined
I am trying to make ReactJS work with rails using this tutorial. I am getting this error:

Uncaught ReferenceError: React is not defined

But I can access the React object in browser console

I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,

var React = require('react') gives the error:

Uncaught ReferenceError: require is not defined

Can anyone suggest me on how to resolve this?

[EDIT 1]

Source code for reference:

This is my comments.js.jsx file:

```<code>var Comment = React.createClass({
  render: function () {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
          {this.props.comment}
      </div>
      );
  }
});

var ready = function () {
  React.renderComponent(
    <Comment author="Richard" comment="This is a comment "/>,
    document.getElementById('comments')
  );
};

$(document).ready(ready);
</code>```

And this is my index.html.erb:

```<code><div id="comments"></div>
</code>```

答:
The displayed error

after that import react

Finally import react-dom

if error is react is not define,please add ==>import React from 'react';

if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';

Body:
I am trying to make ReactJS work with rails using this tutorial. I am getting this error:

Uncaught ReferenceError: React is not defined

But I can access the React object in browser console

I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,

var React = require('react') gives the error:

Uncaught ReferenceError: require is not defined

Can anyone suggest me on how to resolve this?

[EDIT 1]

Source code for reference:

This is my comments.js.jsx file:

var Comment = React.createClass({
  render: function () {
    return (

          {this.props.author}

          {this.props.comment}

      );
  }
});

var ready = function () {
  React.renderComponent(
    <Comment author="Richard" comment="This is a comment "/>,
    document.getElementById('comments')
  );
};

$(document).ready(ready);

And this is my index.html.erb:


来源: stackexchange

问:
Connecting SFTP server using the certificate
One of our vendor is updating their Server certificate and provided us with the certificate file which when I open gets installed. Not sure where it gets installed. Earlier we were just using the username/password credentials for connecting to the server. But I am trying to check if we can the connect to the SFTP server using the certificates through the SFTP adapter. If so how do I link the SFTP adapter settings with the installed certificates.</p>

答:
Installed certificates will be in your certificate store, run certmgr to see what certificates are installed.  However the BizTalk adapter seems to want the location of the .ppk file.

To use the certificate you will have to configure the Client Authentication Mode to PublicKeyAuthentication and you must enter the private key of the user in the PrivateKey property.

See the Microsoft documentation SFTP Adapter and this blog BizTalk Server 2013 R2: SFTP Adapter Tricks and Pitfalls

ContentLicense: CC BY-SA 3.0


问:
fling with AppBarLayout and ViewPager(recycler view)
PIC1

Area1 is an AppBarLayout, ViewPager(recycler view) is below the AppBarLayout.

When I touch the Area2 to scroll up slowly or quickly, it works fine.
But When I touch Area1 to scroll up quickly, sometimes, the view scroll up then scroll down automatically.

support:26.0.2(26.1.0/ 27.0.2)

here's my layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        app:elevation="0dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:background="@android:color/holo_green_light"
            android:gravity="center"
            android:text="TEST"
            android:textColor="@android:color/holo_orange_dark"
            android:textSize="64sp"
            app:layout_scrollFlags="scroll|enterAlways"/>
        <!--category-->
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabIndicatorHeight="4dp"
            app:tabSelectedTextColor="#000"
            app:tabTextColor="#fff"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
</code>```

I use support 23.4.0 instead of 26.0.2, the layouts scroll fine.

答:
This is only happening when AppBar is scrolled/flung while the NestedScrollView(or RecyclerView) has not yet finish flinging.

Solution: Extend AppBar's default Behavior and block the call for AppBar.Behavior's onNestedPreScroll() and onNestedScroll() when AppBar is touched while NestedScroll hasn't stopped yet.

```<code>@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
    if (type == TYPE_FLING) {
        isFlinging = true;
    }
    if (!shouldBlockNestedScroll) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
    }
}

@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
    if (!shouldBlockNestedScroll) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
    }
}
</code>```

then use it on the layout:

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    ...
    app:layout_behavior="com.mypackage.NoBounceBehavior"/>
</code>```

Reference for full code:
https://gist.github.com/ampatron/9d56ea401094f67196f407f82f14551a

Body:
PIC1

Area1 is an AppBarLayout, ViewPager(recycler view) is below the AppBarLayout.

When I touch the Area2 to scroll up slowly or quickly, it works fine.
But When I touch Area1 to scroll up quickly, sometimes, the view scroll up then scroll down automatically.

support:26.0.2(26.1.0/ 27.0.2)

here's my layout:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@null"
        app:elevation="0dp">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:background="@android:color/holo_green_light"
            android:gravity="center"
            android:text="TEST"
            android:textColor="@android:color/holo_orange_dark"
            android:textSize="64sp"
            app:layout_scrollFlags="scroll|enterAlways"/>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            app:tabIndicatorColor="@color/colorAccent"
            app:tabIndicatorHeight="4dp"
            app:tabSelectedTextColor="#000"
            app:tabTextColor="#fff"/>
    </android.support.design.widget.AppBarLayout>
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>

I use support 23.4.0 instead of 26.0.2, the layouts scroll fine.

Body:
This is only happening when AppBar is scrolled/flung while the NestedScrollView(or RecyclerView) has not yet finish flinging.

Solution: Extend AppBar's default Behavior and block the call for AppBar.Behavior's onNestedPreScroll() and onNestedScroll() when AppBar is touched while NestedScroll hasn't stopped yet.

@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
    if (type == TYPE_FLING) {
        isFlinging = true;
    }
    if (!shouldBlockNestedScroll) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
    }
}

@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
    if (!shouldBlockNestedScroll) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
    }
}

then use it on the layout:

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    ...
    app:layout_behavior="com.mypackage.NoBounceBehavior"/>

Reference for full code:
https://gist.github.com/ampatron/9d56ea401094f67196f407f82f14551a


问:
Discord.js deleteMessage() doesn't work
I am creating a Discord bot with discord.js and I'd like to create a command that can clear messages. For now, I have this code (only the interesting part) and I can't figure out why it doesn't work:

```<code>// Importing discord.js, creating bot and setting the prefix
const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = "/";

// Array that stores all messages sent
messages = [];

bot.on('message', (message) => {

   // Store the new message in the messages array
   messages.push(message);

   // Split the command so that "/clear all" becames args["clear", "all"]
   var args = message.content.substring(prefix.length).split(" ");

   // If the command is "/clear all"
   if(args[0] == "clear" && args[1] == "all") {

      bot.deleteMessages(messages); // Code that doesn't work

      // Resets the array
      messages = [];

   }
}

// CONNECT !!!
bot.login('LOGING TOKEN HERE');
</code>```

Can you help me ?

答:
You should use <TextChannel>.bulkDelete instead.

Example:

```<code>msg.channel.bulkDelete(100).then(() => {
    msg.channel.send("Purged 100 messages.").then(m => m.delete(3000));
});
</code>```

This would delete 2 - 100 messages in a channel for every call to this method so you would not receive 429 (Too many Requests) Error frequently which might result in your token being revoked.

Title: Discord.js deleteMessage() doesn't work

Body:
I am creating a Discord bot with discord.js and I'd like to create a command that can clear messages. For now, I have this code (only the interesting part) and I can't figure out why it doesn't work:

// Importing discord.js, creating bot and setting the prefix
const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = "/";

// Array that stores all messages sent
messages = [];

bot.on('message', (message) => {

   // Store the new message in the messages array
   messages.push(message);

   // Split the command so that "/clear all" becames args["clear", "all"]
   var args = message.content.substring(prefix.length).split(" ");

   // If the command is "/clear all"
   if(args[0] == "clear" && args[1] == "all") {

      bot.deleteMessages(messages); // Code that doesn't work

      // Resets the array
      messages = [];

   }
}

// CONNECT !!!
bot.login('LOGING TOKEN HERE');

Can you help me ?

Body:
You should use <TextChannel>.bulkDelete instead.

Example:

msg.channel.bulkDelete(100).then(() => {
    msg.channel.send("Purged 100 messages.").then(m => m.delete(3000));
});

This would delete 2 - 100 messages in a channel for every call to this method so you would not receive 429 (Too many Requests) Error frequently which might result in your token being revoked.


问:
how to scroll the page to bottom whenever the page load?
Requirement-  I want to scroll the content to the bottom of the page whenever the page load.

Here is my html code

```<code><ion-content  style="background-color: #f5f8fa;">
  <p style="line-height:24px;padding-left:10px;margin-top:20px;text-transform:capitalize;font-size:16px;">{{this.TASKDESC}}</p>
 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">
      <div [style.margin]="list.TAG_FROM === loggedinuser ? '0px 0px 0px -12px':'0px -12px 0px 0px'" [style.float]="list.TAG_FROM === loggedinuser ? 'right':'left'" style="width:33px;height:33px;background-color:#818993;overflow:hidden;color:#fff;z-index:9.9999999;border-radius:50%;font-size:14px;text-align:center;padding-top:7px;" >{{list.TAG_FROM.substring(0,2)}}</div>
      </div>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

Current position of the page

What i want-  The image of the page

Scroll to bottom automatically whenever the page load.

答:
use the #content identifier to obtain a reference to <ion-content> using the ViewChild.

```<code><ion-content #content style="background-color: #f5f8fa;">
  <p style="line-height:24px;padding-left:10px;margin-top:20px;text-transform:capitalize;font-size:16px;">{{this.TASKDESC}}</p>
 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">
      <div [style.margin]="list.TAG_FROM === loggedinuser ? '0px 0px 0px -12px':'0px -12px 0px 0px'" [style.float]="list.TAG_FROM === loggedinuser ? 'right':'left'" style="width:33px;height:33px;background-color:#818993;overflow:hidden;color:#fff;z-index:9.9999999;border-radius:50%;font-size:14px;text-align:center;padding-top:7px;" >{{list.TAG_FROM.substring(0,2)}}</div>
      </div>
    </ion-item>
  </ion-list>
</ion-content>
</code>```

Now use the this.content.scrollToBottom to scroll bottom.

```<code>import {Component, ViewChild} from '@angular/core';

@Component({
  templateUrl: 'chatPage.html'
})
export class ChatPage {
  @ViewChild('content') content:any;

  constructor() { }

  ionViewDidEnter(){
    this.content.scrollToBottom(300);
  }
}
</code>```

Body:
Requirement-  I want to scroll the content to the bottom of the page whenever the page load.

Here is my html code

<ion-content  style="background-color: #f5f8fa;">

{{this.TASKDESC}}

 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">

{{list.TAG_FROM.substring(0,2)}}

    </ion-item>
  </ion-list>
</ion-content>

Current position of the page

What i want-  The image of the page

Scroll to bottom automatically whenever the page load.

Body:
use the #content identifier to obtain a reference to <ion-content> using the ViewChild.

<ion-content #content style="background-color: #f5f8fa;">
  <p style="line-height:24px;padding-left:10px;margin-top:20px;text-transform:capitalize;font-size:16px;">{{this.TASKDESC}}</p>
 <ion-list *ngFor="let list of list; let i = index;" style="margin:0;height:auto;padding-top:5px;padding-left:17px;z-index:-1">

    <ion-item text-wrap class="item" style=" margin-top:-25px;padding:0; background-color:#f5f8fa;z-index:-1;">
      <div [style.margin]="list.TAG_FROM === loggedinuser ? '0px 0px 0px -12px':'0px -12px 0px 0px'" [style.float]="list.TAG_FROM === loggedinuser ? 'right':'left'" style="width:33px;height:33px;background-color:#818993;overflow:hidden;color:#fff;z-index:9.9999999;border-radius:50%;font-size:14px;text-align:center;padding-top:7px;" >{{list.TAG_FROM.substring(0,2)}}</div>
      </div>
    </ion-item>
  </ion-list>
</ion-content>

Now use the this.content.scrollToBottom to scroll bottom.

import {Component, ViewChild} from '@angular/core';

@Component({
  templateUrl: 'chatPage.html'
})
export class ChatPage {
  @ViewChild('content') content:any;

  constructor() { }

  ionViewDidEnter(){
    this.content.scrollToBottom(300);
  }
}


问:
Onclick function button inside a javascript
I want to direct the button to another page

```<code>function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}
</code>```

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

答:
Try this

function showInput() {
 document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'https://www.youtube.com/\';" class="btnRegister" value = "New Customer">';
}
showInput()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo">click</p></code>```

Body:
I want to direct the button to another page

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit"
    onclick="location.href = "addnewcustomer.php";" id ="newcust"
    class="btnRegister" value = "New Customer">';
}

I want when i click the New Customer button, it will redirect to addnewcustomer.php but when i run the code, nothing happened.

There are no errors. Just the button didn't function the way i want it to

Body:
Try this

function showInput() {
 document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'https://www.youtube.com/\';" class="btnRegister" value = "New Customer">';
}
showInput()

<p id="demo">click</p>


问:
React Native + Redux Form - Use keyboard next button to go to next TextInput field
I'm using Redux Form (RF) in a React Native application. Everything works fine but I can not figure out how to get the refs from the Field input to go to the next input field with Redux Form.

Without RF this solution would work just fine.

Here is my code:

```<code>class RenderInput extends Component {
   const { input, nextField, refs,
        meta: { touched, error, warning },
        input: { onChange } } = this.props
   render() {
      return (
         <Input
            returnKeyType = {'next'}
            onChangeText={onChange}
            onBlur={input.onBlur}
            onFocus={input.onFocus}
            onSubmitEditing = {(event) => {
               // refs is undefined
               refs[nextField].focus()
            }}/>
      )
   }
}

class Form extends Component {
   render() {
      return (
         <Field
            name="field1"
            focus
            withRef
            ref='field1'
            nextField = "field2"
            component={RenderInput}/>

         <Field
            name="vendor"
            withRef
            ref="field2"
            nextAction = "field3"
            component={RenderInput}/>
      )
   }
}
</code>```

I'm passing on the property nextField to the component to determine the next input field when the Next key on the keyboard is clicked but I can not get the refs property inside the RenderInput component.

Any idea how to get the refs property?

答:
I worked on getting a ref like this that worked for me.

```<code>           const renderComp = ({
             refName,
             meta: { touched, error },
             input,
             ...custom
           }) => (
             <MyComponent
               ref={refName}
               {...custom}
             />
           )

            <Field
              name={name}
              component={renderComp}
              ref={node =>
                isLeft ? (this.compRef1 = node) : (this.compRef2 = node)}
              refName={node =>
                 (this.myRef= node) }
              withRef
            />
</code>```

now access instance functions like this.

```<code>this.myRef.anyFunc()
</code>```

Body:
I'm using Redux Form (RF) in a React Native application. Everything works fine but I can not figure out how to get the refs from the Field input to go to the next input field with Redux Form.

Without RF this solution would work just fine.

Here is my code:

class RenderInput extends Component {
   const { input, nextField, refs,
        meta: { touched, error, warning },
        input: { onChange } } = this.props
   render() {
      return (
         <Input
            returnKeyType = {'next'}
            onChangeText={onChange}
            onBlur={input.onBlur}
            onFocus={input.onFocus}
            onSubmitEditing = {(event) => {
               // refs is undefined
               refs[nextField].focus()
            }}/>
      )
   }
}

class Form extends Component {
   render() {
      return (
         <Field
            name="field1"
            focus
            withRef
            ref='field1'
            nextField = "field2"
            component={RenderInput}/>

         <Field
            name="vendor"
            withRef
            ref="field2"
            nextAction = "field3"
            component={RenderInput}/>
      )
   }
}

I'm passing on the property nextField to the component to determine the next input field when the Next key on the keyboard is clicked but I can not get the refs property inside the RenderInput component.

Any idea how to get the refs property?

Body:
I worked on getting a ref like this that worked for me.

           const renderComp = ({
             refName,
             meta: { touched, error },
             input,
             ...custom
           }) => (
             <MyComponent
               ref={refName}
               {...custom}
             />
           )

            <Field
              name={name}
              component={renderComp}
              ref={node =>
                isLeft ? (this.compRef1 = node) : (this.compRef2 = node)}
              refName={node =>
                 (this.myRef= node) }
              withRef
            />

now access instance functions like this.

this.myRef.anyFunc()


问:
How can I get a list of users who have the same phone number in Zendesk?
I have a setup for Zendesk where tickets are created using multiple methods. One of these methods is via MyFusion Notes, and with this method, a new ticket and a new user is created in the database, with nothing more than the phone number, in this format: +1 (555) 555-5555.

Now, when the same customer calls, the same happens, but the phone number comes up like this: +15555555555

The problem is that when the customer called again, that new phone number format is not recognized as already in the system, and a new user is created.

What I want to do, is to first get a list of users where this happened. In database querying terms, I want something similar to SELECT * FROM users GROUP BY phone having count(*) >= 2. Then I can figure out how to merge these users or just delete the empty ones.

Is this even possible?

答:
Have you tried using the Search API in Zendesk?
https://developer.zendesk.com/rest_api/docs/core/search</p>


问:
ListView always delete the last item
My list view item contains a remove button, and I set it up in my adapter to remove the item from the database. Now once that's done how can i refresh the fragment which contains the listView to remove that item? Relevant code as below:

Remove item function in adapter:

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

            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
            alertDialog.setTitle("Delete item");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            FirebaseMethods firebaseMethods = new FirebaseMethods(mContext);
                            firebaseMethods.deleteHashtagFromDatabase(title);

                            dialog.dismiss();
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    alertDialog.show();

        }
    });
</code>```

Listview is setup like this in my fragment:

```<code>private void setupListView(){

    Log.d(TAG, "setupListView: setting up list");
    final ArrayList<HashTag> hashTags = new ArrayList<>();
    myRef = FirebaseDatabase.getInstance().getReference();
    Query query = myRef.child(getString(R.string.dbname_user_hashtags))
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

                if(singleSnapshot != null){
                    hashTags.add(0, singleSnapshot.getValue(HashTag.class));
                }

            }

            HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            hashtagListView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

Thanks!

UPDATE:

Now I have passed the OnClickListener on the subItem from the adapter to the fragment ListView OnItemClickListener as below:

Updated Adapter

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

            ((ListView) parent).performItemClick(v, position, 0);

        }
    });
</code>```

Updated Fragment

```<code>hashtagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

            long viewId = view.getId();
            Log.d(TAG, "onItemClick: viewId is " + viewId);
            Log.d(TAG, "onItemClick: position is " + position);

            final HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            final HashTag hashTag = hashTags.get(position);
            final String title = hashTag.getTitle();
            Log.d(TAG, "onItemClick: title is " + title);

            if(viewId == R.id.deleteFromListBtn){

                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("delete item");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                FirebaseMethods firebaseMethods = new FirebaseMethods(getActivity());
                                firebaseMethods.deleteHashtagFromDatabase(title);
                                Log.d(TAG, "onClick: title is " + title);

                                // NEW PROBLEM HERE!
                                adapter.remove(hashTag);
                                Log.d(TAG, "onClick: removed hashtag is " + hashTag);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "onItemClick: item removed from list.");

                                dialog.dismiss();
                            }
                        });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                alertDialog.show();

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

But now the problem is when I delete the item, the listView always delete the last item in the view. However, the correct item was deleted from database and according to the log, this code adapter.remove(hashTag) does grab the correct item i intent to delete.

答:
You should first remove the item from the Database and when success come from the database then item should be removed from ArrayList and the Adapter should be notifiy about the changes made in the ArratList.

To remove item from the ArrayList form adapter class.

```<code>//postion is the location of item in the arraylist to be deleted.
dataSet.remove(position);
</code>```

now to notifiy the adapter about the changes in the ArrayList. and it should be called which the Adapter class.

```<code> notifyDataSetChanged();
</code>```

Title: ListView always delete the last item

Body:
My list view item contains a remove button, and I set it up in my adapter to remove the item from the database. Now once that's done how can i refresh the fragment which contains the listView to remove that item? Relevant code as below:

Remove item function in adapter:

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

            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
            alertDialog.setTitle("Delete item");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            FirebaseMethods firebaseMethods = new FirebaseMethods(mContext);
                            firebaseMethods.deleteHashtagFromDatabase(title);

                            dialog.dismiss();
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    alertDialog.show();

        }
    });

Listview is setup like this in my fragment:

private void setupListView(){

    Log.d(TAG, "setupListView: setting up list");
    final ArrayList<HashTag> hashTags = new ArrayList<>();
    myRef = FirebaseDatabase.getInstance().getReference();
    Query query = myRef.child(getString(R.string.dbname_user_hashtags))
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

                if(singleSnapshot != null){
                    hashTags.add(0, singleSnapshot.getValue(HashTag.class));
                }

            }

            HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            hashtagListView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Thanks!

UPDATE:

Now I have passed the OnClickListener on the subItem from the adapter to the fragment ListView OnItemClickListener as below:

Updated Adapter

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

            ((ListView) parent).performItemClick(v, position, 0);

        }
    });

Updated Fragment

hashtagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

            long viewId = view.getId();
            Log.d(TAG, "onItemClick: viewId is " + viewId);
            Log.d(TAG, "onItemClick: position is " + position);

            final HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            final HashTag hashTag = hashTags.get(position);
            final String title = hashTag.getTitle();
            Log.d(TAG, "onItemClick: title is " + title);

            if(viewId == R.id.deleteFromListBtn){

                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("delete item");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                FirebaseMethods firebaseMethods = new FirebaseMethods(getActivity());
                                firebaseMethods.deleteHashtagFromDatabase(title);
                                Log.d(TAG, "onClick: title is " + title);

                                // NEW PROBLEM HERE!
                                adapter.remove(hashTag);
                                Log.d(TAG, "onClick: removed hashtag is " + hashTag);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "onItemClick: item removed from list.");

                                dialog.dismiss();
                            }
                        });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                alertDialog.show();

            }
        }
    });

But now the problem is when I delete the item, the listView always delete the last item in the view. However, the correct item was deleted from database and according to the log, this code adapter.remove(hashTag) does grab the correct item i intent to delete.

Body:
You should first remove the item from the Database and when success come from the database then item should be removed from ArrayList and the Adapter should be notifiy about the changes made in the ArratList.

To remove item from the ArrayList form adapter class.

//postion is the location of item in the arraylist to be deleted.
dataSet.remove(position);

now to notifiy the adapter about the changes in the ArrayList. and it should be called which the Adapter class.

 notifyDataSetChanged();


问:
Check if span contains value but value is after another nestled span
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="quantity">2 ×
  <del>
    <span class="woocommerce-Price-amount amount">
      <span class="woocommerce-Price-currencySymbol">$</span> 21.95
    </span>
  </del>
  <span class="woocommerce-Price-amount amount">
    <span class="woocommerce-Price-currencySymbol">$</span>19.76
  </span>
</span></code>```

答:
Just replace the code,

```<code>var inner = $(this).text();
</code>```

with

```<code>var inner = $(this).contents().eq(2).text();
</code>```

will works for you.

Body:
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});

2 ×

      $ 21.95

    $19.76

Body:
Just replace the code,

var inner = $(this).text();

with

var inner = $(this).contents().eq(2).text();

will works for you.


问:
Firefox automation with selenium how to loop and repeat an action
I would like to code how Firefox opens a website and clicks a button.

I would like Firefox to wait 30 mins and then close everything. I would like to loop this action.

```<code>from selenium.webdriver import Firefox

YOUR_PAGE_URL = 'http://www.websyndic.com/wv3/?qs=OTcxNzAw'
NEXT_BUTTON_XPATH = '/html/body/div[3]/div[3]/div[1]/div/div/div[3]/div/div/a'

browser = Firefox()
browser.get(YOUR_PAGE_URL)

button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()
</code>```

答:
As per your code is concerned, I don't see any issue out there. Now if you want to loop and repeat the actions after any pre-defined interval there are a few options available as follows :

Looping Options :

You can use the ScheduledExecutorService Interface from java.util.concurrent

Use a Continous Integration tool like Jenkins to support building, deploying and automating any project.

You can use the functionalities extended by Windows Scheduler to start your Test Execution.

Configure a Cron Job to execute your Test Suite at pre-defined intervals.

Body:
I would like to code how Firefox opens a website and clicks a button.

I would like Firefox to wait 30 mins and then close everything. I would like to loop this action.

from selenium.webdriver import Firefox

YOUR_PAGE_URL = 'http://www.websyndic.com/wv3/?qs=OTcxNzAw'
NEXT_BUTTON_XPATH = '/html/body/div[3]/div[3]/div[1]/div/div/div[3]/div/div/a'

browser = Firefox()
browser.get(YOUR_PAGE_URL)

button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()


答:
You have to escape quotes in element. Try following code

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Add New Buton
<div id="demo"></div></code>```

Title: Onclick function button inside a javascript

Body:
You have to escape quotes in element. Try following code

function showInput() {
    document.getElementById("demo").innerHTML = '<input type="submit" onclick="location.href = \'addnewcustomer.php\';" id ="newcust" class="btnRegister" value = "New Customer">';
}

<a onclick="showInput()" >Add New Buton</a>
<div id="demo"></div>


问:
How to explode first 10 elements of string ignore the rest (comma separated)
I want to explode the following string upto 10 elements

```<code>$str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o";
</code>```

into array $arr.Tried with

```<code>$arr = explode(",", $str,10);
</code>```

It gives result as

```<code>Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
[7] => h
[8] => i
[9] => j,k,l,m,n,o
)
</code>```

dont want $arr[9]=j,k,l,m,n,o should be $arr[9]=j.

答:
Here you go:</p>

```<code>$str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o";
$arr = explode(",", $str);
$output = array_slice($arr, 0, 10);   // returns a to j
</code>```

Body:
I want to explode the following string upto 10 elements

$str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o";

into array $arr.Tried with

$arr = explode(",", $str,10);

It gives result as

Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
[7] => h
[8] => i
[9] => j,k,l,m,n,o
)

dont want $arr[9]=j,k,l,m,n,o should be $arr[9]=j.

Body:
Here you go:

$str = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o";
$arr = explode(",", $str);
$output = array_slice($arr, 0, 10);   // returns a to j


问:
Plotting two sets of lines from two categories (e.g. colour)
I want to make a line graph of 2 sets of lines across 4 points, with the lines being differentiated by colour (Black or Gray50). The black and gray lines should not be connected.

My dataframe looks like this:

```<code>Index    Frequency Colour
1              1    Black
2              1    Black
3              0.8  Black
4              0    Black
1              0    Gray50
2              0    Gray50
3        0.88235294 Gray50
4              1    Gray50
1              1    Black
2              1    Black
3        0.85714286 Black
4              0    Black
1       0.02631579  Gray50
2         0.0625    Gray50
3          0.875    Gray50
4              1    Gray50
1              1    Black
2              1    Black
3             0.875 Black
4              0    Black
1              0    Gray50
2              0    Gray50
3        0.86666667 Gray50
4              1    Gray50
</code>```

Here is a rough example of the type of line graph I'd like

My code so far:

```<code>#object made from dataframe
alleles <- parallel_allele_freq

##plot

plot(alleles$Index,alleles$Frequency,xlab = "Gradient",xaxt = 'n',
     ylab = "Frequency of P allele",
     col = alleles$Colour, pch = 16, cex = 1.25, type = "b")

axis(1, at = seq(1, 4, by = 1))
</code>```

And here is the graph I'm getting, with black and gray lines connected.

Anybody know how I can get it so that each line is only 4 points long going in order in the file and according to colour?
Any help is GREATLY appreciated!

答:
In the following, I am just running a loop to get each four lines.
I am not sure if this is what you are after...

```<code>x <- read.table("temp.txt", header = TRUE)
plot(x$Index[1:4], x$Frequency[1:4], col=tolower(x$Colour[1]),
     type = "b", lwd = 2,
     xlab = "Gradient", xaxt = 'n',
     ylab = "Frequency of P allele",
     pch = 16, cex = 1.25)

for (j in 1:5)
  points(x$Index[(j*4)+1:4], x$Frequency[(j*4)+1:4],
          col=tolower(x$Colour[(j*4)+1]),
          type = "b", lwd = 2)

axis(1, at = seq(1, 4, by = 1))
</code>```

Body:
I want to make a line graph of 2 sets of lines across 4 points, with the lines being differentiated by colour (Black or Gray50). The black and gray lines should not be connected.

My dataframe looks like this:

Index    Frequency Colour
1              1    Black
2              1    Black
3              0.8  Black
4              0    Black
1              0    Gray50
2              0    Gray50
3        0.88235294 Gray50
4              1    Gray50
1              1    Black
2              1    Black
3        0.85714286 Black
4              0    Black
1       0.02631579  Gray50
2         0.0625    Gray50
3          0.875    Gray50
4              1    Gray50
1              1    Black
2              1    Black
3             0.875 Black
4              0    Black
1              0    Gray50
2              0    Gray50
3        0.86666667 Gray50
4              1    Gray50

Here is a rough example of the type of line graph I'd like

My code so far:

#object made from dataframe
alleles <- parallel_allele_freq

##plot

plot(alleles$Index,alleles$Frequency,xlab = "Gradient",xaxt = 'n',
     ylab = "Frequency of P allele",
     col = alleles$Colour, pch = 16, cex = 1.25, type = "b")

axis(1, at = seq(1, 4, by = 1))

And here is the graph I'm getting, with black and gray lines connected.

Anybody know how I can get it so that each line is only 4 points long going in order in the file and according to colour?
Any help is GREATLY appreciated!

Body:
In the following, I am just running a loop to get each four lines.
I am not sure if this is what you are after...

x <- read.table("temp.txt", header = TRUE)
plot(x$Index[1:4], x$Frequency[1:4], col=tolower(x$Colour[1]),
     type = "b", lwd = 2,
     xlab = "Gradient", xaxt = 'n',
     ylab = "Frequency of P allele",
     pch = 16, cex = 1.25)

for (j in 1:5)
  points(x$Index[(j*4)+1:4], x$Frequency[(j*4)+1:4],
          col=tolower(x$Colour[(j*4)+1]),
          type = "b", lwd = 2)

axis(1, at = seq(1, 4, by = 1))


问:
How do we Check if there are some avro files available inside a HDFS folder?
I have some avro files inside HDFS folder /user/data/output_files/file_2017-10-18

```<code>scala> val hdfsLoc ="/user/data/output_files/file_2017-10-18/*.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/*.avro

scala>  val conf = new Configuration()

scala>   val fs  = FileSystem.get(conf)

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = false
</code>```

The above code gives result as false . It says there is no avro files  inside that HDFS folder

If I give the full name of avro file , then it returns true

```<code>scala>  val hdfsLoc ="/user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = true
</code>```

How do I ensure that there are  one or more avro files inside a HDFS folder?

答:
FileSystem API has a  different function called globStatus which allows you to use wildcards.

It returns Array[org.apache.hadoop.fs.FileStatus]

```<code>val fs = FileSystem.get(Sc.hadoopConfiguration)

fs.globStatus(new Path("/user/data/output_files/file_2017-10-18/*.avro")).length match {
    case x: Int if (x>0) => doSomethingWhenAvroFileExists()
    case _ => doSomethingWhenNoAvroFilesExist()
}
</code>```

Body:
I have some avro files inside HDFS folder /user/data/output_files/file_2017-10-18

scala> val hdfsLoc ="/user/data/output_files/file_2017-10-18/*.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/*.avro

scala>  val conf = new Configuration()

scala>   val fs  = FileSystem.get(conf)

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = false

The above code gives result as false . It says there is no avro files  inside that HDFS folder

If I give the full name of avro file , then it returns true

scala>  val hdfsLoc ="/user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro"
hdfsLoc: String = /user/data/output_files/file_2017-10-18/part-r-00000-ed937f14-c7d1-480a-9c79-1cda3db4e6ce.avro

scala> val result = fs.exists(new Path(hdfsLoc))
result: Boolean = true

How do I ensure that there are  one or more avro files inside a HDFS folder?

Body:
FileSystem API has a  different function called globStatus which allows you to use wildcards.

It returns Array[org.apache.hadoop.fs.FileStatus]

val fs = FileSystem.get(Sc.hadoopConfiguration)

fs.globStatus(new Path("/user/data/output_files/file_2017-10-18/*.avro")).length match {
    case x: Int if (x>0) => doSomethingWhenAvroFileExists()
    case _ => doSomethingWhenNoAvroFilesExist()
}


问:
Change the URL of a docker-machine
I created a machine via docker-machine create -d azure --azure-static-public-IP. But what I did is I intentionally changed the public IP address of that VM. With this move, I can not docker-machine ssh or any docker-machine related command. Seems like it’s still sending request to the previous public-IP. How can I change that IP and convert it to the new one? I tried docker-machine regenerate-certs and even changing the config.json but nothing going to be happened…

The only way I saw fixing this is to reverting back the previous public IP of that VM

答:
Do you mean when you run Docker-machine ssh got this error:

Error checking TLS connection: Error checking and/or regenerating the
  certs: There was an error validating certificates for host
  "13.91.60.237:2376": x509: certificate is valid for 40.112.218.127,
  not 13.91.60.237 You can attempt to regenerate them using
  'docker-machine regenerate-certs [name]'. Be advised that this will
  trigger a Docker daemon restart which might stop running containers.

In my test lab, my first IP address is 40.112.218.127, then I change it to 13.91.60.237, get this error.

Then I use this command to regenerate it:docker-machine regenerate-certs jasonvmm, like this:

```<code>[root@jasoncli@jasonye jasonvmm]# docker-machine regenerate-certs jasonvmm
Regenerate TLS machine certs?  Warning: this is irreversible. (y/n): y
Regenerating TLS certificates
Waiting for SSH to be available...
Detecting the provisioner...
Installing Docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
[root@jasoncli@jasonye jasonvmm]# docker-machine ssh jasonvmm
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-47-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

208 packages can be updated.
109 updates are security updates.

Last login: Fri Dec  8 06:22:09 2017 from 167.220.255.48
</code>```

Also, we can use this command to check the new settings:docker-machine env jasonvmm

```<code>[root@jasoncli@jasonye jasonvmm]# docker-machine env jasonvmm
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://13.91.60.237:2376"
export DOCKER_CERT_PATH="/root/.docker/machine/machines/jasonvmm"
export DOCKER_MACHINE_NAME="jasonvmm"
# Run this command to configure your shell:
# eval $(docker-machine env jasonvmm)
</code>```

Please use this script to regenerate them docker-machine regenerate-certs VMname.

Hope this helps.

Title: Change the URL of a docker-machine

Body:
Do you mean when you run Docker-machine ssh got this error:

Error checking TLS connection: Error checking and/or regenerating the
  certs: There was an error validating certificates for host
  "13.91.60.237:2376": x509: certificate is valid for 40.112.218.127,
  not 13.91.60.237 You can attempt to regenerate them using
  'docker-machine regenerate-certs [name]'. Be advised that this will
  trigger a Docker daemon restart which might stop running containers.

In my test lab, my first IP address is 40.112.218.127, then I change it to 13.91.60.237, get this error.

Then I use this command to regenerate it:docker-machine regenerate-certs jasonvmm, like this:

[root@jasoncli@jasonye jasonvmm]# docker-machine regenerate-certs jasonvmm
Regenerate TLS machine certs?  Warning: this is irreversible. (y/n): y
Regenerating TLS certificates
Waiting for SSH to be available...
Detecting the provisioner...
Installing Docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
[root@jasoncli@jasonye jasonvmm]# docker-machine ssh jasonvmm
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-47-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

208 packages can be updated.
109 updates are security updates.

Last login: Fri Dec  8 06:22:09 2017 from 167.220.255.48

Also, we can use this command to check the new settings:docker-machine env jasonvmm

[root@jasoncli@jasonye jasonvmm]# docker-machine env jasonvmm
export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://13.91.60.237:2376"
export DOCKER_CERT_PATH="/root/.docker/machine/machines/jasonvmm"
export DOCKER_MACHINE_NAME="jasonvmm"
# Run this command to configure your shell:
# eval $(docker-machine env jasonvmm)

Please use this script to regenerate them docker-machine regenerate-certs VMname.

Hope this helps.


问:
Spring ModelAndView not working with ajax call
Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.

Ajax

```<code> $('#example1 tbody').on( 'click', 'button1', function () {
                var eid = table.row( $(this).parents('tr') ).data().eid;
                $.ajax({
                    type:"GET",
                    url:"employee_edit?eid="+eid
                });
</code>```

Controller

```<code>@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  ModelAndView mv=new ModelAndView();
  mv.setViewName("employee/employee_registration");
  mv.addObject("employee",employee);
  return mv;
}
</code>```

After running the code it does not show any error. Going through the  code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.

答:
I think in your ajax call you need to add the success parameter. You can simply modify your call as

```<code> $.ajax({
            type:"GET",
            url:"employee_edit",
            data:{"eid":eid},
            success:function(data){
            }
       });
</code>```

or you can also add only the success parameter in your code

```<code>$.ajax({
            type:"GET",
            url:"employee_edit?eid="+eid
            success:function(data) { }
       });
</code>```

But I prefer the first one. Its more clear.

This should complete the ajax call and your program should work.

Body:
Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.

Ajax

 $('#example1 tbody').on( 'click', 'button1', function () {
                var eid = table.row( $(this).parents('tr') ).data().eid;
                $.ajax({
                    type:"GET",
                    url:"employee_edit?eid="+eid
                });

Controller

@RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(@RequestParam("eid") long eid)
{
  Employee employee=employeeService.getEmployee(eid);
  ModelAndView mv=new ModelAndView();
  mv.setViewName("employee/employee_registration");
  mv.addObject("employee",employee);
  return mv;
}

After running the code it does not show any error. Going through the  code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.

Body:
I think in your ajax call you need to add the success parameter. You can simply modify your call as

 $.ajax({
            type:"GET",
            url:"employee_edit",
            data:{"eid":eid},
            success:function(data){
            }
       });

or you can also add only the success parameter in your code

$.ajax({
            type:"GET",
            url:"employee_edit?eid="+eid
            success:function(data) { }
       });

But I prefer the first one. Its more clear.

This should complete the ajax call and your program should work.


问:
Reading SQLite table information in C#.NET
I would like to read the table and column information in C#.NET Windows application. I know that there is SMO base access for SQL Server. On similar ground is there any API for SQLite?</p>

答:
You can use the GetSchema method :

```<code>DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SQLite");
using (DbConnection connection = factory.CreateConnection())
{
    connection.ConnectionString = @"Data Source=D:\tmp\test.db";
    connection.Open();
    DataTable tables = connection.GetSchema("Tables");
    DataTable columns = connection.GetSchema("Columns");
    tables.Dump();
    columns.Dump();
}
</code>```

GetSchema returns a DataTable that contains information about the tables, columns, or whatever you specify. Valid GetSchema arguments for SQLite include:

MetaDataCollections

DataSourceInformation

DataTypes

ReservedWords

Catalogs

Columns

Indexes

IndexColumns

Tables

Views

ViewColumns

ForeignKeys

Triggers

Body:
You can use the GetSchema method :

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SQLite");
using (DbConnection connection = factory.CreateConnection())
{
    connection.ConnectionString = @"Data Source=D:\tmp\test.db";
    connection.Open();
    DataTable tables = connection.GetSchema("Tables");
    DataTable columns = connection.GetSchema("Columns");
    tables.Dump();
    columns.Dump();
}

GetSchema returns a DataTable that contains information about the tables, columns, or whatever you specify. Valid GetSchema arguments for SQLite include:

MetaDataCollections

DataSourceInformation

DataTypes

ReservedWords

Catalogs

Columns

Indexes

IndexColumns

Tables

Views

ViewColumns

ForeignKeys

Triggers

ContentLicense: CC BY-SA 2.5


问:
combine two query result set and paginate the value
I have two query result set for $users and $logged_action and merged both.If I use all() displayed all value.I want to paginate.If I include paginate(10) instead of all.I caught a error

BadMethodCallException in Macroable.php line 74: Method paginate does
  not exist.

```<code>$users = DB::table('request')->select('asset_request.*')->get();
 $logged_action= DB::table('status_tracker')->select('status_tracker.*')->get();
 $users = $users->merge($logged_action);
 $users=$users->all();
 return view('layouts.approval_view',['users'=>$users]);
</code>```

答:
Maybe you can join the 2 tables by the same key that merge works and then paginate the result?

Something like that:

```<code> $users = DB::table('request')->
join('status_tracker','on' .... )->select ('asset_request.*', ....)->paginate (10);
</code>```

also did not tested but you can try this:

```<code>$users = DB::table('request')->select('asset_request.*')->paginate(10);
 $logged_action= DB::table('status_tracker')->select('status_tracker.*')->paginate(10);
 $users = $users->merge($logged_action);
 $users=$users->all();
 return view('layouts.approval_view',['users'=>$users]);
</code>```

Hope it helps.

Body:
I have two query result set for $users and $logged_action and merged both.If I use all() displayed all value.I want to paginate.If I include paginate(10) instead of all.I caught a error

BadMethodCallException in Macroable.php line 74: Method paginate does
  not exist.

$users = DB::table('request')->select('asset_request.*')->get();
 $logged_action= DB::table('status_tracker')->select('status_tracker.*')->get();
 $users = $users->merge($logged_action);
 $users=$users->all();
 return view('layouts.approval_view',['users'=>$users]);

Body:
Maybe you can join the 2 tables by the same key that merge works and then paginate the result?

Something like that:

 $users = DB::table('request')->
join('status_tracker','on' .... )->select ('asset_request.*', ....)->paginate (10);

also did not tested but you can try this:

$users = DB::table('request')->select('asset_request.*')->paginate(10);
 $logged_action= DB::table('status_tracker')->select('status_tracker.*')->paginate(10);
 $users = $users->merge($logged_action);
 $users=$users->all();
 return view('layouts.approval_view',['users'=>$users]);

Hope it helps.


问:
I want to take input from multiple text inputs and send them to my database, but only the last input sends
I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.

I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.

Here is my html file and the script

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
 return {
  'getSuggestion' : function(suggestion,callback){
   $http.post('/getSuggestion', {
    'suggestion': suggestion
   }).success(function (response) {
    callback(response);
   })
   .error(function (data, status, header, config) {
    callback({
     'error': true,
     'message': "Something went wrong."
    });
   });
  }
 }
}]);

app.controller('app', function($scope,appService) {
 //message send Function
 $scope.$watch('messageInput', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("USERNAME");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput2', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput3', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="app" ng-controller="app">

  <head>
    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
  </head>

  <body>

    <div class="formFields">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username"> <br>

        <input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password"> <br>

        <input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf"> <br>

        <button id="clickButton" class="submitButton">submit</button>

      </form>

    </div>
    <!--<script src="Scripts/login.js"></script>-->
  <script src="js/angular.min.js"></script>
  <script src="js/script.js"></script>
  </body>
</html></code>```

答:
You have a $watch for each input, and you have a submit() for each input. This is why you send only the input that changed. If you want to send them all together you should hold one submit(), means one onClick() that will check all new values are not null and send them to the server, something like this:

```<code>$scope.$watch('allInput', function (newValues, oldValues) {
    //null check
    if (newValues.user !== null && newValues.pass !== null && newValues.pass2 !== null) {
        //wait for the button to be pressed
        button.onclick = function() {
            alert("USERNAME");
            alert("PASSWORD");
            alert("PASSWORD CONF");
            //call server query function
            appService.getSuggestion(newValues, function (response) {
                $scope.suggestionCollection = response.rows;
            });
        };
    }
});
</code>```

and the html:

```<code>      <form class="defaultForm" id="loginForm">

    <input class="loginField" type="text" name="username" ng-model="allInput.name" placeholder="username"> <br>

    <input class="loginField" type="text" name="password" ng-model="allInput.pass" placeholder="password"> <br>

    <input class="loginField" type="text" name="username" ng-model="allInput.pass2" placeholder="pass conf"> <br>

    <button id="clickButton" class="submitButton">submit</button>

  </form>
</code>```

Of course getSuggestion() will change as well:

```<code>app.service('appService', ['$http', function($http){
return {
    'getSuggestion' : function(data,callback){
        $http.post('/getSuggestion', {
            'name': data.name,
            'pass': data.pass,
            'pass2': data.pass2
        }).success(function (response) {
            callback(response);
        })
        .error(function (data, status, header, config) {
            callback({
                'error': true,
                'message': "Something went wrong."
            });
        });
    }
}
</code>```

Body:
I have a mysql database/node backend, connected to an Angular frontend, that I am querying, specifically to send it the data from 3 simple text inputs in a form.

I believe my error is quite trivial for anyone with node/angular experience because I can successfully send my database input from one of the text inputs; however, when I try to detect and send data from all three inputs, it only sends the data from whichever input has its matching controller function as the last one (of the three) in my script.

Here is my html file and the script

var button = document.getElementById("clickButton");

const app = angular.module('app',[]);

app.service('appService', ['$http', function($http){
 return {
  'getSuggestion' : function(suggestion,callback){
   $http.post('/getSuggestion', {
    'suggestion': suggestion
   }).success(function (response) {
    callback(response);
   })
   .error(function (data, status, header, config) {
    callback({
     'error': true,
     'message': "Something went wrong."
    });
   });
  }
 }
}]);

app.controller('app', function($scope,appService) {
 //message send Function
 $scope.$watch('messageInput', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("USERNAME");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput2', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });

 $scope.$watch('messageInput3', function (newValue, oldValue) {
  //null check
  if (newValue !== null) {
   //wait for the button to be pressed
   button.onclick = function() {
    alert("PASSWORD");
    //call server query function
    appService.getSuggestion(newValue, function (response) {
     $scope.suggestionCollection = response.rows;
    });
   };
  }
 });
});

<!DOCTYPE html>

    <title>Node app</title>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

      <form class="defaultForm" id="loginForm">

        <input class="loginField" type="text" name="username" ng-model="messageInput" placeholder="username">

        <input class="loginField" type="text" name="password" ng-model="messageInput2" placeholder="password">

        <input class="loginField" type="text" name="username" ng-model="messageInput3" placeholder="pass conf">

        <button id="clickButton" class="submitButton">submit</button>

      </form>

Body:
You have a $watch for each input, and you have a submit() for each input. This is why you send only the input that changed. If you want to send them all together you should hold one submit(), means one onClick() that will check all new values are not null and send them to the server, something like this:

$scope.$watch('allInput', function (newValues, oldValues) {
    //null check
    if (newValues.user !== null && newValues.pass !== null && newValues.pass2 !== null) {
        //wait for the button to be pressed
        button.onclick = function() {
            alert("USERNAME");
            alert("PASSWORD");
            alert("PASSWORD CONF");
            //call server query function
            appService.getSuggestion(newValues, function (response) {
                $scope.suggestionCollection = response.rows;
            });
        };
    }
});

and the html:

      <form class="defaultForm" id="loginForm">

    <input class="loginField" type="text" name="username" ng-model="allInput.name" placeholder="username"> <br>

    <input class="loginField" type="text" name="password" ng-model="allInput.pass" placeholder="password"> <br>

    <input class="loginField" type="text" name="username" ng-model="allInput.pass2" placeholder="pass conf"> <br>

    <button id="clickButton" class="submitButton">submit</button>

  </form>

Of course getSuggestion() will change as well:

app.service('appService', ['$http', function($http){
return {
    'getSuggestion' : function(data,callback){
        $http.post('/getSuggestion', {
            'name': data.name,
            'pass': data.pass,
            'pass2': data.pass2
        }).success(function (response) {
            callback(response);
        })
        .error(function (data, status, header, config) {
            callback({
                'error': true,
                'message': "Something went wrong."
            });
        });
    }
}