text:
Q: How to delete a ToDo Item onClick in React? I'm doing a simple todo app with React, just to practise. How can I delete a list item, when clicking on it?
Here is my todos.js
export default class Todos extends Component {
    constructor(props) {
        super(props);
        this.state = { todos: [], text: '' };
    }

    addTodo(e) {
        e.preventDefault();
        this.setState({ todos: [ this.state.text, ...this.state.todos ] });
        this.setState({ text: ''});
    }

    updateValue(e) {
        this.setState({ text: [e.target.value]})
    }

    render() {
        return(

                <form onSubmit = {(e) => this.addTodo(e)}>
                    <input
                        placeholder="Add Todo"
                        value={this.state.text}
                        onChange={(e) => {this.updateValue(e)}}
                    />
                    <button type="submit">Add Todo</button>
                </form>
                <TodoList todos={this.state.todos}/>

        );
    }
}

And here is the TodoList.js, where I'm trying to remove a list item from.
import React, { Component } from 'react';
import { connect } from 'react-redux';

export default class TodoList extends Component {
    removeItem(e) {
        // splice this.props.todos??
    }
    render() {
        return(

                { this.props.todos.map((todo) => {
                    return
 { this.removeItem(e)}} key={todo}>{ todo }

                })}

        );
    }
}

A: You have called setState two times in the addTodo function. You can set todos and text in a single setState function like this:
addTodo(e) {
    e.preventDefault();
    this.setState({ todos: [ this.state.text, ...this.state.todos ], text: '' });
}

Do not write removeItem function in TodoList Component as it is purely working on props. Pass a removeItem function from Todos to it and remove that item in Todos's removeItem function like this:
import React, {Component} from 'react'
export default class Todos extends Component {
  constructor(props) {
    super(props);
    this.state = { todos: [], text: '' };
    this.removeItem = this.removeItem.bind(this)
  }

  addTodo(e) {
    e.preventDefault();
    this.setState({ todos: [ this.state.text, ...this.state.todos ], text: '' });
  }

  updateValue(e) {
    this.setState({ text: [e.target.value]})
  }
  removeItem(index) {
    const todos = this.state.todos.filter((todo, todoIndex) => {
      return todoIndex !== index
    })
    this.setState({ todos })
  }
  render() {
    return(

        <form onSubmit = {(e) => this.addTodo(e)}>
          <input
            placeholder="Add Todo"
            value={this.state.text}
            onChange={(e) => {this.updateValue(e)}}
            />
          <button type="submit">Add Todo</button>
        </form>
        <TodoList todos={this.state.todos} removeItem={this.removeItem} />

    );
  }
}

class TodoList extends Component {
  render() {
    return(

        { this.props.todos.map((todo, index) => {
          return
 { this.props.removeItem(index)}} key={todo}>{ todo }

        })}

    );
  }
}

Hope, it helps.

A: To delete the todo items, first pass a function from parent component:
<TodoList todos={this.state.todos} removeTodo={this.removeTodo}/>

Bind this function in the constructor:
this.removeTodo = this.removeTodo.bind(this);

Define this function in parent component, it will delete that item from state variable:
removeTodo(name){
    this.setState({
        todo: this.state.todo.filter(el => el !== name)
    })
}

Then inside child component call this method to delete todo:
export default class TodoList extends Component {
    removeItem(e) {
        this.props.removeTodo(item);
    }
    render() {
        return(

                { this.props.todos.map((todo) => {
                    return
 { this.removeItem(todo)}} key={todo}>{ todo }

                })}

        );
    }
}

Suggestion:
Don't call setState multiple time within a function if you want to set multiple state values then write it like this:
this.setState({
    a: value1,
    b: value2,
    c: value3
})

Working example:

class Todos extends React.Component {
    constructor(props) {
        super(props);
        this.state = { todos: [], text: '' };
        this.removeTodo = this.removeTodo.bind(this);
    }

    addTodo(e) {
        e.preventDefault();
        this.setState({
         todos: [ this.state.text, ...this.state.todos ],
         text: ''
        });
    }

    removeTodo(name, i){
        let todos = this.state.todos.slice();
        todos.splice(i, 1);
        this.setState({
            todos
        });
    }

    updateValue(e) {
        this.setState({ text: e.target.value})
    }

    render() {
        return(

                <form onSubmit = {(e) => this.addTodo(e)}>
                    <input
                        placeholder="Add Todo"
                        value={this.state.text}
                        onChange={(e) => {this.updateValue(e)}}
                    />
                    <button type="submit">Add Todo</button>
                </form>
                <TodoList todos={this.state.todos} removeTodo={this.removeTodo}/>

        );
    }
}

class TodoList extends React.Component {

    removeItem(item, i) {
        this.props.removeTodo(item, i);
    }

    render() {
        return(

                { this.props.todos.map((todo,i) => {
                    return
 { this.removeItem(todo, i)}} key={i}>{ todo }

                })}

        );
    }
}

ReactDOM.render(<Todos/>, document.getElementById('app'))

Update:
This is for @whs.bsmith doubt, the code that i suggested will work properly in the case where user will add the unique items in the todo list, if he will try to add the same item it will not reflect in ui because OP is using the todo items name as the key and key should be unique.
To solve that issue:
In working snippet i used indexes in place of todo items name for key, that will work properly and it will allow the user to add same item multiple times and on deletion, it will delete only that specific item not all the item having that same name, But it's not a good idea to use indexes as the key.

A: class TodoList extend React.Component{
    constructor(props){
        super(props);
        this.state = {
            todos: [],
            todo: ''
        }
        this.changeTodo = this.changeTodo.bind(this);
        this.addTodo = this.addTodo.bind(this);
        this.removeTodo = this.removeTodo.bind(this);
    }

    changeTodo(event){
        this.setState({
            todo: event.target.value
        })
    }

    addTodo(){
        let { todo, todos } = this.state;
        this.setState({
            todo: '',
            todos: [...todos, todo]
        })
    }

    removeTodo(index){
        let { todos } = this.state;
        todos.splice(index, 1);
        this.setState({
            todos: todos
        })
    }

    render(){
        let { todo, todos } = this.state;
        return

            <input value={todo} onChange={this.changeTodo}/>
            <button onClick={this.addTodo}>Add Todo</button>
            {
                todos.map((todo, index)=>{
                    return
{todo}

                })
            }

    }
}

This is a small example for TodoList. Go through this code to understand remove todo in your TodoList app.

A: Only thing to do is to move todos to state in TodoList and pass the index of the current todo in to the removeItem method. Then splice it as you suggested.
In TodoList:
constructor(props) {
    super(props);

    this.state = { todos: props.todos };
}

removeItem(index) {
    this.setState({
        todos: this.state.todos.filter((_, i) => i !== index)
    });
}

render() {
    return(

            { this.state.todos.map((todo, index) => {
                return
 { this.removeItem(index)}} key={todo}>{ todo }

            })}

    );
}

Remove item courtesy of Removing element from array in component state

A: First, you would want the removeItem method to exist in the Todos class, since that is where that
state is stored.  Then, you can either use filter or slice
export default class Todos extends Component {
    constructor(props) {
        super(props);
        this.state = { todos: [], text: '' };
    }

    addTodo(e) {
        e.preventDefault();
        this.setState({ todos: [ this.state.text, ...this.state.todos ] });
        this.setState({ text: ''});
    }

    updateValue(e) {
        this.setState({ text: [e.target.value]})
    }

    removeItem = index => {
        //either use filter
        const { todos } = this.state;
        const newTodos = todos.filter((todo, i) => i !== index);
        this.setState({ todos: newTodos});

        //or use slice
        const slicedNewTodos = todos.slice(0, index).concat(todos.slice(index + 1));
        this.setState({ todos: slicedNewTodos});
    }

    render() {
        return(

                <form onSubmit = {(e) => this.addTodo(e)}>
                    <input
                        placeholder="Add Todo"
                        value={this.state.text}
                        onChange={(e) => {this.updateValue(e)}}
                    />
                    <button type="submit">Add Todo</button>
                </form>
                <TodoList removeItem={this.removeItem} todos={this.state.todos}/>

        );
    }
}

import React, { Component } from 'react';
import { connect } from 'react-redux';

class TodoList extends Component {
    render() {
        return(

                { this.props.todos.map((todo, index) => {
                    return
 this.props.removeItem(index)} key={todo}>{ todo }

                })}

        );
    }
}

A: Everyone has given a good big picture overview.
I find this to be a good way to delete the todo from the todolist

todolist.splice(index, 1);

Splice removes 1 element from the startIndex of index (in the todolist array)

A: We can set a flag for the todo data and on initializing that data we can set the flag as true and when we delete the todo list we can set the flag as false. Please refer the below code.
const TodoComponent = ({ dataArray }) => {

  const [todos, setTodos] = useState(dataArray)

  // initial loading of todo items.
  useEffect(() =>{
    if (dataArray.length) {
      dataArray.forEach(todo =>{
        todo.show = true
      })
      setTodos(dataArray)
    }
  }, [dataArray])

 // Close the todo Item.
  const closeTodoItem = (todo, index) =>{
    todo.show = false
    todos[index] = todo
    setTodos([...todos])
  }

  return (
    todos.filter(todo => todo.show === true).length >0  &&
    (
      <Col span={24} className={style.todoBg} style={compStyle}>
        {todos.map((todo,index) => (
          (todo.show && (
            <Col span={24} className={style.todo}>
              <Col className={style.todoInner}>

 {todo.content}

              </Col>
              <Icon onClick={() => closeTodoItem(todo, index)} className={style.close}>close</Icon>
            </Col>
          ))
        ))}
      </Col>
    )
  )}

The above approach worked for me.


