问:
Use Javascript Cookies to Track HP in an HTML5-Based Game
I am working on a website, which is essentially a linear choose-your-own-adventure game (Scene 1 goes to Scene 2 no matter what choice you choose). However, each choice you make will cause a change in health, if the health hits 0 you lose. At this point, I am supposed to create this using mainly HTML5 & CSS3 with some JavaScript integration.

I built the game so that there are links from one page to the next page, I am just not sure how to track the hp. My instructor suggested that we look into cookies, but I have not been able to get the cookies to be made (Problem 1). Even if I were able to get the cookies to work, I don't know how I would change the destination of the link if they hit 0hp, so that the game ended, and the final message is displayed.

If it helps here is the HTML

The three options

```<code><ul id="horizontal-list">
    <li><a
        href="S3B.html"
        class="ghost-button">Option 1</a></li>
    <li><a
        href="S3C.html"
        class="ghost-button">Option 2</a></li>
    <li class="third"><a
        href="S3A.html"
        class="ghost-button">Option 3</a></li>
</ul>
</code>```

Then on the next page

```<code><ul>
    <li><a
        href="../S4/S4.html"
        class="ghost-button">Go on to the next scene</a></li>
</ul>
</code>```

I need it to check the value of the players HP after they click the "Go on to the next scene" button, and if they have a HP of 0, they go to a different page, but if they have an HP greater than 0, they go to the file at

../S4/S4.html

I have a very basic knowledge of js syntax, but am an experienced programmer in general and understand most of the concepts involved in programming.

答:
One method you could do this would be to store their health as a variable in the browser's local store:

```<code>if (typeof(Storage) !== "undefined") {
    localStorage.setItem("HP", "100");
} else {
    // Sorry! No Web Storage support..
}
</code>```

and if you'd like to manipulate that value, you would simply change it just like you would do with an object property:

```<code>localStorage.HP = parseInt(localStorage.HP) - hitpointsLost;
</code>```

(localStorage variables are stored as strings, so we have to use parseInt to treat it like an integer and remove some HP)

You can then destroy the data sample when they lose by doing:

```<code>localStorage.removeItem("HP");
</code>```

Whenever you're remove the HP, have some function or check to see if the user's HP has hit 0 or less, and then use window.location.assign('newlocation.html') to redirect them to the "You Lost" page.

Body:
I am working on a website, which is essentially a linear choose-your-own-adventure game (Scene 1 goes to Scene 2 no matter what choice you choose). However, each choice you make will cause a change in health, if the health hits 0 you lose. At this point, I am supposed to create this using mainly HTML5 & CSS3 with some JavaScript integration.

I built the game so that there are links from one page to the next page, I am just not sure how to track the hp. My instructor suggested that we look into cookies, but I have not been able to get the cookies to be made (Problem 1). Even if I were able to get the cookies to work, I don't know how I would change the destination of the link if they hit 0hp, so that the game ended, and the final message is displayed.

If it helps here is the HTML

The three options

Option 1

Option 2

Option 3

Then on the next page

Go on to the next scene

I need it to check the value of the players HP after they click the "Go on to the next scene" button, and if they have a HP of 0, they go to a different page, but if they have an HP greater than 0, they go to the file at

../S4/S4.html

I have a very basic knowledge of js syntax, but am an experienced programmer in general and understand most of the concepts involved in programming.

Body:
One method you could do this would be to store their health as a variable in the browser's local store:

if (typeof(Storage) !== "undefined") {
    localStorage.setItem("HP", "100");
} else {
    // Sorry! No Web Storage support..
}

and if you'd like to manipulate that value, you would simply change it just like you would do with an object property:

localStorage.HP = parseInt(localStorage.HP) - hitpointsLost;

(localStorage variables are stored as strings, so we have to use parseInt to treat it like an integer and remove some HP)

You can then destroy the data sample when they lose by doing:

localStorage.removeItem("HP");

Whenever you're remove the HP, have some function or check to see if the user's HP has hit 0 or less, and then use window.location.assign('newlocation.html') to redirect them to the "You Lost" page.


来源: stackexchange

问:
Error in mapPropsToState upon clicking react-router Link
I have been trying to learn redux, by building a simple blog.

Everything seemed to be going pretty well, until I used a react-router Link component to use a blog title in blog list page to navigate to blog detail page.

So, I have the following react routes:

Root (/)

Show Post (/posts/:id)

If I go to each of the routes by entering them in the browser, it works fine.

However, the issue is when I am in the root page, and then I click a link to go to blog post detail path.

Here's my redux state:

```<code>import {
  FETCH_POST_LIST_REQUEST,
  FETCH_POST_LIST_SUCCESS,
  FETCH_POST_LIST_ERROR,
  FETCH_POST_REQUEST,
  FETCH_POST_SUCCESS,
  FETCH_POST_ERROR,
  CREATE_POST_REQUEST,
  CREATE_POST_SUCCESS,
  CREATE_POST_ERROR
} from '../constants'

const initialState = {
  postsList: {
    data: { collection: [] },
    isLoading: false
  },
  newPost: {
    data: {},
    isLoading: false
  },
  post: {
    data: {},
    isLoading: false
  }
}

const posts = function(state = initialState, action) {
  switch (action.type) {
  case FETCH_POST_LIST_REQUEST:
    return {
      postsList: { data: { collection: [] }, isLoading: true }
    }
  case FETCH_POST_LIST_SUCCESS:
    return {
      postsList: { data: action.data, isLoading: false }
    }
  case FETCH_POST_LIST_ERROR:
    return {
      postsList: { data: [], isLoading: false }
    }
  case FETCH_POST_REQUEST:
    return {
      post: { data: {}, isLoading: true }
    }
  case FETCH_POST_SUCCESS:
    return {
      post: { data: action.data, isLoading: false }
    }
  case FETCH_POST_ERROR:
    return {
      post: { data: {}, isLoading: false }
    }
  case CREATE_POST_REQUEST:
    return {
      newPost: { data: {}, isLoading: true }
    }
  case CREATE_POST_SUCCESS:
    return {
      newPost: { data: action.data, isLoading: false }
    }
  case CREATE_POST_ERROR:
    return {
      newPost: { data: {}, isLoading: false }
    }
  default:
    return state
  }
}
</code>```

I was also able to figure out why I was getting the error.

When I am in root path, my redux state is posts: { postsList: ... }

When I directly go to a show path, my redux state changes to posts: { post: ... }

When I click the Link, it i supposed to route me to /posts/1, and render the following container:

```<code>import PostShow from '../components/post-show'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actionCreators from '../actions'

const mapStateToProps = function(state) {
  return {
    data: state.posts.post.data,
    isLoading: state.posts.post.isLoading
  }
}

const mapDispatchToProps = function(dispatch) {
  return {
    actions: bindActionCreators(actionCreators, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PostShow)
</code>```

This container is connected to the following component:

```<code>import React from 'react'

class PostShow extends React.Component {
  componentDidMount() {
    this.props.actions.fetchPost(this.props.id)
  }

  render() {
    return (
      <div>
        {
            this.props.isLoading ?
            'Loading...' :
            (
             <div className="post">
              <p className="title">{this.props.data.title}</p>
              <p className="content">{this.props.data.content}</p>
              <p className="author">{this.props.data.author}</p>
            </div>
            )
        }
      </div>
    )
  }
}

export default PostShow
</code>```

Upon transition from root path to show path, via clicking the react-router link, in the following code:

```<code>const mapStateToProps = function(state) {
  return {
    data: state.posts.post.data,
    isLoading: state.posts.post.isLoading
  }
}
</code>```

The redux state is still posts: { postsList: ... }, instead of posts: { post: ... }, which causes error at state.posts.post.data, causing the container to throw error.

The way I am doing things, the state is changed only after a store dispatch is triggered in componentDidMount:

```<code>componentDidMount() {
  this.props.actions.fetchPost(this.props.id)
}
</code>```

I guess I am either doing things the wrong way, or missing something.

Can anyone help me with this?

Thanks.

答:
You have to change your reducer a bit,

```<code>const posts = function(state = initialState, action) {
  switch (action.type) {
  case FETCH_POST_LIST_REQUEST:
    return {
      ...state,
      postsList: { data: { collection: [] }, isLoading: true }
    }
  case FETCH_POST_LIST_SUCCESS:
    return {
      ...state,
      postsList: { data: action.data, isLoading: false }
    }
  case FETCH_POST_LIST_ERROR:
    return {
      ...state,
      postsList: { data: [], isLoading: false }
    }
  case FETCH_POST_REQUEST:
    return {
      ...state,
      post: { data: {}, isLoading: true }
    }
  case FETCH_POST_SUCCESS:
    return {
      ...state,
      post: { data: action.data, isLoading: false }
    }
  case FETCH_POST_ERROR:
    return {
      ...state,
      post: { data: {}, isLoading: false }
    }
  case CREATE_POST_REQUEST:
    return {
      ...state,
      newPost: { data: {}, isLoading: true }
    }
  case CREATE_POST_SUCCESS:
    return {
      ...state,
      newPost: { data: action.data, isLoading: false }
    }
  case CREATE_POST_ERROR:
    return {
      ...state,
      newPost: { data: {}, isLoading: false }
    }
  default:
    return state
  }
}
</code>```

