text:
Q: How can I initiate react to reload after a data change on the node js side? So I added a calendar to react which changes the workout data to a specific date.  When I change the date the data does change correctly.  If I refresh the react web pages I get the updated data.  I'm just a little confused on how to have node js initiate the data update in react.  After changing the data I have node emitting to this socket...
import { format } from 'date-fns'
import ScrapeExperienceLevel from './ScrapeExperienceLevel'

export default (websockets, queue, timer, workouts, scrapeExperienceLevel) => {
websockets.on('connection', socket => {
socket.on('joinRoom', roomName => {
  socket.join(roomName)
})
socket.on('leaveRoom', roomName => {
  socket.leave(roomName)
})
setInterval(function(){
  socket.emit('GetCheckedInMemebers', queue.dump());
}, 3000);
socket.on('initScreen', screen => {
  const screenWorkouts = workouts.current.filter(workout => workout.station == screen)

  socket.emit('screenInfo', screenWorkouts)
  socket.emit('queueInfo', queue.screen(screen - 1))
  socket.emit('timer', { time: timer.formatTime().formattedTime })
})

//  code in question
socket.on('GetWorkoutDate', async function (date) {
  await workouts.getNewWorkouts(date.date)
  const screenWorkouts = workouts.current.filter(workout => workout.station == 1)
  socket.emit('UpdateWorkouts', screenWorkouts)
})
socket.on('initAdmin', () => {
  socket.emit('queue', queue.dump())
  socket.emit('timer', { time: timer.formatTime().formattedTime })
})
socket.on('initOverview', () => {
  socket.emit('workouts', workouts.current)
  socket.emit('queue', queue.dump())
  socket.emit('timer', { time: timer.formatTime().formattedTime })
})
socket.on('addUser', async (person) => {
  if(typeof person.member_id == 'undefined')
    person.member_id = ''
  else{
    person.experiencelevel = await scrapeExperienceLevel.getExperienceLevel(person.member_id)
    person.firstname = person.firstname + ' '
  }
  queue.add(person, timer)
  websockets.emit('queue', queue.dump())
})
socket.on('removeUser', ({ group, person, list }) => {
  queue.remove(group, person, list)
  websockets.emit('queue', queue.dump())
})
socket.on('reorder', waiting => {
  queue.reorder(waiting)
  websockets.emit('queue', queue.dump())
})
socket.on('toggleTimer', () => {
  if (timer.isRunning()) {
    timer.pause()
  } else {
    timer.start()
  }
})
})
}

Here's my Screen page's react...
import React, { Component } from 'react'
import { defaultTo } from 'ramda'

import './styles.css'

class Screen extends Component {
  state = {
    time: '',
    rest: false,
    workout: [],
    queue: [],
  }

  UpdateTimer = ({ time, rest }) => {
    this.setState({ time, rest })
  }

  UpdateScreenInfo = ({ data }) => {
    this.setState({ workout: defaultTo({}, data[0]) })
  }

  UpdateQueueInfo = ({ data }) => {
    this.setState({ queue: defaultTo({}, data) })
  }

  UpdateQueue = ({ queue, screenNumber }) => {
    this.setState({ queue: defaultTo({}, queue[screenNumber - 1]) })
  }

  componentDidMount() {
    const screenNumber = this.props.match.params.id
    const { socket } = this.props

    socket.on('connect', () => {
      socket.emit('joinRoom', 'screens')
      socket.emit('initScreen', screenNumber)
    })
    socket.on('timer', ({ time, rest }) => this.UpdateTimer({ time, rest }))
    socket.on('screenInfo', data => this.UpdateScreenInfo({ data }))
    socket.on('queueInfo', data => this.UpdateQueueInfo({ data }))
    socket.on('queue', ({ queue }) => this.UpdateQueue({ queue, screenNumber }))
    //socket.on('UpdateWorkouts', (updatedData) => this.UpdateWorkoutsData(updatedData))
  }

  componentWillUnmount() {
    const { socket } = this.props

    socket.off('timer', this.UpdateTimer)
    socket.off('screenInfo', this.UpdateScreenInfo)
    socket.off('queueInfo', this.UpdateQueueInfo)
    socket.off('queue', this.UpdateQueue)
  }

  renderMovement = (movement, equipment) => {
    if (!movement) return

    return (

        {equipment && `${equipment.title} `}
        {movement.title}

    )
  }

  render() {
    const { time, rest, queue } = this.state
    const { workout } = this.props
    const variation = defaultTo({}, workout.variation)
    const person1 = defaultTo({}, queue[0])
    const person2 = defaultTo({}, queue[1])

    return (

            {(() => {
              if (person1.experiencelevel === 'novice') {
                //  light purple
                return (

{person1.firstname}

                )
              } else if (person1.experiencelevel === 'beginner') {
                //   light blue
                return (

{person1.firstname}

                )
              } else if (person1.experiencelevel === 'intermediate') {
                return (

{person1.firstname}

                )
              } else if (person1.experiencelevel === 'advanced') {
                //  gym green
                return (

{person1.firstname}

                )
              }else if (person1.experiencelevel === 'expert') {
                return (

{person1.firstname}

                )
              }
            })()}

          <span className={`screenTimer alt ${rest ? 'rest' : ''}`}>{time ? time : '0:00'}

          {(() => {
              if (person2.experiencelevel === 'novice') {
                //    light purple
                return (

{person2.firstname}

                )
              } else if (person2.experiencelevel === 'beginner') {
                //  light blue
                return (

{person2.firstname}

                )
              } else if (person2.experiencelevel === 'intermediate') {
                return (

{person2.firstname}

                )
              } else if (person2.experiencelevel === 'advanced') {
                //   gym green
                return (

{person2.firstname}

                )
              }else if (person2.experiencelevel === 'expert') {
                return (

{person2.firstname}

                )
              }
            })()}

{variation.title}

          {this.renderMovement(workout.movementOne, workout.equipmentOne)}
          {this.renderMovement(workout.movementTwo, workout.equipmentTwo)}
          {this.renderMovement(workout.movementThree, workout.equipmentThree)}

    )
  }
}

export default Screen

Also found the parent component Daniele enlightened me about.  Now I'm sharing 1 socket connection throughout all the components.
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { path } from 'ramda'
import { connect, Provider } from 'react-redux'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom'
import openSocket from 'socket.io-client'
import { defaultTo } from 'ramda'

import './index.css'
import 'semantic-ui-css/semantic.min.css'

import store from './redux/store'
import Admin from './screens/Admin'
import Screens from './screens/Screens'
import Auth from './screens/Auth'
import BackScreen from './screens/Screens/Back'
import FrontScreen from './screens/Screens/Front'

const socket = openSocket(`http://${window.location.hostname}:${process.env.REACT_APP_WEBSOCKET_PORT}`)

function mapState(state) {
  return {
    loggedIn: path(['conf', 'loggedIn'], state),
  }
}

class App extends Component {
  state = {
    workout: []
  }

  static propTypes = {
    loggedIn: PropTypes.bool,
  }

  componentDidMount() {
    socket.on('UpdateWorkouts', (workout) => { console.log(workout[0]); this.setState({ workout: defaultTo({}, workout[0]) }) })
  }

  render() {
    const { loggedIn } = this.props
    const workout = this.state

    return (
      <BrowserRouter>
        <Switch>
          {!loggedIn && <Route path="/" component={(props) => <Auth socket={socket} {...props} /> }/> }
          <Route exact path="/admin" component={(props) => <Admin socket={socket} {...props} /> } />
          <Route path="/s/back" component={(props) => <BackScreen socket={socket} {...props} /> } />
          <Route path="/s/front" component={(props) => <FrontScreen socket={socket} {...props} /> } />
          <Route path="/s/:id" component={(props) => <Screens {...props} socket={socket} workout={workout} /> } />
          <Redirect to={'/s/1'} />
        </Switch>
      </BrowserRouter>
    )
  }
}

const ConnectedApp = connect(mapState)(App)
const rootEl = document.getElementById('root')
ReactDOM.render(
  <Provider store={store}>
    <ConnectedApp />
  </Provider>,
  rootEl,
)

Here's my Admin page.
import React, { Component, Fragment } from 'react'
import { Button, Grid, Header, Dimmer, Loader } from 'semantic-ui-react'
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import { defaultTo } from 'ramda'

import './styles.css'

import WaitingList from './WaitingList'
import Stations from './Stations'
import AddUserModal from './AddUserModal'

class Admin extends Component {
  state = {
    loading: false,
    time: '',
    rest: false,
    data: {
      waiting: [],
      queue: [],
    },
    startDate: new Date(),
    showAddUserModal: false,
  }

  handleChange = date => {
    const { socket } = this.props

    this.setState({
      startDate: date
    })
    socket.emit('GetWorkoutDate', { date })
  }

  UpdateTimer = ({ time, rest }) => {
    this.setState({ time, rest })
  }

  UpdateQueue = ({ data }) => {
    this.setState({ queue: defaultTo({}, data) })
  }

  GetCheckedInMemebers = ({ data }) => {
    this.setState({ data })
  }

  componentDidMount() {
    const { socket } = this.props

    socket.on('connect', () => {
      socket.emit('initAdmin')
    })
    socket.on('timer', ({ time, rest }) => this.UpdateTimer({ time, rest }))
    socket.on('queue', data => this.UpdateQueue({ data }))
    socket.on('GetCheckedInMemebers', data => this.GetCheckedInMemebers({ data }))
  }

  componentWillUnmount() {
    const { socket } = this.props

    socket.off('timer', this.UpdateTimer)
    socket.off('queue', this.UpdateQueue)
    socket.off('GetCheckedInMemebers', this.GetCheckedInMemebers)
  }

  addPersonToWaitingList = person => {
    const { socket } = this.props

    socket.emit('addUser', person)
  }

  removePersonFromList = (groupIndex, personIndex, list) => {
    const { socket } = this.props

    socket.emit('removeUser', { group: groupIndex, person: personIndex, list: list })
  }

  reorderWaitingList = waiting => {
    const { data } = this.state
    const { socket } = this.props

    this.setState({ data: { ...data, waiting } })
    socket.emit('reorder', waiting)
  }

  toggleTimer = () => {
    const { socket } = this.props

    socket.emit('toggleTimer')
  }

  render() {
    const { loading, rest, time, data, showAddUserModal } = this.state

    return (
      <Fragment>
        change workout date   <DatePicker
        dateFormat="M/d/yy"
        selected={this.state.startDate}
        onChange={this.handleChange}
      />
        <Grid container columns={2} divided id="adminWrapper">
          <Grid.Row className="fGrow">
            <Grid.Column className="listWrapper">

                Queue
                <Button positive floated="right" onClick={() => this.setState({ showAddUserModal: true })}>
                  Add
                </Button>

              <WaitingList
                className="adminList"
                waiting={data.waiting}
                reorder={this.reorderWaitingList}
                removeFromList={this.removePersonFromList}
              />
            </Grid.Column>
            <Grid.Column className="listWrapper">

                Stations

              <Stations className="adminList" queue={data.queue}
                removeFromList={this.removePersonFromList}
              />
            </Grid.Column>
          </Grid.Row>
          <Grid.Row>
            <Button fluid color={rest ? 'red' : 'blue'} onClick={this.toggleTimer}>
              {time ? time : '0:00'}
            </Button>
          </Grid.Row>
        </Grid>
        <AddUserModal
          show={showAddUserModal}
          handleClose={() => this.setState({ showAddUserModal: false })}
          addUser={this.addPersonToWaitingList}
          setLoading={isLoading => this.setState({ loading: isLoading })}
          loading={loading}
        />
        <Dimmer active={loading} page>
          <Loader />
        </Dimmer>
      </Fragment>
    )
  }
}