text:
Q: drill not showing hive or hbase tables I've created both a hbase and hive table to store some data logging information.  I can query both hbase and hive from the command line no prob.
hbase:  scan MVLogger;  // comes back with 9k plus records
hive:   select * from MVLogger;  // comes back with 9k plus records
my hbase table definition is
'MVLogger', {NAME => 'dbLogData', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'ROW',     REPLICATION_SCOPE => '0', VERSIONS true
  => '1', COMPRESSION => 'NONE', MIN_VERSIONS => '0', TTL => '2147483647', KEEP_DELETED_CELLS => 'false', BLOCKSIZE => '65
 536', IN_MEMORY => 'false', BLOCKCACHE => 'true'}

My hive (external) table definition is:
CREATE EXTERNAL TABLE `MVLogger`(
`rowid` int,
`ID` int,
`TableName` string,
`CreatedDate` string,
`RowData` string,
`ClientDB` string)
ROW FORMAT SERDE
'org.apache.hadoop.hive.hbase.HBaseSerDe'
STORED BY
'org.apache.hadoop.hive.hbase.HBaseStorageHandler'
WITH SERDEPROPERTIES (
 'serialization.format'='1',
'hbase.columns.mapping'=':key,dbLogData:ID,dbLogData:TableName,dbLogData:CreatedDate,dbLogData:RowData,dbLogData:ClientDB')
TBLPROPERTIES (
'hbase.table.name'='MVLogger')

When I use sqlline and look at the drill schema this is what I see
0: jdbc:drill:zk=ip-*.compu> show schemas;

+-------------+
| SCHEMA_NAME |
+-------------+
| hive.default |
| dfs.default |
| dfs.root    |
| dfs.tmp     |
| cp.default  |
| hbase       |
| sys         |
| INFORMATION_SCHEMA |
+-------------+

and when I do a use [schema] (any of them but sys) and then do a show tables I get nothing... For example
0: jdbc:drill:zk=ip-*.compu> use hbase;
+------------+------------+
|     ok     |  summary   |
+------------+------------+
| true       | Default schema changed to 'hbase' |
+------------+------------+
1 row selected (0.071 seconds)
0: jdbc:drill:zk=ip-*.compu> show tables;
+--------------+------------+
| TABLE_SCHEMA | TABLE_NAME |
+--------------+------------+
+--------------+------------+
No rows selected (0.37 seconds)

In the Drill Web UI (ambari) under storage options for Drill I see an enabled hbase and hive.  The configuration for the hive storage is the following.
{
  "type": "hive",
  "enabled": true,
  "configProps": {
    "hive.metastore.uris": "thrift://ip-*.compute.internal:9083",
    "hive.metastore.warehouse.dir": "/apps/hive/warehouse/",
    "fs.default.name": "hdfs://ip-*.compute.internal:8020/",
    "hive.metastore.sasl.enabled": "false"
  }
}

Any ideas of why I'm not able to query hive/hbase ?
Update:  The table is showing up in the hive schema now but when I try to query it with a simple select * from ... it just hangs and I can't find anything in any of the log files.  The hive table's actual data store is hbase BTW.
Found out Hbase .98 is not yet compatible with the drill/hbase plugin... http://mail-archives.apache.org/mod_mbox/incubator-drill-user/201410.mbox/%3CCAKa9qDmN_fZ8V8W1JKW8HVX%3DNJNae7gR-UMcZC9QwKVNynQJkA%40mail.gmail.com%3E

A: it's maybe too late but for others who may see the post and having this issue .
0: jdbc:drill:zk=ip-*.compu> use hbase;
+------------+------------+
|     ok     |  summary   |
+------------+------------+
| true       | Default schema changed to 'hbase' |
+------------+------------+
1 row selected (0.071 seconds)
0: jdbc:drill:zk=ip-*.compu> show tables;
+--------------+------------+
| TABLE_SCHEMA | TABLE_NAME |
+--------------+------------+
+--------------+------------+
No rows selected (0.37 seconds)

the user that is running drill has no access permission on hbase . grant drill user access on hbase and you will see the tables .
try going to hbase shell with drill user and run "list" it will also be empty until you grant permission then u will see the tables .

redpajama_set_name: RedPajamaStackExchange


text:
Q: __name__ in Python, Pydev I am making a package in python3, using PyDev. One of my .py files has a simple relative import, from . import filename. When I use another file outside of the package to import from the package and test out that file it works fine, but running that file directly in PyDev fails with this error:
ImportError: attempted relative import with no known parent package

After a lot of searching, I found some code that works when I add it before any imports are made:
__path__ = [""] # indicates local directory
__package__ = ["package_name"]

Then everything runs fine. However, just a test, in that file I put this line: print(__name__)
The output is two strings!
package_name
__main__

I suspect this is just because it's in a package and being run directly, but then how do I do something like if __name__ == "__main__": ?
Here are some more outputs when I messed around with the __name__ var more:
print(repr(__name__))
# output
'package_name'
'__main__'

print(__name__.endswith("__main__"))
# output
False
True

print(type(__name__))
# output
<class 'str'>
<class 'str'>

I don't even understand how a variable could have two separate strings assigned to it. What is going on?

A: This is a known Python issue... files run as __main__ cannot have relative imports in them unless they're run with the -m flag (which imports the module with the name given and then changes its __name__ to run it as __main__.
By default PyDev just runs the file regularly, but you can also ask it to run the file by its computed module name (see preferences > PyDev > Run > Launch modules with "python -m mod.name").
Personally, I suggest you don't put relative imports in your __main__ module (because then users won't also be able to run your module as python filename.py and will also have to run with the -m flag), but if that's Ok for you, you can enable that option in PyDev.


text:
Q: ++ operator overload c++ Meaning I am new in C++ and I've got some questions. I saw operator ++ overloading at complex numbers and I cant understand:

*

*Why I create a tmp variable

*why my first operator is Complex & and second it's just Complex

*Why return *this;(i know cause of Complex& but why)

*if i used Complex without & what would happened?(i run it and its the same result)

Don't look at comments it's Greek :)
Complex &   Complex::operator ++(){
     r=r+1;
     return *this;//to this einai to pointer tou trexontos alla 8eloume dereference ara vazoume *this gia na epistrepsoume refernce//
}

Complex     Complex::operator ++(int ){
     Complex tmp(*this);
     operator ++();
        return tmp;//ftiaxnoume ena tmp tou antikimenou pou exoume meta efarmozoume to operator++ kai epistrefoume to tmp//
}

A: the different signature (Complex& vs Complex) is because these operations i++ and ++i do different things. One returns a copy of the old value (the second one) by value, the first one returns a reference to the actual value if x - by reference
The tmp variable is needed because you need to return the old value after incrementing the value (thats what x++ does)
you need to return a reference to the current object - so return *this - this is a pointer to the current object; *this is the object

A: 2 - Complex & returns a reference to the same object, Complex returns a copy of it.
1 - that is why a temp variable is created, in order to increment the actual object but return the copy, in order to simulate the "use and then increment" postfix operator.
3 - because while i++ returns a copy of i (and increments i), ++i returns i incremented.
4 - the operator will return a copy of the incremented object, not the actual incremented object.

A: With a variable x, you can write ++x or x++.  Former will do a ++, and if it is part of a bigger expression, use the new x. Latter will do the ++ too, but uses the old x for the current expression (it´s like the ++ comes a line after the current one).
If you overload ++, you need to separate if it is prefixed or suffixed.
It looks somewhat strange, but if you mean the suffixed version, you need to have a nameless int as parameter of the function (nothing for prefix). There is no meaningful value passed or something,
it´s just to make a difference between the two possibilites.
So, in the suffix variant, you´ll have a temporary copy to keep
the old value while you´re doing the ++ (ant return the old value for this one time).


text:
Q: CSS file showing as "text/x-csrc", being read as text/html in browser and ignored Several css files included in a Traq installation package are showing a MIME type of "text/x-csrc" on the server.  The files are being read as text/html by the browser and are ignored.
CSS files for other virtualhosted sites appear as text/css.

I've tried copying and pasting contents of the "text/x-csrc" file into a text editor, then creating a new file on the server and pasting with vi.   Same result.
Here is the suspect file, install.css:
/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

/*!
 * Traq Install
 * Copyright (c) 2009-2012 Traq.io
 * @license GNU General Public License v3 only
 */
body {
    font-family: Arial, Helvetica, sans-serif;
    background: #e9e9e9;
    color: #fff;
    margin: 30px; }

#wrapper {
    width: 580px;
    margin: 0 auto;
    border-radius: 5px;
    box-shadow: 0 0 25px 1px rgba(0, 0, 0, 0.4); }

header {
    background: #3478AA;
    padding: 10px;
    height: 20px;
    border-radius: 5px 5px 0 0; }
header h1 {
    font-weight: bold;
    float: left; }
header h2 {
    float: right;
    font-weight: bold; }

#page {
    background: #fff;
    color: #000;
    padding: 10px;
    border-radius: 5px;
    margin: -5px 0;
    z-index: 10;
    position: relative;
    font-size: 14px; }

code {
    font-family: "Courier New", Courier, monospace;
}

#licence, #config_code {
    width: 550px;
    height: 400px;
    overflow: scroll;
    margin: 0 auto;
    background: #F6F6F6;
    border: 1px solid #e4e4e4;
    padding: 4px;
    font-size: 12px;
    font-family: "Courier New", Courier, monospace; }
#config_code {
    height: 125px }

.tabular .group {
    margin: 0;
    padding: 5px 0;
    padding-left: 250px;
    clear: left; }
.tabular label {
    font-weight: bold;
    float: left;
    margin-left: -250px;
    text-align: right;
    width: 245px;
    font-size: 12px;
    padding-top: 3px; }
.tabular input {
    margin-top: 0px;
    vertical-align: middle; }
.tabular select {
    margin-top: 0; }

.actions {
    text-align: center;
    margin-top: 5px; }

.error label {
    color: red; }
.error input {
    border: 1px solid red;
    padding: 2px; }

footer {
    font-size: 11px;
    padding: 6px;
    padding-top: 10px;
    background: #d9d9d9;
    color: #000;
    border-radius: 0 0 5px 5px; }