have a look here: http://redux.js.org/docs/basics/Reducers.html

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to learn redux, by building a simple blog.

Everything seemed to be going pretty well, until I used a react-router Link component to use a blog title in blog list page to navigate to blog detail page.

So, I have the following react routes:

Root (/)

Show Post (/posts/:id)

If I go to each of the routes by entering them in the browser, it works fine.

However, the issue is when I am in the root page, and then I click a link to go to blog post detail path.

Here's my redux state:

import {
  FETCH_POST_LIST_REQUEST,
  FETCH_POST_LIST_SUCCESS,
  FETCH_POST_LIST_ERROR,
  FETCH_POST_REQUEST,
  FETCH_POST_SUCCESS,
  FETCH_POST_ERROR,
  CREATE_POST_REQUEST,
  CREATE_POST_SUCCESS,
  CREATE_POST_ERROR
} from '../constants'

const initialState = {
  postsList: {
    data: { collection: [] },
    isLoading: false
  },
  newPost: {
    data: {},
    isLoading: false
  },
  post: {
    data: {},
    isLoading: false
  }
}

const posts = function(state = initialState, action) {
  switch (action.type) {
  case FETCH_POST_LIST_REQUEST:
    return {
      postsList: { data: { collection: [] }, isLoading: true }
    }
  case FETCH_POST_LIST_SUCCESS:
    return {
      postsList: { data: action.data, isLoading: false }
    }
  case FETCH_POST_LIST_ERROR:
    return {
      postsList: { data: [], isLoading: false }
    }
  case FETCH_POST_REQUEST:
    return {
      post: { data: {}, isLoading: true }
    }
  case FETCH_POST_SUCCESS:
    return {
      post: { data: action.data, isLoading: false }
    }
  case FETCH_POST_ERROR:
    return {
      post: { data: {}, isLoading: false }
    }
  case CREATE_POST_REQUEST:
    return {
      newPost: { data: {}, isLoading: true }
    }
  case CREATE_POST_SUCCESS:
    return {
      newPost: { data: action.data, isLoading: false }
    }
  case CREATE_POST_ERROR:
    return {
      newPost: { data: {}, isLoading: false }
    }
  default:
    return state
  }
}

I was also able to figure out why I was getting the error.

When I am in root path, my redux state is posts: { postsList: ... }

When I directly go to a show path, my redux state changes to posts: { post: ... }

When I click the Link, it i supposed to route me to /posts/1, and render the following container:

import PostShow from '../components/post-show'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actionCreators from '../actions'

const mapStateToProps = function(state) {
  return {
    data: state.posts.post.data,
    isLoading: state.posts.post.isLoading
  }
}