export default Admin

New to node and react.  Appreciate the guidance!
Edit:  The calendar (date picker) is on another react page.  GetWorkoutDate is being called.  However, react never gets the data from the emit socket.emit('UpdateWorkouts', screenWorkouts).  I verified the everything works correctly except getting the new data to update the react state.
Final Edit:
So for some reason I was not able to send the workout through props for the Screen page.  Although, it is the correct way for react there just must be something going on with my environment.  Here's what I did get working for me.  When Screen page loads it loads the workout.  Then I just added settimeout to repeat getting the workout every 5 secs.
socket.on('initScreen', async screen => {
  setInterval(async function(){
    const screenWorkouts = await workouts.current.filter(workout => workout.station == screen)

    socket.emit('screenInfo', screenWorkouts)
  }, 5000)
  socket.emit('queueInfo', queue.screen(screen - 1))
  socket.emit('timer', { time: timer.formatTime().formattedTime })
})

What's weird is after sending the workout to screens between 3 and 8 times correctly eventually it sends an empty array.  So to prevent the workout from updating when it's empty I check it for length before I try and update the state.
UpdateScreenInfo = ({ data }) => {
  if(data.length !== 0)
    this.setState({ workout: defaultTo({}, data[0]) })

I'm awarding Daniele the points since they are about to expire and Daniele helped so much!

A: The problem is that each time you call openSocket you open a new connection to the server. Looking at your server code it seems that your 'GetWorkoutDate' message handler replies with 'UpdateWorkouts' message on the same socket connection; the problem is that 'UpdateWorkouts' is received by the react component sending the 'GetWorkoutDate' message and not by other react components due they open a new connection each.
The proper way to handle with WebSockets in a react app where more components needs to access the WebSocket is to open it only in the root component and passing it to child components as a property. Something like:
MainComponent extends React.Component {
  componentDidMount() {
    // Open the socket only in the main component
    this.socket = openSocket(...);
  }

  componentWillUnmount() {
    this.socket.close();
  }

  render() {
    return (

        {/* pass the socket as property to child components;
            this can be repeated with all nested sub-component */}
        <ChildComponent socket={this.socket}>

    )
  }
}

ChildComponent extends React.Component {
  componentDidMount() {
    const { socket } = this.props;

    // create the required handlers and store them
    this.handler = data => { /* do what you need with data */ };

    // add the handlers to the socket
    socket.on("message", this.handler);
  }

  componentWillUnmount() {
    const { socket } = this.props;

    // remove the handlers from the socket
    socket.off("message", this.handler);
  }
}

By this way you open a single connection and you share it between all components, now you can send messages to the server from a component and handle the response message on any other component.
Edit after last question update:
Two things:

*

*the parent component is the root App component ok, but I can't still understand which is the component which emits the 'GetWorkoutDate' message (I was thinking it was the Screen 's parent component, but it seems I'm wrong); probably to find final solution we need to clarify this;

*you are passing the socket (as a property) to the Route component, not to the Screen component: you need to change your routes as follows

<Route path="/s/:id" component={() => <Screens socket={socket} />} />
I checked better last version of your Screen component: you can't do this in componentDidMount method:
socket.on('timer', ({ time, rest }) => this.setState({ time, rest }))

you need to store the reference of the handler function in order to remove it later in componentWillUnmount method.
You can't do this in componentWillUnmount method:
socket.close();

now you have only one connection shared between all components of your app, if you close it once, you close it forever.
The strategy is: in componentDidMount method:

*

*for each message (or more on general for each event), to create a handler function and store its reference

*attache the referenced handler function to the desired message (or more in general, to the desired event)

then, in componentWillUnmount method:

*to detach the handler function (throug the reference we still have) from the message (or more in general from the event),

by this way each time the component is mounted it starts listening on the desired messages/events, each time the component is unmounted it stops doing it and no actions will be performed on it while not mounted be the message/event handlers.
Edit:

*

*Having circular import dependency is a bad idea: it's better to remove any var App = require('./index') (or similar) from child component files

*But moreover, if the purpose of handleChange is only to emit something on the ws you don't need a so complicated design pattern: you can access the socket from Admin Component.

Probably what you need is
class App extends Component {
  componentDidMount() {
    // App component will never unmount: the reference for unmounting is not required
    socket.on('UpdateWorkouts', ([workout]) => this.setState({ workout }));
  }

  render() {
    const { workout } = this.state;

    return (
      ...
      <Route path="/s/:id" component={props => <Screens {...props, socket, workout} />} />
      ...
    );
  }
}

class Screen extends Component {
  render() {
    const { time, rest, queue } = this.state;
    const { workout } = this.props;
    ...
  }
}

A: You are calling componentDidMount function when socket emits UpdateWorkouts which is causing the loop. You should not call componentDidMount function of a react component, react handles the lifecycles methods itself. You can have another method to handle updates as following.
handleUpdateWorkouts = (updatedData) => {
   //Update your workout, queue etc. whatever you update
   this.setState({updatedData})

}

And assign this function as callback to on "UpdateWorkouts" events.
this.socket.on('UpdateWorkouts', (updatedData) => this.handleUpdateWorkouts(updatedData));

A: *

*Make sure you are emitting GetWorkoutDate properly upon the calendar onChange.

this.socket.on('GetWorkoutDate', date); //something like this

*If getNewWorkouts function is an async, then use await
socket.on('GetWorkoutDate', async function (date) {
    await workouts.getNewWorkouts(date.date) //<----- here
    const screenWorkouts = workouts.current.filter(workout => workout.station == 1)
    console.log(screenWorkouts[0])
    socket.emit('UpdateWorkouts', screenWorkouts)
  })

A: I do have one solution at architect level which is, Return synchronous actions from the nodeJs sockets. So the moment client receive it, just dispatch the action received via socket and then automatically update it.
For eg: if socket returns
{
  type: 'actionName',
  data
}

then dispatching it directly would result in auto update of subscribed components.


text:
Q: Problems with parsing a .csv file in c using commas I am using this code to parse a .csv file in C.
It works if the fields are in this format
ENTRY1,ENTRY2,ENTRY3,ENTRY4
or even if there are commas here:
ENTRY1, ENTRY2, ENTRY3, ENTRY4
However, if after an entry and before a comma there is a space, the program crashes. Like so: ENTRY1 ,ENTRY2,ENTRY3,ENTRY4
CODE:
#include <stdio.h>
#include <string.h>

int main()
{
        FILE *input_fp =fopen("file", "r");
        char buf[100];

        while (fgets(buf, sizeof buf, input_fp) != NULL) {
                char field1[30], field2[30], field3[30], field4[30];
#define VFMT " %29[^ ,\n\t]" //Defines limit of one entry to be 30 characters
                int n; // Use to check for trailing junk

                if (4 == sscanf(buf, VFMT "," VFMT "," VFMT "," VFMT " %n", field1, field2,
                                field3, field4, &n) && buf[n] == '\0') {
                        // Suspect OP really wants this wfield1th to be 1 more
                        if (printf("%s %s %s %s\n", field1, field2, field3, field4) < 0)
                                break;
                } else
                        break; // format error
        }
        fclose(input_fp);
return 0;
}

Example run:
file contains:
ENTRY1, ENTRY2, ENTRY3, ENTRY4
ENTRY5,ENTRY6,ENTRY7,ENTRY8
ENTRY5 , ENTRY6, ENTRY7, ENTRY8
ENTRY1, ENTRY2, ENTRY3, ENTRY4

the output is:
ENTRY1 ENTRY2 ENTRY3 ENTRY4
ENTRY5 ENTRY6 ENTRY7 ENTRY8

it stops before concluding the third line and exits.

A: Going by your example and the expected output, I would prefer to use fgetc to process the input character in place.
This would allow us to parse and reject unwanted characters,thus avoiding the overhead of storing data- as in fgets and then parsing the stored data.
The result (fputc)could be directed to a file as well...
The code would look like this.....Hope this helps......
#include <stdio.h>

int main()
{
  FILE *input_fp =fopen("file", "r");
  int c;
  while ((c=fgetc(input_fp)) != EOF)
   {
      if(c == ' ' || c == '\t')//if space or tab
        ;                      //do nothing
      else
        fputc(c,stdout); //print c
   }
  fclose(input_fp);
  return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the permissions for an existing user in hdfs on linux I am new to Hadoop and I've run across an issue I'm not sure how to solve.
I have two existing HDFS users: one called hdfs and one called user1. When I write a file to HDFS as user1, both users can see and delete the files. However if I add the file as the user hdfs, user1 throws a file not found error when I try to use it. Why would one user be able to edit a file while the other can't? Is there anything I can do to allow user1 to also be able to edit the file?
Here are the permissions for the users:
hdfs  = drwxr-xr-x
user1 = drwxrwxr-x

I am running HDFS as part of OpenJDK 1.8 on CentOS 6.6

A: hdfs is super-user who is not restricted by permission checks and can particularly access files of other users, like user1
chmod can be done as follows: hdfs dfs -chmod XXX /dir

A: hdfs user is a super user, so whenever you copy a file as hdfs, other uses cannot see. if you want to see those file you have to execute command as like below
sudo -u hdfs hdfs dfs -cat /path/
user1 is a normal user, so whenever you copy a file as user1, hdfs user can have access to those files
yes, there is command like below to change groups, users, owners, etc
hdfs dfs chgrp
hdfs dfs chmod
hdfs dfs chown

A: HDFS is the super-user here so it has access to all the files but if you want to see the file which has user and group as hdfs through user1 then you can't able to see directly.
Firstly you need to change the user and group of that file then only you can able to see that file.
For changing the owner and group of that file use the below commands :-
hadoop fs -chown [-R] [OWNER][:[GROUP]] URI [URI ]


text:
Q: React select check on key down event whether menu is open or closed I am using react-select in my project for the select elements.
I wonder if there is a way to check on keydown event in the select (can be both the select input or on the menu) if the menu is open or closed.
I am using react select version ^2.4.2, and have to support explorer.
P.S: for whoever is not familiar with the react-select library: it doesnt create typical HTML 'select' and 'option' elements, but rather a text input and on each click (or some dedicated keydown events (accessibility)) on the input/menu - it toggles a div with the options.
Thank you!

A: found the answer for it - I am using the built in onMenuClose and onMenuOpen props to toggle a custom attribute (e.g. 'is-open') value between true/false on the input.


text:
Q: C++11 result_of deducing my function type failed I was trying a program below:
#include<type_traits>
using namespace std;
template <class F, class R = typename result_of<F()>::type>
R call(F& f) { return f(); }
int answer() { return 42; }

int main()
{
    call(answer);
    return 0;
}

"call(answer)" fails to compile
VC says 'R call(F&)' could not deduce template argument for 'R'
GCC says |note:   template argument deduction/substitution failed:|error: function returning a function
I'm not sure if a "function name" could be used for templates. Where did I get wrong, how to make my call(answer) work?

A: You are calling f as an lvalue, so:
template <class F, class R = typename result_of<F&()>::type>
//                                               ^
R call(F& f) { return f(); }

A: You can use forwarding references in these cases:
#include<type_traits>
#include<utility>
#include<cassert>

using namespace std;

template <class F, class R = typename result_of<F()>::type>
R call(F&& f) { return std::forward<F>(f)(); }

int answer() { return 42; }

int main()
{
    assert(call(answer) == 42);
    return 0;
}

It usually avoids troubles.
That said, why your code doesn't work is nicely explained by @T.C. in his answer.
See also the comments to this question for further details.

A: I suppose you could avoid the second template argument and use a combination of auto and decltype().
Something like
#include<type_traits>

using namespace std;

template <class F>
auto call(F& f) -> decltype( f() )
 { return f(); }

int answer()
 { return 42; }

int main()
{
    call(answer);

    return 0;
}

If you (when you) can use C++14, you can use simply auto
template <class F>
auto call(F& f)
 { return f(); }

p.s.: sorry for my bad English.


text:
Q: Check if in a set of numbers, a number n is equal to sum of its subset I have an array :
$permissionVals = array (1,2,4,8,16,32);

and a variable
$effectivePermission = 13;

I need to check whether this variable is equal to sum of any subset of the given array of numbers in an optimized way.
Subset sum doesn't seems to work for me here.
Thanks

A: Assuming that $permissionVals contains always powers of 2, you can use the bit comparison:
$permissionVals = array(1,2,4,8,16,32);
$target = 13;
$res = array();

foreach ($permissionVals as $val) {
    if ($target & $val) $res[] = $val;
}

if (array_sum($res) == $target)
    print_r($res);
else
    echo 'the message you want';

A variant that will stop the foreach loop when the sum is reached. (useful if $permissionVals is big):
$sum = 0;
$message = 'the message you want';

foreach ($permissionVals as $val) {
    if ($target & $val) {
        $res[] = $val;
        $sum += $val;
    }
    if ($sum == $target) {
    $message = '';
    print_r($res);
    break;
    }
}

echo $message;

A: Thanks for your replies
I tried various ways. And was finally able to get it work :
<?php

    $gcount = 0;

    $set = array(1,2,4,8,16,32);

    $needle = 33;
    $sum = 0;

    foreach ($set as $k => $v){
        $sum += $v;
    }

    function evaluate_array($s, $sum){
        $arr = array();
        $arr[0] = 0;

        foreach ($s as $k => $v) {
            for( $i = 0; $i <= $sum; $i++){
                if( isset($arr[$i]) ){
                    if( $arr[$i] != $v && $i + $v < $sum){
                        if( !isset($arr[$i + $v]) ){
                            $arr[$i + $v] = $v;
                        }
                    }
                }
            }
        }

        return $arr;
    }

    function solve($set, $sum, $needle){
        $stack = evaluate_array($set, $sum);

        while ($needle > 0){
            echo $stack[$needle] . "
";
            $needle -= $stack[$needle];
        }
    }

    function brute_force($set, $needle){
        global $gcount;
        $gcount++;
        $sub = array(
            'found' => false
            , 'vals' => array()
            );

        $workset = $set;

        foreach($workset as $k => $v){
            if( $v == $needle){
                $sub['found'] = true;
                array_push($sub['vals'], $v);
                return $sub;
            }else{
                array_shift($workset);
                if( $needle - $v < 0){ return $sub; }
                $r = brute_force($workset, $needle - $v);
                if( $r['found'] ){
                    array_push($r['vals'], $v);
                    return $r;
                }
            }
        }

        return $sub;

    }

    function solve_bf($set, $needle){
        global $gcount;
        $sub = brute_force($set, $needle);
        $sum = 0;
        foreach($sub['vals'] as $k => $v){
            echo $v . "
";
            $sum += $v;
        }

        echo "
Sum: " . $sum;
        echo "
# Recursions: " . $gcount;
    }

    //solve($set, $sum, $needle);
    solve_bf($set, $needle);

?>

If $sum = 0, then no such subset exists.
(Ref. : https://github.com/burento/Subset-Sum-Problem/commit/ba549a8e67d6495fdaffafcd2e51833b7b6a57d4)


text:
Q: Error after running "sbt test" in Chisel 3 I'm trying to use chisel 3.
I tried to test GCD.scala file in the chisel project template repo using sbt test and sbt "test-only example.GCD" commands following the answer to a previous question. But this gives an error(s) that I cannot find the reason for. I didn't do any changes to the build.sbt file or repo layout. I'm posting only the last part of the error message since it is very long and repetitive.
[info] Loading project definition from /home/isuru/fyp/ChiselProjects/TrialProject/project
[info] Set current project to chisel-module-template (in build file:/home/isuru/fyp/ChiselProjects/TrialProject/)
[info] Compiling 1 Scala source to /home/isuru/fyp/ChiselProjects/TrialProject/target/scala-2.11/classes...
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:5: not found: object Chisel3
[error] import Chisel3._
[error]        ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:7: not found: type Module
[error] class GCD extends Module {
[error]                   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:8: not found: type Bundle
[error]   val io = new Bundle {
[error]                ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:9: not found: value UInt
[error]     val a  = UInt(INPUT,  16)
[error]              ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:9: not found: value INPUT
[error]     val a  = UInt(INPUT,  16)
[error]                   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:10: not found: value UInt
[error]     val b  = UInt(INPUT,  16)
[error]              ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:10: not found: value INPUT
[error]     val b  = UInt(INPUT,  16)
[error]                   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:11: not found: value Bool
[error]     val e  = Bool(INPUT)
[error]              ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:11: not found: value INPUT
[error]     val e  = Bool(INPUT)
[error]                   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:12: not found: value UInt
[error]     val z  = UInt(OUTPUT, 16)
[error]              ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:12: not found: value OUTPUT
[error]     val z  = UInt(OUTPUT, 16)
[error]                   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:13: not found: value Bool
[error]     val v  = Bool(OUTPUT)
[error]              ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:13: not found: value OUTPUT
[error]     val v  = Bool(OUTPUT)
[error]                   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:15: not found: value Reg
[error]   val x  = Reg(UInt())
[error]            ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:15: not found: value UInt
[error]   val x  = Reg(UInt())
[error]                ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:16: not found: value Reg
[error]   val y  = Reg(UInt())
[error]            ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:16: not found: value UInt
[error]   val y  = Reg(UInt())
[error]                ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:17: not found: value when
[error]   when   (x > y) { x := x - y }
[error]   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:18: not found: value unless
[error]   unless (x > y) { y := y - x }
[error]   ^
[error] /home/isuru/fyp/ChiselProjects/TrialProject/src/main/scala/example/GCD.scala:19: not found: value when
[error]   when (io.e) { x := io.a; y := io.b }
[error]   ^
[error] 20 errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Dec 1, 2016 8:26:25 PM

A: The errors you have shown suggest that sbt is somehow not finding Chisel, could you by chance show the full list of errors (especially early on ones)? With the following sequence of commands I am unable to reproduce the errors you are seeing:
git clone git@github.com:ucb-bar/chisel-template.git
cd chisel-template
sbt test

It is not the cause of this issue, but to run the test in chisel-template you should actually run sbt "test-only examples.test.GCDTester". example.GCD is the top of the design, but to run the test you have to refer to the Tester class in src/test/scala/examples/test/GCDUnitTest.scala.

A: I just encountered this same problem when making my own chisel project. However it was not that the import chisel3._ was wrong. The problem I had was I did not have a build.sbt file included in my directory.
I found my solution here.
https://chisel.eecs.berkeley.edu/2.0.6/getting-started.html


text:
Q: Change Capistrano strategy I want to change the default strategy that Capistrano uses to Copy. For this I have included the following line in the Capfile
set :strategy, Capistrano::Deploy::Strategy::Copy.new(self)

But it throws an exception
Capfile:17:in `load': uninitialized constant Capistrano::Deploy::Strategy::Copy (NameError)

A: How is this?
set :deploy_via, :copy

refs: https://github.com/capistrano/capistrano/blob/master/lib/capistrano/recipes/deploy.rb#L46


text:
Q: Lightweight wrapper - is this a common problem and if yes, what is its name? I have to use a library that makes database calls which are not thread-safe. Also I occasionally have to load larger amounts of data in a background thread.
It is hard to say which library functions actually access the DB, so I think the safest approach for me is to protect every library call with a lock.
Let's say I have a library object:
dbLib::SomeObject someObject;

Right now I can do something like this:
dbLib::ErrorCode errorCode = 0;
std::list<dbLib::Item> items;
{
    DbLock dbLock;
    errorCode = someObject.someFunction(&items);
} // dbLock goes out of scope

I would like to simplify that to something like this (or even simpler):
dbLib::ErrorCode errorCode =
    protectedCall(someObject, &dbLib::SomeObject::someFunction(&items));

The main advantage of this would be that I won't have to duplicate the interface of dbLib::SomeObject in order to protect each call with a lock.
I'm pretty sure that this is a common pattern/idiom but I don't know its name or what keywords to search for. (Looking at http://www.vincehuston.org/dp/gof_intents.html I think, it's more an idiom than a pattern).
Where do I have to look for more information?

A: You could make protectedCall a template function that takes a functor without arguments (meaning you'd bind the arguments at the call-site), and then creates a scoped lock, calls the functor, and returns its value. For example something like:
template <typename Ret>
Ret protectedCall(boost::function<Ret ()> func)
{
    DbLock lock;
    return func();
}

You'd then call it like this:
dbLib::ErrorCode errorCode = protectedCall(boost::bind(&dbLib::SomeObject::someFunction, &items));

EDIT. In case you're using C++0x, you can use std::function and std::bind instead of the boost equivalents.

A: In C++0x, you can implement some form of decorators:
template <typename F>
auto protect(F&& f) -> decltype(f())
{
    DbLock lock;
    return f();
}

usage:
dbLib::ErrorCode errorCode = protect([&]()
{
    return someObject.someFunction(&items);
});

A: From your description this would seem a job for Decorator Pattern.
However, especially in the case of resources, I wouldn't recommend using it.
The reason is that in general these functions tend to scale badly, require higher level (less finegrained) locking for consistency, or return references to internal structures that require the lock to stay locked until all information is read.
Think, e.g. about a DB function that calls a stored procedure that returns a BLOB (stream) or a ref cursor: the streams should not be read outside of the lock.
What to do?
I recommend instead to use the Facade Pattern. Instead of composing your operations directly in terms of DB calls, implement a facade that uses the DB layer; This layer could then manage the locking at exactly the required level (and optimize where needed: you could have the facade be implemented as a thread-local Singleton, and use separate resources, obviating the need for locks, e.g.)

A: The simplest (and still straightforward) solution might be to write a function which returns a proxy for the object. The proxy does the locking and overloads -> to allow calling the object. Here is an example:
#include <cstdio>

template<class T>
 class call_proxy
 {
  T &item;
  public:

  call_proxy(T &t) : item(t) { puts("LOCK"); }
  T *operator -> () { return &item; }
  ~call_proxy() { puts("UNLOCK"); }
 };

template<class T>
call_proxy<T> protect(T &t)
{
 return call_proxy<T>(t);
}

Here's how to use it:
class Intf
{
 public:
  void function()
 {
  puts("foo");
 }
};

int main()
{
 Intf a;
 protect(a)->function();
}

The output should be:
LOCK
foo
UNLOCK

If you want the lock to happen before the evaluation of the arguments, then can use this macro:
#define PCALL(X,APPL) (protect(X), (X).APPL)
PCALL(x,x.function());

This evaluates x twice though.

A: This article by Andrei Alexandrescu has a pretty interesting article how to create this kind of thin wrapper and combine it with dreaded volatile keyword for thread safety.

A: Mutex locking is a similar problem. It asked for help here: Need some feedback on how to make a class "thread-safe"
The solution I came up with was a wrapper class that prevents access to the protected object. Access can be obtained via an "accessor" class. The accessor will lock the mutex in its constructor and unlock it on destruction. See the "ThreadSafe" and "Locker" classes in Threading.h for more details.


text:
Q: ModelMetadata.FromStringExpression doesn't work on nested properties I have a complex type in my model with some meta-data;
[ComplexType]
public class ComplexModel
{
    [Display("Name Label")]
    public string Name { get; set; }
}

public class MainModel
{
    // ...

    public ComplextModel ComplexModel { get; set; }
}

This code works correctly;
Html.DisplayFor(model => model.ComplexModel.Name)

But this one doesn't;
Html.Display("ComplexModel.Name")

Even I go farther and find out the problem which is ModelMetadata.FromStringExpression.
ModelMetadata.FromStringExpression("ComplexModel.Name", viewData) returns incorrect result. While ModelMetadata.FromLambdaExpression(expression, viewData) works correctly.
Is it a bug?
I just wanted Html.Display("ComplexModel.Name") to work correctly and return "Name Label" in this example.

A: You have to create a new custom HtmlHelper class that uses a new Model or new ViewData, so :
public static class CustomHtmlHelperExtensions
{
    public static HtmlHelper CustomHtmlHelper(this HtmlHelper helper, Object model)
    {
        ViewDataDictionary customViewData = new ViewDataDictionary(helper.ViewData) { Model = model };
        ViewDataContainer customViewDataContainer = new ViewDataContainer(customViewData);
        ViewContext customViewContext =
            new ViewContext(helper.ViewContext.Controller.ControllerContext, helper.ViewContext.View, customViewData, helper.ViewContext.TempData, helper.ViewContext.Writer);

        return new HtmlHelper(customViewContext, customViewDataContainer, helper.RouteCollection);

    }

    private class ViewDataContainer : IViewDataContainer
    {
        public ViewDataDictionary ViewData { get; set; }

        public ViewDataContainer(ViewDataDictionary viewData)
        {
            ViewData = viewData;
        }
    }

}

Then you can write your own custom helpers for Display or use the Display helper like this :
@Html.CustomHtmlHelper(Model.ComplexModel).Display("Name");

And DisplayName for the "Name Lable":
@Html.CustomHtmlHelper(Model.ComplexModel).DisplayName("Name);

Custom Display method to be used directly with @Html :
public static class CustomDisplayHelper
{
    public static MvcHtmlString CustomDisplay(this HtmlHelper helper, string expression, Object model)
    {
        HtmlHelper customHelper = helper.CustomHtmlHelper(model);
        return customHelper.Display(expression);
    }

    public static MvcHtmlString CustomDisplayName(this HtmlHelper helper, string expression, Object model)
    {
        HtmlHelper customHelper = helper.CustomHtmlHelper(model);
        return customHelper.DisplayName(expression);
    }
}

:
@Html.CustomDisplay("Name", Model.ComplexModel)
@Html.CustomDisplayName("Name", Model.ComplexModel)

If you want to use ModelMetadata.FromStringExpression to get the "Name Lable" , the code look like this :
ViewDataDictionary myViewData = new ViewDataDictionary(Model.ComplexModel);
ModelMetadata metadata ModelMetadata.FromStringExpression("Name", MyViewData);

And get the display name or any other attributes :
String displayName = metadata.DisplayName;

Or better way :
String displayName = metadata.GetDisplayName;


text:
Q: Understanding Simpson's paradox with random effects Simpson's paradox is well known as a situation where the correlation between 2 variables in groups (ie within-group slope) is of opposite sign to the overall correlationed between the 2 variables, ignoring the subgroups (between-group slope)
I have seen several posts where this is illustrated with a simulation. This seems to be a good one:
Can adding a random intercept change the fixed effect estimates in a regression model?
Following the code in the above answer:
library(tidyverse)
library(lme4)

set.seed(1234)
n_subj = 5
n_trials = 20
subj_intercepts = rnorm(n_subj, 0, 1)
subj_slopes = rep(-.5, n_subj)

subj_mx = subj_intercepts*2

# Simulate data
data = data.frame(subject = rep(1:n_subj, each=n_trials),
                  intercept = rep(subj_intercepts, each=n_trials),
                  slope = rep(subj_slopes, each=n_trials),
                  mx = rep(subj_mx, each=n_trials)) %>%
  mutate(
    x = rnorm(n(), mx, 1),
    y = intercept + (x-mx)*slope + rnorm(n(), 0, 1))

#subject_means = data %>%
#   group_by(subject) %>%
#   summarise_if(is.numeric, mean)
# subject_means %>% select(intercept, slope, x, y) %>% plot()

# Plot
ggplot(data, aes(x, y, color=factor(subject))) +
  geom_point() +
  stat_smooth(method='lm', se=F) +
  stat_smooth(group=1, method='lm', color='black') +
  labs(x='Stimulus', y='Response', color='Subject') +
  theme_bw(base_size = 18)

The scenario seems quite obvious form the plot. The overall (between-subject) correlation is positive, bue the within-subject correlations are negative. To illustrate this we un an overall regression (lm()) and a regression with random effects (random intercepts for Subject using lmer()):
lm(y ~ x, data = data) %>% summary() %>% coef()
lmer(y ~ x + (1|subject), data = data) %>% summary() %>% coef()

Giving estimates of 0.24 for the between slope and -0.39 for the within slopes. This is good but I thought it would be better if we can see the within and between slopes in the same model. Also the slopes clearly differ quite a lot between subjects, so I thought we could fit the model with random slopes for x:
lmer(y ~ x + (x|subject), data = data) %>% summary() %>% coef()

However this gives a singular fit - correlation between random slopes and intercepts of -1 which does not make sense,  so I tried it without the correlation:
lmer(y ~ x + (x||subject), data = data) %>% summary() %>% coef()

but again this is a singular fit because the variance of the random slopes is zero - which also does not make sense because it is clearly quite variable (from the plot).
Advice in this and this post says that we should simplify the random structure. However, that just means goin back to the model with random intercepts only.
So how can we investigate this further and find the within and between subject slopes from the same model ?

A:
but again this is a singular fit because the variance of the random slopes is zero - which also does not make sense because it is clearly quite variable (from the plot).

The first thing I notice here is, just eyeballing the plot, I have to disagree that the variation in the slopes is clear. The slopes all appear fairly similar. Then there is this line in your code:
subj_slopes = rep(-.5, n_subj)

The slopes are simulated to all be -0.5 ! So it not surprising that you obtain a singular gfit with random slopes.
If you change that line to, for example:
subj_slopes = rnorm(n_subj, -0.5, 0.5)

And then do the plot, you get:

where it really is now quite obvious that the slopes vary, and running the random slopes models they fit without singular fit warnings:
> lmer(y ~ x + (x|subject), data=data) %>% summary()
Linear mixed model fit by REML ['lmerMod']
Formula: y ~ x + (x | subject)
   Data: data

REML criterion at convergence: 320.7

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.83147 -0.59817 -0.00588  0.52935  2.98311

Random effects:
 Groups   Name        Variance Std.Dev. Corr
 subject  (Intercept) 6.6353   2.5759
          x           0.3193   0.5651   -0.70
 Residual             1.0948   1.0463
Number of obs: 100, groups:  subject, 5

Fixed effects:
            Estimate Std. Error t value
(Intercept)   0.1947     1.1811   0.165
x            -0.6800     0.2768  -2.456

> lmer(y ~ x + (x||subject), data=data) %>% summary()
Linear mixed model fit by REML ['lmerMod']
Formula: y ~ x + ((1 | subject) + (0 + x | subject))
   Data: data

REML criterion at convergence: 322.8

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.83873 -0.62491  0.00786  0.51776  2.90389

Random effects:
 Groups    Name        Variance Std.Dev.
 subject   (Intercept) 7.8235   2.7971
 subject.1 x           0.3054   0.5526
 Residual              1.0951   1.0465
Number of obs: 100, groups:  subject, 5

Fixed effects:
            Estimate Std. Error t value
(Intercept)  0.03628    1.28880   0.028
x           -0.69406    0.27343  -2.538

and we recover good estimates of the random intercepts and random slopes variance components.
Note that, as it stands, these models cannot reveal the between and within slopes. To do that you need to model "contextual effects" - centre the independent variable for each subject and also include the subject means:
> mydata <- merge(data, data %>% group_by(subject) %>% summarise(subject_mean = mean(x)))
> mydata$mean_cent <- mydata$x - mydata$subject_mean
> lmer(y ~ mean_cent + subject_mean +  (1|subject), data = mydata) %>% summary()
Linear mixed model fit by REML ['lmerMod']
Formula: y ~ mean_cent + subject_mean + (1 | subject)
   Data: mydata

REML criterion at convergence: 317.5

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.70128 -0.51542 -0.03518  0.62543  2.48001

Random effects:
 Groups   Name        Variance Std.Dev.
 subject  (Intercept) 0.204    0.4517
 Residual             1.259    1.1221
Number of obs: 100, groups:  subject, 5

Fixed effects:
             Estimate Std. Error t value
(Intercept)   0.19598    0.24301   0.806
mean_cent    -0.76498    0.12396  -6.171
subject_mean  0.43955    0.08972   4.899

So now we have the between subject slope of 0.44 and the within-subject slope of -0.77, as requested. Of course you could also fit random slopes for mean_cent if you wish:
> lmer(y ~ mean_cent + subject_mean +  (mean_cent|subject), data = mydata) %>% summary()
Linear mixed model fit by REML ['lmerMod']
Formula: y ~ mean_cent + subject_mean + (mean_cent | subject)
   Data: mydata

REML criterion at convergence: 310

Scaled residuals:
     Min       1Q   Median       3Q      Max
-2.82854 -0.64286 -0.01652  0.59854  2.81995

Random effects:
 Groups   Name        Variance Std.Dev. Corr
 subject  (Intercept) 0.2230   0.4723
          mean_cent   0.2729   0.5224   0.65
 Residual             1.0964   1.0471
Number of obs: 100, groups:  subject, 5

Fixed effects:
             Estimate Std. Error t value
(Intercept)   0.24382    0.24469   0.996
mean_cent    -0.74379    0.26276  -2.831
subject_mean  0.49657    0.07819   6.351

and we find that the standard error for the fixed effect of mean_cent is higher due to the variation in it's slope being modelled by the random slopes.
In case you are wondering why the within-subject slope is -0.74, and not -0.5 (the mean we specified when we simulated them) it's because there are only 5 subjects, and:
> mean(subj_slopes)
[1] -0.7069806

Finally, it is also worth noting that you could also get basically the same result if you use a mutivariable regression (not a mixed mode) and fitted subject as a fixed effect :
> lm(y ~ subject + mean_cent + subject_mean, data = mydata) %>% summary()

Coefficients:
             Estimate Std. Error t value Pr(>|t|)
(Intercept)   0.59982    0.28457   2.108   0.0376 *
subject      -0.13151    0.08359  -1.573   0.1189
mean_cent    -0.76498    0.12905  -5.928 4.81e-08 ***
subject_mean  0.45063    0.04590   9.817 3.67e-16 ***

where subject here is not a factor (as per your simulation code). If it was a factor then you would need to exclude subject_mean from the model, as it would be perfectly collinear with the levels of subject.


text:
Q: Tkinter Radiobutton problema Hola muy buenas soy nuevo aquí y estoy aprendiendo a usar pyhton en tkinter, ahora me propuse hacer un mini proyecto de registrar usuarios con tkinter tipo CRUD con conexion sqlite3 , me pude guiar de un youtuber , mi GUI puede guardar y eliminar usuarios sin problemas ,pero el problema surge con la función editar los campos:
from tkinter import *
from tkinter import ttk
import sqlite3

class usuarios():
    # connection dir property
    db_name = 'databeis.db'

    def __init__(self, raiz):

        self.root = raiz
        self.root.title("Lists Users")
        self.gender = StringVar()
        self.gender.set(None)

        miFrame = Frame(self.root,width=800, height=800)
        miFrame.grid(row=0, column=0, columnspan=3, pady=20)

        # Name Input
        Label(miFrame, text = 'user_name: ').grid(row = 1, column = 0)
        self.user_name = Entry(miFrame)
        self.user_name.focus()
        self.user_name.grid(row = 1, column = 1)

        # Password Input
        Label(miFrame, text = 'password: ').grid(row = 2, column = 0)
        self.password = Entry(miFrame)
        self.password.grid(row = 2, column = 1)

        # Name Input
        Label(miFrame, text = 'name: ').grid(row = 3, column = 0)
        self.name = Entry(miFrame)
        self.name.grid(row = 3, column = 1)

        # RADIOBUTTON GENRE
        Radiobutton(miFrame, text="Male", variable=self.gender, value="Male").grid(
            row=4, column=0, padx=5, pady=5)

        Radiobutton(miFrame, text="Female", variable=self.gender, value="Female").grid(
            row=4, column=1, padx=5, pady=5)

        Radiobutton(miFrame, text="Other", variable=self.gender, value="Other").grid(
            row=4, column=2, padx=5, pady=5)

        # City Input
        Label(miFrame, text = 'City: ').grid(row = 5, column = 0)
        self.city = Entry(miFrame)
        self.city.grid(row = 5, column = 1)

        # Button Add
        Button(miFrame, text = 'Save User', command = self.add_user).grid(row = 6, columnspan = 2, sticky = W + E)
        # Button Delete
        Button(text = 'DELETE User', command= self.delete_user).grid(row = 9, column = 0, columnspan = 1, sticky = W + E)
         # Button Edit
        Button(text = 'EDIT User', command=self.edit_user).grid(row = 9, column = 2, columnspan =1 , sticky = W+E)

        # Output Messages
        self.message = Label(text = '', fg = 'red')
        self.message.grid(row = 6, column = 1, columnspan = 1, sticky = W + E)

        # Table
        self.tree = ttk.Treeview(miFrame,heigh=10,columns=("#1","#2","#3","#4"))#SI PONGO #4 SE AGREGARA UNA COLUMNA VACIA
        self.tree.grid(row = 7, column = 0, columnspan = 4 ,pady=10,sticky=W+E+N+S)
        self.tree.column("#0", width=450, minwidth=270, stretch=NO)
        self.tree.column("#1", width=150, minwidth=150, stretch=NO)
        self.tree.column("#2", width=80, minwidth=20, stretch=NO)
        self.tree.column("#3", width=80, minwidth=20, stretch=NO)
        self.tree.column("#4", width=80, minwidth=20, stretch=NO)
        self.tree.heading('#0', text = 'Username', anchor = CENTER)
        self.tree.heading('#1', text = 'Password', anchor = CENTER)
        self.tree.heading('#2', text = 'Name', anchor = CENTER)
        self.tree.heading('#3', text = 'Gender', anchor = CENTER)
        self.tree.heading('#4', text = 'City', anchor = CENTER)

        vsb = Scrollbar(miFrame, orient="vertical", command=self.tree.yview)
        vsb.grid(row=7, column=5, sticky='nse',pady=10)
        self.tree.configure(yscrollcommand=vsb.set)

        hsb = Scrollbar(miFrame, orient="horizontal", command=self.tree.xview)
        hsb.grid(row = 8, column=0, columnspan=5, sticky = W+E)
        self.tree.configure(xscrollcommand = hsb.set)

        # Filling the Rows
        self.get_user()

        # Function to Execute Database Querys
    def run_query(self, query, parameters = ()):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            result = cursor.execute(query, parameters)
            conn.commit()
        return result

        # Get User from Database
    def get_user(self):
        # cleaning Table
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)
        # getting data
        query = 'SELECT * FROM users ORDER BY user DESC'
        db_rows = self.run_query(query)
        # filling data
        for row in db_rows:
            self.tree.insert('', 0, text = row[1], values = (row[2],row[3],row[4],row[5]))

    # User Input Validation
    def validation(self):
        return len(self.user_name.get()) != 0 and len(self.password.get()) != 0 and len(self.name.get()) != 0 and len(self.gender.get()) != 0 and len(self.city.get()) != 0

    def add_user(self):
        if self.validation():
            query = 'INSERT INTO users VALUES(NULL, ?, ?, ?, ?, ?)'
            parameters =  (self.user_name.get(), self.password.get(), self.name.get(), self.gender.get(), self.city.get())
            self.run_query(query, parameters)
            self.message['text'] = 'User {} added Successfully'.format(self.user_name.get())
            self.user_name.delete(0, END)
            self.password.delete(0, END)
            self.name.delete(0, END)
            self.gender.set(None)
            self.city.delete(0, END)
        else:
            self.message['text'] = 'All fields are Required'
        self.get_user()

    def delete_user(self):
        self.message['text'] = ''
        try:
           self.tree.item(self.tree.selection())['text'][0]
        except IndexError as e:
            self.message['text'] = 'Please select a Record'
            return
        self.message['text'] = ''
        user_name = self.tree.item(self.tree.selection())['text']
        query = 'DELETE FROM users WHERE user = ?'
        self.run_query(query, (user_name, ))
        self.message['text'] = 'Record {} deleted Successfully'.format(user_name)
        self.get_user()

    def edit_user(self):
        self.message['text'] = ''
        try:
            self.tree.item(self.tree.selection())['values'][0]
        except IndexError as e:
            self.message['text'] = 'Please, select Record'
            return
        user_name = self.tree.item(self.tree.selection())['text']
        old_password = self.tree.item(self.tree.selection())['values'][0]
        old_name = self.tree.item(self.tree.selection())['values'][1]
        old_gender = self.tree.item(self.tree.selection())['values'][2]
        old_city = self.tree.item(self.tree.selection())['values'][3]
        self.edit_wind = Toplevel()
        self.edit_wind.title = 'Edit User'

        # Old username
        Label(self.edit_wind, text = 'Old username:').grid(row = 0, column = 1)
        Entry(self.edit_wind, textvariable = StringVar(self.edit_wind, value = user_name ), state = 'readonly').grid(row = 0, column = 2)
        # New username
        Label(self.edit_wind, text = 'New username:').grid(row = 1, column = 1)
        new_username = Entry(self.edit_wind)
        new_username.grid(row = 1, column = 2)

        # Old password
        Label(self.edit_wind, text = 'Old Pass:').grid(row = 2, column = 1)
        Entry(self.edit_wind, textvariable = StringVar(self.edit_wind, value = old_password), state = 'readonly').grid(row = 2, column = 2)
        # New password
        Label(self.edit_wind, text = 'New Pass:').grid(row = 3, column = 1)
        new_password = Entry(self.edit_wind)
        new_password.grid(row = 3, column = 2)

        # Old genre
        Label(self.edit_wind, text = 'Old Genre:').grid(row = 4, column = 1)
        Entry(self.edit_wind, textvariable = StringVar(self.edit_wind, value = old_gender), state = 'readonly').grid(row = 4, column = 2)

        # New GENRE
        self.new_gender = StringVar()
        self.new_gender.set(None)

        Radiobutton(self.edit_wind,text="Male", variable=self.new_gender, value="Male").grid(
            row=5, column=0, padx=5, pady=5)

        Radiobutton(self.edit_wind,text="Female", variable=self.new_gender, value="Female").grid(
            row=5, column=1, padx=5, pady=5)

        Radiobutton(self.edit_wind, text="Other", variable=self.new_gender, value="Other").grid(
            row=5, column=2, padx=5, pady=5)

        # Old name
        Label(self.edit_wind, text = 'Old name:').grid(row = 6, column = 1)
        Entry(self.edit_wind, textvariable = StringVar(self.edit_wind, value = old_name), state = 'readonly').grid(row = 6, column = 2)
        # New name
        Label(self.edit_wind, text = 'New name:').grid(row = 7, column = 1)
        new_name = Entry(self.edit_wind)
        new_name.grid(row = 7, column = 2)

        # Old city
        Label(self.edit_wind, text = 'Old city:').grid(row = 8, column = 1)
        Entry(self.edit_wind, textvariable = StringVar(self.edit_wind, value = old_city), state = 'readonly').grid(row = 8, column = 2)
        # New city
        Label(self.edit_wind, text = 'New city:').grid(row = 9, column = 1)
        new_city = Entry(self.edit_wind)
        new_city.grid(row = 9, column = 2)

        Button(self.edit_wind, text = 'Update', command = lambda: self.edit_records(new_username.get(), user_name, new_password.get(), old_password, new_gender.get(), old_gender, new_name.get(), old_name, new_city.get(), old_city)).grid(
            row = 10, column = 2, sticky = W)

        self.edit_wind.mainloop()

    def edit_records(self, new_username, user_name, new_password, old_password, new_gender, old_gender, new_name, old_name, new_city, old_city):
        query = 'UPDATE usuarios SET user = ?, password = ?, name = ?, gender = ?, city = ? WHERE user = ? AND password = ? AND name = ? AND genre = ? AND city = ?'
        parameters = (new_username, new_password, new_gender, new_name, new_city, user_name, old_pasword, old_gender, old_name, old_city)
        self.run_query(query, parameters)
        self.edit_wind.destroy()
        self.message['text'] = 'Record {} updated successfylly'.format(user_name)
        self.get_user()

if __name__ == "__main__":
    raiz = Tk()
    aplicacion = usuarios(raiz)
    raiz.mainloop()

El problema me dice esto y si self.new_gender = StringVar() lo estoy definiendo ,la verdad es que no se como puedo solucionarlo , he intentado eliminar radiobutton haber que pasa , y si funciona correctamente pero quisiera implementar radiobutton para los géneros en este miniproyecto que me propuse.

 **Button(self.edit_wind, text = 'Update', command = lambda:
     self.edit_records(new_username.get(), user_name, new_password.get(),
   old_password, new_gender.get(), old_gender, new_name.get(), old_name,
   new_city.get(), old_city)).grid(
         NameError: name 'new_gender' is not defined**

Aqui:
    Button(self.edit_wind, text = 'Update', command = lambda: self.edit_records(new_username.get(), user_name, new_password.get(), old_password, new_gender.get(), old_gender, new_name.get(), old_name, new_city.get(), old_city)).grid(
        row = 10, column = 2, sticky = W)

    self.edit_wind.mainloop()

def edit_records(self, new_username, user_name, new_password, old_password, new_gender, old_gender, new_name, old_name, new_city, old_city):
    query = 'UPDATE usuarios SET user = ?, password = ?, name = ?, gender = ?, city = ? WHERE user = ? AND password = ? AND name = ? AND genre = ? AND city = ?'
    parameters = (new_username, new_password, new_gender, new_name, new_city, user_name, old_pasword, old_gender, old_name, old_city)
    self.run_query(query, parameters)
    self.edit_wind.destroy()
    self.message['text'] = 'Record {} updated successfylly'.format(user_name)
    self.get_user()

La conexión con sqlite3 y mi tabla están bien , les agradecería que me ayuden, he estado intentando solucionarlo pero no encuentro en que fallo.


text:
Q: Node Js Microsoft Cognitive Services i am having a problem calling Cognitive Services from NodeJs.  i am pretty new with Node so doing a conversion from straight JavaScript to Node has been a challenge.  when i use an image that is on the internet it works, but i need to use an image that is on the local server and have tried many things to meet the requirement of it being a raw binary file.  Here is what I have been trying...
    const cognitiveServices = require('cognitive-services');
    var fs = require('fs');
    var apiKey = "myapikey";
    var apiUrl="https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze"
    const FRIENDS_IMAGE_URL ='http://az616578.vo.msecnd.net/files/2016/10/09/636115830685164048-686058602_friends.jpg';

    const parameters ={ "visualFeatures": "Tags","details": "Celebrities","language": "en"}
    //var body = { "url": FRIENDS_IMAGE_URL };

   var body = { "url":  getlocalimage()};
   //var body = getlocalimage();

   function getlocalimage()
    {
      var fn = "test.jpg"
      var base64 = fs.readFileSync(fn).toString('base64');
      //  var myimage = "data:image/jpeg:base64," + base64;
      var myimage =  base64;
      return new Buffer(myimage, 'base64').toString('binary');
     }

    function cogtest()
      {
        const chkImage = new cognitiveServices.computerVision({
                     apiKey: apiKey,
                     endpoint: "westus.api.cognitive.microsoft.com"
      })

    chkImage.analyzeImage({  parameters,  body  })
      .then(response => { console.log(response); })
      .catch((err) => { console.log(err);});

      }

       cogtest();

Since the call can be made successfully when using an image from the web and the error i keep getting is:
   { StatusCodeError: 400 - {"code":"InvalidImageUrl","requestId":"96432967-59d8-4851-a039-1e5b281b4cb7","message":"Can't fetch the image."}
    at new StatusCodeError (/Users/Tim/Downloads/0PiNode/node_modules/request-promise-core/lib/errors.js:32:15)
    at /Users/Tim/Downloads/0PiNode/node_modules/request-promise-core/lib/plumbing.js:97:41
    at tryCatcher (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromiseCtx (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/promise.js:606:10)
    at Async._drainQueue (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/async.js:138:12)
    at Async._drainQueues (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/Users/Tim/Downloads/0PiNode/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:800:20)
    at tryOnImmediate (timers.js:762:5)
    at processImmediate [as _immediateCallback] (timers.js:733:5)
  name: 'StatusCodeError',
  statusCode: 400,
  message: '400 - {"code":"InvalidImageUrl","requestId":"96432967-59d8-4851-a039-1e5b281b4cb7","message":"Can\'t fetch the image."}',
  error:
   { code: 'InvalidImageUrl',
     requestId: '96432967-59d8-4851-a039-1e5b281b4cb7',
     message: 'Can\'t fetch the image.' },
  options:
   { uri: 'https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze',
     method: 'POST',
     headers:
      { 'Ocp-Apim-Subscription-Key': 'KEY' },
     qs:
      { visualFeatures: 'Tags',
        details: 'Celebrities',
        language: 'en' },
     json: true,

any ideas?  i believe it has to do with passing a raw binary image in the body.
 Per the module
https://github.com/joshbalfour/node-cognitive-services
https://github.com/joshbalfour/node-cognitive-services/tree/v0.2.0#computer-vision---analyze-image
thanks for any help

A: You don't need to convert the image to the base64 representation. You can simply do this:
var parameters = {
    "visualFeatures": "Tags",
    "details": "Celebrities",
    "language": "en"
}

var body = fs.readFileSync("test.jpg");

var chkImage = new cognitiveServices.computerVision({
    apiKey: "myapikey",
    endpoint: "westus.api.cognitive.microsoft.com"
})

chkImage.analyzeImage({
    parameters,
    body
})
    .then(response => {
        console.log(response);
    })
    .catch((err) => {
        console.log(err);
    });

I.e., just send over the result of fs.readFileSync as the body of the request.


text:
Q: android expanded notification view I have an app that puts the date in the status bar, but in order to make it look decent, I have to use two notifications.  This causes it to use two expanded notifications when you pull down the status bar.  Is there any way to get rid of one of the expanded views(or both of them)?

A:
Is there any way to get rid of one of
  the expanded views(or both of them)?

No, sorry.


text:
Q: Google Map MyCurrentLocation is not Working I am working with the android emulator,
Once I run the app,
It centers in the right longitude and latitude,
but the blue dot is not in there to indicate my current location.
   @Override
    public void onMapReady(GoogleMap mGoogleMap) {
        if (ActivityCompat.checkSelfPermission(Navi.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Navi.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            this.gMap = mGoogleMap;
            if (lat != 0.0 & lng != 0.0) {
                if (this.gMap != null) {
                    this.gMap.setMyLocationEnabled(true);
                    this.gMap.getUiSettings().setMyLocationButtonEnabled(true);
                    this.gMap.getUiSettings().setCompassEnabled(true);
                    this.gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    this.gMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
                    this.gMap.animateCamera(CameraUpdateFactory.zoomTo(14f));
                }
            } else {
                if (this.gMap != null) {
                    LatLng latLng = new LatLng(14.6760, 121.0437);
                    this.gMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                    this.gMap.animateCamera(CameraUpdateFactory.zoomTo(14f));
                }
            }
        } else {
            ActivityCompat.requestPermissions(Navi.this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST);
        }
    }

But once I received my new Longitude and latitude,
The blue dot appears.
 private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            // TODO Auto-generated method stub
            lat = arg1.getDoubleExtra("lat", 0);
            lng = arg1.getDoubleExtra("long", 0);
            if (lat != 0.0 & lng != 0.0) {
                if (gMap != null) {
                    if (ActivityCompat.checkSelfPermission(Navi.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Navi.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        gMap.setMyLocationEnabled(true);
                        gMap.getUiSettings().setMyLocationButtonEnabled(true);
                        gMap.getUiSettings().setCompassEnabled(true);
                        gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                        gMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lng)));
                        gMap.animateCamera(CameraUpdateFactory.zoomTo(14f));
                    }
                }
            }
            Log.e("LAT", "" + lat);
            Log.e("LNG", "" + lng);
        }

    }

What's the cause of this problem?


text:
Q: Creating multi module Maven Projects in Eclipse Trying to create a multi module maven project in eclipse.
Parent Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>parent</groupId>
  <artifactId>proj1</artifactId>
  <version>${myversion}</version>
  <packaging>pom</packaging>
  <properties>
   <myversion>1.0.0</myversion>
  </properties>
  <modules>
   <module>child1</module>
   <module>child2</module>
  </modules>
</project>

Child-Module 1 Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>proj1</artifactId>
    <groupId>parent</groupId>
    <version>${myversion}</version>
  </parent>
  <groupId>parent</groupId>
  <artifactId>child1</artifactId>
  <version>${myversion}</version>
</project>

Child Module 2 Pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>proj1</artifactId>
    <groupId>parent</groupId>
    <version>${myversion}</version>
  </parent>
  <groupId>parent</groupId>
  <artifactId>child2</artifactId>
  <version>${myversion}</version>
  <dependencies>
   <dependency>
    <groupId>parent</groupId>
    <artifactId>child1</artifactId>
    <version>${myversion}</version>
    <type>jar</type>
    <scope>compile</scope>
   </dependency>
  </dependencies>
</project>

If I use mvn clean install on command line from the parent folder I can build find. All the projects are build successfully.
But in eclipse I keep getting an error for Child Module 2 pom.xml
Description Resource Path Location Type
parent:child1:1.0.0:jar Missing:
----------
1) parent:proj1:pom:${myversion}
----------
1 required artifact is missing.

for artifact:
  parent:proj1:pom:${myversion}

from the specified remote repositories:
  central (http://repo1.maven.org/maven2, releases=true, snapshots=false)
 pom.xml /child2 line 1 Maven Problem

I need to achieve 2 things
1. have a maven property define the version in the parent pom file.
2. use this property to define the version in all the child modules.
What should I do? I am stuck. Please help.
I am using Eclipse Galileo with m2Eclipse

A: This can't work, you can't get the version of the parent to use from the parent (and actually, properties don't get substituted in the parent element, see MNG-624). So you need to hard code the version and your parent POM should be:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>parent</groupId>
  <artifactId>proj1</artifactId>
  <version>1.0.0</version>
  <packaging>pom</packaging>
  <modules>
   <module>child1</module>
   <module>child2</module>
  </modules>
</project>

And in your child POM 1. you need to hardcode the version in /project/parent/version 2. you don't need to specify the <version> (you inherit it) 3. use the ${project.version} property in dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>proj1</artifactId>
    <groupId>parent</groupId>
    <version>1.0.0</version>
  </parent>
  <groupId>parent</groupId>
  <artifactId>child2</artifactId>
  <!--version>${myversion}</version--> <!-- Inherited -->
  <dependencies>
   <dependency>
    <groupId>parent</groupId>
    <artifactId>child1</artifactId>
    <version>${project.version}</version> <!-- use the built-in property here -->
    <!--type>jar</type--> <!-- This is a default, you can omit it -->
    <!--scope>compile</scope--> <!-- This is a default, you can omit it -->
   </dependency>
  </dependencies>
</project>

Versionless parent elements will be supported in Maven 3.1.
See also

*

*Missing artifact error in Maven

*Eliminate Maven POM Redundancy

*Maven 3 - Worth it???


text:
Q: Rails same named route but with parameter raises an error As of Rails 4.2, I cannot do the following:
  get 'profile', to: 'profile#index', as: 'profile'
  get 'profile/:slug', to: 'profile#show', as: 'profile'

because it will raise error saying route is already defined. Why is that? Obviously profile_path and profile_path(User.last.slug) are not the same, and there should be no difficulty differentiating the two even if they happen to share the same base name (You check if a param is passed).
Thoughts?

A: In rails, the helper names for different routes should be different. And hence, as you rightly   understood, you will receive an error if you use the same helper name (ie as: 'profile' in your case) for two different routes.
This restriction in Rails helps maintain sanity in your routes.rb file as well as in your application. For instance consider two methods for a controller:
class XyzController < ApplicationController
  def method_a(param1)
  end

  def method_b(param1)
  end
end

In your routes file if there was no restriction of keeping helper names different, you could have used :
get 'xyz/method_a', to: 'profile#method_a', as: 'profile_method'
get 'xyz/method_b', to: 'profile#method_b', as: 'profile_method'

Correspondingly in your view file:
 link_to 'link_1', profile_method_path('param1')  #intended to route for method_a
 link_to 'link_2', profile_method_path('param2')  #intended to route for method_b

As obvious, in the view file, not only is it difficult to make out which route is intended for which method, its also not possible to route to any other controller method using the helper 'profile_method' except the method that is first to use this helper in your routes.rb file (as routes are read sequentially).
Hope this helps :)

A: For both routes you specified as: 'profile' and that's your problem here. Besides that, use pluralized route names for #index action, e.g:
get 'profiles', to: 'profile#index'


text:
Q: range(-8.00, 8.00, 0.05) acting very strange Does anyone know why range(-8.00, 8.00, 0.05) seems fail?
Array
(
[0] => -8
[1] => -7.95
[2] => -7.9
[3] => -7.85
[4] => -7.8
[5] => -7.75
[6] => -7.7
[7] => -7.65
[8] => -7.6
[9] => -7.55
[10] => -7.5
[11] => -7.45
[12] => -7.4
[13] => -7.35
[14] => -7.3
[15] => -7.25
[16] => -7.2
[17] => -7.15
[18] => -7.1
[19] => -7.05
[20] => -7
[21] => -6.95
[22] => -6.9
[23] => -6.85
[24] => -6.8
[25] => -6.75
[26] => -6.7
[27] => -6.65
[28] => -6.6
[29] => -6.55
[30] => -6.5
[31] => -6.45
[32] => -6.4
[33] => -6.35
[34] => -6.3
[35] => -6.25
[36] => -6.2
[37] => -6.15
[38] => -6.1
[39] => -6.05
[40] => -6
[41] => -5.95
[42] => -5.9
[43] => -5.85
[44] => -5.8
[45] => -5.75
[46] => -5.7
[47] => -5.65
[48] => -5.6
[49] => -5.55
[50] => -5.5
[51] => -5.45
[52] => -5.4
[53] => -5.35
[54] => -5.3
[55] => -5.25
[56] => -5.2
[57] => -5.15
[58] => -5.1
[59] => -5.05
[60] => -5
[61] => -4.95
[62] => -4.9
[63] => -4.85
[64] => -4.8
[65] => -4.75
[66] => -4.7
[67] => -4.65
[68] => -4.6
[69] => -4.55
[70] => -4.5
[71] => -4.45
[72] => -4.4
[73] => -4.35
[74] => -4.3
[75] => -4.25
[76] => -4.2
[77] => -4.15
[78] => -4.1
[79] => -4.05
[80] => -4
[81] => -3.95
[82] => -3.9
[83] => -3.85
[84] => -3.8
[85] => -3.75
[86] => -3.7
[87] => -3.65
[88] => -3.6
[89] => -3.55
[90] => -3.5
[91] => -3.45
[92] => -3.4
[93] => -3.35
[94] => -3.3
[95] => -3.25
[96] => -3.2
[97] => -3.15
[98] => -3.1
[99] => -3.05
[100] => -3
[101] => -2.95
[102] => -2.9
[103] => -2.85
[104] => -2.8
[105] => -2.75
[106] => -2.7
[107] => -2.65
[108] => -2.6
[109] => -2.55
[110] => -2.5
[111] => -2.45
[112] => -2.4
[113] => -2.35
[114] => -2.3
[115] => -2.25
[116] => -2.2
[117] => -2.15
[118] => -2.1
[119] => -2.05
[120] => -2
[121] => -1.95
[122] => -1.9
[123] => -1.85
[124] => -1.8
[125] => -1.75
[126] => -1.7
[127] => -1.65
[128] => -1.6
[129] => -1.55
[130] => -1.5
[131] => -1.45
[132] => -1.4
[133] => -1.35
[134] => -1.3
[135] => -1.25
[136] => -1.2
[137] => -1.15
[138] => -1.1
[139] => -1.05
[140] => -1
[141] => -0.95000000000002
[142] => -0.90000000000002
[143] => -0.85000000000002
[144] => -0.80000000000002
[145] => -0.75000000000002
[146] => -0.70000000000002
[147] => -0.65000000000002
[148] => -0.60000000000002
[149] => -0.55000000000002
[150] => -0.50000000000002
[151] => -0.45000000000002
[152] => -0.40000000000002
[153] => -0.35000000000002
[154] => -0.30000000000002
[155] => -0.25000000000002
[156] => -0.20000000000002
[157] => -0.15000000000002
[158] => -0.10000000000002
[159] => -0.05000000000002
[160] => -2.0053403382292E-14
[161] => 0.04999999999998
[162] => 0.09999999999998
[163] => 0.14999999999998
[164] => 0.19999999999998
[165] => 0.24999999999998
[166] => 0.29999999999998
[167] => 0.34999999999998
[168] => 0.39999999999998
[169] => 0.44999999999998
[170] => 0.49999999999998
[171] => 0.54999999999998
[172] => 0.59999999999998
[173] => 0.64999999999998
[174] => 0.69999999999998
[175] => 0.74999999999998
[176] => 0.79999999999998
[177] => 0.84999999999998
[178] => 0.89999999999998
[179] => 0.94999999999998
[180] => 0.99999999999998
[181] => 1.05
[182] => 1.1
[183] => 1.15
[184] => 1.2
[185] => 1.25
[186] => 1.3
[187] => 1.35
[188] => 1.4
[189] => 1.45
[190] => 1.5
[191] => 1.55
[192] => 1.6
[193] => 1.65
[194] => 1.7
[195] => 1.75
[196] => 1.8
[197] => 1.85
[198] => 1.9
[199] => 1.95
[200] => 2
[201] => 2.05
[202] => 2.1
[203] => 2.15
[204] => 2.2
[205] => 2.25
[206] => 2.3
[207] => 2.35
[208] => 2.4
[209] => 2.45
[210] => 2.5
[211] => 2.55
[212] => 2.6
[213] => 2.65
[214] => 2.7
[215] => 2.75
[216] => 2.8
[217] => 2.85
[218] => 2.9
[219] => 2.95
[220] => 3
[221] => 3.05
[222] => 3.1
[223] => 3.15
[224] => 3.2
[225] => 3.25
[226] => 3.3
[227] => 3.35
[228] => 3.4
[229] => 3.45
[230] => 3.5
[231] => 3.55
[232] => 3.6
[233] => 3.65
[234] => 3.7
[235] => 3.75
[236] => 3.8
[237] => 3.85
[238] => 3.9
[239] => 3.95
[240] => 4
[241] => 4.05
[242] => 4.1
[243] => 4.15
[244] => 4.2
[245] => 4.25
[246] => 4.3
[247] => 4.35
[248] => 4.4
[249] => 4.45
[250] => 4.5
[251] => 4.55
[252] => 4.6
[253] => 4.65
[254] => 4.7
[255] => 4.75
[256] => 4.8
[257] => 4.85
[258] => 4.9
[259] => 4.95
[260] => 5
[261] => 5.05
[262] => 5.1
[263] => 5.15
[264] => 5.2
[265] => 5.25
[266] => 5.3
[267] => 5.35
[268] => 5.4
[269] => 5.45
[270] => 5.5
[271] => 5.55
[272] => 5.6
[273] => 5.65
[274] => 5.7
[275] => 5.75
[276] => 5.8
[277] => 5.85
[278] => 5.9
[279] => 5.95
[280] => 6
[281] => 6.05
[282] => 6.1
[283] => 6.15
[284] => 6.2
[285] => 6.25
[286] => 6.3
[287] => 6.35
[288] => 6.4
[289] => 6.45
[290] => 6.5
[291] => 6.55
[292] => 6.6
[293] => 6.65
[294] => 6.7
[295] => 6.75
[296] => 6.8
[297] => 6.85
[298] => 6.9
[299] => 6.95
[300] => 7
[301] => 7.05
[302] => 7.1
[303] => 7.15
[304] => 7.2
[305] => 7.25
[306] => 7.3
[307] => 7.35
[308] => 7.4
[309] => 7.45
[310] => 7.5
[311] => 7.55
[312] => 7.6
[313] => 7.65
[314] => 7.7
[315] => 7.75
[316] => 7.8
[317] => 7.85
[318] => 7.9
[319] => 7.95
[320] => 8
)

A: That would be because floating point numbers are not precise and not all numbers can be represented exactly using floats.

A: You may want to try a range between 800 and -800 with steps of 5 and then add in the decimal points / divide by 100 afterward.

A: That's a known problem, hopefully already fixed. See bug #54459.
Basically now instead of making consecutive floating point additions, the range  function now increments an integer and multiplies it by the step.
Basically, you know have:
-8.00, -8.00 + 1 * 0.05, -8.00 + 2 * 0.05, ...

instead of
-8.00, -8.00 + 0.05, -8.00 + 0.05 + 0.05, ...

You can see this makes a difference:
$ php
<?php
for ($i = 0; $i < 9.99; $i += .1) {}
echo sprintf("%.17f", $i);
^D
9.99999999999998046

while:
$ php -r 'echo sprintf("%.17f", .1*100);'
10.00000000000000000


text:
Q: Analyze Thread Dump fow web application Hello i have taken the thread dump for my web application which is giving out of memory again and again using the JSTACK but i am little bit confused that how to find the correct culprit thread can some one give the tips that how to analyze the dump file.

A: Use VisualVM which is included with the JDK.

A: When you have a OutOfMemoryError, the first step is to read the associated message. It explains the cause of the error : heap, perm, thread,...
Depending on the cause, you have to check the configuration of the space : -Xms and -Xmx for the heap, -XX:PermSize and -XX:MaxPermSize for the perm (Java 7-), -XX:MaxMetaspaceSize for the metaspace (Java 8+),... The config may be too low for your need.
After that, use tools to understand how the memory is consumed. VisualVM is great, it provides metrics on the memory, helps you to make heap dumps or to profile the memory (not in production). You may add the -XX:+HeapDumpOnOutOfMemoryError option in your startup script so that the heap dump will be automatically generated when you run an OutOfMemoryError.
If you have memory leaks, I suggest to use more advanced (and not free) profiling tools such as JProfiler or YourKit.


text:
Q: Set color per even on kendo scheduler MVC I have a grid here which shows all the projects from the Db that have their statuses as "Open". Now I want to show a different colour for each project on the scheduler. Currently, it's showing the projects with the same colour, which can confuse users. Please see the images below of the screen and the code.
@(Html.Kendo().Scheduler<Website.Models.ResourcePlanner.ResourcePlannerGridModel>()
        .Name("scheduler")
        .Date(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day))
        .StartTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second))
        .Height(600)
        .Views(views =>
        {

            views.WeekView(weekView => weekView.Selected(false));
            views.MonthView(monthView => monthView.Selected(true));
            views.AgendaView();
            views.TimelineView();
            views.TimelineMonthView();
        })
        .Resources(resource =>
        {
            resource.Add(m => m.Title)
            .Title("Room")
            .DataTextField("Text")
            .DataValueField("Value")
            .DataColorField("Color")
            .BindTo(new[]
            {
    new { Text = "Venue 101", Value = 1, Color = "#6eb4fa" },
    new { Text = "Venue 201", Value = 2, Color = "#f58a8a" }
            });
        })
        .DataSource(d => d
        .Model(m =>
        {
        })
        .Read(read => read.Action("Read", "ResourcePlanner"))
       .Destroy(delete => delete.Action("Delete", "ResourcePlanner"))
        )
)

Scheduler display:

Scheduler code:

Thank you in advance.

A: I had the very same issue and solved it by assigning a special class within my event template and doing some additional magic once the DataBound-event was triggered.
// The template

// The CSS
.pageScheduler .k-scheduler-content .eventAction1Applied,
.pageScheduler .k-scheduler-content .eventAction2Applied,
.pageScheduler .k-scheduler-content .eventAction3Applied {
    color: white;
}

.pageScheduler .k-scheduler-content .eventAction1Applied {
    background-color: rgb(0, 159, 227);
    border-color: rgb(0, 159, 227);
}

// The method to call on DataBound
function scheduledTasksDataBound() {
    var events = $(".customEvent");
    for (var i = 0; i < events.length; i++) {
        var event = $(events[i]);

        var bgClass = null;
        if (event.hasClass("eventAction1")) {
            bgClass = "eventAction1Applied";
        }
        else if (event.hasClass("eventAction2")) {
            bgClass = "eventAction2Applied";
        }
        else if (event.hasClass("eventAction3")) {
            bgClass = "eventAction3Applied";
        }
        event.parent().addClass(bgClass);
    }
}

If I remember correcltly, the stuff in scheduledTasksDataBound was necessary as the styles were not applied otherwise.


text:
Q: Unclosed `` tag in edit history when removing del'ed text I noticed yesterday that the edit history contains unclosed tags if a  tag is removed from it.  See revision 5 of this question's edit history to see what I'm talking about. In revision 4 I put the text "say, 30 minutes?" inside a .  Then in revision 5 I rolled back to revision 3 (i.e. removed the ).  However, in the edit history for revision 5, the  tag is never closed, making it look like the whole second paragraph was deleted as well.

I don't know if this is specific to the  tag or not.  I have at least confirmed (on this question's edit history) that the problem isn't reproducible for the  tag.

A: This problem has been fixed and is marked status-completed.


text:
Q: Azure Notification Hub - NotificationHubClient.SendAppleNativeNotificationAsync Hanging I have the following code:
 var alert = "{\"aps\":{\"alert\":\"" + message + "\"}}";
 outcome = await ApnsNotifications.Instance.Hub.SendAppleNativeNotificationAsync(alert, username);

Bu the await just hangs forever and never returns.  Should I just "fire and forget" this by not awaiting, or is there some other way to make sure this doesn't hang?
I should note that the username may or may not have an iphone - so hopefully there's no requirement to actually have a device to send to with these.


text:
Q: Force Maven Shade Plugin to apply latest SNAPSHOT dependency in a multi-module build I am using the maven-shade-plugin in a multi-module build to generate a shaded JAR.
Everything works as expected, except that SNAPSHOT dependencies from my modules do not get updated unless I clean the aggregate project.
pom.xml
  |
  +-a/pom.xml (a-1.0.0-SNAPSHOT.jar)
  |
  +-b/pom.xml (b-1.0.0-SNAPSHOT.jar)
  |
  +-aggregate/pom.xml (a_and_b-1.0.0-SNAPSHOT-jar)

In the example, the aggregate project builds the shaded jar. The aggregate project lists "b" as a dependency, and "b" lists "a" as a dependency. If I make a change to code in "a" and run "mvn install" from the parent directory, "a" is rebuilt but the shaded JAR does not contain the updated "a".
Previously, I used the dependency and assembly plugins to create the fat jar file. The dependency plugin provides this behaviour with the overWriteIfNewer and overwriteSnapshots options. I can do a "mvn clean -pl aggregate; mvn install", but want to know if there is a similar shade plugin option for me to force the shade plugin to pull in newer dependencies?
I am using apache-maven-3.3.9 and version 2.4.3 of the maven-shade-plugin.


text:
Q: Do browsers take into account that network can be faster than disk cache? One thing came to my mind. Nowadays the internet connection speed is often comparable to hard drive speeds. It means I can fully imagine there might be cases when it would be better (for a selfish web client) to retrieve a resource from network than to read it from disk. Especially when the size of the resource is relatively small the time cost of disk operations may exceed the download time.
Do web browsers have such a functionality?
The reason for my question is pure curiosity, not a real problem. BTW, I am not convinced such idea is worth implementing as the more bandwidth is taken for some very small local benefits.

A: Keep in mind, besides sheer bandwidth, there is significant latency when traversing a network and HTTP is chatty.  Additionally, every call to the server causes server load so what's best for one client may negatively affect others as well.
To directly answer your question, I doubt the browsers test network speed before choosing whether to download or use cache.


text:
Q: Want user to enter only Letter on Console.ReadLine(); In C#, how can I restrict user to enter only text example (a to z) letters? only
namespace ConsoleApplication14
{
    class Program
    {
        public void studentProfile()
        {
            Dictionary<string, int> satya = new Dictionary<string, int>();
            {
                satya.Add("Acpl", 2);
                satya.Add("Bio", 1);
                satya.Add("Ch", 4);
                satya.Add("Om", 5);
            }

            Dictionary<string, int> rahul = new Dictionary<string, int>();
            {
                rahul.Add("Acpl", 2);
                rahul.Add("Bio", 1);
                rahul.Add("Ch", 4);
                rahul.Add("Om", 5);
            }
        }

        static void Main(string[] args)
        {
            int maxAttempts = 5;
        }
    }
}

A: You have to read what they type and reject it if you don't like what they entered.
string input;
do
{
    input = Console.ReadLine();
} while (input.Any(c => !char.IsLetter(c)));


text:
Q: Error Message: TOK_ALLCOLREF is not supported in current context - while Using DISTINCT in HIVE I'm using the simple command: SELECT DISTINCT * FROM first_working_table;  in HIVE 0.11, and I'm receiving the following error message:

FAILED: SemanticException TOK_ALLCOLREF is not supported in current
  context.

Does anyone know why this is happening? How can we solve it?
Thank you,
Gal.

A: Hive doesn't support DISTINCT * syntax. You can manually specify every field of the table to get the same result:
SELECT DISTINCT field1, field2, ...., fieldN
  FROM first_working_table

A: As specified in earlier comment distinct * not supported. Which is true.
One trick can be like this.
Distinct * can be used in this fashion:
select distinct * from (
select t1.col1,t1.col2,t1.col3,t2.* from t1,t2
)tbl;

I have used this syntax in Hive 2.x. So I can confirm that this works.


text:
Q: Publish Web service using Visual Studio development server I have a Web Service that I am trying to publish from VS.
This is the configuration in my project's properties:

When I try to run the code I get this message:

It works when I choose Use Local IIS Web Server, but why doesn't it work in the first case as well?


text:
Q: Build a dataframe of nested tibbles in R? I have a couple of tibbles:
1:
structure(list(contacts = c(151, 2243, 4122, 6833, 76, 123)), .Names = "contacts", row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

2:
structure(list(image_names = c("/storage/emulated/0/Pictures/1.png",
"/storage/emulated/0/Pictures/10.png", "/storage/emulated/0/Pictures/2.png",
"/storage/emulated/0/Pictures/3.png", "/storage/emulated/0/Pictures/4.png",
"/storage/emulated/0/Pictures/5.png")), .Names = "image_names", row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

3:
structure(list(phone_number = c(22881, 74049, 74049, 22881, 22881,
22881), isInContact = c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE),
    callDuration = c(1, 0, 0, 71, 13, 54), Date = structure(c(17689,
    17689, 17689, 17690, 17690, 17690), class = "Date"), Time = structure(c(76180,
    77415, 84620, 27900, 28132, 29396), class = c("hms", "difftime"
    ), units = "secs")), .Names = c("phone_number", "isInContact",
"callDuration", "Date", "Time"), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))

And consider that for each set of these dataframes I can get an identifier, say UUID.
I want to build a large dataframe object where the identifier will be user's uuid and all other columns will be nested tibbles:
UUID contacts images    call_logs
123  <tibble> <tibble>  <tibble>
456  <tibble> <tibble>  <tibble>

Please advise how can I build such thing, I am trying to use map_dfr without luck.

A: We could place the tibbles in a list to create a single row
tblN <- tibble(contacts = list(tbl1), images = list(tbl2),
               call_logs = list(tbl3))

It is not clear whether the same dataset should be replicated or not for different 'UUID's.
list(`123` = tblN, `456` = tblN) %>%
                bind_rows(.id = 'UUID')


text:
Q: Is it possible to have foreign key enforced without object-to-object mapping? Assuming the following mappings are provided:
<class name="A" table="a_table">
  <id name="id"/>
  <many-to-one name="entityB" column="fk_B" not-null="false" unique="true"/>
</class>

<class name="B" table="b_table">
  <id name="id"/>
</class>

Java class:
public class A {
   private long id;
   private B entityB;
   // getters and setters skipped
}

Is it possible to change the Hibernate mapping so that foreign key is still enforced and created by Hibernate upon startup, but class A would look like as the following:
public class A {
   private long id;
   private long idOfB;
   // getters and setters skipped
}

I understand that if I convert <many-to-one... into a <property... this would work, but foreign key would not be enforced by the database.
I need to do this because object B might (or might not) be initialized separately which sometimes causes
org.hibernate.LazyInitializationException: could not initialize proxy - no Session exceptions to occur when a.getB() is called. I would prefer to have it as a long idOfB and load whole object whenever is necessary; this would also make loading of object A quicker.
I believe my question is very similar to this one, yet the offered solution (to use lazy loading) is not appropriate in my case as even if I call a.getB().getId(), I'd get LazyInitializationException whereas if I call a.getIdOfB() I wouldn't.
Thanks very much in advance.

A: You could always create the Foreign Key DDL manually in your hibernate hbm.xml file:
<hibernate-mapping>
    ...
    <database-object>
        <create>[CREATE FK]</create>
        <drop>[DROP FK]</drop>
    </database-object>
</hibernate-mapping>

You can also scope this if different dialects need to be supported.
Check out 5.7. Auxiliary database objects

A: As said

I understand that if I convert <many-to-one... into a <property... this would work, but foreign key would not be enforced by the database.

So my advice is: use both
public class EntityA {

    private Integer idOfB;

    private EntityB entityB;

    // getter's and setter's

}

And
<class name="A" table="a_table">
    <id name="id"/>
    <property name="idOfB" column="fk_B" not-null="false" unique="true"/>
    <many-to-one name="entityB" update="false" insert="false" column="fk_B"/>
</class>

Notice when two properties share the same column, you have to put settings about it in just one property. Otherwise, Hibernate will complain some errors. It explains why i define update="false" and insert="false" in entityB property.
regards,

A: Another approach you could take is to define the FK with your B mapping rather than the A mapping.  I've added the JPA code, you'd have to translate this to your hibernate mapping file if you're not using annotations.
@Entity
public class B
{
    private long id;
    private List<A> aList;

    @Id
    @Column( name = "ID" )
    public long getId()
    {
        return id;
    }

    @OneToMany
    @JoinColumn( name = "B_ID" )
    public List<A> getAList()
    {
        return aList;
    }
    public void setId( long id )
    {
        this.id = id;
    }
    public void setAList( List<A> aList )
    {
        this.aList = aList;
    }
}

A.java would not look like this:
@Entity
public class A
{
    private long id;
    private long idOfB;

    @Id
    @Column( name = "ID" )
    public long getId()
    {
        return id;
    }
    @Column( name = "B_ID" )
    public long getIdOfB()
    {
        return idOfB;
    }
    public void setId( long id )
    {
        this.id = id;
    }
    public void setIdOfB( long idOfB )
    {
        this.idOfB = idOfB;
    }
}

A: I recommend you to associate objects to objects to get full advantages of Hibernate. I think the problem is the exception you get. This is because Hibernate session is already closed when you try to get the lazy object. There are several posts in this blog which show answers to this problem, for example this one:link text.
In case you're using spring you can use OpenEntityManagerInViewFilter so the session will keep opened until the view is renderes.