What in this file could be triggering an incorrect MIME type?
EDIT:
The first two characters in install.css were /* - opening tag of a comment.  Apparently my Apache magic file interpreted this as "C Source" instead of CSS.
Adding a line return to the beginning of the default install.css file changed the MIME type from C Source to CSS.
The file is still being incorrectly identified as text/html by Chrome/Firefox.  I've added this to httpd.conf:
AddType text/css .css

Still no dice.  Both Firefox and Chrome are incorrectly reading this as text/html.
Help?

A: Your reading this from a external database or something? I guess you missed the tags to open and close style.


text:
Q: Unable to run pig script in pentaho I'm using Hadoop in distributed mode. I wanted to execute pig script on hadoop cluster through remote machine. So to achive this I'm using pentaho & pig script utility. I set all parameter such as
HDFS HostName: Hadoop master name
HDFS Port: 8020
Job tracker Hostname: another slave machine name
Job tracker port: 8021
Pig script path
I followed this link enter link description here
But pig script getting failed Below is the  ERROR LOG
2015/03/27 16:10:20 – RepositoriesMeta – Reading repositories XML file: C:\Users\vijay.shinde\.kettle\repositories.xml
2015/03/27 16:10:21 – Version checker – OK
2015/03/27 16:10:45 – Spoon – Connected to metastore : pentaho, added to delegating metastore
2015/03/27 16:11:03 – Spoon – Spoon
2015/03/27 16:11:28 – Spoon – Starting job…
**2015/03/27 16:11:28 – Job_pig – Start of job execution**
2015/03/27 16:11:28 – Job_pig – Starting entry [Pig Script Executor]
2015/03/27 16:11:29 – Pig Script Executor – 2015/03/27 16:11:29 – Connecting to hadoop file system at: hdfs://server_name:8020
2015/03/27 16:11:31 – Pig Script Executor – 2015/03/27 16:11:31 – Connecting to map-reduce job tracker at:job_tracker:8021
2015/03/27 16:11:32 – Pig Script Executor – 2015/03/27 16:11:32 – Pig features used in the script: GROUP_BY,FILTER
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – {RULES_ENABLED=[AddForEach, ColumnMapKeyPrune, DuplicateForEachColumnRewrite, FilterLogicExpressionSimplifier, GroupByConstParallelSetter, ImplicitSplitInserter, LimitOptimizer, LoadTypeCastInserter, MergeFilter, MergeForEach, NewPartitionFilterOptimizer, PartitionFilterOptimizer, PushDownForEachFlatten, PushUpFilter, SplitFilter, StreamTypeCastInserter]}
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – File concatenation threshold: 100 optimistic? false
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – Choosing to move algebraic foreach to combiner
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – MR plan size before optimization: 1
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – MR plan size after optimization: 1
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – Pig script settings are added to the job
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – mapred.job.reduce.markreset.buffer.percent is not set, set to default 0.3
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – Reduce phase detected, estimating # of required reducers.
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – Using reducer estimator: org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.InputSizeReducerEstimator
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – BytesPerReducer=1000000000 maxReducers=999 totalInputFileSize=110
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – Setting Parallelism to 1
2015/03/27 16:11:33 – Pig Script Executor – 2015/03/27 16:11:33 – creating jar file Job9065727596293143224.jar
2015/03/27 16:11:38 – Pig Script Executor – 2015/03/27 16:11:38 – jar file Job9065727596293143224.jar created
2015/03/27 16:11:38 – Pig Script Executor – 2015/03/27 16:11:38 – Setting up single store job
2015/03/27 16:11:38 – Pig Script Executor – 2015/03/27 16:11:38 – Key [pig.schematuple] is false, will not generate code.
2015/03/27 16:11:38 – Pig Script Executor – 2015/03/27 16:11:38 – Starting process to move generated code to distributed cache
2015/03/27 16:11:38 – Pig Script Executor – 2015/03/27 16:11:38 – Setting key [pig.schematuple.classes] with classes to deserialize []
2015/03/27 16:11:39 – Pig Script Executor – 2015/03/27 16:11:39 – 1 map-reduce job(s) waiting for submission.
**2015/03/27 16:37:31 – Pig Script Executor – 2015/03/27 16:37:31 – 0% complete
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – Ooops! Some job has failed! Specify -stop_on_failure if you want Pig to stop immediately on failure.**
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – job null has failed! Stop running all dependent jobs
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – 100% complete
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – There is no log file to write to.
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – Backend error message during job submission

N/A filtered_records,grouped_records,max_temp,records   GROUP_BY,COMBINER   Message: java.net.ConnectException: Call From server_name/ip_address to server_name:8050 failed on connection exception: java.net.ConnectException: Connection refused: no further information; For more details see: http://wiki.apache.org/hadoop/ConnectionRefused
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.GeneratedConstructorAccessor26.newInstance(Unknown Source)
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
2015/03/27 16:37:36 – Pig Script Executor – at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:783)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:730)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client.call(Client.java:1351)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client.call(Client.java:1300)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:206)
2015/03/27 16:37:36 – Pig Script Executor – at com.sun.proxy.$Proxy21.getNewApplication(Unknown Source)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.yarn.api.impl.pb.client.ApplicationClientProtocolPBClientImpl.getNewApplication(ApplicationClientProtocolPBClientImpl.java:167)
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.GeneratedMethodAccessor20.invoke(Unknown Source)
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2015/03/27 16:37:36 – Pig Script Executor – at java.lang.reflect.Method.invoke(Method.java:483)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:186)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
2015/03/27 16:37:36 – Pig Script Executor – at com.sun.proxy.$Proxy22.getNewApplication(Unknown Source)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.yarn.client.api.impl.YarnClientImpl.getNewApplication(YarnClientImpl.java:127)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.yarn.client.api.impl.YarnClientImpl.createApplication(YarnClientImpl.java:135)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapred.ResourceMgrDelegate.getNewJobID(ResourceMgrDelegate.java:175)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapred.YARNRunner.getNewJobID(YARNRunner.java:229)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:355)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1268)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1265)
2015/03/27 16:37:36 – Pig Script Executor – at java.security.AccessController.doPrivileged(Native Method)
2015/03/27 16:37:36 – Pig Script Executor – at javax.security.auth.Subject.doAs(Subject.java:422)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1491)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapreduce.Job.submit(Job.java:1265)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2015/03/27 16:37:36 – Pig Script Executor – at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2015/03/27 16:37:36 – Pig Script Executor – at java.lang.reflect.Method.invoke(Method.java:483)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.pig.backend.hadoop23.PigJobControl.submit(PigJobControl.java:128)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.pig.backend.hadoop23.PigJobControl.run(PigJobControl.java:191)
2015/03/27 16:37:36 – Pig Script Executor – at java.lang.Thread.run(Thread.java:745)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:270)
2015/03/27 16:37:36 – Pig Script Executor – Caused by: java.net.ConnectException: Connection refused: no further information
2015/03/27 16:37:36 – Pig Script Executor – at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
2015/03/27 16:37:36 – Pig Script Executor – at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:716)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:529)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:493)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:547)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:642)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client$Connection.access$2600(Client.java:314)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client.getConnection(Client.java:1399)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.hadoop.ipc.Client.call(Client.java:1318)
2015/03/27 16:37:36 – Pig Script Executor – … 30 more
2015/03/27 16:37:36 – Pig Script Executor – /data/pig/input/test1,

**Input(s):
Failed to read data from "/data/pig/input/pigtest.txt"
Output(s):
Failed to produce result in "/data/pig/input/test1″
Counters:
Total records written : 0
Total bytes written : 0
Spillable Memory Manager spill count : 0
Total bags proactively spilled: 0
Total records proactively spilled: 0
Job DAG:**
null
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – Failed!
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – ERROR 2244: Job failed, hadoop does not return any error message
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – There is no log file to write to.
2015/03/27 16:37:36 – Pig Script Executor – 2015/03/27 16:37:36 – org.apache.pig.backend.executionengine.ExecException: ERROR 2244: Job failed, hadoop does not return any error message
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.pig.tools.grunt.GruntParser.executeBatch(GruntParser.java:148)
2015/03/27 16:37:36 – Pig Script Executor – at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:202)
2015/03/27 16:37:36 – Pig Script Executor – at org.pentaho.hadoop.shim.common.CommonPigShim.executeScript(CommonPigShim.java:105)
2015/03/27 16:37:36 – Pig Script Executor – at org.pentaho.di.job.entries.pig.JobEntryPigScriptExecutor.execute(JobEntryPigScriptExecutor.java:492)
2015/03/27 16:37:36 – Pig Script Executor – at org.pentaho.di.job.Job.execute(Job.java:678)
2015/03/27 16:37:36 – Pig Script Executor – at org.pentaho.di.job.Job.execute(Job.java:815)
2015/03/27 16:37:36 – Pig Script Executor – at org.pentaho.di.job.Job.execute(Job.java:500)
2015/03/27 16:37:36 – Pig Script Executor – at org.pentaho.di.job.Job.run(Job.java:407)
2015/03/27 16:37:36 – Pig Script Executor – Num successful jobs: 0 num failed jobs: 1
2015/03/27 16:37:36 – Job_pig – Finished job entry [Pig Script Executor] (result=[false])
2015/03/27 16:37:36 – Job_pig – Job execution finished
2015/03/27 16:37:36 – Spoon – Job has ended.

This is my pig script.
records = LOAD '/data/pig/input/pigtest.txt' USING PigStorage(',') AS (year:chararray,temperature:int,quality:int);
filtered_records = FILTER records BY quality==1;
grouped_records = GROUP filtered_records BY year;
max_temp = FOREACH grouped_records GENERATE group,MAX(filtered_records.temperature);
STORE max_temp into '/data/pig/input/test1′;

Thanks


text:
Q: How to select a table record depending on table element using selenium webdriver A table has 2 or more rows (depending on previous action) and the contents are not ordered.  One of the column has unique elements.  I need to select the row depending on the unique element using selenium webdriver (java). I am passing the locators using an excel sheet.
For eg, I have the following kind of table:

Select         Name     Id
Radio_button   ABC        Id1
Radio_button   ABC        Id2
Suppose for the above table, the order of the rows are not same all the time and depending on id value, I need to select the correct radio button.  How do I identify the correct radio button depending on the id value?

A: Use xpath for finding your element:
//tr[*[@id='id1']]//input

This is a locator for Radio_button that is in the same row as id1.
If you provide your html code of the table, the answer will be more precisely, but the general idea is clear, I suppose.

A: Though the selenium doesnt give any error for the xpath (verifyVisible), which you had mentioned , am not able to click/check on that particular radio button.
It identifies only the first radio button and checks on that.


text:
Q: Angular 2, reset form before navigate I have an onSubmit method.
    onSubmit() {

    let user = this.form.value
    this._userService.postUser(user)
    this.form.reset();
    this._router.navigate(['users'])
}

I'm using
    this.form.reset();

to prevent dirty tracking but when I use this line it seems to disable
  this._router.navigate(['users'])

If I don't reset the form I have a dirty tracking alert message.
Is there any way I can have my cake and eat it?

A: I should have used
this.form.markAsPristine()

instead of
this.form.reset()


text:
Q: Select a photo from gallery/camera InAppBrowser I have an app with Cordova that execute InAppBrowser, and I need open the contextual menu with the options to get a photo like this: http://puu.sh/nJUP0/433fa31c83.jpg
In Iphone 6 this work but in android not.
I have the input
<input type="file" accept="image/*" />

A: he Camera docs cover this. Is this not working for you? Check out Camera.PictureSourceType for details. The docs site givens this example for deriving an image thus:
function getPhoto(source) {
   // Retrieve image file location from specified source
   navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
   destinationType: destinationType.FILE_URI,
   sourceType: source });
}

sourceType is the crucial bit here. It can be Camera.PictureSourceType.CAMERA (the default), or more useful for you it can be Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM.
read more


text:
Q: feature an item based on the date I have an events table with a 'featureEvent' boolean column.
I need to display a featured event of the day on the home page
what id like to do is display the featured event for the entire day. For this i think i need to link it to the date somehow.
public Event GetTodaysFeatureEvent()
{
    var ev = db.Events.Where(x => x.featureEvent == true && x.eventDate> DateTime.Now.Date);
    //gets a pool of feature-able events
}

how can I do it so that whatever event is displayed is the same one for the entire day?
Edit - I'll try making more sense.
I set events to be featureable (featureEvent=true). what i want to do is pick out from a pool of featurable events (that will occur in the future) one single event.
i dont want to use firstOrDefault as this could potentially show the same event N days in a row. ideally I'd like something whereby a different event is selected from the featurable events each day... i cant just pick a random one as during the same day different events will be featured and for different users. so i want that one event to be shown the entire day to all users.
I dont mind featuring the same event more than once, ie if all the featurable events have already been featured then go back to the first one?
now it gets even more complicated as i can set an event to featured at any time so not sure how to handle that side of things.
hope thats a little clearer....probably not!

A: (This answer assumes that eventDate always has a time component of zero -- in other words, that the value would always be something like 12/31/2012 00:00:00.000 and never something like 12/31/2012 11:30:00.000.)
Note that your logic only chooses events occurring after today.  To choose events occurring today or later, change > to >=.  To choose events occurring today only, use ==.
If it is possible to have more than one feature event for a given day, you can do this in one of two ways

*

*pick an arbitrary item, and save a reference to it somewhere so you can reuse it, or

*apply some unambiguous ordering to your linq query, so that the objects are guaranteed always to have the same order; then pick the first one.
For example, assuming there's a property P whose value is unique to each event, and whose type is T where T implements IComparable<T>, then you could do this:
public Event GetTodaysFeatureEvent()
{
    var ev = db.Events.Where(x => x.featureEvent && x.EventDate >= DateTime.Now.Date)
        .OrderByDescending(x => x.EventDate)
        .ThenBy(x => x.P)
        .FirstOrDefault();
}

This picks a future event that occurs on the next day for which there's at least one event.  Since the events are ordered by P,  and P is by assumption unique, the events will always be retrieved in the same order.
If you prefer to display featured events only on the actual day (and display nothing on days that have no featured events), then change the >= to ==:
public Event GetTodaysFeatureEvent()
{
    var ev = db.Events.Where(x => x.featureEvent && x.EventDate == DateTime.Now.Date)
        .OrderByDescending(x => x.EventDate)
        .ThenBy(x => x.P)
        .FirstOrDefault();
}

In response to your edits:

ideally I'd like something whereby a different event is selected from the featurable events each day... i cant just pick a random one as during the same day different events will be featured and for different users. so i want that one event to be shown the entire day to all users.

To achieve this, you'll definitely need persistent information about which event is featured on a given day.  It seems now that your question is more about how to do that than about specific linq expressions.

I dont mind featuring the same event more than once, ie if all the featurable events have already been featured then go back to the first one?

If you want to make sure that events aren't featured repeatedly before all other events have been featured, you could save a "lastFeaturedOn" date for each featured event.  When choosing an event to feature, first pick one that was never featured (i.e., lastFeaturedOn == null); if there are no such events, pick the one with the smallest lastFeaturedOn date.
This will give you the events in the same repeated order; if you'd rather reshuffle them you could instead set all dates to null when they are all non-null (or use a boolean).
Once you've picked an event, you'll need to save it and a date in your database, to identify it as the featured event for that date.  You could use the "lastFeaturedOn" date, and define "today's featured item" as "the item whose lastFeaturedOn date is today's date."

A: If I understood you :...
if you want only for the whole day
  public Event GetTodaysFeatureEvent()
    {
        var now = DateTime.Now;
        var ev = db.Events.Where(x => x.featureEvent == true && x.eventDate> new DateTime(now.year,now.month,now.day) && x.eventDate< new DateTime(now.year,now.month,now.day).AddDays(1));
        //gets a pool of feature-able events
    }

A: You could try
return ev.OrderBy(x => x.eventDate).FirstOrDefault();

If you just want to display the earliest from that day, or could order by any other property.

A: I'm not really sure what actually your answer is, but if you don't know how to get all events of today, this might help:
db.Events.Where(x => x.featureEvent == true
                  && x.eventDate >= DateTime.Today
                  && x.eventDate <  DateTime.Today.AddDays(1).Date
               );

http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx


text:
Q: django unprintable templatesyntaxerror object caused by urlconf? I'm trying to get a django project set up, and I seem to be having trouble with my urlconf.  I'm not sure what the deal is, and the error below isn't entirely helpful to me.  I don't think it really has anything to do with template rendering, actually, because I stepped through the execution path until just before the render_to_response function completes (which is where the urlconf seems to be causing an error) and the template objects are parsed correctly.
Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2978, in _HandleRequest
    base_env_dict=env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 411, in Dispatch
    base_env_dict=base_env_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2244, in Dispatch
    self._module_dict)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2162, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "C:\Program Files\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2058, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "C:\Users\Ben\Development\workspace\ringbot\src\main.py", line 52, in <module>
    main()
  File "C:\Users\Ben\Development\workspace\ringbot\src\main.py", line 49, in main
    util.run_wsgi_app(application)
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 97, in run_wsgi_app
    run_bare_wsgi_app(add_wsgi_middleware(application))
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\util.py", line 115, in run_bare_wsgi_app
    result = application(env, _start_response)
  File "C:\Python25\lib\site-packages\django\core\handlers\wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 134, in get_response
    return self.handle_uncaught_exception(request, resolver, exc_info)
  File "C:\Python25\lib\site-packages\django\core\handlers\base.py", line 154, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "C:\Python25\lib\site-packages\django\views\debug.py", line 40, in technical_500_response
    html = reporter.get_traceback_html()
  File "C:\Python25\lib\site-packages\django\views\debug.py", line 114, in get_traceback_html
    return t.render(c)
  File "C:\Python25\lib\site-packages\django\template\__init__.py", line 178, in render
    return self.nodelist.render(context)
  File "C:\Python25\lib\site-packages\django\template\__init__.py", line 779, in render
    bits.append(self.render_node(node, context))
  File "C:\Python25\lib\site-packages\django\template\debug.py", line 81, in render_node
    raise wrapped
TemplateSyntaxError: <unprintable TemplateSyntaxError object>

Here is my top-level urlconf:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
   (r'', include('pub.urls')),
)

And pub.urls:
from django.conf.urls.defaults import *
import pub

urlpatterns = patterns('pub.views',
    (r'^$', 'index')
)

and pub.views.index:
# Create your views here.
from django.shortcuts import render_to_response
from django.http import HttpResponse
import openidgae

# this needs to be moved somewhere else, but for now it can live here
def index(request):
    lip = openidgae.get_current_person(request, HttpResponse())
    resp = render_to_response('pub/index.html', {'lip': lip}) # exception thrown here
    return resp

A: Make sure each of your .py files is syntactically correct. Run python manage.py shell and then import each of your modules and make sure it loads with no errors. Since syntax errors are runtime errors in python, mistakes sometimes show up at odd times and in odd places.

A: Here's another suggestion which could come in handy in the future.
The stack trace printed in the web interface isn't always optimal for a number of possible reasons. However, you can also get a stack trace out to the console which might give you information that was omitted on the web page.
The easiest way to do that is to run django using the built-in webserver (i.e. python manage.py runserver 0.0.0.0:8000), and visit THAT page with your browser. You should see a stack trace appear inline with the web server logging output on the console, which may include otherwise "unprintable" error content.

A: looks like the problem is because of a NoReverseMatch exception being thrown because my templates contain a {% url ... %} block that doesn't resolve. From the django site: Note that if the URL you're reversing doesn't exist, you'll get an NoReverseMatch exception raised, which will cause your site to display an error page.


text:
Q: One base to rule them all. One base to bring them all and in the darkness bind them Is it possible to write a universal base class which all other classes (except it) publicly and virtually inherit?  (Is there a workaround for gcc?).  It would be preferable to not explicitly inherit...because I want the standard library stuff to inherit from this also....And is this wise to do?
If you down vote please explain why (I do believe this is a legitimate question even if it is a stupid thing to do, which it might be, but that is part of the question)

A: Trying to shoehorn in a common virtual base would break C++ badly.
There are a number of language rules that allow special treatment for standard-layout and trivially copyable types.  Classes with a virtual base class qualify for neither of these.
Even other systems which purportedly have a common base class (e.g. Microsoft's .NET) have some blit-able types for which inheritance from the base class is a convenient lie -- virtual dispatch is not permitted, all calls relating to inherited members of these classes must be resolved at compile time.

A: Yes.  Define a class with a public virtual destructor.  Call it base.
Now after each class foo do this:
class foo:
  public virtual base

And done!
Naturaly this only works on your own types.  If you want to enforce it on other types, such as std, simply reimplement std in your own notstd namespace type by type and inherit all types from your base.  Similarly for any third party libraries you want to use: some may prove impractical.
Note that this can change the binary layout of the class, and change what guaratees exist: no such class foo is standard layout, for example.
On the other hand, if you want a new language that behaves mostly like C++, but forces a base class on all classes, and disntinguishes classes from structs, consider java.


text:
Q: How to collect and return aggregated data as an Array from a table in Protractor? I am trying to aggregate a list of dates from a data table, written in Angular, in a Protractor test.  I'm doing the aggregation from a PageObject class that is called in the Protractor test. I know that my code is successfully grabbing the text I want, but when I try to console.log the returned array, I get an empty array.  I'm still new to Javascript/Typescript, Angular, and Protractor and this may be a result of my newness to the asynchronous nature of this development environment.
Code is as follows,
The PageObject SpecMapper class with method:
import { browser, element, by } from 'protractor';

export class SpecMapperPage {
    getImportDateSubmittedColumnValues() {
        let stringDatesArray: Array<string> = [];
        // currently this css selector gets rows in both import and export tables
        // TODO: get better identifiers on the import and export tables and columns
        element.all(by.css('md-card-content tbody tr.ng-tns-c3-0')).each(function(row, index){
            // check outerHTML for presence of "unclickable", the rows in the export table
            row.getAttribute('outerHTML').then(function(outerHTML:string) {
                // specifically look for rows without unclickable
                if(outerHTML.indexOf("unclickable") < 0){
                    // grab the columns and get the third column, where the date submitted field is
                    // TODO: get better identifiers on the import and export columns
                    row.all(by.css("td.ng-tns-c3-0")).get(2).getText().then(function(text:string) {
                       stringDatesArray.push(text);
                    });
                }
            });
        });
        return stringDatesArray;
    }
}

I know it's not the prettiest code, but it's temporary place holder while my devs make me better attributes/classes/ids to grab my variables.  Key things to note is that I create a string Array to hold the values I consider relevant to be returned when the method is finished.
I used WebStorm and put a breakpoint at the stringDatesArray.push(text) and return stringDatesArray lines. The first line shows that the text variable has a string variable that I'm looking for and is successfully getting pushed.  I see the success in debug mode as I can see the stringDatesArray and see the values in it.  The second line though, the array return, shows that the local variable stringDatesArray is empty.  This is echoed in the following code when I try to console.log the array:
The Protractor run Spec class with my test in it:
import { SpecMapperPage } from "./app.po";
import {browser, ExpectedConditions} from "protractor";

describe('spec mapper app', () => {
    let page: SpecMapperPage;
    let PROJECT_ID: string = '57';
    let PROJECT_NAME: string = 'DO NOT DELETE - AUTOMATED TESTING PROJECT';

    beforeEach(() => {
        page = new SpecMapperPage();
    });

    describe('import/export page', () => {
        it('verify sort order is desc', () => {
            browser.waitForAngularEnabled(false);
            // Step 1: Launch Map Data from Dashboard
            page.navigateTo(PROJECT_ID);
            browser.driver.sleep(5000).then(() => {
                // Verify: Mapping Screen displays
                // Verify on the specmapper page by checking the breadcrumbs
                expect(page.getProjectNameBreadCrumbText()).toContain(PROJECT_NAME);
                expect(page.getProjectMapperBreadCrumbText()).toEqual("MAPPER");

                // Verify: Verify Latest Submitted Date is displayed at the top
                // Verify: Verify the Submitted Date column is in descending order
                console.log(page.getImportDateSubmittedColumnValues());
            });
        });
    });
});

I acknowledge that this code is not actively using the niceties of Protractor, there's a known issue with our app that will not be addressed for a couple of months, so I am accessing the driver directly 99% of the time.
You'll note that I call the method I posted above as the very last line in the browser.driver.sleep().then() clause, page.getImportDateSubmittedColumnValues().
I thought maybe I was running into asynchronous issues with the call being done before the page was loaded, thus I put it in the .then() clause; but learned with debugging that was not the case.  This code should work once I have the array returning properly though.
The console.log is printing an empty [] array. That is synonymous with the results I saw when debugging the above method directly in the PageObject SpecMapper class. I wish to do some verification that the strings are returned properly formatted, and then I'm going to do some date order comparisons. I feel like returning an array of data retrieved from a page is not an unusual request, but I can't seem to find a good way to Google what I'm trying to do.
My apologies if I am hitting some very obvious roadblock, I'm still learning the nuances of Typescript/Angular/Protractor.  Thank you for your consideration!

My attempted to used collated promises seemed promising, but fell through on execution.
My Updated PageObject SpecMapper Class
import {browser, element, by, protractor} from 'protractor';

export class SpecMapperPage {
    getImportDateSubmittedColumnValues() {
        let promisesArray = [];
        let stringDatesArray: Array<string> = [];
        // This CSS selector grabs the import table and any cells with the label .created-date
        element.all(by.css('.import-component .created-date')).each(function(cell, index) {
            // cell.getText().then(function(text:string) {
            //    console.log(text);
            // });
            promisesArray.push(cell.getText());
        });
        return protractor.promise.all(promisesArray).then(function(results) {
           for(let result of results) {
               stringDatesArray.push(result);
           }
           return stringDatesArray;
        });
    }
}

My Updated Spec test Using The Updated SpecMapper PO Class
import { SpecMapperPage } from "./specMapper.po";
import {browser, ExpectedConditions} from "protractor";

describe('spec mapper app', () => {
    let page: SpecMapperPage;
    let PROJECT_ID: string = '57';
    let PROJECT_NAME: string = 'DO NOT DELETE - AUTOMATED TESTING PROJECT';

    beforeEach(() => {
        page = new SpecMapperPage();
    });

    describe('import/export page', () => {
        it('TC2963: ImportComponentGrid_ShouldDefaultSortBySubmittedDateInDescendingOrder_WhenPageIsLoaded', () => {
            browser.waitForAngularEnabled(false);
            // Step 1: Launch Map Data from Dashboard
            page.navigateTo(PROJECT_ID);
            browser.driver.sleep(5000).then(() => {
                // Verify: Mapping Screen displays
                // Verify on the specmapper page by checking the breadcrumbs
                expect(page.getProjectNameBreadCrumbText()).toContain(PROJECT_NAME);
                expect(page.getProjectMapperBreadCrumbText()).toEqual("MAPPER");

                // Verify: Verify Latest Submitted Date is displayed at the top
                // Verify: Verify the Submitted Date column is in descending order
                page.getImportDateSubmittedColumnValues().then(function(results) {
                    for(let value of results) {
                        console.log("a value is: " + value);
                    }
                });
            });
        });
    });
});

When I breakpoint in the PO class at the return stringDatesArray; line, I have the following variables in my differing scopes.  Note that the promisesArray has 3 objects, but the results array going into the protractor.promise.all( block has 0 objects.  I'm not sure what my disconnect is. :/

I think I'm running into a scopes problem that I am having issues understanding. You'll note the commented out promise resolution on the getText(), and this was my POC proving that I am getting the string values I'm expecting, so I'm not sure why it's not working in the Promise Array structure presented as a solution below.

Only other related question that I could find has to do with grabbing a particular row of a table, not specifically aggregating the data to be returned for test verification in Protractor. You can find it here if you're interested.

A: As you've alluded to your issue is caused by the console.log returning the value of the variable before its actually been populated.
I've taken a snippet from this answer which should allow you to solve it: Is there a way to resolve multiple promises with Protractor?
var x = element(by.id('x')).sendKeys('xxx');
var y = element(by.id('y')).sendKeys('yyy');
var z = element(by.id('z')).sendKeys('zzz');

myFun(x,y,z);
//isEnabled() is contained in the expect() function, so it'll wait for
// myFun() promise to be fulfilled
expect(element(by.id('myButton')).isEnabled()).toBe(true);

// in a common function library
function myFun(Xel,Yel,Zel) {
  return protractor.promise.all([Xel,Yel,Zel]).then(function(results){
     var xText = results[0];
     var yText = results[1];
     var zText = results[2];

  });
}

So in your code it would be something like
getImportDateSubmittedColumnValues() {
    let promisesArray = [];
    let stringDatesArray: Array<string> = [];
    // currently this css selector gets rows in both import and export tables
    // TODO: get better identifiers on the import and export tables and columns
    element.all(by.css('md-card-content tbody tr.ng-tns-c3-0')).each(function(row, index){
        // check outerHTML for presence of "unclickable", the rows in the export table
        row.getAttribute('outerHTML').then(function(outerHTML:string) {
            // specifically look for rows without unclickable
            if(outerHTML.indexOf("unclickable") < 0){
                // grab the columns and get the third column, where the date submitted field is
                // TODO: get better identifiers on the import and export columns
                promisesArray.push(row.all(by.css("td.ng-tns-c3-0")).get(2).getText());
            }
        });
    });
    return protractor.promise.all(promisesArray).then(function(results){
        // In here you'll have access to the results

    });
}

Theres quite a few different ways you could do it. You could process the data in that method at the end or I think you could return the array within that "then", and access it like so:
page.getImportDateSubmittedColumnValues().then((res) =>{
    //And then here you will have access to the array
})

A: I don't do the Typescript but if you're just looking to get an array of locator texts back from your method, something resembling this should work...
getImportDateSubmittedColumnValues() {
    let stringDatesArray: Array<string> = [];

    $$('.import-component .created-date').each((cell, index) => {
        cell.getText().then(text => {
            stringDatesArray.push(text);
        });
    }).then(() => {
        return stringDatesArray;
    });
}

A: The answer ended up related to the answer posted on How do I return the response from an asynchronous call?
The final PageObject class function:
import {browser, element, by, protractor} from 'protractor';

export class SpecMapperPage {
    getImportDateSubmittedColumnValues() {
        let stringDatesArray: Array<string> = [];
        let promisesArray = [];
        // return a promise promising that stringDatesArray will have an array of dates
        return new Promise((resolve, reject) => {
            // This CSS selector grabs the import table and any cells with the label .created-date
            element.all(by.css('.import-component .created-date')).map((cell) => {
                // Gather all the getText's we want the text from
                promisesArray.push(cell.getText());
            }).then(() => {
                protractor.promise.all(promisesArray).then((results) => {
                    // Resolve the getText's values and shove into array we want to return
                    for(let result of results) {
                        stringDatesArray.push(result);
                    }
                }).then(() => {
                    // Set the filled array as the resolution to the returned promise
                    resolve(stringDatesArray);
                });
            });
        });
    }
}

The final test class:
import { SpecMapperPage } from "./specMapper.po";
import {browser, ExpectedConditions} from "protractor";

describe('spec mapper app', () => {
    let page: SpecMapperPage;
    let PROJECT_ID: string = '57';
    let PROJECT_NAME: string = 'DO NOT DELETE - AUTOMATED TESTING PROJECT';

    beforeEach(() => {
        page = new SpecMapperPage();
    });

    describe('import/export page', () => {
        it('TC2963: ImportComponentGrid_ShouldDefaultSortBySubmittedDateInDescendingOrder_WhenPageIsLoaded', () => {
            browser.waitForAngularEnabled(false);
            // Step 1: Launch Map Data from Dashboard
            page.navigateTo(PROJECT_ID);
            browser.driver.sleep(5000).then(() => {
                // Verify: Mapping Screen displays
                // Verify on the specmapper page by checking the breadcrumbs
                expect(page.getProjectNameBreadCrumbText()).toContain(PROJECT_NAME);
                expect(page.getProjectMapperBreadCrumbText()).toEqual("MAPPER");

                // Verify: Verify Latest Submitted Date is displayed at the top
                // Verify: Verify the Submitted Date column is in descending order
                page.getImportDateSubmittedColumnValues().then((results) => {
                    console.log(results);
                });
            });
        });
    });
});

The biggest thing was waiting for the different calls to get done running and then waiting for the stringDataArray to be filled.  That required the promise(resolve,reject) structure I found in the SO post noted above.  I ended up using the lambda (()=>{}) function calls instead of declared (function(){}) for a cleaner look, the method works the same either way.  None of the other proposed solutions successfully propagated the array of strings back to my test. I'm working in Typescript, with Protractor.


text:
Q: SDL, random color generator My friend gave me a bit of code for my SDL program, all I know that it makes a random color but I have no idea how it works , here is the code
 int unsigned temp = 10101;//seed
    for(int y = 0;y < times;y++){
        temp = temp*(y+y+1);
        temp = (temp^(0xffffff))>>2;
        //printf("%x\n",temp);
        SDL_FillRect(sprite[y],NULL,temp);
        SDL_BlitSurface(sprite[y],&paste[y],rScreen(),NULL);
        }

My question is , How does this code work and how does it make a random color

A: Your friend is creating a "random RGB value" ranging from 0x000000 to 0xFFFFFF out of some amateur PRNG he invented.
I'll explain the code with comments:
This is the so called "seed". The initial value that will generate the pseudo-random sequence of values.
 int unsigned temp = 10101; //seed

then we got the for loop:
 for(int y = 0;y < times;y++)
 {
    temp = temp*(y+y+1);
    temp = (temp^(0xffffff))>>2;

each round your friend is trying to make complicated multiplications and sums to come up with a new temp value which is divided by 2 (the >>2 in the code above) and then masked with 0xFFFFFFF to get a value in the range of 0x000000 to 0xFFFFFFF (he wrongly used bitwise XOR ^ instead of bitwise AND &)
The resulting value is used as a RGB value for the SDL_FillRect() function.
    //printf("%x\n",temp);
    SDL_FillRect(sprite[y],NULL,temp);
    SDL_BlitSurface(sprite[y],&paste[y],rScreen(),NULL);
 }

A: The magic is in these four lines:
unsigned int temp = 10101; // seed - this seeds the random number generator

temp = temp * (y + y + 1); // this performs a multiplication with the number itself and y
// which is incremented upon each loop cycle
temp = (temp ^ 0xffffff) >> 2; // this reduces the generated random number
// in order it to be less than to 2 ^ 24
SDL_FillRect(sprite[y], NULL, temp); // and this fills the rectangle using `temp` as the color
// perhaps it interprets `temp` as an RGB 3-byte color value


text:
Q: Import sheet from subfolder I'm trying to get a sheet from a Workbook which is a subfolder and import it in my current Workbook, where I write my macro.
The path and file would look like below
strPath = Application.ActiveWorkbook.Path & "\Subfolder"
strFile = "myExcel.xlsx"

with a workbook called myWorkbook.
How do I import it and do I need an empty sheet in my current workbook?

A: You'll need to open the source workbook, then copy the sheet and then close the workbook. You don't need to have an empty sheet in your current workbook (but you must have at least 1 sheet). Something like below will work:
Dim strPath As String, strFile As String

strPath = Thisworkbook.Path & "\Subfolder\" ' take note of the extra "\"
strFile = "myExcel.xlsx"

Application.ScreenUpdating = False
Dim wb As Workbook
Set wb = Workbooks.Open(strPath & strFile)

wb.Sheets("SheetName").Copy Thisworkbook.Sheets(1) ' copies before the first sheet
wb.Close False ' close without saving
Application.ScreenUpdating = True


text:
Q: How to solve an equation with a nested function I have the equation
f[f[x]] == 28 + 9 x

How can I solve this for f[x]? I note that this post relates to the topic, but Wolfram|Alpha doesn't work for my equation. So is there a method that can do it?

A: As the link you provided in your question shows, there is no unique solution. For example (and illustration), assuming a form (linear function) yields 2 solutions:
lhs = CoefficientRules[Nest[a # + b &, x, 2], x]
rhs = CoefficientRules[28 + 9 x, x]
{f1, f2} =
 a # + b & /.
  Solve[{({1} /. lhs) == ({1} /. rhs), ({0} /. lhs) == ({0} /. rhs)}, {a, b}]

yields:

{-3 #1 - 14 &, 3 #1 + 7 &}

Testing:
Simplify[Nest[f1, x, 2]]
Simplify[Nest[f2, x, 2]]

Both yield

28 + 9 x

A: It is interesting to see if there are some slightly more general solutions.  For example, by assuming that the function has a fixed point for some unknown value c we can do a series expansion to various orders:
f[f[x]] == 28 + 9 x
Series[%, {x, c, 6}]
% //. f[c] -> c
LogicalExpand[%]
Reduce[%]
FullSimplify[%]
Solve[%]

which gives
$\left\{\left\{c\to -\frac{7}{2},f'\left(-\frac{7}{2}\right)\to -3,f''\left(-\frac{7}{2}\right)\to 0,f^{(3)}\left(-\frac{7}{2}\right)\to 0,f^{(4)}\left(-\frac{7}{2}\right)\to 0,f^{(5)}\left(-\frac{7}{2}\right)\to 0,f^{(6)}\left(-\frac{7}{2}\right)\to 0\right\},\left\{c\to -\frac{7}{2},f'\left(-\frac{7}{2}\right)\to 3,f''\left(-\frac{7}{2}\right)\to 0,f^{(3)}\left(-\frac{7}{2}\right)\to 0,f^{(4)}\left(-\frac{7}{2}\right)\to 0,f^{(5)}\left(-\frac{7}{2}\right)\to 0,f^{(6)}\left(-\frac{7}{2}\right)\to 0\right\}\right\}$
This obviously supports the idea that the only analytic functions with a fixed point satisfying the equation are linear.

A: Here's my attempt to construct a non-analytic solution. The idea is to use one of the analytic solutions in the accepted answer when x belongs to a set of points reachable through successive application of either analytic solution or their inverses, and the other solution otherwise. This set must not be equal the set of reals, otherwise the solution just reduces to one of the analytic solutions. I thought of a way to show this set is countable, and therefore can't be equal the real set, but realized it's easier to show by counterexample after finding the set.
I start with a couple of observations to facilitate finding this set. The first is the convenient commutativity of f1 and f2:
Simplify[f1[f2[x]] == f2[f1[x]]]

which means any sequence of f1 and f2 is equivalent to one with the same total number n1 and n2 of f1 and f2 calls respectively, e.g. n1 f1 calls followed by n2 f2 calls. This commutativity also implies the inverses are commutative, and sequences of InverseFunction[f1] and InverseFunction[f2] can be similarly ordered.
The second is the nth application of f1 or f2 is the sum of a constant term, which is a geometric series of length n, and a linear term, which is the nth term in another geometric series. These terms can be computed by hand, but Mathematica gives a convenient way to do so:
s1[x_]=FindSequenceFunction[NestList[f1,x,3]];
s2[x_]=FindSequenceFunction[NestList[f2,x,3]];

It can be shown the nth application of InverseFunction[f1] or InverseFunction[f2] to x is equal s1[x][-n] or s2[x][-n] respectively.
With these results, the set of points that can be reached from x0 satisfies:
criteria = Simplify[Reduce[{s2[s1[x][n1]][n2] == x0}, {n1, n2}],
                    Assumptions -> {{n1, n2} \[Element] Integers, {x, x0} \[Element] Reals}]

$$
\left(x=-\frac{7}{2}\land \text{x0}=-\frac{7}{2}\right)\lor \left(c_1\in \mathbb{Z}\land 2 x+7\neq 0\land 2 \text{x0}+7\neq 0\land \\
\log (3) (\text{n1}+\text{n2})-2 i \pi  c_1=\log \left(-\frac{9 (-1)^{\text{n1}} (2 \text{x0}+7)}{2 x+7}\right)\right)
$$

Unless x0 is the fixed point -7/2, we can reach x if there are integers n1 and n2 satisfying this equation.
Here, the only imaginary terms are $2i\pi c_1$ and from the log on the right-hand side. Since x and x0 are real, the imaginary part of the log can only be 0 or $i\pi$. The former requires $c_1=0$, while the latter cannot be satisfied for any $c_1\in \mathbb{Z}$. We can therefore set $c_1=0$.
Moreover, given x and x0, there are only two possibilities for the log, one with n1 even, and one with n1 odd. Regardless of whether n1 is even or odd, n2 is arbitrary, so n1+n2 need only be integral and can be either even or odd:
condition[x_,x0_]=And @@ Reverse @ (Or @@ (n\[Element]Integers/.Simplify[
          Solve[criteria/.n1+n2->n,n][[1]],Assumptions->{x,x0}\[Element]Reals]/.C[1]->0/.#&
          /@ {n1->1,n1->2}))

$$
x\neq -\frac{7}{2}\land \text{x0}\neq -\frac{7}{2}\land \left(\frac{\log \left(-\frac{9 (2 \text{x0}+7)}{2 x+7}\right)}{\log (3)}\in \mathbb{Z}\lor \frac{\log \left(\frac{9 (2 \text{x0}+7)}{2 x+7}\right)}{\log (3)}\in \mathbb{Z}\right)
$$

This condition is sufficient to show the set of points that can be reached is not the real set, e.g. condition[1,0] returns False, showing x=1 cannot be reached from x0=0.
With this condition, we construct a non-analytic solution, as f1[x] for x satisfying the condition, and f2[x] otherwise:
f[x_, x0_] = Piecewise[{{f1[x], condition[x, x0]}}, f2[x]];

Testing:
ff=FullSimplify[f[f[x,x0],x0],Assumptions->{x,x0}\[Element]Reals]

unfortunately gives a long condition for 28+9x I have to simplify by brute force:
(ff[[1,1,2]]/.Log[x_]:>Log[Factor[x]]//PowerExpand//ExpandAll//FullSimplify)/.
(Log[x_]-Log[y_]:>Log[x/y])/.I \[Pi]+Log[x_]->Log[-x]/.
{x_\[Element]Integers->integerQ[x],x_\[NotElement]Integers:>!integerQ[x]}//FullSimplify

True

A: Inspired by @obsolesced, it is simple to find solutions based on any set that is mapped to itself by f1 and f2.  For example, let
S = {q1 + q2 Sqrt[2]}  for {q1, q2} rational

then
f[x] = f1[x]   x in S
f[x] = f2[x]   x not in S

satisfies the required functional relation.  It is continuous nowhere (except x = -7/2) and S is countably infinite and its complement uncountably infinite.
Alternatively, make S the Algebraic numbers, then its complement is the Transcendentals - both uncountably infinite.
It would be interesting to know if there are any solutions to the functional equation with f[x] not in {f1[x],f2[x]}.


text:
Q: Fanatic Badge is not showing right away in profile under "Badges" right after receiving it After 100 days of consistency I've attained the first gold badge "Fanatic". Now the badge is disappeared there.

Also this my Stack Overflow profile. I don't know what it happened and what to do to recover it back.


text:
Q: System.NullPointerException: Attempt to de-reference a null object. Null pointer I am checking in the Cases list in my trigger, for record type Id and only if case is of that particular Record Type do I want a SOQL query to run.
But since a list is empty it throws a Null Pointer error. How can I prevent this?
if(cases[0].RecordTypeId == 'RecordTypeId') {

    cases_Creative = [SELECT Id, CaseNumber,Counter_Survey__c FROM Case Where RecordTypeId ='RecordTypeId' and Counter_Survey__c != null and createdDate = Last_N_Days:10 order by Counter_Survey__c desc limit 1];
  }

A: It sounds like you may need to bulkify your code, because multiple records could occur in a trigger. That said, to solve your immediate problem, you just need to use the && shortcircuit operator:
if(!cases.isEmpty() && cases[0].RecordTypeId == 'RecordTypeId') {


text:
Q: Parse Server (express) Error: Can't set headers after they are sent I am using the following function on Parse Server running on NodeChef:
var sendMail = function(sendMailData) {
    return Parse.Cloud.httpRequest({
        method: 'POST',
        url: 'https://api.sparkpost.com/api/v1/transmissions',
        body: {
            content: {
                from: 'noreply@domain.com',
                subject: sendMailData.subject,
                template_id: sendMailData.templateId,
            },
            substitution_data: sendMailData.substitution_data,
            recipients: sendMailData.recipients
        },
        headers: {
            'Authorization': 'AUTHKEY',
            'Content-Type': 'application/json'
        }
    });
}

sendMail(defaultSendMailData).then(function(okresp) {
    var attemptedSend = false;
    if (request.user.get('config')) {
        var userConfig = request.user.get('config')
        if (userConfig.copyPrescription === true) {
            attemptedSend = true;
            sendMail(defaultSendMailData).then(function(okresp) {
                var attemptedSend = false;
                if (request.user.get('config')) {
                    var userConfig = request.user.get('config')
                    if (userConfig.copyPrescription === true) {
                        attemptedSend = true;
                        sendMail(copyPrescriptionSendMailData).then(function(okresp) {
                            console.log('Woohoo! You just sent your first mailing 1!');
                            response.success("Great! Your program has been sent!");
                        }, function(errresp) {
                            console.log('Whoops! Something went wrong 1');
                            console.log(errresp);
                            response.error(errresp);
                        });
                    }
                };
                console.log('Woohoo! You just sent your first mailing 2!');
                if (!attemptedSend) {
                    response.success("Great! Your program has been sent!");
                }
            }, function(errresp) {
                console.log('Whoops! Something went wrong 2');
                console.log(errresp);
                response.error(errresp);
            });
        });
    }
});

and getting the following error:
at Immediate.<anonymous> (/bundle/node_modules/express/lib/router/index.js:618:15)
at Immediate.<anonymous> (/bundle/node_modules/express/lib/application.js:232:9)
at next (/bundle/node_modules/express/lib/router/index.js:271:10)
at Function.process_params (/bundle/node_modules/express/lib/router/index.js:330:12)
at /bundle/node_modules/express/lib/router/index.js:280:7
at trim_prefix (/bundle/node_modules/express/lib/router/index.js:312:13)
at Layer.handle [as handle_request] (/bundle/node_modules/express/lib/router/layer.js:95:5)
at jsonParser (/bundle/node_modules/parse-server/node_modules/body-parser/lib/types/json.js:94:7)
at next (/bundle/node_modules/express/lib/router/index.js:271:10)
at Function.process_params (/bundle/node_modules/express/lib/router/index.js:330:12)
at /bundle/node_modules/express/lib/router/index.js:280:7
at trim_prefix (/bundle/node_modules/express/lib/router/index.js:312:13)
at Layer.handle [as handle_request] (/bundle/node_modules/express/lib/router/layer.js:95:5)
at allowCrossDomain (/bundle/index.js:439:9)
at ServerResponse.header (/bundle/node_modules/express/lib/response.js:719:10)
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
Error: Can't set headers after they are sent.

Whilst the function seems to work, I'm concerned about this error and where it is coming from. I don't believe that this was the case on Parse.com (where i was using this exact same code). This error doesn't show up in my Parse.com logs. Any assistance on making my Parse Server production  deployment actually stick this time (3rd time of trying!) would be great appreciated.

A: Thanks to all comments above in trying to resolve this. I have been contacted by Node Chef who said this:

The error was been cased by a 2.2.17 parse server update on saturday.
Other users noticed it and reported it and we had to roll back back
  the updates.
Currently, auto updates have been turned off and you can manually
  update the server anytime from server settings > runtime settings
  after you are confident the new version will work well with your app.

The rollback has worked and I don't have any errors now.


text:
Q: Aggregation by substring in Mongo I have a set of objects like:
{
  "_id":"mongoid",
  "requests": {
     "uri": "test.php",
     "clicks" : 15
   },
},
{
  "_id":"mongoid",
  "requests": {
     "uri": "test.php/",
     "clicks" : 10
   }
}

Is it possible to make aggregation by field requests.uri ("test.php" and "test.php/" must be understood by Mongo as the same) to get clicks in sum 25? Mongo version is 3.2.
I watch here, but the main difference is that uri can have various length.
Thanks to everybody for help.


text:
Q: Have a file appear in multiple folders I have 50+ folders, each of which contain a large amount of data that needs to be processed. All of them are processed using the exact same code, utilizing os.path.dirname(os.path.realpath(file)) to get the directory in which the python script is located so there is no manual editing needed by the user, they just need to double click.
I need the script to appear to be in each folder while actually only being in 1 place, so I can edit it once and then when it is run from any of these locations have the folder path be correct. The alternative is editing the master and then pasting one folder at a time though all 50+ folders any time I update the code, which is very very tedious and error prone. On Linux I could set this up with a symbolic link, but I can't figure out a way to do it on windows.
Alternately, a way to paste the file into all the target directories at once, instead of one at a time, would accomplish the same goal.

A: You need a symbolic link or a hard link.
Symbolic links (or symlinks for short) are quite similar to shortcuts: there's one actual file and multiple references (symlinks) to it. They even have that little arrow icon on them. Unlike shortcuts, symlinks can have any extension.
Hard links bind file on a hard drive to a location in the directory tree. Each file has at least one hard link, otherwise it wouldn't exist in any directory. If a file has multiple hard links, the original one cannot be distinguished and the file physically exists in only one location.
Both have their limitations:

*

*Some software doesn't play nicely with symlinks

*Deleting original file leaves all its symlinks broken

*You cannot hard link folders (but you can create a directory junction if symlink is not enough)

*Creating cross-partition hard links is impossible

Symlinks are usually sufficient.
To create a symlink or a hard link:

*

*Launch privileged command line: press Win, type cmd, press Ctrl+Shift+Enter

*Issue mklink command:

*

*mklink link_name link_target for file symlink

*mklink /d link_name link_target for folder symlink

*mklink /h link_name link_target for file hard link

*mklink /j link_name link_target for directory junction

A: On Win Vista and newer, you can create sym links or hard links, which behave as you'd expect on Linux. You can create a hard link or sym link by using the MKLINK command built in Windows Visa and newer. (Making sym links require admin privilege.)
Or, for the alternative you mentioned, if the folders are simply the immediate subfolders of the folder where the script resides, you can do in the command prompt at the script's folder:
for /d %D in (*) do (copy /y "myscript.py" "%D")

to update them in one go. If writing this command in batch, you need to use the following code instead:
for /d %%D in (*) do (copy /y "myscript.py" "%%D")


text:
Q: Azure DevOps pipelines resource trigger not working I have an Azure DevOps pipeline (Pipeline1) that should be triggered when another (Pipeline2) completes. To that end I have implemented a pipelines resource as described in the documentation -

*

*Trigger one pipeline after another

*YAML schema reference
However, it's simply not working. In reality Pipeline2 will be triggered when a new PR is created or manually. I've tested creating a new PR, updating a PR several times, and several manual runs, but no matter what I do Pipeline1 will not trigger.
I've tried two of the examples as defined in the YAML schema reference, and reading further into the Trigger one pipeline after another document, I've tried to prefix the all branches wildcard with refs/heads/.
What must I do to get this working?
What I've tried
Without any branchs explicitly defined -
resources:
  pipelines:
    - pipeline: pipeline2
      source: Pipeline2
      trigger: true

With all branches explicitly defined -
resources:
  pipelines:
    - pipeline: pipeline2
      source: Pipeline2
      trigger:
        branches:
          - "*"

Prefixed the all branches wildcard with refs/heads/ -
resources:
  pipelines:
    - pipeline: pipeline2
      source: Pipeline2
      trigger:
        branches:
          - refs/heads/*

Update
It seems that sadly the pipelines resource does not work on PR's. Why That's the case, I couldn't tell you.
After some further investigation I stumbled across the Incoming Webhook Service Connection in a sprint update. This update is from six months ago and at the time of writing nothing has been added to the YAML schema reference.
However, it turns out that this feature just doesn't work full stop, and even if it did it looks like it will only trigger the default branch of a pipeline, which is no good for us (and probably no good for most use cases).
I did eventually find some documentation on GitHub from a year ago, but unfortunately this only seems to confirm that the Incoming Webhook Service Connection is of no use to us in this case.

A: This answer solved it for me.
I had a main and dev branch, and the target pipeline yaml file was not yet pushed up to main. The "Default branch for manual and scheduled builds" in the target pipeline must contain the source file in order for the pipeline to be triggered automatically. (The version of the pipeline that will actually be triggered will be the branch that triggered the original pipeline, as long as they are in the same project.) I changed the value to dev and that solved it.
You can change this setting by going to Edit/Triggers/Yaml/Get sources:

A: For me works this
resources:
  pipelines:
  - pipeline: build_pipeline
    source: kmadof.devops-manual (14)
    branch: master
    trigger:
     branches:
     - '*'

steps:
- bash: env | sort
- task: Bash@3
  inputs:
    targetType: 'inline'
    script: |
      echo 'Hello world'

So in your case I would try this:
resources:
  pipelines:
    - pipeline: pipeline2
      source: Pipeline2
      branch: master
      trigger:
        branches:
          - '*'

A: The Pipeline2 is triggered by PR, so the source branch (Build.SourceBranch) that triggers the pipeline run is the PR merge branch (refs/pull/{PR_ID}/merge).
I also have tested with the 3 ways you posted above, and only the first way can work as expected.
According to my further investigation, it seems that the branch filters on the pipeline resource trigger are only available to the repository branches that you can see on the 'Repos/Branches' page. These branches have the same prefix 'refs/heads/'. The PR merge branch (refs/pull/{PR_ID}/merge) seems is not included.
In your case, the first way should can work. You need to check with the following things:

*

*Make sure you have specified the correct pipeline name of Pipeline2 to the 'source' key.

*Check whether Pipeline1 and Pipeline2 are in the same project. If not, make sure you have used the 'project' key to specify the correct project where Pipeline2 is in, and make sure the projects are in the same organization.


text:
Q: handwaving substitution in integral involving branch cut and derivative of sqrt + generalization Want to compute
$$ I = \int_0^i \mathrm{d}z \frac{z}{\sqrt{z^2-1}}$$
on the complex plane using complex methods.
QUESTION: is the result $i \left( \sqrt{2}-1 \right)$ which one gets imposing $\arg\in[0,2\pi)$ the only possible one?
Perhaps, I can post here a GENERALIZATION of my previous question:
Prove that one can define a branch of the function $\sqrt{1-z^2}$ in every region $D\subset \mathbb{C}$ such that the points $-1$ and 1 belong to the same connected component of the complement of $D.$
How many values can the integral
$$\int_\gamma \frac{\mathrm{d}z}{\sqrt{1-z^2}}$$
take along a closed path $\gamma$ contained in $D$ ?

A: The integrand has a primitive $\sqrt{z^2-1}$. That said, you need to be careful with the being on a consistent branch of the square root throughout the integration interval.  Other than that, it doesn't matter what the contour is.
Assume we are on a branch of the square root such that $\sqrt{-1}=i$.  Then the integral is
$$  \sqrt{-2}-\sqrt{-1} = (\sqrt{2}-1) i$$
EDIT
What if we do cross a branch cut?  Assume we do at $z=i a$ where $0<a<1$.  Then if the second branch is $\sqrt{-1}=-i$, then the integral has value
$$\left (\sqrt{2}-\sqrt{1+a^2}\right) (-i) + \left ( \sqrt{1+a^2}-1\right) i$$


text:
Q: Minimum of $\tan x+\tan y+\tan z$ using Lagrange multipliers for acute angled triangle $\Delta xyz$ Consider an acute angled triangle $\Delta xyz$. Suppose we want to minimise the function $f(x,y,z)=\tan x+\tan y+\tan z$. So as per the method of Lagrange multipliers here is what I did.

$$\begin{aligned}&\text{minimise}: f(x,y,z)=\tan x +\tan y+\tan z \\ &\text{given: }x+y+z=\pi \end{aligned}$$

$$\begin{aligned}\sec^2 x&=\lambda\\ \sec^2 y&=\lambda \\ \sec^2 z&=\lambda\end{aligned}$$
Now we have the constraint $x+y+z=\pi$ and $0\lt x,y,z\lt \pi/2$. Also do have $4$ unknowns and $4$ equations to solve for $x,y,z,\lambda$. But I am not clear on how to use these equations, managing the $\pm$ signs when we take square roots. Besides if it was not given that $\Delta xyz$ is acute angled, then the minimum would have been in the case of a degenerate triangle when any one of the angles is $0$ and others add up to $\pi$, in which case, $f(x,\pi-x,0)=0$, but I do not understand the jump from $0$ to $3\sqrt{3}$ either for the minimum. Can it not attain values in $(0,3\sqrt{3})$? Why? . Any hints are appreciated. Thanks.

A: To handle this problem with the Lagrange Multipliers method, we need first of all, convert the inequalities into equations so with the help of slack variables $(s_x,s_y,s_z,e_x,e_y,e_z)$ the formulation could be
$$
\min_{x,y,z} \tan x + \tan y + \tan z\ \ \  \text{s. t.}\cases{x+y+z=\pi\\
x = s_x^2\\
y = s_y^2\\
z = s_z^2\\
\frac{\pi}{2}-x = e_x^2\\
\frac{\pi}{2}-y = e_y^2\\
\frac{\pi}{2}-x = e_z^2\\
}
$$
and the corresponding lagrangian
$$
L = \tan x + \tan y + \tan z + \lambda(x+y+z-\pi)+\sum_{k=\{x,y,z\}} \eta_k(k-s_k^2)+ \sum_{k=\{x,y,z\}} \mu_k\left(\frac{\pi}{2}-k-e_k^2\right)
$$
so the set of stationary points for $L$ could contain the solution. Now the minimization problem has the variables $\{x,y,z,\lambda,\eta_k,\mu_k,s_k,e_k\},\ \ k=\{x,y,z\}$. Also, to avoid algebraic problems to obtain the solutions for equations involving trigonometric functions, we can use
$$
\tan x\approx x + \frac{x^3}{3}
$$


text:
Q: React Router Dom v4 Multiple Nested Routes On Home Activeclass I need multiple nested routes in react-router-dom in home Page
--- Home
--- Page 1
--- Page 2
--- About
I have home page that contains two subs the active class will be worked based the path Home/HomeNested page This my requirement.
But It work on The home page is active on page load if I click  nested homepage page the home page active gone.
code sandbox Link:https://codesandbox.io/s/react-router-nesting-forked-71x4z?file=/example.js

A: I've debuged your code a bit. You've missed exact on '/' path. Please check nesting routes I've made in /topics/[route] for you here:
sandbox
Thank you for example of NavLink. I didn't even know about this component from react-router :p


text:
Q: Добавление модели (Relationships Laravel) Три таблицы.
users, verification_types, - хранит id, name и slug. Например, id = 1, name = 'Подтверждённый', slug = 'verificated'. users_verifications - id, user_id (связь с users`.`id), verification_id (связь с verification_types`.`id.
Хочу, чтобы при регистрации пользователя, можно было одной строчкой добавить запись в таблицу users_verifications запись по типу: id = USER_ID, verification_id = 1
Можно ли как-то параллельно записать данные путём отношений таблиц?
Имеются миграции, помимо стандартной таблицы users:
Таблица verification_types (Уровни верификации по типу: 1 = Гость, 2 = Подтвержден E-Mail и т.д.)
Schema::create('verification_types', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->comment('Название уровня верификации');
        $table->string('slug')->comment('Системное название');
        $table->timestamps();
    });

Таблица users_verifications (Верификации по типу: user_id:1, verification_id:3 = Подтверждён номер и E-Mail и т.д.)
Schema::create('users_verifications', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned()->comment('ID пользователя');
        $table->integer('verification_id')->unsigned()->comment('ID типа верификации');
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('verification_id')->references('id')->on('verification_types')->onDelete('cascade');
    });

Модель VerificationTypes
class VerificationTypes extends Authenticatable
{
    ...

    public function userVerification() {
        $this->belongsToMany('App/User');
    }
}

Модель User
class User extends Authenticatable
{
    use Notifiable;
    use HasRoleAndPermission;

    ...

    /**
     * User -> Тип верификации
     */
    public function verificationStatus() {
        $this->belongsToMany('App\Entities\User\VerificationTypes', 'users_verifications', 'user_id', 'verification_id');
    }
}