const mapDispatchToProps = function(dispatch) {
  return {
    actions: bindActionCreators(actionCreators, dispatch)
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(PostShow)

This container is connected to the following component:

import React from 'react'

class PostShow extends React.Component {
  componentDidMount() {
    this.props.actions.fetchPost(this.props.id)
  }

  render() {
    return (

        {
            this.props.isLoading ?
            'Loading...' :
            (

{this.props.data.title}

{this.props.data.content}

{this.props.data.author}

            )
        }

    )
  }
}

export default PostShow

Upon transition from root path to show path, via clicking the react-router link, in the following code:

const mapStateToProps = function(state) {
  return {
    data: state.posts.post.data,
    isLoading: state.posts.post.isLoading
  }
}

The redux state is still posts: { postsList: ... }, instead of posts: { post: ... }, which causes error at state.posts.post.data, causing the container to throw error.

The way I am doing things, the state is changed only after a store dispatch is triggered in componentDidMount:

componentDidMount() {
  this.props.actions.fetchPost(this.props.id)
}

I guess I am either doing things the wrong way, or missing something.

Can anyone help me with this?

Thanks.

Body:
You have to change your reducer a bit,

const posts = function(state = initialState, action) {
  switch (action.type) {
  case FETCH_POST_LIST_REQUEST:
    return {
      ...state,
      postsList: { data: { collection: [] }, isLoading: true }
    }
  case FETCH_POST_LIST_SUCCESS:
    return {
      ...state,
      postsList: { data: action.data, isLoading: false }
    }
  case FETCH_POST_LIST_ERROR:
    return {
      ...state,
      postsList: { data: [], isLoading: false }
    }
  case FETCH_POST_REQUEST:
    return {
      ...state,
      post: { data: {}, isLoading: true }
    }
  case FETCH_POST_SUCCESS:
    return {
      ...state,
      post: { data: action.data, isLoading: false }
    }
  case FETCH_POST_ERROR:
    return {
      ...state,
      post: { data: {}, isLoading: false }
    }
  case CREATE_POST_REQUEST:
    return {
      ...state,
      newPost: { data: {}, isLoading: true }
    }
  case CREATE_POST_SUCCESS:
    return {
      ...state,
      newPost: { data: action.data, isLoading: false }
    }
  case CREATE_POST_ERROR:
    return {
      ...state,
      newPost: { data: {}, isLoading: false }
    }
  default:
    return state
  }
}

have a look here: http://redux.js.org/docs/basics/Reducers.html


问:
electron, after browserify, fs.existsSync is not a function
i read a lot about browserify and electron and the gui browser issue
yet there is still a problem with  browserify, saying "fs.existsSync is not a function", and "required is not defined"

* The full story*
i created simple gui with electron   ,
there are the package.json file, the main.js and the index.html file + 3,4 html files, where there i want to create simple "load show save window" that work with require

That feature worked in the index.html file yet doesn't work properly in the load.html file, so i browserify the main.js with the commands

var  fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote ```
</div>
</div>
 </p>

<p>into main.bundle3.js, with, (in the cmd)</p>

```browserify main.js > main.bundle3.js
```

<p>yet then the load.html file shouted that require is not define and    </p>

```> main.bundle3.js:6945 Uncaught TypeError: fs.existsSync is not a function
    at Object.<anonymous> (main.bundle3.js:6945)
    at Object.require.36.fs (main.bundle3.js:6951)
    at s (main.bundle3.js:1)
    at main.bundle3.js:1
    at Object.<anonymous> (main.bundle3.js:6794)
    at Object.require.35._process (main.bundle3.js:6937)
    at s (main.bundle3.js:1)
    at e (main.bundle3.js:1)
    at main.bundle3.js:1
(anonymous) @   main.bundle3.js:6945
require.36.fs   @   main.bundle3.js:6951
s   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:6794
require.35._process @   main.bundle3.js:6937
s   @   main.bundle3.js:1
e   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
```

<p>The package.json</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "name": "RDF",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "test": "mocha -u exports -R spec test/index"
  },
  "devDependencies": {
    "electron": "^1.6.2",
    "electron-packager": "^8.6.0",
    "html-browserify": "0.0.6",
    "jquery": "^3.2.1"
  }
}</code>```

 and load.html file

<!DOCTYPE html>

    <meta charset="UTF-8">

LOAD

load the data

            <input type="text" placeholder="just select a file" id="actual-file" disabled="disabled"/>
            <input type="button" value="Choose a file" id="select-file"/>

        <textarea id="content-editor" rows="5"></textarea>

        <input type="button" id="save-changes" value="Save changes"/>
        <input type="button" id="delete-file" value="Delete file"/>

  he file content will be the same as the editor.

        <input type="button" value="Choose a file" id="create-new-file"/>

```
</div>
</div>
</p>

<p>the the main.js file in full</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//console.log(require('fs'));
console.log(require('module').globalPaths);
const {
  electron
} = require('electron');
const {
  BrowserWindow
} = require('electron')
const {
  app
} = require('electron');
//  @show(app)
const path = require('path')
//console.log( process.env.PATH);
// (D:\electron-v1.6.1-win32-x64\resources\default_app.asr\main.js:325:5)
 //const BrowserWindow = require('browser-window')
const url = require('url')
var html = require('html-browserify');
var fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote
//dialog = require('electron').dialog
//dialog =remote.require('dialog')

//var load_=require('./load_.js')
// broserify html
var through = require('through');
var htmlclean = require('htmlclean');

module.exports = function(file, options) {

  options = options || {};
  options.htmlclean =
   typeof options.htmlclean !== 'undefined'
      ?      options.htmlclean : true;

  var buffer = '';

  if (!/\.(tpl|html)/.test(file)) {

    return through();

  } else {

    return through(function(chunk) {

      return buffer += chunk.toString();

    }, function() {

      var jst = buffer.toString();

      if (options.htmlclean) {
        //options.htmlclean is truthy

        if (typeof options.htmlclean === 'object') {
          //options.htmlclean is an options object for the htmlclean module
          jst = htmlclean(jst, options.htmlclean);
        } else {
          //otherwise, clean using default options
          jst = htmlclean(jst);
        }
      }

      var compiled = 'module.exports = ';
      compiled += JSON.stringify(jst);
      compiled += ';\n';

      this.queue(compiled);
      return this.queue(null);

    });

  }

}
//requirejs.config({
//By default load any module IDs from js/lib
//  baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
//paths: {
//  app: '  '
//}
//});

// Start the main app logic.
//requirejs(['jquery', 'canvas', 'app/sub'],
//function   ($,        canvas,   sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
//});
//const fs = require('fs');
//const app = require('electron').app.
//const remote = require('electron').remote;

// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1050,
    height: 814
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.</code>```

答:
alright the command

```<code>npm install browserify-fs
</code>```

and then the

```<code>browserify -fs main.js >main.bundle.js
</code>```

solved the "fs.existsSnc not a function", yet not the problem. probably just removing the fs from the problem. (the reason to present this  :  that reply appeared in question about fs and browserify)

Body:
i read a lot about browserify and electron and the gui browser issue
yet there is still a problem with  browserify, saying "fs.existsSync is not a function", and "required is not defined"

* The full story*
i created simple gui with electron   ,
there are the package.json file, the main.js and the index.html file + 3,4 html files, where there i want to create simple "load show save window" that work with require

That feature worked in the index.html file yet doesn't work properly in the load.html file, so i browserify the main.js with the commands

var  fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote

into main.bundle3.js, with, (in the cmd)

browserify main.js > main.bundle3.js

yet then the load.html file shouted that require is not define and

> main.bundle3.js:6945 Uncaught TypeError: fs.existsSync is not a function
    at Object.<anonymous> (main.bundle3.js:6945)
    at Object.require.36.fs (main.bundle3.js:6951)
    at s (main.bundle3.js:1)
    at main.bundle3.js:1
    at Object.<anonymous> (main.bundle3.js:6794)
    at Object.require.35._process (main.bundle3.js:6937)
    at s (main.bundle3.js:1)
    at e (main.bundle3.js:1)
    at main.bundle3.js:1
(anonymous) @   main.bundle3.js:6945
require.36.fs   @   main.bundle3.js:6951
s   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:6794
require.35._process @   main.bundle3.js:6937
s   @   main.bundle3.js:1
e   @   main.bundle3.js:1
(anonymous) @   main.bundle3.js:1

The package.json

{
  "name": "RDF",
  "version": "0.1.0",
  "main": "main.js",
  "scripts": {
    "test": "mocha -u exports -R spec test/index"
  },
  "devDependencies": {
    "electron": "^1.6.2",
    "electron-packager": "^8.6.0",
    "html-browserify": "0.0.6",
    "jquery": "^3.2.1"
  }
}

 and load.html file

<!DOCTYPE html>

    <meta charset="UTF-8">

LOAD

load the data

            <input type="text" placeholder="just select a file" id="actual-file" disabled="disabled"/>
            <input type="button" value="Choose a file" id="select-file"/>

        <textarea id="content-editor" rows="5"></textarea>

        <input type="button" id="save-changes" value="Save changes"/>
        <input type="button" id="delete-file" value="Delete file"/>

  he file content will be the same as the editor.

        <input type="button" value="Choose a file" id="create-new-file"/>

the the main.js file in full

//console.log(require('fs'));
console.log(require('module').globalPaths);
const {
  electron
} = require('electron');
const {
  BrowserWindow
} = require('electron')
const {
  app
} = require('electron');
//  @show(app)
const path = require('path')
//console.log( process.env.PATH);
// (D:\electron-v1.6.1-win32-x64\resources\default_app.asr\main.js:325:5)
 //const BrowserWindow = require('browser-window')
const url = require('url')
var html = require('html-browserify');
var fs = require('electron')
//console.log(require('fs').existsSync);
var remote = require('electron').remote;
//  var remote = require('remote');
var dialog = require('electron').remote
//dialog = require('electron').dialog
//dialog =remote.require('dialog')

//var load_=require('./load_.js')
// broserify html
var through = require('through');
var htmlclean = require('htmlclean');

module.exports = function(file, options) {

  options = options || {};
  options.htmlclean =
   typeof options.htmlclean !== 'undefined'
      ?      options.htmlclean : true;

  var buffer = '';

  if (!/\.(tpl|html)/.test(file)) {

    return through();

  } else {

    return through(function(chunk) {

      return buffer += chunk.toString();

    }, function() {

      var jst = buffer.toString();

      if (options.htmlclean) {
        //options.htmlclean is truthy

        if (typeof options.htmlclean === 'object') {
          //options.htmlclean is an options object for the htmlclean module
          jst = htmlclean(jst, options.htmlclean);
        } else {
          //otherwise, clean using default options
          jst = htmlclean(jst);
        }
      }

      var compiled = 'module.exports = ';
      compiled += JSON.stringify(jst);
      compiled += ';\n';

      this.queue(compiled);
      return this.queue(null);

    });

  }

}
//requirejs.config({
//By default load any module IDs from js/lib
//  baseUrl: 'js/lib',
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
//paths: {
//  app: '  '
//}
//});

// Start the main app logic.
//requirejs(['jquery', 'canvas', 'app/sub'],
//function   ($,        canvas,   sub) {
//jQuery, canvas and the app/sub module are all
//loaded and can be used here now.
//});
//const fs = require('fs');
//const app = require('electron').app.
//const remote = require('electron').remote;

// be closed automatically when the JavaScript object is garbage collected.
let win

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1050,
    height: 814
  })

  // and load the index.html of the app.
  win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // Open the DevTools.
  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    win = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

Body:
alright the command

npm install browserify-fs

and then the

browserify -fs main.js >main.bundle.js

solved the "fs.existsSnc not a function", yet not the problem. probably just removing the fs from the problem. (the reason to present this  :  that reply appeared in question about fs and browserify)


问:
JQuery working Intermittently
I'm hoping I'm missing an obvious solution here. The below code only works intermittently. If you load with a cleared cache / incognito mode, then click on .gifslide twice before the page has finished loading - it breaks. Typing that I realize how specific this is but regardless, please help.

The offending code:

```<code>$(document).ready(function(){
    $(".gifslide").on('click', function () {
      $('.gifslide').toggle();
 // below is a workaround to make
 // it appear the the image is sliding upward and not down.
      $("#load-gif-container").slideToggle(500);
      $('.gif-content').slideToggle(500);
    });
  });
</code>```

It's HTML sidekick:

```<code>  <div id="load-gif-container">
    <img src="{{'source.png' | asset_url}}" id="load-gif"  />
  </div>
  <div class="gifslide"><span>&#9650<br>Expand</span>
  </div>
  <div class="gif-content">
    <img src="{{ 'source.gif' | asset_url }}", id="gif-banner"/>
  </div>
</code>```

ya I'm programming in liquid but aside from that - what's the problem here?

UPDATE / EDIT:

When I said "it breaks" I should have said ".gif-content displays without performing the slideToggle. #load-gif container also doesn't toggle but .gifslide does". No errors displayed. It does look ridiculous but nothing in the console that would help.

I replied back to current comment on this question explaining what happened when I tried that.

I've also tried not triggering the function until the image inside of #gif-content loads. It didn't work but I have a feeling that this is where the problem is stemming from. It's a massive gif, above the fold, surrounded by other massive images. I'm not sure there is enough compressing / minimizing in the world to get all of these things to function smoothly on limited connections but I'm hoping that I'm wrong.

答:
You have the click event binding after the document is ready. When reloading the page under normal circumstances, your script is cached and can therefore give you the functionality you are looking for. The reason you are running into this problem only in incognito mode or after you have cleared cache is because your script is not cached, and therefore not accessible. Your script is still loading, the page is not "ready", and so it is not able to pick up your clicks/doubleclicks ... while it is still loading.

There are a few other changes I would recommend as well that will give you better performance (obviously after the document is ready) and more consistent behavior:

```<code>// from
$(document).ready(function() {});

// to
$(function() {});

// these are equivalent and the latter is more terse
</code>```

If you are ever in a situation where there is more than one .gifslide in a document, clicking on one of them will propagate that click event to all of them. Additionally, to clear the event queue of any other click events related to .gifslide, use .off() before .on(). You can resolve these issues like this:

```<code>$(function() {
    $('.gifslide').off('click').on('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        $(event.target).toggle();
    });
});
</code>```

It is also recommended to cache your elements in a variable. In terms of performance, touching the DOM is very expensive. So...

```<code>$(function() {
    var $gifSlide = $('.gifslide'),
        $loadGif = $('#load-gif-container'),
        $gifContent = $('.gif-content');

    $gifSlide.off('click').on('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        $(event.target).toggle();

        $loadGif.slideToggle(500);
        $gifContent.slideToggle(500);
    });
});
</code>```

Finally, because you have a span nested within .gifslide, if someone clicks on the span, you may end up handling the click event behavior on that target instead of the .gifslide (what you want).

```<code>$(function() {
    var $gifSlide = $('.gifslide'),
        $loadGif = $('#load-gif-container'),
        $gifContent = $('.gif-content');

    $gifSlide.off('click').on('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        var $me = ($(event.target).is('.gifslide')) ? $(event.target): $(event.target).closest('.gifslide');
        $me.toggle();

        $loadGif.slideToggle(500);
        $gifContent.slideToggle(500);
    });
});
</code>```

Title: JQuery working Intermittently

Body:
I'm hoping I'm missing an obvious solution here. The below code only works intermittently. If you load with a cleared cache / incognito mode, then click on .gifslide twice before the page has finished loading - it breaks. Typing that I realize how specific this is but regardless, please help.

The offending code:

$(document).ready(function(){
    $(".gifslide").on('click', function () {
      $('.gifslide').toggle();
 // below is a workaround to make
 // it appear the the image is sliding upward and not down.
      $("#load-gif-container").slideToggle(500);
      $('.gif-content').slideToggle(500);
    });
  });

It's HTML sidekick:

&#9650
Expand

ya I'm programming in liquid but aside from that - what's the problem here?

UPDATE / EDIT:

When I said "it breaks" I should have said ".gif-content displays without performing the slideToggle. #load-gif container also doesn't toggle but .gifslide does". No errors displayed. It does look ridiculous but nothing in the console that would help.

I replied back to current comment on this question explaining what happened when I tried that.

I've also tried not triggering the function until the image inside of #gif-content loads. It didn't work but I have a feeling that this is where the problem is stemming from. It's a massive gif, above the fold, surrounded by other massive images. I'm not sure there is enough compressing / minimizing in the world to get all of these things to function smoothly on limited connections but I'm hoping that I'm wrong.

Body:
You have the click event binding after the document is ready. When reloading the page under normal circumstances, your script is cached and can therefore give you the functionality you are looking for. The reason you are running into this problem only in incognito mode or after you have cleared cache is because your script is not cached, and therefore not accessible. Your script is still loading, the page is not "ready", and so it is not able to pick up your clicks/doubleclicks ... while it is still loading.

There are a few other changes I would recommend as well that will give you better performance (obviously after the document is ready) and more consistent behavior:

// from
$(document).ready(function() {});

// to
$(function() {});

// these are equivalent and the latter is more terse

If you are ever in a situation where there is more than one .gifslide in a document, clicking on one of them will propagate that click event to all of them. Additionally, to clear the event queue of any other click events related to .gifslide, use .off() before .on(). You can resolve these issues like this:

$(function() {
    $('.gifslide').off('click').on('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        $(event.target).toggle();
    });
});

It is also recommended to cache your elements in a variable. In terms of performance, touching the DOM is very expensive. So...

$(function() {
    var $gifSlide = $('.gifslide'),
        $loadGif = $('#load-gif-container'),
        $gifContent = $('.gif-content');

    $gifSlide.off('click').on('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        $(event.target).toggle();

        $loadGif.slideToggle(500);
        $gifContent.slideToggle(500);
    });
});

Finally, because you have a span nested within .gifslide, if someone clicks on the span, you may end up handling the click event behavior on that target instead of the .gifslide (what you want).

$(function() {
    var $gifSlide = $('.gifslide'),
        $loadGif = $('#load-gif-container'),
        $gifContent = $('.gif-content');

    $gifSlide.off('click').on('click', function(event) {
        event.preventDefault();
        event.stopPropagation();
        var $me = ($(event.target).is('.gifslide')) ? $(event.target): $(event.target).closest('.gifslide');
        $me.toggle();

        $loadGif.slideToggle(500);
        $gifContent.slideToggle(500);
    });
});


问:
What is the easiest way to "detach/daemonize" a Bash script?
What I am trying to do is write a Bash script that sleeps for a set amount of time before using the mac say command to speak some text.

I'd like to be able to run the command and then close the terminal so it will still speak at the set time. I've looked into nohup, detach, launchd, and putting the process in the background, but all of these solutions still result in the process being terminated once the terminal is closed. Should I somehow make some sort of zombie child process to do this? What is the best solution? Thank you

```<code># Simple Example of main code
sleep 10;
say hello;
exit;
</code>```

答:
All the solution here are very good, but they don't provide an easy way to "look" what happen in the program without doing a redirection that would fill the hard drive.

Using screen you can then very easily run a script, close your terminal/ssh session, and then come back latter, and "attach" again to the script. Do do that it's pretty easy.

Install

First install screen:

```<code>sudo apt-get install screen
</code>```

Detach

and then put in your bash file

```<code>#!/usr/bin/env bash
screen -S myscreen -d -m bash -c 'ls; exec bash'
</code>```

(replace ls with your program) It will create (-S) a "screen" named myscreen, and detach it (-d) by running the commands inside the ``-c``` option. Then if you want to connect later to this screen:</p>

<h1>And attach later</h1>

```screen -rd myscreen
```

<p>if you want to list all screen currently running:</p>

```screen -ls
```

NB: if you want to close the screen when it's finished, remove the bash at the end of the command.

Body:
What I am trying to do is write a Bash script that sleeps for a set amount of time before using the mac say command to speak some text.

I'd like to be able to run the command and then close the terminal so it will still speak at the set time. I've looked into nohup, detach, launchd, and putting the process in the background, but all of these solutions still result in the process being terminated once the terminal is closed. Should I somehow make some sort of zombie child process to do this? What is the best solution? Thank you

# Simple Example of main code
sleep 10;
say hello;
exit;

Body:
All the solution here are very good, but they don't provide an easy way to "look" what happen in the program without doing a redirection that would fill the hard drive.

Using screen you can then very easily run a script, close your terminal/ssh session, and then come back latter, and "attach" again to the script. Do do that it's pretty easy.

Install

First install screen:

sudo apt-get install screen

Detach

and then put in your bash file

#!/usr/bin/env bash
screen -S myscreen -d -m bash -c 'ls; exec bash'

(replace ls with your program) It will create (-S) a "screen" named myscreen, and detach it (-d) by running the commands inside the ``-c``` option. Then if you want to connect later to this screen:

And attach later

screen -rd myscreen

if you want to list all screen currently running:

screen -ls

NB: if you want to close the screen when it's finished, remove the bash at the end of the command.


问:
How to use a Windows Shortcut in WAMP www directory?
I want to run PHP files in the browser that are stored on a separate partition from the www folder in the WAMP folder. I created a shortcut and put it in the www folder, but got 404 error when I tried to browse the file localhost/directory-name/index.html.

How do you set up shortcuts to other folders in the WAMP www folder on Windows XP?

OK, after doing some research, I found FollowSymLinks needs to be set in the Apache config file. It includes Options Indexes FollowSymLinks, but still 404 error.

答:
You can do this By using the CMD mklink function.

Like(LINKFOLDER MOST NOT EXIST, IT WILL BE CREATED):

```<code>mklink /J LINKFOLDER ORIGINALFOLDER
</code>```

OR include the path in quotes if it has spaces.

```<code>mklink /J "LINK FOLDER" "ORIGINAL FOLDER"
</code>```

Successful output will be:

```<code>Junction created for LINKFOLDER <<===>> ORIGINALFOLDER
</code>```

Body:
You can do this By using the CMD mklink function.

Like(LINKFOLDER MOST NOT EXIST, IT WILL BE CREATED):

mklink /J LINKFOLDER ORIGINALFOLDER

OR include the path in quotes if it has spaces.

mklink /J "LINK FOLDER" "ORIGINAL FOLDER"

Successful output will be:

Junction created for LINKFOLDER <<===>> ORIGINALFOLDER


问:
sending OSC between machines on a LAN using Node.js and OSC.js
Has anyone created a working setup where OSC is being sent between machines on a LAN using Node.js?  Ideally, using Colin Clark's osc.js package?

I have what I think should be a pretty simple example, except that it doesn't work - I get an EADDRNOTAVAIL error, which implies that the remote address isn't available.  I can ping the other laptop successfully, however.

Here's the code and the error, for reference:

Sending code (laptop at 192.168.0.5):

```<code>var osc = require("osc");

var udp = new osc.UDPPort({
    localAddress: "127.0.0.1", // shouldn't matter here
    localPort: 5000, // not receiving, but here's a port anyway
    remoteAddress: "192.168.0.7", // the other laptop
    remotePort: 9999 // the port to send to
});

udp.open();

udp.on("ready", function () {

    console.log("ready");
    setInterval(function () {
        udp.send({
            address: "/sending/every/second",
            args: [1, 2, 3]
        })
    }, 1000);
});
</code>```