Контроллер RegisterController
class RegisterController extends Controller
{

...

    protected function create(array $data)
    {
        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);

        $role = Role::where('slug', '=', 'guest')->first(); // Прикрепляем роль к пользователю
        $user->attachRole($role);

        /*
         * Прикрепляем уровень верификации
         */
        $user->verificationStatus()->attach([$user->id, 1]);

        return $user;
    }
}

Заранее спасибо!
Версия Laravel: 5.x

A: Исправлено!
Ошибка была в том, что забыл в моделях return.
Потом, в таблицу добавлялись две записи. id=USER_ID, verification_id=1 и id=USER_ID, verification_id=USER_ID
Тогда просто вместо

$user->verificationStatus()->attach([$user->id, 1]);

Сделал:
$user->verificationStatus()->attach([1]);


text:
Q: ATS iOS 9: how to enable MAMP to TLS 1.2 Up to few days ago I was developing my iOS 8 app but this morning my XCode updated to version 7 and iOS simulator to iOS 9. So, in order to meet iOS9 ATS requirements I must update MAMP so that it supports TLS 1.2 and the other requirements. Up to now I haven't found anything useful to me, so I would like to ask if you can explain me hot to set MAMP in order to support iOS9 ATS and TLS 1.2. The URLs my app is trying to use are like the following:
https://localhost:443/excogitoweb/mobile/loginM.php