Receive code (on laptop at 192.168.0.7):

```<code>var osc = require("osc");
var udp = new osc.UDPPort({
    localAddress: "192.168.0.7",
    localPort: 9999
});

udp.open();

udp.on("ready", function () {
    console.log("receiver is ready");
});

udp.on("message", function(message, timetag, info) {
   console.log(message);
});
</code>```

Here's the error I get when I run the sending code:

```<code>ready
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: send EADDRNOTAVAIL 192.168.0.7:9999
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at SendWrap.afterSend [as oncomplete] (dgram.js:345:11)
</code>```

答:
The issue is that the osc.UDPPort that you are using to send OSC messages has its localAddress bound to the loopback address, which is limited to connections within your local computer. As a result, your sender can't find your receiver.

The solution is to bind your sender's localAddress to an appropriate network interface. If your 192.168.0.5 IP address is stable and you don't need to worry about it changing when you connect your laptops to another network (say, for a gig or a gallery installation), then you can just use that. Otherwise, you might want to use an mDNS name ("foo.local") or the "all interfaces" address, 0.0.0.0.

This change to your "Sender code" worked for me when I tried it on my network:

```<code>var osc = require("osc");

var udp = new osc.UDPPort({
    localAddress: "0.0.0.0", // Totally does matter here :)
    localPort: 5000,
    remoteAddress: "192.168.0.7", // the other laptop
    remotePort: 9999 // the port to send to
});

udp.open();

udp.on("ready", function () {
    console.log("ready");
    setInterval(function () {
        udp.send({
            address: "/sending/every/second",
            args: [1, 2, 3]
        })
    }, 1000);
});
</code>```

As a side note, osc.js's behaviour does differ from a regular Node.js UDP socket, since if the local address is omitted Node will default to 0.0.0.0. An osc.UDPPort, however, will always bind to 127.0.0.1 if localAddress is omitted (which seemed a little safer to me when originally implementing osc.js, but I can see how it might be confusing).

This issue is also discussed on the osc.js issue tracker, and I will update the documentation to prevent the kind of confusion you encountered here. Best of luck with your project!

Body:
Has anyone created a working setup where OSC is being sent between machines on a LAN using Node.js?  Ideally, using Colin Clark's osc.js package?

I have what I think should be a pretty simple example, except that it doesn't work - I get an EADDRNOTAVAIL error, which implies that the remote address isn't available.  I can ping the other laptop successfully, however.

Here's the code and the error, for reference:

Sending code (laptop at 192.168.0.5):

var osc = require("osc");

var udp = new osc.UDPPort({
    localAddress: "127.0.0.1", // shouldn't matter here
    localPort: 5000, // not receiving, but here's a port anyway
    remoteAddress: "192.168.0.7", // the other laptop
    remotePort: 9999 // the port to send to
});

udp.open();

udp.on("ready", function () {

    console.log("ready");
    setInterval(function () {
        udp.send({
            address: "/sending/every/second",
            args: [1, 2, 3]
        })
    }, 1000);
});

Receive code (on laptop at 192.168.0.7):

var osc = require("osc");
var udp = new osc.UDPPort({
    localAddress: "192.168.0.7",
    localPort: 9999
});

udp.open();

udp.on("ready", function () {
    console.log("receiver is ready");
});

udp.on("message", function(message, timetag, info) {
   console.log(message);
});

Here's the error I get when I run the sending code:

ready
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: send EADDRNOTAVAIL 192.168.0.7:9999
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at SendWrap.afterSend [as oncomplete] (dgram.js:345:11)

Body:
The issue is that the osc.UDPPort that you are using to send OSC messages has its localAddress bound to the loopback address, which is limited to connections within your local computer. As a result, your sender can't find your receiver.

The solution is to bind your sender's localAddress to an appropriate network interface. If your 192.168.0.5 IP address is stable and you don't need to worry about it changing when you connect your laptops to another network (say, for a gig or a gallery installation), then you can just use that. Otherwise, you might want to use an mDNS name ("foo.local") or the "all interfaces" address, 0.0.0.0.

This change to your "Sender code" worked for me when I tried it on my network:

var osc = require("osc");

var udp = new osc.UDPPort({
    localAddress: "0.0.0.0", // Totally does matter here :)
    localPort: 5000,
    remoteAddress: "192.168.0.7", // the other laptop
    remotePort: 9999 // the port to send to
});

udp.open();

udp.on("ready", function () {
    console.log("ready");
    setInterval(function () {
        udp.send({
            address: "/sending/every/second",
            args: [1, 2, 3]
        })
    }, 1000);
});

As a side note, osc.js's behaviour does differ from a regular Node.js UDP socket, since if the local address is omitted Node will default to 0.0.0.0. An osc.UDPPort, however, will always bind to 127.0.0.1 if localAddress is omitted (which seemed a little safer to me when originally implementing osc.js, but I can see how it might be confusing).

This issue is also discussed on the osc.js issue tracker, and I will update the documentation to prevent the kind of confusion you encountered here. Best of luck with your project!


问:
How to check in an array if a value exists
I am building an javascript app with Backbone/Marionette (and Coffeescript) and I want to check if a value is contained within a textfield.

If I do this it does not work:

```<code>questions = $("input[name='questions']").val().split(',')
      if questions.indexOf(1) == -1
        @ui.check.removeClass("green")
      else
        @ui.check.addClass("green")
</code>```

If I do this it works (hard code the array):

```<code>questions = [1]
      if questions.indexOf(1) == -1
        @ui.check.removeClass("green")
      else
        @ui.check.addClass("green")
</code>```

What am I doing wrong?

答:
From the fine String.prototype.split manual:

Return value

An array of strings split at each point where the separator occurs in the given string.

and the fine Array.prototype.indexOf manual:

Description

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

So when you say this:

```<code>questions = $("input[name='questions']").val().split(',')
if questions.indexOf(1) == -1
  #...
</code>```

you're searching an array of strings (questions) for a number using strict equality. In JavaScript, 1 === '1' will never be true (unlike 1 == '1') so your search will fail to find anything. Your hard-coded example works because question is an array of numbers (not strings) there.

Either search for a string:

```<code>if questions.indexOf('1') == -1
</code>```

or convert your strings to numbers before searching:

```<code>questions = $("input[name='questions']").val().split(',').map (s) -> +s
if questions.indexOf(1) == -1
</code>```

Which approach you'd use depends on where the 1 comes from and what else you plan to do with questions.

Body:
I am building an javascript app with Backbone/Marionette (and Coffeescript) and I want to check if a value is contained within a textfield.

If I do this it does not work:

questions = $("input[name='questions']").val().split(',')
      if questions.indexOf(1) == -1
        @ui.check.removeClass("green")
      else
        @ui.check.addClass("green")

If I do this it works (hard code the array):

questions = [1]
      if questions.indexOf(1) == -1
        @ui.check.removeClass("green")
      else
        @ui.check.addClass("green")

What am I doing wrong?

Body:
From the fine String.prototype.split manual:

Return value

An array of strings split at each point where the separator occurs in the given string.

and the fine Array.prototype.indexOf manual:

Description

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

So when you say this:

questions = $("input[name='questions']").val().split(',')
if questions.indexOf(1) == -1
  #...

you're searching an array of strings (questions) for a number using strict equality. In JavaScript, 1 === '1' will never be true (unlike 1 == '1') so your search will fail to find anything. Your hard-coded example works because question is an array of numbers (not strings) there.

Either search for a string:

if questions.indexOf('1') == -1

or convert your strings to numbers before searching:

questions = $("input[name='questions']").val().split(',').map (s) -> +s
if questions.indexOf(1) == -1

Which approach you'd use depends on where the 1 comes from and what else you plan to do with questions.


问:
Can jQuery detect when user resizes browser?
I wrote simple code with jQuery that hides navbar when user scrolls the page. I works great, but now I want add one more thing.

I want it to work like it does now when user viewport width is more than 768px.
But when user viewport is smaller then 768px I want that navbar to be visible all the time.

The code should be smart enough, that it can detect browser was resized by user and it should still work.

To sum up:

User start my page with chrome viewport 1024px - when he scrolls page down navbar is hiding, when he goes back to the top of the page navbar is reappearing.

Then user resizes chrome and has viewport 700px - when he scrolls page down navbar should be always on.

Any smart ideas how to achieve it?

```<code>$(document).ready(function() {
  $(".navbar").show();
  $(function() {
    $(window).scroll(function() {
      if ($(this).scrollTop() > 300) {
        $(".navbar").fadeOut();
      } else {
        $(".navbar").fadeIn();
      }
    });
  });
});
</code>```

答:
It could be solve by using $(window).resize. Here is the full demo how it is done. Hope this answer yours.

$(document).ready(function() {
  $(function() {
    var winWidth = $(window).width();
    $(window).resize(function() {
      winWidth = $(window).width();
    });
    $(window).scroll(function() {
      if (winWidth <= 700) {
        $(".navbar").css({
          position: "fixed",
          width: "100%"
        });
        $("p").css("margin-top","60px");
      } else {
        if ($(this).scrollTop() > 300) {
          $(".navbar").fadeOut();
        } else {
          $(".navbar").fadeIn();
        }
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
        Brand
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li class="active">Home <span class="sr-only">(current)</span></li>
          <li>About Us</li>
          <li>Contact</li>
        </ul>
      </div>
      <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
  </nav>
  <div class="container-fluid">
    <p>
    The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur adipiscing 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."
    Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
    architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia
    dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
    ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" 1914 translation by H. Rackham "But I must explain to
    you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one
    rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires
    to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain
    some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
  </p>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html></code>```

Body:
I wrote simple code with jQuery that hides navbar when user scrolls the page. I works great, but now I want add one more thing.

I want it to work like it does now when user viewport width is more than 768px.
But when user viewport is smaller then 768px I want that navbar to be visible all the time.

The code should be smart enough, that it can detect browser was resized by user and it should still work.

To sum up:

User start my page with chrome viewport 1024px - when he scrolls page down navbar is hiding, when he goes back to the top of the page navbar is reappearing.

Then user resizes chrome and has viewport 700px - when he scrolls page down navbar should be always on.

Any smart ideas how to achieve it?

$(document).ready(function() {
  $(".navbar").show();
  $(function() {
    $(window).scroll(function() {
      if ($(this).scrollTop() > 300) {
        $(".navbar").fadeOut();
      } else {
        $(".navbar").fadeIn();
      }
    });
  });
});

Body:
It could be solve by using $(window).resize. Here is the full demo how it is done. Hope this answer yours.

$(document).ready(function() {
  $(function() {
    var winWidth = $(window).width();
    $(window).resize(function() {
      winWidth = $(window).width();
    });
    $(window).scroll(function() {
      if (winWidth <= 700) {
        $(".navbar").css({
          position: "fixed",
          width: "100%"
        });
        $("p").css("margin-top","60px");
      } else {
        if ($(this).scrollTop() > 300) {
          $(".navbar").fadeOut();
        } else {
          $(".navbar").fadeIn();
        }
      }
    });
  });
});

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>
  <nav class="navbar navbar-default">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
        <a class="navbar-brand" href="#">Brand</a>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home <span class="sr-only">(current)</span></a></li>
          <li><a href="#">About Us</a></li>
          <li><a href="#">Contact</a></li>
        </ul>
      </div>
      <!-- /.navbar-collapse -->
    </div>
    <!-- /.container-fluid -->
  </nav>
  <div class="container-fluid">
    <p>
    The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur adipiscing 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."
    Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
    architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia
    dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
    ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?" 1914 translation by H. Rackham "But I must explain to
    you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one
    rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires
    to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain
    some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
  </p>
  </div>
  <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>


问:
Class 'mPDF' not found - kartik gridview
i'm using kartik gridview for export to pdf, and i need help to resolve this problem.

When I export to pdf yii2 return:
"PHP Fatal Error"

"Class 'mPDF' not found"

```<code>public function setApi()
{
    $this->_mpdf = new mPDF(
        $this->mode,
        $this->format,
        $this->defaultFontSize,
        $this->defaultFont,
        $this->marginLeft,
        $this->marginRight,
        $this->marginTop,
        $this->marginBottom,
        $this->marginHeader,
</code>```

Gridview options:

```<code>'exportConfig' => [
            GridView::PDF => [
                'config' => [
                    'contentBefore' => '<b> XXX - YYYY </b>',
                    'contentAfter'  => '<a href="#">Test</a>',
                ],
            ],
</code>```

Installed components: vendor/mpdf/mpdf and vendor/kartik-v/yii2-mpdf.

Could someone help me solve this? Sorry for my English.

答:
kartik-v/yii2-mpdf requires mpdf/mpdf
try
    composer require mpdf/mpdf "*"
after or before installing kartik-v/yii2-mpdf

Body:
i'm using kartik gridview for export to pdf, and i need help to resolve this problem.

When I export to pdf yii2 return:
"PHP Fatal Error"

"Class 'mPDF' not found"

public function setApi()
{
    $this->_mpdf = new mPDF(
        $this->mode,
        $this->format,
        $this->defaultFontSize,
        $this->defaultFont,
        $this->marginLeft,
        $this->marginRight,
        $this->marginTop,
        $this->marginBottom,
        $this->marginHeader,

Gridview options:

'exportConfig' => [
            GridView::PDF => [
                'config' => [
                    'contentBefore' => ' XXX - YYYY ',
                    'contentAfter'  => 'Test',
                ],
            ],

Installed components: vendor/mpdf/mpdf and vendor/kartik-v/yii2-mpdf.

Could someone help me solve this? Sorry for my English.


问:
string operator and valgrind
I having some problem with correctly write method:
Edited i wrote new probably good

```<code>void operator += ( const string& s )
{
    size_t newLen = len + s.len;
    char    *tmpStr = new char [newLen+1];
    size_t i = 0;
    for(i;i<len;i++)
        {tmpStr[i] = p[i];}
    for(size_t j=0;j<s.len;j++)
    {
    tmpStr[i] = s[j];
    i++;
    }
    delete []p;
    p = tmpStr;
    len = newLen;
    p[len] = '\0';
}
</code>```

Valgrind return me, i got some error and 1 memory leak

```<code>HEAP SUMMARY:
==10152==     in use at exit: 72,704 bytes in 1 blocks
==10152==   total heap usage: 5 allocs, 4 frees, 73,747 bytes
allocated

==10152== LEAK SUMMARY:
==10152==    definitely lost: 0 bytes in 0 blocks
==10152==    indirectly lost: 0 bytes in 0 blocks
==10152==      possibly lost: 0 bytes in 0 blocks
==10152==    still reachable: 72,704 bytes in 1 blocks
==10152==         suppressed: 0 bytes in 0 blocks
==10152== Reachable blocks (those to which a pointer was found) are
not shown.
==10152== To see them, rerun with: --leak-check=full --show-leak-
kinds=all

==10152== For counts of detected and suppressed errors, rerun with: -v
==10152== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

I tried it for:

```<code>string s2 = "hello";
string s3 = "abc";
s3 += s2;
</code>```

And my next question is how write, any idea what i have to do?

```<code>void operator += ( char c );
</code>```

Here you are my constructor:

```<code>string( )
  : len{0},
    p{ nullptr }
{ }

string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s[i];
}

string( const string& s )
  : len{ s. len },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s.p[i];
}
</code>```

Its correct: Leak memory still reachable: 72,704 bytes in 1 blocks

答:
The constructor isn't putting a trailing null byte in the p array, which is needed for any strXXX() functions. You need to add 1 to the len when allocating the array. Then use strcpy() to initialize the p array, which will copy all the characters and the null byte.

```<code>string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len+1 ] }
{
  strcpy(p, s);
}

string( const string& s )
  : len{ s. len },
    p{ new char[ len + 1 ] }
{
  strcpy(p, s.p);
}
</code>```

Also, the += function needs to check if p == nullptr, and not call strcpy() in that case.

```<code>void operator += ( const string& s )
{
    size_t newLen = len + s.len;
    if (newLen == 0) { // Appending empty string to empty string, nothing to do
        return;
    }
    char *tmpStr = new char [newLen+1];
    if (p) {
        strcpy(tmpStr, p);
    }
    if (s.p) {
        strcpy(tmpStr + len, s.p);
    }
    delete []p;
    p = tmpStr;
    len = newLen;
}
</code>```

Title: string operator and valgrind

Body:
I having some problem with correctly write method:
Edited i wrote new probably good

void operator += ( const string& s )
{
    size_t newLen = len + s.len;
    char    *tmpStr = new char [newLen+1];
    size_t i = 0;
    for(i;i<len;i++)
        {tmpStr[i] = p[i];}
    for(size_t j=0;j<s.len;j++)
    {
    tmpStr[i] = s[j];
    i++;
    }
    delete []p;
    p = tmpStr;
    len = newLen;
    p[len] = '\0';
}

Valgrind return me, i got some error and 1 memory leak

HEAP SUMMARY:
==10152==     in use at exit: 72,704 bytes in 1 blocks
==10152==   total heap usage: 5 allocs, 4 frees, 73,747 bytes
allocated

==10152== LEAK SUMMARY:
==10152==    definitely lost: 0 bytes in 0 blocks
==10152==    indirectly lost: 0 bytes in 0 blocks
==10152==      possibly lost: 0 bytes in 0 blocks
==10152==    still reachable: 72,704 bytes in 1 blocks
==10152==         suppressed: 0 bytes in 0 blocks
==10152== Reachable blocks (those to which a pointer was found) are
not shown.
==10152== To see them, rerun with: --leak-check=full --show-leak-
kinds=all

==10152== For counts of detected and suppressed errors, rerun with: -v
==10152== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

I tried it for:

string s2 = "hello";
string s3 = "abc";
s3 += s2;

And my next question is how write, any idea what i have to do?

void operator += ( char c );

Here you are my constructor:

string( )
  : len{0},
    p{ nullptr }
{ }

string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s[i];
}

string( const string& s )
  : len{ s. len },
    p{ new char[ len ] }
{
  for( size_t i = 0; i < len; ++ i )
     p[i] = s.p[i];
}

Its correct: Leak memory still reachable: 72,704 bytes in 1 blocks

Body:
The constructor isn't putting a trailing null byte in the p array, which is needed for any strXXX() functions. You need to add 1 to the len when allocating the array. Then use strcpy() to initialize the p array, which will copy all the characters and the null byte.

string( const char* s )
  : len{ strlen(s) },
    p{ new char[ len+1 ] }
{
  strcpy(p, s);
}

string( const string& s )
  : len{ s. len },
    p{ new char[ len + 1 ] }
{
  strcpy(p, s.p);
}

Also, the += function needs to check if p == nullptr, and not call strcpy() in that case.

void operator += ( const string& s )
{
    size_t newLen = len + s.len;
    if (newLen == 0) { // Appending empty string to empty string, nothing to do
        return;
    }
    char *tmpStr = new char [newLen+1];
    if (p) {
        strcpy(tmpStr, p);
    }
    if (s.p) {
        strcpy(tmpStr + len, s.p);
    }
    delete []p;
    p = tmpStr;
    len = newLen;
}


问:
Firebase firebase-web.js missing
I installed angular firebase using node.js however the firebase-web.js file is missing. I have searched for this file and cannot find it. Does anyone know a solution?</p>

答: After that, you can see the firebase-web.js file.

Title: Firebase firebase-web.js missing


问:
What's a good quick-for-users wiki/cms?
What's a good wiki/cms system that's super easy for users?  I'm building an info directory website for public use.  I need a system that makes it quick and easy for users to add pages and modify content.  Remember how craigslist was back in the day (you didn't have to create an account to post)?  Like that!

I've looked at http://www.wikimatrix.org/ but was overwhelmed with options and didn't give opinions and reviews on them.  Hopefully somebody here can help me out!

答: We've used Dokuwiki and found it to be pretty good.</p>

ContentLicense: CC BY-SA 2.5

Title: What's a good quick-for-users wiki/cms?


问:
Why does Spark report "java.net.URISyntaxException: Relative path in absolute URI" when working with DataFrames?
I am running Spark locally on a Windows machine. I was able to launch the spark shell successfully and also read in text files as RDDs. I was also able to follow along the various online tutorials on this subject and was able to perform various operations on the RDDs.

However, when I try to convert an RDD into a DataFrame I am getting an error. This is what I am doing:

```<code>val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._

//convert rdd to df
val df = rddFile.toDF()
</code>```

This code generates a long series of error messages that seem to relate to the following one:

```<code>Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at org.apache.hadoop.fs.Path.initialize(Path.java:205)
        at org.apache.hadoop.fs.Path.<init>(Path.java:171)
        at org.apache.hadoop.hive.metastore.Warehouse.getWhRoot(Warehouse.java:159)
        at org.apache.hadoop.hive.metastore.Warehouse.getDefaultDatabasePath(Warehouse.java:177)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB_core(HiveMetaStore.java:600)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
        at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
        at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
        ... 85 more
Caused by: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at java.net.URI.checkPath(URI.java:1823)
        at java.net.URI.<init>(URI.java:745)
        at org.apache.hadoop.fs.Path.initialize(Path.java:202)
        ... 96 more
</code>```

The entire stack trace follows.

```<code>16/08/16 12:36:20 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
16/08/16 12:36:20 WARN Hive: Failed to access metastore. This class should not accessed in runtime.
org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
        at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1236)
        at org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions(Hive.java:174)
        at org.apache.hadoop.hive.ql.metadata.Hive.<clinit>(Hive.java:166)
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:503)
        at org.apache.spark.sql.hive.client.HiveClientImpl.<init>(HiveClientImpl.scala:171)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.spark.sql.hive.client.IsolatedClientLoader.createClient(IsolatedClientLoader.scala:258)
        at org.apache.spark.sql.hive.HiveUtils$.newClientForMetadata(HiveUtils.scala:359)
        at org.apache.spark.sql.hive.HiveUtils$.newClientForMetadata(HiveUtils.scala:263)
        at org.apache.spark.sql.hive.HiveSharedState.metadataHive$lzycompute(HiveSharedState.scala:39)
        at org.apache.spark.sql.hive.HiveSharedState.metadataHive(HiveSharedState.scala:38)
        at org.apache.spark.sql.hive.HiveSharedState.externalCatalog$lzycompute(HiveSharedState.scala:46)
        at org.apache.spark.sql.hive.HiveSharedState.externalCatalog(HiveSharedState.scala:45)
        at org.apache.spark.sql.hive.HiveSessionState.catalog$lzycompute(HiveSessionState.scala:50)
        at org.apache.spark.sql.hive.HiveSessionState.catalog(HiveSessionState.scala:48)
        at org.apache.spark.sql.hive.HiveSessionState$$anon$1.<init>(HiveSessionState.scala:63)
        at org.apache.spark.sql.hive.HiveSessionState.analyzer$lzycompute(HiveSessionState.scala:63)
        at org.apache.spark.sql.hive.HiveSessionState.analyzer(HiveSessionState.scala:62)
        at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:49)
        at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:64)
        at org.apache.spark.sql.SparkSession.baseRelationToDataFrame(SparkSession.scala:382)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:143)
        at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:401)
        at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:342)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:24)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:29)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:31)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw.<init>(<console>:33)
        at $line14.$read$$iw$$iw$$iw$$iw.<init>(<console>:35)
        at $line14.$read$$iw$$iw$$iw.<init>(<console>:37)
        at $line14.$read$$iw$$iw.<init>(<console>:39)
        at $line14.$read$$iw.<init>(<console>:41)
        at $line14.$read.<init>(<console>:43)
        at $line14.$read$.<init>(<console>:47)
        at $line14.$read$.<clinit>(<console>)
        at $line14.$eval$.$print$lzycompute(<console>:7)
        at $line14.$eval$.$print(<console>:6)
        at $line14.$eval.$print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:786)
        at scala.tools.nsc.interpreter.IMain$Request.loadAndRun(IMain.scala:1047)
        at scala.tools.nsc.interpreter.IMain$WrappedRequest$$anonfun$loadAndRunReq$1.apply(IMain.scala:638)
        at scala.tools.nsc.interpreter.IMain$WrappedRequest$$anonfun$loadAndRunReq$1.apply(IMain.scala:637)
        at scala.reflect.internal.util.ScalaClassLoader$class.asContext(ScalaClassLoader.scala:31)
        at scala.reflect.internal.util.AbstractFileClassLoader.asContext(AbstractFileClassLoader.scala:19)
        at scala.tools.nsc.interpreter.IMain$WrappedRequest.loadAndRunReq(IMain.scala:637)
        at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:569)
        at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:565)
        at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:807)
        at scala.tools.nsc.interpreter.ILoop.command(ILoop.scala:681)
        at scala.tools.nsc.interpreter.ILoop.processLine(ILoop.scala:395)
        at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:415)
        at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:923)
        at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:909)
        at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:909)
        at scala.reflect.internal.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:97)
        at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:909)
        at org.apache.spark.repl.Main$.doMain(Main.scala:68)
        at org.apache.spark.repl.Main$.main(Main.scala:51)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
        at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1523)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:86)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:132)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:104)
        at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3005)
        at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3024)
        at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1234)
        ... 74 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1521)
        ... 80 more
Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at org.apache.hadoop.fs.Path.initialize(Path.java:205)
        at org.apache.hadoop.fs.Path.<init>(Path.java:171)
        at org.apache.hadoop.hive.metastore.Warehouse.getWhRoot(Warehouse.java:159)
        at org.apache.hadoop.hive.metastore.Warehouse.getDefaultDatabasePath(Warehouse.java:177)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB_core(HiveMetaStore.java:600)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
        at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
        at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
        ... 85 more
Caused by: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at java.net.URI.checkPath(URI.java:1823)
        at java.net.URI.<init>(URI.java:745)
        at org.apache.hadoop.fs.Path.initialize(Path.java:202)
        ... 96 more
</code>```

答:
I set spark.sql.warehouse.dir property to fix the error in my existing code

```<code>System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");
</code>```

Here is the code snippet

```<code>System.setProperty("hadoop.home.dir", "c:/winutil/");
System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");
val conf = new SparkConf().setAppName("test").setMaster("local[*]")
val sc = new SparkContext(conf)
val lines = sc.textFile("C:/user.txt")
</code>```

Body:
I am running Spark locally on a Windows machine. I was able to launch the spark shell successfully and also read in text files as RDDs. I was also able to follow along the various online tutorials on this subject and was able to perform various operations on the RDDs.

However, when I try to convert an RDD into a DataFrame I am getting an error. This is what I am doing:

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._

//convert rdd to df
val df = rddFile.toDF()

This code generates a long series of error messages that seem to relate to the following one:

Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at org.apache.hadoop.fs.Path.initialize(Path.java:205)
        at org.apache.hadoop.fs.Path.<init>(Path.java:171)
        at org.apache.hadoop.hive.metastore.Warehouse.getWhRoot(Warehouse.java:159)
        at org.apache.hadoop.hive.metastore.Warehouse.getDefaultDatabasePath(Warehouse.java:177)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB_core(HiveMetaStore.java:600)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
        at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
        at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
        ... 85 more
Caused by: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at java.net.URI.checkPath(URI.java:1823)
        at java.net.URI.<init>(URI.java:745)
        at org.apache.hadoop.fs.Path.initialize(Path.java:202)
        ... 96 more

The entire stack trace follows.

16/08/16 12:36:20 WARN ObjectStore: Failed to get database default, returning NoSuchObjectException
16/08/16 12:36:20 WARN Hive: Failed to access metastore. This class should not accessed in runtime.
org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
        at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1236)
        at org.apache.hadoop.hive.ql.metadata.Hive.reloadFunctions(Hive.java:174)
        at org.apache.hadoop.hive.ql.metadata.Hive.<clinit>(Hive.java:166)
        at org.apache.hadoop.hive.ql.session.SessionState.start(SessionState.java:503)
        at org.apache.spark.sql.hive.client.HiveClientImpl.<init>(HiveClientImpl.scala:171)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.spark.sql.hive.client.IsolatedClientLoader.createClient(IsolatedClientLoader.scala:258)
        at org.apache.spark.sql.hive.HiveUtils$.newClientForMetadata(HiveUtils.scala:359)
        at org.apache.spark.sql.hive.HiveUtils$.newClientForMetadata(HiveUtils.scala:263)
        at org.apache.spark.sql.hive.HiveSharedState.metadataHive$lzycompute(HiveSharedState.scala:39)
        at org.apache.spark.sql.hive.HiveSharedState.metadataHive(HiveSharedState.scala:38)
        at org.apache.spark.sql.hive.HiveSharedState.externalCatalog$lzycompute(HiveSharedState.scala:46)
        at org.apache.spark.sql.hive.HiveSharedState.externalCatalog(HiveSharedState.scala:45)
        at org.apache.spark.sql.hive.HiveSessionState.catalog$lzycompute(HiveSessionState.scala:50)
        at org.apache.spark.sql.hive.HiveSessionState.catalog(HiveSessionState.scala:48)
        at org.apache.spark.sql.hive.HiveSessionState$$anon$1.<init>(HiveSessionState.scala:63)
        at org.apache.spark.sql.hive.HiveSessionState.analyzer$lzycompute(HiveSessionState.scala:63)
        at org.apache.spark.sql.hive.HiveSessionState.analyzer(HiveSessionState.scala:62)
        at org.apache.spark.sql.execution.QueryExecution.assertAnalyzed(QueryExecution.scala:49)
        at org.apache.spark.sql.Dataset$.ofRows(Dataset.scala:64)
        at org.apache.spark.sql.SparkSession.baseRelationToDataFrame(SparkSession.scala:382)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:143)
        at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:401)
        at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:342)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:24)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:29)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw$$iw.<init>(<console>:31)
        at $line14.$read$$iw$$iw$$iw$$iw$$iw.<init>(<console>:33)
        at $line14.$read$$iw$$iw$$iw$$iw.<init>(<console>:35)
        at $line14.$read$$iw$$iw$$iw.<init>(<console>:37)
        at $line14.$read$$iw$$iw.<init>(<console>:39)
        at $line14.$read$$iw.<init>(<console>:41)
        at $line14.$read.<init>(<console>:43)
        at $line14.$read$.<init>(<console>:47)
        at $line14.$read$.<clinit>(<console>)
        at $line14.$eval$.$print$lzycompute(<console>:7)
        at $line14.$eval$.$print(<console>:6)
        at $line14.$eval.$print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:786)
        at scala.tools.nsc.interpreter.IMain$Request.loadAndRun(IMain.scala:1047)
        at scala.tools.nsc.interpreter.IMain$WrappedRequest$$anonfun$loadAndRunReq$1.apply(IMain.scala:638)
        at scala.tools.nsc.interpreter.IMain$WrappedRequest$$anonfun$loadAndRunReq$1.apply(IMain.scala:637)
        at scala.reflect.internal.util.ScalaClassLoader$class.asContext(ScalaClassLoader.scala:31)
        at scala.reflect.internal.util.AbstractFileClassLoader.asContext(AbstractFileClassLoader.scala:19)
        at scala.tools.nsc.interpreter.IMain$WrappedRequest.loadAndRunReq(IMain.scala:637)
        at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:569)
        at scala.tools.nsc.interpreter.IMain.interpret(IMain.scala:565)
        at scala.tools.nsc.interpreter.ILoop.interpretStartingWith(ILoop.scala:807)
        at scala.tools.nsc.interpreter.ILoop.command(ILoop.scala:681)
        at scala.tools.nsc.interpreter.ILoop.processLine(ILoop.scala:395)
        at scala.tools.nsc.interpreter.ILoop.loop(ILoop.scala:415)
        at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply$mcZ$sp(ILoop.scala:923)
        at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:909)
        at scala.tools.nsc.interpreter.ILoop$$anonfun$process$1.apply(ILoop.scala:909)
        at scala.reflect.internal.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:97)
        at scala.tools.nsc.interpreter.ILoop.process(ILoop.scala:909)
        at org.apache.spark.repl.Main$.doMain(Main.scala:68)
        at org.apache.spark.repl.Main$.main(Main.scala:51)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:729)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:185)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:210)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:124)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
        at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1523)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.<init>(RetryingMetaStoreClient.java:86)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:132)
        at org.apache.hadoop.hive.metastore.RetryingMetaStoreClient.getProxy(RetryingMetaStoreClient.java:104)
        at org.apache.hadoop.hive.ql.metadata.Hive.createMetaStoreClient(Hive.java:3005)
        at org.apache.hadoop.hive.ql.metadata.Hive.getMSC(Hive.java:3024)
        at org.apache.hadoop.hive.ql.metadata.Hive.getAllDatabases(Hive.java:1234)
        ... 74 more
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.apache.hadoop.hive.metastore.MetaStoreUtils.newInstance(MetaStoreUtils.java:1521)
        ... 80 more