They perfectly work if I type them in a browser but if I run my app I get this:
2015-09-21 20:55:10.217 ExcogitoWeb[3848:34387] CFNetwork SSLHandshake failed (-9824)
2015-09-21 20:55:10.218 ExcogitoWeb[3848:34387] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9824)

so either I am making a mistake in MAMP configuration of I have missed something but I don't know what. This is what I've done up to now:

*

*create a self signed certificate with sha256 running
openssl req -x509 -nodes -sha256 -days 365 -newkey rsa:2048 -keyout server.key -out server.crt
And configure my httpd-ssl.conf file where I've tried enabling also Forward Secrecy ciphers as required from ATS
In my httpd-ssl.conf file I have something like:
<VirtualHost localhost:443>
  DocumentRoot "/Applications/MAMP/htdocs/protected"
  ServerName localhost
  SSLEngine on
  SSLProtocol all -SSLv2 -SSLv3
  SSLHonorCipherOrder on
  SSLCertificateFile "/Applications/MAMP/conf/apache/server.crt"
  SSLCertificateKeyFile "/Applications/MAMP/conf/apache/server.key"
      SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
</VirtualHost>

I also have  configured in the same way.
So, when I run my app it crashes with the error mentioned above, the error code 9824  which, according to what I have read here, means an error about TLS protocol handshaking. So I am afraid my MAMP 3.3 free in not running TLS 1.2.
Would someone please help me and tell me what I'm missing?
Thanks to all for your attention
UPDATE
I've just tried with
SSLProtocol +TLSv1.2