Caused by: java.lang.IllegalArgumentException: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at org.apache.hadoop.fs.Path.initialize(Path.java:205)
        at org.apache.hadoop.fs.Path.<init>(Path.java:171)
        at org.apache.hadoop.hive.metastore.Warehouse.getWhRoot(Warehouse.java:159)
        at org.apache.hadoop.hive.metastore.Warehouse.getDefaultDatabasePath(Warehouse.java:177)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB_core(HiveMetaStore.java:600)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.createDefaultDB(HiveMetaStore.java:620)
        at org.apache.hadoop.hive.metastore.HiveMetaStore$HMSHandler.init(HiveMetaStore.java:461)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.<init>(RetryingHMSHandler.java:66)
        at org.apache.hadoop.hive.metastore.RetryingHMSHandler.getProxy(RetryingHMSHandler.java:72)
        at org.apache.hadoop.hive.metastore.HiveMetaStore.newRetryingHMSHandler(HiveMetaStore.java:5762)
        at org.apache.hadoop.hive.metastore.HiveMetaStoreClient.<init>(HiveMetaStoreClient.java:199)
        at org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient.<init>(SessionHiveMetaStoreClient.java:74)
        ... 85 more
Caused by: java.net.URISyntaxException: Relative path in absolute URI: file:C:/Users/spark/spark-warehouse
        at java.net.URI.checkPath(URI.java:1823)
        at java.net.URI.<init>(URI.java:745)
        at org.apache.hadoop.fs.Path.initialize(Path.java:202)
        ... 96 more

Body:
I set spark.sql.warehouse.dir property to fix the error in my existing code

System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");

Here is the code snippet

System.setProperty("hadoop.home.dir", "c:/winutil/");
System.setProperty("spark.sql.warehouse.dir", "file:///C:/spark-warehouse");
val conf = new SparkConf().setAppName("test").setMaster("local[*]")
val sc = new SparkContext(conf)
val lines = sc.textFile("C:/user.txt")