and now the Apache server won't start anymore. Nothing is written on the log. Do I need to update ssl on my MAC Yosemite? How?
Anyway, restoring with
SSLProtocol all -SSLv2 -SSLv3

this is what I get from my browser if I type https://localhost

so MAMP still uses TLS 1.0... is there a way to force it?


text:
Q: Как реализовать опрос множества серверов на erlang? Здравствуйте, у меня мало опыта в erlang, но возникла острая необходимость в опросе множества серверов по протоколам udp и tcp. С чего начать, в какую сторону копать? Я начал уже изучать erlang, но многое еще непонятно, в сети очень мало практической информации.

A:
но возникла острая необходимость в опросе множества серверов по протоколам udp и tcp

Вам нужно будет для каждого сервера создать отдельный процесс, который его будет опрашивать. Процесс удобнее всего создать с помощью gen_server, и подсоединить его как child к какому-нибудь supervisor.
На этом erlang-специфика здесь исчерпывается, в остальном всё будет также как и на любом другом языке.


text:
Q: Multi-tenant Heroku app with SSL + GoDaddy SSL on custom domains I have a multi-tenant Heroku app running Ruby on Rails with a wildcard SSL certificate on *.xyz.com which serves https://customer1-app.xyz.com securely & as expected. The problem is I can't add a GoDaddy SSL certificate to a custom domain (customer1.com) also at Godaddy pointing to one of the subdomains (customer1-app.xyz.com).
The approach I'm trying is fully described at here: https://help.heroku.com/8P5TVA4T/how-can-i-configure-multiple-ssl-certificates-for-a-single-app
Simply put:

*

*I created a shell application customer1-endpoint on Heroku

*I added the SSL-Endpoint addon & installed the certificated bought
from GoDaddy on the shell application

*I copied the endpoint (DNS target - abc.ssl.herokudns.com) from the Heroku CLI to theCNAME
record of GoDaddy

*I added the custom domain (customer1.com, www.customer1.com) to my main production (xyz.com)
Heroku app

When I try to access https://www.customer1.com/ I receive a "No such app" message on Heroku.
Any ideas what's going on wrong?

A: For anyone coming through Google, my issue was that I had my SSL-endpoint in a different region than my main app. This approach works, make sure that both apps are on the same region.

A: SSL Endpoint is deprecated as of July 31st, 2021.