问:
Laravel 5 - Use 'isAdmin' role check method when querying a model
I have implemented a basic role system that uses a table 'role_user'.

On my user model I have a few methods that check the roles, one of them is:

```<code>public function isStaff()
{
    foreach ($this->roles()->get() as $role)
    {
        if ($role->id == 3)
        {
            return true;
        }
    }

    return false;
}
</code>```

How can I use this method when I am querying users?

This query here:

```<code>return User::where('name', 'like', "%".$request->name."%")
    ->orWhere('email', 'like', "%".$request->name."%")
    ->whereDoesntHave('Teams', function ($query) use($teamId) {
        $query->whereId($teamId);
    })
    ->with('teams')
    ->get();
</code>```

Currently returns all users, but I only wish to return users that have a role of 3 (isStaff)

答:
You can have a scope called staff in your User model, then use that to narrow down your result:

```<code>public function scopeStaff($query, $roll_id = 3)
{
    return $query->where('role_id', '=', $roll_id)
}
</code>```

So when checking (with the model) for staff roles, you can improve the function that does that:

```<code>public function isStaff($role_id = 3)
{
    return $this->role_id = $role_id ? $this : false;
}
</code>```

Therefore, when using the query builder you can use the first method to narrow the result to those with the specified id, as you can see the default is 3 but will change to any value you give:

```<code>$staff_users = User::staff()->get();
</code>```

Then the other one for verifying if a matched user model is a staff:

```<code>$user = User::find(1);
$is_staff = $user->isStaff(); //false or returns the same model
</code>```

Hope this helps

Body:
I have implemented a basic role system that uses a table 'role_user'.

On my user model I have a few methods that check the roles, one of them is:

public function isStaff()
{
    foreach ($this->roles()->get() as $role)
    {
        if ($role->id == 3)
        {
            return true;
        }
    }

    return false;
}

How can I use this method when I am querying users?

This query here:

return User::where('name', 'like', "%".$request->name."%")
    ->orWhere('email', 'like', "%".$request->name."%")
    ->whereDoesntHave('Teams', function ($query) use($teamId) {
        $query->whereId($teamId);
    })
    ->with('teams')
    ->get();

Currently returns all users, but I only wish to return users that have a role of 3 (isStaff)

Body:
You can have a scope called staff in your User model, then use that to narrow down your result:

public function scopeStaff($query, $roll_id = 3)
{
    return $query->where('role_id', '=', $roll_id)
}

So when checking (with the model) for staff roles, you can improve the function that does that:

public function isStaff($role_id = 3)
{
    return $this->role_id = $role_id ? $this : false;
}

Therefore, when using the query builder you can use the first method to narrow the result to those with the specified id, as you can see the default is 3 but will change to any value you give:

$staff_users = User::staff()->get();

Then the other one for verifying if a matched user model is a staff:

$user = User::find(1);
$is_staff = $user->isStaff(); //false or returns the same model

Hope this helps


来源: stackexchange

问:
How do I generate script for LocalDB database?
I'm using localdb for development with Visual Studio and SSDT. I want to export the database schema and import it in full-fledged SQL Server instance. How do I do that?

I don't have (or want to install) SSMS. Can this be done with Visual Studio/SSDT only?

答: Just publish the SSDT project to another SQL Server instance/edition</p>

ContentLicense: CC BY-SA 3.0


问:
How to send GPS cordinates and current moving speed to phone db with timestamp
I'm new in to Android. I tried several ways to store GPS coordinates in my phone db.

Now the problem is I want to store GPS cordinates every x seconds with current moving vehicle speed and the time.

Also this function should start after a button click event.

答:
You just need to make one background service which will continuously fetch the GPS coordinates in every x seconds. The main reason behind making the service for this is when your application is not visible and it is minimized than also your service will be kept running and in the background of the application the GPS coordinates will be updated periodically.

For implementing you would need a FusedLocationAPI and GooglAPiClient. If you want a very simple code than follow this link:
Android make method run every X seconds (involves gps and server call)


问:
What are practical guidelines for evaluating a language's "Turing Completeness"?
I've read "what-is-turing-complete" and the wikipedia page, but I'm less interested in a formal proof than in the practical implications of requirements for being Turing Complete.

What I'm actually trying to decide is if the toy language I've just designed could be used as a general-purpose language.  I know I can prove it is if I can write a Turing machine with it.  But I don't want to go through that exercise until I'm fairly certain of success.

Is there a minimum set of features without which Turing Completeness is impossible?
Is there a set of features which virtually guarantees completeness?

(My guess is that conditional branching and a readable/writeable memory store will get me most of the way there)

EDIT:

I think I've gone off on a tangent by saying "Turing Complete".   I'm trying to guess with reasonable confidence that a newly invented language with a certain feature set (or alternately, a VM with a certain instruction set) would be able to compute anything worth computing.  I know that proving you can build a Turing machine with it is one way, but not the only way.

What I was hoping for was a set of guidelines like: "if a language can do X,Y,and Z, it can probably do anything".

答:
...than in the practical implications of being Turing Complete.

I doubt there are any practical implications of being Turing complete.

If you look at some of the examples of Turing complete machines, e.g., the original Turing machine, you'll see that the are so far from being useful for real computations that the concept must only be of theoretical interest.

OwnerDisplayName: AShelly

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: AShelly

OwnerDisplayName: David Norman

ContentLicense: CC BY-SA 2.5


问:
jquery - stretch background image to fill document rather than window?
I'm using this plugin: https://github.com/srobbin/jquery-backstretch to stretch a background in a good way.

So the issue is that if the content of the document is long enough to cause a scrollbar, then when you scroll, the image stays in the same place (just looks like a stationary background). You can see it in his demo here: http://srobbin.com/jquery-plugins/jquery-backstretch/ (this page uses the plugin. Just scroll and notice the background doesn't move).

I'm wondering if there's a way to change the plugin to not use the window height or something and rather use the document height? I've looked, but to no avail. I know this isn't a great idea in the case that the content is long, but it's done on only a single page that doesn't have much content at all. Really the only issues are if the browser real estate (not counting the chrome) is like less than around 650px in height.

Here's the plugin code. Pretty short and well written from what I can tell:
https://github.com/srobbin/jquery-backstretch/raw/master/jquery.backstretch.js

答:
I once had the same problem, this was my solution.

```<code>$(window).resize(bg);
function bg() {
    var imgWidth = 1088,
        imgHeight = 858,
        imgRatio = imgWidth / imgHeight,
        bgWidth = $(document).width(),
        bgHeight = bgWidth / imgRatio;

        $('body').css({backgroundPosition: 'top center'});
        if ($(document).width() < imgWidth && $(document).height() < imgHeight && $(document).height() > bgHeight) {
            $('body').css({backgroundSize: 'auto 100%'});
        } else {
            $('body').css({backgroundSize: '100% auto'});
        }
}
bg();
$('body').css({backgroundRepeat: 'repeat-x'});
$('body').css({backgroundImage: 'url("images/bg-state/bg_static2.png")'});
</code>```

Note: It do not stretch on IE due to the code uses the css3 property background-size and you need to set your own width and height of the image in the code.

Body:
I once had the same problem, this was my solution.

$(window).resize(bg);
function bg() {
    var imgWidth = 1088,
        imgHeight = 858,
        imgRatio = imgWidth / imgHeight,
        bgWidth = $(document).width(),
        bgHeight = bgWidth / imgRatio;

        $('body').css({backgroundPosition: 'top center'});
        if ($(document).width() < imgWidth && $(document).height() < imgHeight && $(document).height() > bgHeight) {
            $('body').css({backgroundSize: 'auto 100%'});
        } else {
            $('body').css({backgroundSize: '100% auto'});
        }
}
bg();
$('body').css({backgroundRepeat: 'repeat-x'});
$('body').css({backgroundImage: 'url("images/bg-state/bg_static2.png")'});

Note: It do not stretch on IE due to the code uses the css3 property background-size and you need to set your own width and height of the image in the code.


问:
Asynchronous method has no availble extension methods, but resulting variable does have
I'm createing some methods in a standard repository class using MongoDB with c# and async methods and I've stumbled upon some strange behaviour.

In the end it's probably not strange at all, rather the problem lies in my own inexperience with async programming.

Consider this code:

```<code>public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id);

            return await model.FirstOrDefaultAsync();
        }
</code>```

Now that is totally fine, no compilation errors but I'm actually not sure its's correct calling await 2 times.

Now consider this code:

```<code>public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id).FirstOrDefaultAsync();

            return model;
        }
</code>```

Thats illegal according to the compiler. It's complaining about FirstOrDefaultAsync() not being an availble method to call. I would have to call .Result first to get access to .FirstOrDefaultAsync().

What is going on here?

答:
I think it actually should be

var model = await (await col.FindAsync(x => x.Id == id)).FirstOrDefaultAsync();

both Async methods return a Task object, and Tasks don't have FirstOrDefault() method( this is why await in () is required). The other one is needed because this way model is your object and not a Task.

Body:
I'm createing some methods in a standard repository class using MongoDB with c# and async methods and I've stumbled upon some strange behaviour.

In the end it's probably not strange at all, rather the problem lies in my own inexperience with async programming.

Consider this code:

public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id);

            return await model.FirstOrDefaultAsync();
        }

Now that is totally fine, no compilation errors but I'm actually not sure its's correct calling await 2 times.

Now consider this code:

public async Task<T> GetItem<T>(ObjectId id) where T : BaseItemEntity
        {
            var col = GetTypedCollection<T>();

            var model = await col.FindAsync(x => x.Id == id).FirstOrDefaultAsync();

            return model;
        }

Thats illegal according to the compiler. It's complaining about FirstOrDefaultAsync() not being an availble method to call. I would have to call .Result first to get access to .FirstOrDefaultAsync().

What is going on here?


问:
Filtering by multiple items in React
I am trying to filter the list of items in state.items by adding items from state.filterItems to my state.filter array

if I use this.state.items.filter(items => items.cat === 'veg' ) of course this works but I need to be able to filter dynamically using the list of items added to my state.filter array and I'm not sure how to do this,

I would also like to be able select multiple options and then hit a button to apply the filters rather than selecting them one by one

https://www.webpackbin.com/bins/-KoCT_DiT2CNLz8ddr4O

Hello.js

```<code>import React, { Component } from 'react';
import logo from './logo.svg'
import './App.css'
import update from 'immutability-helper'
import TodoList from './TodoList'
import styled from 'styled-components'
import FilterList from './FilterList'

const Wrapper = styled.div`
  max-width:1280px;
  background: papayawhip;
  margin: 0 auto;
  padding:20px;
`

const Grid = styled.div`
  display:flex;
  flex-wrap:wrap;
`

const Cell = styled.div`
  flex: 0 0 25%;
  padding: 20px;
`

export default class hello extends Component {
  constructor(props) {
    super(props)
    this.state = {
      items: [
        {id: 1, cat: 'fruit', text: 'apples'},
        {id: 2, cat: 'fruit', text: 'oranges'},
        {id: 3, cat: 'fruit', text: 'peaches'},
        {id: 4, cat: 'veg', text: 'carrots'},
        {id: 5, cat: 'veg', text: 'aubergine'},
        {id: 6, cat: 'veg', text: 'peaches'},
        {id: 7, cat: 'bread', text: 'olive bread'},
        {id: 8, cat: 'bread', text: 'bread roll'},
        {id: 9, cat: 'bread', text: 'bagel'},
      ],
      filterItems: [
        {id: 1, text: 'bread'},
        {id: 2, text: 'fruit'},
        {id: 3, text: 'vegetables'},
      ],
      filter: [
        {text: 'bread'}
      ],
    }
  }

  handleFilterChange = (filter) => {
    this.setState({filter: filter})
  }

  render() {
    return (
      <Wrapper>
        <div>
        <FilterList
          value={this.state.filter}
          onChange={this.handleFilterChange}
          filterItems={this.state.filterItems}
        />
        </div>
        <Grid>
          {
            this.state.items.filter(items => items.cat === 'veg', 'fruit' )
            .map(item =>
              <Cell>
                {console.log(this.state.filter.text)}
                <div>{item.cat}</div>
                <div>{item.text}</div>
              </Cell>
            )
          }
        </Grid>
      </Wrapper>
    )
  }
}

//  ```{JSON.stringify(this.state, null, 4)} ```
</code>```

FilterList.js

```<code>import React, { Component } from 'react';
import TodoItem from './TodoItem'
import update from 'immutability-helper'
import styled from 'styled-components'

const FilterListBg = styled.div`
  background: lightblue;
  width: 100%;
  height: 60px;
`

const FilterListItem = styled.div`
  float: left;
  height: 40px;
  width: 100px;
  padding:10px;
  border-right: 1px solid #ff00ff;
`

const FilterBg = styled.div`
  width: 100%;
  height:40px;
  background: #fff;
  margin-top:20px;
`

const FilterItem = styled.div`
  float: left;
  height: 40px;
  width: 100px;
  padding:10px;
  border-right: 1px solid #ff00ff;
`
export default class FilterList extends Component {
  constructor() {
    super()

    this.state = {
      search: ''
    }
  }
  handleAdd = (item) => {
      const value = update(this.props.value, {
          $push: [
            {
            text: item,
            id: Math.random(),
            }
          ]
      })
      this.props.onChange(value)
    }

  handleRemove = (index) => {
      const value = update(this.props.value, {
        $splice: [
          [index, 1]
        ]
      })
      this.props.onChange(value)
    }

  handleFilterUpdate = event => {
    this.setState({ search: event.target.value })
  }

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.search}
          onChange={this.handleFilterUpdate}
          placeholder="Hledat podle nazvu"
        />
        {this.state.search}
        <FilterListBg>
          {
            this.props.filterItems.filter(items => items.text.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0)
            .map((item,cat,index) =>
              <FilterListItem key={item.id} onClick={()=>this.handleAdd(item.text)}>
                {item.text}
              </FilterListItem>
            )
          }
        </FilterListBg>
        Aktivní filtry
        <FilterBg>
          {
            this.props.value.map((item, index) =>
            <FilterItem key={item.id} onClick={this.handleRemove}>
              {item.text}
            </FilterItem>
            )
          }
        </FilterBg>

      </div>
    )
  }
}
</code>```

答:
Assuming you want to show the items matching your filterList, shouldn't something simple like this work?

```<code>const filterTexts = this.state.filter.map(item => item.text);
const itemsToShow = this.state.items.filter(
                      item => filterTexts.indexOf(item.cat) !== -1);
</code>```

And then you can map over itemsToShow to create your Cells.

If you want a one-liner to simply copy-paste:

```<code>this.state.items.filter(items => this.state.filterItems.map(item => item.text)
                          .indexOf(items.cat) !== -1 )
    .map(item =>
        <Cell>
            {console.log(this.state.filter.text)}
            <div>{item.cat}</div>
            <div>{item.text}</div>
        </Cell>
    )
</code>```

Title: Filtering by multiple items in React

Body:
I am trying to filter the list of items in state.items by adding items from state.filterItems to my state.filter array

if I use this.state.items.filter(items => items.cat === 'veg' ) of course this works but I need to be able to filter dynamically using the list of items added to my state.filter array and I'm not sure how to do this,

I would also like to be able select multiple options and then hit a button to apply the filters rather than selecting them one by one

https://www.webpackbin.com/bins/-KoCT_DiT2CNLz8ddr4O

Hello.js

import React, { Component } from 'react';
import logo from './logo.svg'
import './App.css'
import update from 'immutability-helper'
import TodoList from './TodoList'
import styled from 'styled-components'
import FilterList from './FilterList'

const Wrapper = styled.div`
  max-width:1280px;
  background: papayawhip;
  margin: 0 auto;
  padding:20px;
`

const Grid = styled.div`
  display:flex;
  flex-wrap:wrap;
`

const Cell = styled.div`
  flex: 0 0 25%;
  padding: 20px;
`

export default class hello extends Component {
  constructor(props) {
    super(props)
    this.state = {
      items: [
        {id: 1, cat: 'fruit', text: 'apples'},
        {id: 2, cat: 'fruit', text: 'oranges'},
        {id: 3, cat: 'fruit', text: 'peaches'},
        {id: 4, cat: 'veg', text: 'carrots'},
        {id: 5, cat: 'veg', text: 'aubergine'},
        {id: 6, cat: 'veg', text: 'peaches'},
        {id: 7, cat: 'bread', text: 'olive bread'},
        {id: 8, cat: 'bread', text: 'bread roll'},
        {id: 9, cat: 'bread', text: 'bagel'},
      ],
      filterItems: [
        {id: 1, text: 'bread'},
        {id: 2, text: 'fruit'},
        {id: 3, text: 'vegetables'},
      ],
      filter: [
        {text: 'bread'}
      ],
    }
  }

  handleFilterChange = (filter) => {
    this.setState({filter: filter})
  }

  render() {
    return (
      <Wrapper>

        <FilterList
          value={this.state.filter}
          onChange={this.handleFilterChange}
          filterItems={this.state.filterItems}
        />

        <Grid>
          {
            this.state.items.filter(items => items.cat === 'veg', 'fruit' )
            .map(item =>
              <Cell>
                {console.log(this.state.filter.text)}

{item.cat}

{item.text}

              </Cell>
            )
          }
        </Grid>
      </Wrapper>
    )
  }
}

//
{JSON.stringify(this.state, null, 4)}

FilterList.js

import React, { Component } from 'react';
import TodoItem from './TodoItem'
import update from 'immutability-helper'
import styled from 'styled-components'

const FilterListBg = styled.div`
  background: lightblue;
  width: 100%;
  height: 60px;
`

const FilterListItem = styled.div`
  float: left;
  height: 40px;
  width: 100px;
  padding:10px;
  border-right: 1px solid #ff00ff;
`

const FilterBg = styled.div`
  width: 100%;
  height:40px;
  background: #fff;
  margin-top:20px;
`

const FilterItem = styled.div`
  float: left;
  height: 40px;
  width: 100px;
  padding:10px;
  border-right: 1px solid #ff00ff;
`
export default class FilterList extends Component {
  constructor() {
    super()

    this.state = {
      search: ''
    }
  }
  handleAdd = (item) => {
      const value = update(this.props.value, {
          $push: [
            {
            text: item,
            id: Math.random(),
            }
          ]
      })
      this.props.onChange(value)
    }

  handleRemove = (index) => {
      const value = update(this.props.value, {
        $splice: [
          [index, 1]
        ]
      })
      this.props.onChange(value)
    }

  handleFilterUpdate = event => {
    this.setState({ search: event.target.value })
  }

  render() {
    return (

        <input
          type="text"
          value={this.state.search}
          onChange={this.handleFilterUpdate}
          placeholder="Hledat podle nazvu"
        />
        {this.state.search}
        <FilterListBg>
          {
            this.props.filterItems.filter(items => items.text.toLowerCase().indexOf(this.state.search.toLowerCase()) >= 0)
            .map((item,cat,index) =>
              <FilterListItem key={item.id} onClick={()=>this.handleAdd(item.text)}>
                {item.text}
              </FilterListItem>
            )
          }
        </FilterListBg>
        Aktivní filtry
        <FilterBg>
          {
            this.props.value.map((item, index) =>
            <FilterItem key={item.id} onClick={this.handleRemove}>
              {item.text}
            </FilterItem>
            )
          }
        </FilterBg>

    )
  }
}

Body:
Assuming you want to show the items matching your filterList, shouldn't something simple like this work?

const filterTexts = this.state.filter.map(item => item.text);
const itemsToShow = this.state.items.filter(
                      item => filterTexts.indexOf(item.cat) !== -1);

And then you can map over itemsToShow to create your Cells.

If you want a one-liner to simply copy-paste:

this.state.items.filter(items => this.state.filterItems.map(item => item.text)
                          .indexOf(items.cat) !== -1 )
    .map(item =>
        <Cell>
            {console.log(this.state.filter.text)}
            <div>{item.cat}</div>
            <div>{item.text}</div>
        </Cell>
    )


答:
In SSDT, just do a schema compare against a blank database and it will build a change script for you.

https://msdn.microsoft.com/en-us/library/hh272690(v=vs.103).aspx

Title: How do I generate script for LocalDB database?

Body:
I'm using localdb for development with Visual Studio and SSDT. I want to export the database schema and import it in full-fledged SQL Server instance. How do I do that?

I don't have (or want to install) SSMS. Can this be done with Visual Studio/SSDT only?


问:
java gregoriancalendar off by an hour
I did:

```<code>GregorianCalendar gc = new GregorianCalendar(Locale.French);
</code>```

And the hour is off by one hour. I get 14:17 instead of 15:17.
My first thought was DST, but I think gregoriancalendar takes that into account.

The time is set correctly on my pc.

答: I am not sure what you are trying, but GregorianCalendar(Locale) is always based on your default time zone.  -- Maybe you should have a look at GregorianCalendar(TimeZone zone, Locale aLocale)

Title: java gregoriancalendar off by an hour

Body:
I did:

GregorianCalendar gc = new GregorianCalendar(Locale.French);

And the hour is off by one hour. I get 14:17 instead of 15:17.
My first thought was DST, but I think gregoriancalendar takes that into account.

The time is set correctly on my pc.


问:
Is it possible to access QML anchors from C++?
When creating QML QQuickItems from c++ code, is it possible to access/modify anchors?

All anchors properties are declared as Q_PRIVATE_PROPERTY in QQuickItem and I don't see any method which could help.

Or do I have to implement anchors by my own by using signals/events and QLayout?

What I would need is for example:

```<code>Rectangle {
    // ...
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 0
    anchors.top: parent.top
    anchors.topMargin: 0
    anchors.right: parent.right
    anchors.rightMargin: -10
    // ...
}
</code>```

答:
Unlike what the previous answers indicate, it is both possible and has valid use cases. All Qt objects, even the private ones, have introspection APIs. Those APIs what you use from the QML engine. They can be used from C++ too:

```<code>qvariant_cast<QObject*>(
    item->property("anchors")
)->setProperty("top", otherItem->property("bottom"));
</code>```

Note that there is a race condition because some threads are involved.

QML only supports model lists. Displaying other structures like trees or table is either badly implemented (QtQuickControls 1.x) or mindbogglingly  inefficient (recursive repeaters). For some data structures, C++ is also the only way to implement lazy loading correctly. QML Loader go a long way, but not all the way.

Body:
When creating QML QQuickItems from c++ code, is it possible to access/modify anchors?

All anchors properties are declared as Q_PRIVATE_PROPERTY in QQuickItem and I don't see any method which could help.

Or do I have to implement anchors by my own by using signals/events and QLayout?

What I would need is for example:

Rectangle {
    // ...
    anchors.bottom: parent.bottom
    anchors.bottomMargin: 0
    anchors.top: parent.top
    anchors.topMargin: 0
    anchors.right: parent.right
    anchors.rightMargin: -10
    // ...
}

Body:
Unlike what the previous answers indicate, it is both possible and has valid use cases. All Qt objects, even the private ones, have introspection APIs. Those APIs what you use from the QML engine. They can be used from C++ too:

qvariant_cast<QObject*>(
    item->property("anchors")
)->setProperty("top", otherItem->property("bottom"));

Note that there is a race condition because some threads are involved.

QML only supports model lists. Displaying other structures like trees or table is either badly implemented (QtQuickControls 1.x) or mindbogglingly  inefficient (recursive repeaters). For some data structures, C++ is also the only way to implement lazy loading correctly. QML Loader go a long way, but not all the way.


问:
How can I include the CSS or JS files from a ZIP folder in my HTML page?
I have a zipped folder of all the CSS and JS files for my desktop Electron application. I am trying to refer a CSS file from this zip using the below syntax which isn't working:

```<code><link rel="stylesheet" type="text/css"
  href="../css/resources.zip/assets/styles/style.min.css">
</code>```

Is this even possible or am I making some syntax errors?

答:
You could do this by using a package like adm-zip.

You could open the zip using this and get the files you want and just add the file content to your page using fs. Its not the best method but it is possible.

Like @domdom said you could just unzip it.

Body:
I have a zipped folder of all the CSS and JS files for my desktop Electron application. I am trying to refer a CSS file from this zip using the below syntax which isn't working:

<link rel="stylesheet" type="text/css"
  href="../css/resources.zip/assets/styles/style.min.css">

Is this even possible or am I making some syntax errors?


问:
Is there a way to just rotate text vertically? Without rotating the whole cell?
I'm trying to do it using this:

```<code>.VerticalText {
transform: rotate(-90deg);
}
</code>```

but it's rotating the text and cell. How do I just rotate the text vertically inside the cell?

答:
You should make a div what is outside the text, and rotate that the other way.

So: If

```<code>.VerticalText {
    transform: rotate(-90deg);
}
</code>```

and the div outside is called for example .VerticalTextWrapper

```<code>.VerticalTextWrapper {
    transform: rotate(90deg);
}
</code>```

Hope that helps!

Body:
I'm trying to do it using this:

.VerticalText {
transform: rotate(-90deg);
}

but it's rotating the text and cell. How do I just rotate the text vertically inside the cell?

Body:
You should make a div what is outside the text, and rotate that the other way.

So: If

.VerticalText {
    transform: rotate(-90deg);
}

and the div outside is called for example .VerticalTextWrapper

.VerticalTextWrapper {
    transform: rotate(90deg);
}

Hope that helps!


问:
Cascading LOVS - default values
I have two cascading LOVs. After changing value of my first LOV in second LOV appropriate values are populated.

First LOV:
name - P2_DEPTNO

```<code>select dname, deptno
from dept
order by 1;
</code>```

Second LOV:
name - P2_EMPNO

```<code>select ename, empno
from emp
where deptno = :P2_DEPTNO;
</code>```

cascading LOV parent - P2_DEPTNO

What should I add to set default value of second LOV (first row from query) after changing first LOV value?

答: Make sure you have Display Null Value set to No and it should use the first value in the list. (Although I am not sure what it will do with Popup LOV). </p>

Title: Cascading LOVS - default values

Body:
I have two cascading LOVs. After changing value of my first LOV in second LOV appropriate values are populated.

First LOV:
name - P2_DEPTNO

select dname, deptno
from dept
order by 1;

Second LOV:
name - P2_EMPNO

select ename, empno
from emp
where deptno = :P2_DEPTNO;

cascading LOV parent - P2_DEPTNO

What should I add to set default value of second LOV (first row from query) after changing first LOV value?


问:
Realm objects can only be accessed on the thread they were created
I am downloading JSON data from a url and since i plan it to use across many activities, i am storing it offline using Realm, now when i try to access the stored data from mainactivity, it is working fine, but the data is such that, it is a arraylist consisting of two more arraylists (nested arraylists).
So whenever i want to access one of the arraylists of the main object in the second screen, i am sending the position of the object from main to second. and am trying to get the data from there. but it is showing that error.

Any help would be appreciated. Thanks in advance.

Stack Trace

```<code>    FATAL EXCEPTION: main
                                                                         Process: com.example.vamshi.baking, PID: 2643
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vamshi.baking/com.example.vamshi.baking.UI.SecondScreenDetails}: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                                             at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                                          Caused by: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
                                                                             at io.realm.BaseRealm.checkIfValid(BaseRealm.java:385)
                                                                             at io.realm.IngredientsRealmProxy.realmGet$quantity(IngredientsRealmProxy.java:98)
                                                                             at com.example.vamshi.baking.Data.Ingredients.getQuantity(Ingredients.java:28)
                                                                             at com.example.vamshi.baking.UI.SecondScreenDetails.setDisplay(SecondScreenDetails.java:63)
                                                                             at com.example.vamshi.baking.UI.SecondScreenDetails.onCreate(SecondScreenDetails.java:42)
                                                                             at android.app.Activity.performCreate(Activity.java:6303)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                                             at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-04 17:42:44.452 2643-2643/com.example.vamshi.baking E/MQSEventManagerDelegate: failed to get MQSService.
</code>```

MainActivity

```<code>    public class MainActivity extends AppCompatActivity {

    public static ListView myList;
    public static ListAdapter myAdapter;
    public static Realm realm;

    @Override
    protected  void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Realm.init(this);
        realm = Realm.getDefaultInstance();

        DownloadTask newTask = new DownloadTask();
        newTask.execute("hi");
        setContentView(R.layout.activity_main);
        myList = (ListView) findViewById(R.id.Recipe_list);

       // getData();

        setDisplay();

        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String p = String.valueOf(position);
//                Toast.makeText(MainActivity.this, p, Toast.LENGTH_SHORT).show();
                Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
                in.putExtra("Position", p);
                startActivity(in);
            }
        });

    }

    public void setDisplay(){

        ArrayList<Recipe> finalRecipies = new ArrayList<>();
        RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();

        for(Recipe r: rrRecipies){
            finalRecipies.add(r);
//            Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
        }
        myAdapter = new ListViewAdapter(this, finalRecipies);
        myList.setAdapter(myAdapter);

    }

    @Override
    protected void onDestroy() {
        realm.close();
        super.onDestroy();
    }
}
</code>```

SecondScreenActivity (Problem Activity)

```<code>    public class SecondScreenDetails extends AppCompatActivity {

    public Realm realm;
    @BindView(R.id.ingredients_list)RecyclerView ingre_list;
    @BindView(R.id.steps_button)Button next_button;
    public int position;
    public static SecondScreenRecyclerViewAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second_screen_details);
        Realm.init(this);
        realm = Realm.getDefaultInstance();
        setDisplay();
        ButterKnife.bind(this);
        next_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void setDisplay() {
        ArrayList<Recipe> finalRecipies = new ArrayList<>();
        ArrayList<Ingredients> finalIngredients = new ArrayList<>();
        RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
        Intent in = getIntent();
        position = Integer.parseInt(in.getStringExtra("Position"));
        for(Recipe r: rrRecipies){
            finalRecipies.add(r);
        }
        int i = finalRecipies.get(position).getIngredients().size();
        for( int j = 0 ; j<i ; j++){
            Ingredients n = new Ingredients(finalRecipies.get(position).getIngredients().get(j).getQuantity(),
                    finalRecipies.get(position).getIngredients().get(j).getMeasure(),
                    finalRecipies.get(position).getIngredients().get(j).getIngredient());
            finalIngredients.add(n);
        }
        myAdapter = new SecondScreenRecyclerViewAdapter(finalIngredients);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        ingre_list.setLayoutManager(mLayoutManager);
        ingre_list.setItemAnimator(new DefaultItemAnimator());
        ingre_list.setAdapter(myAdapter);
    }
}
</code>```

DownloadingData Class

```<code>    public class DownloadTask extends AsyncTask<String,Void,String> {

    private RealmList<Recipe> realmRecipe = new RealmList<>();
    String result;

    @Override
    protected String doInBackground(String... params) {
        result = "";
        Realm realm = null;
            realm = Realm.getDefaultInstance();
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
                    try {
                        result = client.newCall(request).execute().body().string();
                        Log.i("RESULT", result);
                        JSONArray rootArray = new JSONArray(result);
                        for (int i = 0; i < rootArray.length(); i++) {
                            JSONObject tempObject = rootArray.getJSONObject(i);
                            JSONArray jIngredients = tempObject.getJSONArray("ingredients");
                            JSONArray jSteps = tempObject.getJSONArray("steps");

                            // Get the ingredients
                            List<Ingredients> ingredients = new ArrayList<>();
                            for (int j = 0; j < jIngredients.length(); j++) {
                                JSONObject tempIngredient = jIngredients.getJSONObject(j);
                                Ingredients nIngredient = realm.createObject(Ingredients.class);
                                nIngredient.setIngredient(tempIngredient.getString("ingredient"));
                                nIngredient.setMeasure(tempIngredient.getString("measure"));
                                nIngredient.setQuantity(tempIngredient.getString("quantity"));
//                                Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
//                                        tempIngredient.getString("measure"),
//                                        tempIngredient.getString("ingredient"));
//                                ingredients.add(newIngredient);
                                ingredients.add(nIngredient);
                            }

                            // Get the steps
                            List<Steps> steps = new ArrayList<>();
                            for (int j = 0; j < jSteps.length(); j++) {
                                JSONObject tempStep = jSteps.getJSONObject(j);
                                Steps nStep = realm.createObject(Steps.class);
                                nStep.setDescription(tempStep.getString("description"));
                                nStep.setId(tempStep.getString("id"));
                                nStep.setShortDescription(tempStep.getString("shortDescription"));
                                nStep.setVideoURL(tempStep.getString("videoURL"));
                                steps.add(nStep);
//                                Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
//                                        tempStep.getString("description"), tempStep.getString("videoURL"));
//                                steps.add(newStep);
                            }

                            // Create the recipe

                            Recipe nRecipe = realm.createObject(Recipe.class);
                            nRecipe.setId(tempObject.getString("id"));
                            nRecipe.setName(tempObject.getString("name"));
                            nRecipe.setServings(tempObject.getString("servings"));
                            nRecipe.setIngredients(ingredients);
                            nRecipe.setSteps(steps);
                            realmRecipe.add(nRecipe);
//                            Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
//                            MainActivity.mRecipies.add(newRecipe);

                        }
                    }catch (Exception e){
                        Log.i("Error Message", e.getMessage());
                    }

                }
            });

        return null;
    }

    @Override
    protected void onPostExecute(String s) {

            super.onPostExecute(s);
        }
    }
</code>```

答: You can abstract all the logic of the data request within the AsyncTask, and within decide whether to return realm data or service data.</p>

Body:
I am downloading JSON data from a url and since i plan it to use across many activities, i am storing it offline using Realm, now when i try to access the stored data from mainactivity, it is working fine, but the data is such that, it is a arraylist consisting of two more arraylists (nested arraylists).
So whenever i want to access one of the arraylists of the main object in the second screen, i am sending the position of the object from main to second. and am trying to get the data from there. but it is showing that error.

Any help would be appreciated. Thanks in advance.

Stack Trace

    FATAL EXCEPTION: main
                                                                         Process: com.example.vamshi.baking, PID: 2643
                                                                         java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vamshi.baking/com.example.vamshi.baking.UI.SecondScreenDetails}: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2449)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                                             at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
                                                                          Caused by: java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
                                                                             at io.realm.BaseRealm.checkIfValid(BaseRealm.java:385)
                                                                             at io.realm.IngredientsRealmProxy.realmGet$quantity(IngredientsRealmProxy.java:98)
                                                                             at com.example.vamshi.baking.Data.Ingredients.getQuantity(Ingredients.java:28)
                                                                             at com.example.vamshi.baking.UI.SecondScreenDetails.setDisplay(SecondScreenDetails.java:63)
                                                                             at com.example.vamshi.baking.UI.SecondScreenDetails.onCreate(SecondScreenDetails.java:42)
                                                                             at android.app.Activity.performCreate(Activity.java:6303)
                                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
                                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2402)
                                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2509)
                                                                             at android.app.ActivityThread.access$1000(ActivityThread.java:153)
                                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
07-04 17:42:44.452 2643-2643/com.example.vamshi.baking E/MQSEventManagerDelegate: failed to get MQSService.

MainActivity

    public class MainActivity extends AppCompatActivity {

    public static ListView myList;
    public static ListAdapter myAdapter;
    public static Realm realm;

    @Override
    protected  void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Realm.init(this);
        realm = Realm.getDefaultInstance();

        DownloadTask newTask = new DownloadTask();
        newTask.execute("hi");
        setContentView(R.layout.activity_main);
        myList = (ListView) findViewById(R.id.Recipe_list);

       // getData();

        setDisplay();

        myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String p = String.valueOf(position);
//                Toast.makeText(MainActivity.this, p, Toast.LENGTH_SHORT).show();
                Intent in = new Intent(MainActivity.this, SecondScreenDetails.class);
                in.putExtra("Position", p);
                startActivity(in);
            }
        });

    }

    public void setDisplay(){

        ArrayList<Recipe> finalRecipies = new ArrayList<>();
        RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();

        for(Recipe r: rrRecipies){
            finalRecipies.add(r);
//            Toast.makeText(this, r.getName(), Toast.LENGTH_SHORT).show();
        }
        myAdapter = new ListViewAdapter(this, finalRecipies);
        myList.setAdapter(myAdapter);

    }

    @Override
    protected void onDestroy() {
        realm.close();
        super.onDestroy();
    }
}

SecondScreenActivity (Problem Activity)

    public class SecondScreenDetails extends AppCompatActivity {

    public Realm realm;
    @BindView(R.id.ingredients_list)RecyclerView ingre_list;
    @BindView(R.id.steps_button)Button next_button;
    public int position;
    public static SecondScreenRecyclerViewAdapter myAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second_screen_details);
        Realm.init(this);
        realm = Realm.getDefaultInstance();
        setDisplay();
        ButterKnife.bind(this);
        next_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    private void setDisplay() {
        ArrayList<Recipe> finalRecipies = new ArrayList<>();
        ArrayList<Ingredients> finalIngredients = new ArrayList<>();
        RealmResults<Recipe> rrRecipies = realm.where(Recipe.class).findAll();
        Intent in = getIntent();
        position = Integer.parseInt(in.getStringExtra("Position"));
        for(Recipe r: rrRecipies){
            finalRecipies.add(r);
        }
        int i = finalRecipies.get(position).getIngredients().size();
        for( int j = 0 ; j<i ; j++){
            Ingredients n = new Ingredients(finalRecipies.get(position).getIngredients().get(j).getQuantity(),
                    finalRecipies.get(position).getIngredients().get(j).getMeasure(),
                    finalRecipies.get(position).getIngredients().get(j).getIngredient());
            finalIngredients.add(n);
        }
        myAdapter = new SecondScreenRecyclerViewAdapter(finalIngredients);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        ingre_list.setLayoutManager(mLayoutManager);
        ingre_list.setItemAnimator(new DefaultItemAnimator());
        ingre_list.setAdapter(myAdapter);
    }
}

DownloadingData Class

    public class DownloadTask extends AsyncTask<String,Void,String> {

    private RealmList<Recipe> realmRecipe = new RealmList<>();
    String result;

    @Override
    protected String doInBackground(String... params) {
        result = "";
        Realm realm = null;
            realm = Realm.getDefaultInstance();
            realm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json").build();
                    try {
                        result = client.newCall(request).execute().body().string();
                        Log.i("RESULT", result);
                        JSONArray rootArray = new JSONArray(result);
                        for (int i = 0; i < rootArray.length(); i++) {
                            JSONObject tempObject = rootArray.getJSONObject(i);
                            JSONArray jIngredients = tempObject.getJSONArray("ingredients");
                            JSONArray jSteps = tempObject.getJSONArray("steps");

                            // Get the ingredients
                            List<Ingredients> ingredients = new ArrayList<>();
                            for (int j = 0; j < jIngredients.length(); j++) {
                                JSONObject tempIngredient = jIngredients.getJSONObject(j);
                                Ingredients nIngredient = realm.createObject(Ingredients.class);
                                nIngredient.setIngredient(tempIngredient.getString("ingredient"));
                                nIngredient.setMeasure(tempIngredient.getString("measure"));
                                nIngredient.setQuantity(tempIngredient.getString("quantity"));
//                                Ingredients newIngredient = new Ingredients(tempIngredient.getString("quantity"),
//                                        tempIngredient.getString("measure"),
//                                        tempIngredient.getString("ingredient"));
//                                ingredients.add(newIngredient);
                                ingredients.add(nIngredient);
                            }

                            // Get the steps
                            List<Steps> steps = new ArrayList<>();
                            for (int j = 0; j < jSteps.length(); j++) {
                                JSONObject tempStep = jSteps.getJSONObject(j);
                                Steps nStep = realm.createObject(Steps.class);
                                nStep.setDescription(tempStep.getString("description"));
                                nStep.setId(tempStep.getString("id"));
                                nStep.setShortDescription(tempStep.getString("shortDescription"));
                                nStep.setVideoURL(tempStep.getString("videoURL"));
                                steps.add(nStep);
//                                Steps newStep = new Steps(tempStep.getString("id"), tempStep.getString("shortDescription"),
//                                        tempStep.getString("description"), tempStep.getString("videoURL"));
//                                steps.add(newStep);
                            }

                            // Create the recipe

                            Recipe nRecipe = realm.createObject(Recipe.class);
                            nRecipe.setId(tempObject.getString("id"));
                            nRecipe.setName(tempObject.getString("name"));
                            nRecipe.setServings(tempObject.getString("servings"));
                            nRecipe.setIngredients(ingredients);
                            nRecipe.setSteps(steps);
                            realmRecipe.add(nRecipe);
//                            Recipe newRecipe = new Recipe(tempObject.getString("id"), tempObject.getString("name"), tempObject.getString("servings"), ingredients, steps);
//                            MainActivity.mRecipies.add(newRecipe);

                        }
                    }catch (Exception e){
                        Log.i("Error Message", e.getMessage());
                    }

                }
            });

        return null;
    }

    @Override
    protected void onPostExecute(String s) {

            super.onPostExecute(s);
        }
    }


问:
UNRESOLVED_REFERENCE in widget (TextView) resolved to error element in android-kotlin
How to update the text of Textview in kotlin. Set Text on-create function works but when I tried outside main fun it says unresolved ref.

How can I declare widget for reuse TextView for update the Text Value?
I don't have exp with kotlin. Can somebody help me?

```<code>class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        val Tv_test = findViewById(R.id.tv_text) as TextView

        Tv_test.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        // Error is here. I can't set text.
        Tv_test.setText("$fullName :: $score ")
    }

}
</code>```

答:
You should declare your Views as class level properties, and then you can access them from anywhere within the class. A variable declared inside a function is only accessible in that function.

```<code>class MediaPickedActivity : AppCompatActivity() {
    lateinit var Tv_test: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        Tv_test = findViewById(R.id.tv_text) as TextView
    }

    private fun setText() {
        Tv_test.setText("$fullName :: $score ")
    }
}
</code>```

I used lateinit in this example, but see a detailed discussion about different ways to declare the property here.

Body:
How to update the text of Textview in kotlin. Set Text on-create function works but when I tried outside main fun it says unresolved ref.

How can I declare widget for reuse TextView for update the Text Value?
I don't have exp with kotlin. Can somebody help me?

class MediaPickedActivity : AppCompatActivity() {

    val fullName = "Test User"
    var score = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        val Tv_test = findViewById(R.id.tv_text) as TextView

        Tv_test.setText("$fullName :: $score ")

        if (score in 0..300) {
            score = 5
            setText()
        }

    }

    private fun setText() {
        // Error is here. I can't set text.
        Tv_test.setText("$fullName :: $score ")
    }

}

Body:
You should declare your Views as class level properties, and then you can access them from anywhere within the class. A variable declared inside a function is only accessible in that function.

class MediaPickedActivity : AppCompatActivity() {
    lateinit var Tv_test: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_media_picked)

        Tv_test = findViewById(R.id.tv_text) as TextView
    }

    private fun setText() {
        Tv_test.setText("$fullName :: $score ")
    }
}

I used lateinit in this example, but see a detailed discussion about different ways to declare the property here.


问:
Custom ajax validation for text length doesn't work yii2
I am trying to check the length of the text entered but without success. It is working with the required rule because i get the field is empty error but not with mine validation. My custom rule works only on form submit. Also tried to enable ajax validation of the form but again nothing.

```<code>public function rules()
    {
        return [
            [['author_id', 'title', 'review'], 'required'],
            [['author_id'], 'integer'],
            [['review'], 'string'],
            [['review'], function($attribute, $params){
                if(strlen($this->$attribute) < 10){
                    $this->addError($attribute, 'The review is too short! Minimum 10 symbols!');
                }
            }],
            [['review'], 'trim'],
            [['dt'], 'safe'],
            [['title'], 'string', 'max' => 255],
            [['author_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['author_id' => 'id']],
            [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => News::className(), 'targetAttribute' => ['post_id' => 'id']],
        ];
    }
</code>```

My form:

```<code><?php $form=\yii\bootstrap\ActiveForm::begin([
                                'method' => 'post',
                                'options' => [
                                    'id' => 'textarea_' . $model->id . '',
                                    'class' => "textarea_review"
                                ],

                            ]) ?>

                            <input type="hidden" name="flag" value="1"/>
                            <input type="hidden" name="model_id" value="<?= $model->id ?>"/>
                            <?= $form->field($model, 'review')->textarea(['id'=>'update_text_'.$model->id.''])->label(false) ?>
                            <?= $form->field($model, 'csrf_token')->hiddenInput(['value' => $session['token']])->label(false) ?>

                            <?= Html::button('Изпрати', ['onclick'=>'editComment('.$model->id.')', 'class'=>'btn btn-primary send-button']) ?>
                            <?php \yii\bootstrap\ActiveForm::end() ?>
</code>```

Thank you in advance!

答:
For client-side validation you have to set whenClient property aswell, where you put javascript validation.

Here docs: Client Side Validation

Body:
I am trying to check the length of the text entered but without success. It is working with the required rule because i get the field is empty error but not with mine validation. My custom rule works only on form submit. Also tried to enable ajax validation of the form but again nothing.

public function rules()
    {
        return [
            [['author_id', 'title', 'review'], 'required'],
            [['author_id'], 'integer'],
            [['review'], 'string'],
            [['review'], function($attribute, $params){
                if(strlen($this->$attribute) < 10){
                    $this->addError($attribute, 'The review is too short! Minimum 10 symbols!');
                }
            }],
            [['review'], 'trim'],
            [['dt'], 'safe'],
            [['title'], 'string', 'max' => 255],
            [['author_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['author_id' => 'id']],
            [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => News::className(), 'targetAttribute' => ['post_id' => 'id']],
        ];
    }

My form:

<?php $form=\yii\bootstrap\ActiveForm::begin([
                                'method' => 'post',
                                'options' => [
                                    'id' => 'textarea_' . $model->id . '',
                                    'class' => "textarea_review"
                                ],

                            ]) ?>

                            <input type="hidden" name="flag" value="1"/>
                            <input type="hidden" name="model_id" value="<?= $model->id ?>"/>
                            <?= $form->field($model, 'review')->textarea(['id'=>'update_text_'.$model->id.''])->label(false) ?>
                            <?= $form->field($model, 'csrf_token')->hiddenInput(['value' => $session['token']])->label(false) ?>

                            <?= Html::button('Изпрати', ['onclick'=>'editComment('.$model->id.')', 'class'=>'btn btn-primary send-button']) ?>
                            <?php \yii\bootstrap\ActiveForm::end() ?>

Thank you in advance!


问:
How to merge develop branch to master branch within SourceTree?
I have created a local git repository in C:\temp\ConsoleApplication1. Then I click the Git Flow button and follow by OK to accept all default settings. Now under the branches, I can see develop and master.

Next I click Git Flow again to start a new feature, then make some changes and finally finish the feature.

Now my branch looks as follows:

```<code>[develop] add line 1
[master] initial commit
</code>```

Question: I would like to merge the develop into the master branch. What is the right method to achieve that?

I have tried to select develop branch, then click Merge button. No matter which commit I choose, there is nothing happens. I also tried to select master and see no difference.

答:
Within SourceTree, switch your working copy to the local/branch

Merge the changes from the remote/master using SourceTree or git command prompt

Resolve conflicts using Sourcetree or external text editor.(save changes to yours that you want to keep, discard remote conflict)

Commit and push the changes to remote/branch

On the GitHub web UI, switch to the relevant branch, then create a new pull request(If all conflicts are not resolved you will not be able to create a pull request)

Admins will be notified of pull request and changes will be accepted or changes will be requested. If there are no admins setup, the pull request will automatically get merged.

Body:
I have created a local git repository in C:\temp\ConsoleApplication1. Then I click the Git Flow button and follow by OK to accept all default settings. Now under the branches, I can see develop and master.

Next I click Git Flow again to start a new feature, then make some changes and finally finish the feature.

Now my branch looks as follows:

[develop] add line 1
[master] initial commit

Question: I would like to merge the develop into the master branch. What is the right method to achieve that?

I have tried to select develop branch, then click Merge button. No matter which commit I choose, there is nothing happens. I also tried to select master and see no difference.


问:
fire event when touch up inside uiview and outside button
I have a view overlayed to the iPhone's camera view. In this view I have some uibuttons that are displayed in positions depending of values from accelerometer/compass.
I need to fire an event when the user touch up inside the view but he doesn't touch up inside the uibuttons, I mean, the opposite action of touch up inside the uibuttons.
Anyone knows a kind to do this?
Thanks! </p>

答:
If you implement the UIResponder touchesBegan:withEvent: method..

```<code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
</code>```

...on your view, you'll be able to tell when the user has pressed outside of the buttons.

See the UIResponder Class Reference for more information.

Body:
If you implement the UIResponder touchesBegan:withEvent: method..

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

...on your view, you'll be able to tell when the user has pressed outside of the buttons.

See the UIResponder Class Reference for more information.


问:
Android - Firebase notifications not working
I'm having an issue with Firebase notifications. I set up it as the docs but it's not working. Below, you can see my code. Although I think everything is right.

Here's my NotificationsService

```<code>public class NotificationsService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String TAG = "Notification";

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
}
</code>```

And the AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.usefashion.useapp">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".NotificationsService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".InstanceIdService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>
</code>```

It would be great if anyone could help me. I have an InstanceIdService too but its not the part of this question.

Edit 1:

I realized that when I send a notification by console, this message is showed in debug:

```<code>E/FirebaseInstanceId: Error resolving target intent service, skipping classname enforcement. Resolved service was: com.taplane.triviaquiz/com.msi.logocore.helpers.thirdparty.firebase.FirebaseServiceListener
</code>```

What is it?

答:
hers's my fcm services:

=> public class MyFirebaseInstanceIdServices extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";

```<code>@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "FireBase token: " + refreshedToken);
    Prefs.setFirebaseToken(getApplicationContext(), refreshedToken);
}
</code>```

}

=> public class MyFirebaseMessagingServices extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";

```<code>@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getData() + " Message Body");
    Map<String, String> notiMessage = remoteMessage.getData();
    String type = notiMessage.get("type");
    String title = notiMessage.get("title");
    String message = notiMessage.get("message");
    String orderId = notiMessage.get("order_id");
    sendNotification(type, title, message, orderId);
}

//This method is only generating push notification
private void sendNotification(String type, String title, String message, String orderId) {

    if (Prefs.getIsLogin(this)) {
        Intent intent = null;
        if (type.equals("order")) {
            intent = new Intent(this, OrderConfirmationActivity.class);
            intent.putExtra(Constant.ORDER_ID, orderId);
            intent.putExtra("FromNoti", true);
        } else {
            intent = new Intent(this, HomeActivity.class);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_marker);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(bitmap)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}
</code>```

}

=> In Manifest file:

```<code>    <service android:name="com.labagel.fcm.MyFirebaseMessagingServices">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name="com.labagel.fcm.MyFirebaseInstanceIdServices">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
</code>```

Body:
I'm having an issue with Firebase notifications. I set up it as the docs but it's not working. Below, you can see my code. Although I think everything is right.

Here's my NotificationsService

public class NotificationsService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String TAG = "Notification";

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        }

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
}

And the AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.usefashion.useapp">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.NoActionBar">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service android:name=".NotificationsService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".InstanceIdService"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
            </intent-filter>
        </service>
    </application>
</manifest>

It would be great if anyone could help me. I have an InstanceIdService too but its not the part of this question.

Edit 1:

I realized that when I send a notification by console, this message is showed in debug:

E/FirebaseInstanceId: Error resolving target intent service, skipping classname enforcement. Resolved service was: com.taplane.triviaquiz/com.msi.logocore.helpers.thirdparty.firebase.FirebaseServiceListener

What is it?

Body:
hers's my fcm services:

=> public class MyFirebaseInstanceIdServices extends FirebaseInstanceIdService {
    private static final String TAG = "MyFirebaseIIDService";

@Override
public void onTokenRefresh() {
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "FireBase token: " + refreshedToken);
    Prefs.setFirebaseToken(getApplicationContext(), refreshedToken);
}

}

=> public class MyFirebaseMessagingServices extends FirebaseMessagingService {
    private static final String TAG = "MyFirebaseMsgService";

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getData() + " Message Body");
    Map<String, String> notiMessage = remoteMessage.getData();
    String type = notiMessage.get("type");
    String title = notiMessage.get("title");
    String message = notiMessage.get("message");
    String orderId = notiMessage.get("order_id");
    sendNotification(type, title, message, orderId);
}

//This method is only generating push notification
private void sendNotification(String type, String title, String message, String orderId) {

    if (Prefs.getIsLogin(this)) {
        Intent intent = null;
        if (type.equals("order")) {
            intent = new Intent(this, OrderConfirmationActivity.class);
            intent.putExtra(Constant.ORDER_ID, orderId);
            intent.putExtra("FromNoti", true);
        } else {
            intent = new Intent(this, HomeActivity.class);
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_marker);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(bitmap)
                .setContentTitle(title)
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
    }
}

}

=> In Manifest file:

    <service android:name="com.labagel.fcm.MyFirebaseMessagingServices">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name="com.labagel.fcm.MyFirebaseInstanceIdServices">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>


问:
Create path without looping through rows of data frame
Imagine I have a dataframe that contain information for different persons and there location.

```<code>Person <- c('A','A','A','B','B','C')
Place  <- c('Ber','Mun','Stu','LA','NY','Ber')

df <- as.data.frame(cbind(Person,Place))
</code>```

Now I would like to have a new data frame that tells me how the person traveled. It should look somehow like this:

```<code>Person From  To
A       Ber   Mun
A       Mun   Stu
B        LA   NY
</code>```

I could do it with by looping over the data frame. But I want to do this for several million rows. Does somebody no a better way?

Best,
Felix

答:
I put two subsets of the df side by side, one without the head, one without the tail, and then I keep the result only if the person is the same on each side:</p>

```<code>library(magrittr)
df2 <- df[-nrow(df),] %>%
  cbind(df[-1,]) %>%
  setNames(c("Person","From","Person2","To")) %>%
  subset(Person == Person2) %>%
  '['(,-3)

#   Person From  To
# 1      A  Ber Mun
# 2      A  Mun Stu
# 4      B   LA  NY
</code>```

Body:
Imagine I have a dataframe that contain information for different persons and there location.

Person <- c('A','A','A','B','B','C')
Place  <- c('Ber','Mun','Stu','LA','NY','Ber')

df <- as.data.frame(cbind(Person,Place))

Now I would like to have a new data frame that tells me how the person traveled. It should look somehow like this:

Person From  To
A       Ber   Mun
A       Mun   Stu
B        LA   NY

I could do it with by looping over the data frame. But I want to do this for several million rows. Does somebody no a better way?

Best,
Felix

Body:
I put two subsets of the df side by side, one without the head, one without the tail, and then I keep the result only if the person is the same on each side:

library(magrittr)
df2 <- df[-nrow(df),] %>%
  cbind(df[-1,]) %>%
  setNames(c("Person","From","Person2","To")) %>%
  subset(Person == Person2) %>%
  '['(,-3)

#   Person From  To
# 1      A  Ber Mun
# 2      A  Mun Stu
# 4      B   LA  NY


问:
inter processes shared memory and pthread_barrier: how to be safe?
I wanted a simple solution for inter processes barrier. Here a solution: solution

But I am totally lost with mmap... With my first try, it fails one out of ten times (segfault or deadlock).

I understand my problem comes from a synchronization issue, but I can't find it. I found an example to set up mmaped memory (example), but I am not sure it is good for a mmaped pthread_barrier.

Here an extract of my code:

```<code>#define MMAP_FILE "/tmp/mmapped_bigdft.bin"

void init_barrier() {
  pthread_barrier_t *shared_mem_barrier;
  pthread_barrierattr_t barattr;
  pthread_barrierattr_setpshared(&barattr, PTHREAD_PROCESS_SHARED);

  hbcast_fd = open(MMAP_FILE, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
  result = lseek(hbcast_fd, sizeof(pthread_barrier_t)-1, SEEK_SET);
  result = write(hbcast_fd, "", 1);
  shared_mem_barrier = (pthread_barrier_t*) mmap(0, sizeof(pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, hbcast_fd, 0);
  if (mpi_rank == 0) {
    int err = pthread_barrier_init(shared_mem_barrier, &barattr, host_size);
  }
  MPI_Barrier(some_communicator);
}
</code>```

Questions:

do I miss something in mmap initialization?

which operation should be performed by all processes, and which should be by only one?

New question

Which is safier for managing pthread barrier? Or are they based on the same mechanism?

shmget

shm_open

mmap

another one

答:
You should use shm_open to create a shared segment.

With the paramenter O_CREAT you
should be able to detect if a process
is the first to create the segment.

Only that process should trunctate
the segment to the appropriate length, map it
and initialize the barrier.

All the others that detect that they
are not the first should sleep for a
while, a second or so should suffice, and then map the segment.

After that all processes may
synchronize of the barrier.

Body:
I wanted a simple solution for inter processes barrier. Here a solution: solution

But I am totally lost with mmap... With my first try, it fails one out of ten times (segfault or deadlock).

I understand my problem comes from a synchronization issue, but I can't find it. I found an example to set up mmaped memory (example), but I am not sure it is good for a mmaped pthread_barrier.

Here an extract of my code:

#define MMAP_FILE "/tmp/mmapped_bigdft.bin"

void init_barrier() {
  pthread_barrier_t *shared_mem_barrier;
  pthread_barrierattr_t barattr;
  pthread_barrierattr_setpshared(&barattr, PTHREAD_PROCESS_SHARED);

  hbcast_fd = open(MMAP_FILE, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
  result = lseek(hbcast_fd, sizeof(pthread_barrier_t)-1, SEEK_SET);
  result = write(hbcast_fd, "", 1);
  shared_mem_barrier = (pthread_barrier_t*) mmap(0, sizeof(pthread_barrier_t), PROT_READ | PROT_WRITE, MAP_SHARED, hbcast_fd, 0);
  if (mpi_rank == 0) {
    int err = pthread_barrier_init(shared_mem_barrier, &barattr, host_size);
  }
  MPI_Barrier(some_communicator);
}

Questions:

do I miss something in mmap initialization?

which operation should be performed by all processes, and which should be by only one?

New question

Which is safier for managing pthread barrier? Or are they based on the same mechanism?

shmget

shm_open

mmap

another one


问:
Keypress but not when input or textarea is in focus
I'm using the code below :

```<code>$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});
</code>```

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !

答:
Alternatively to e.target, you could test if the current active element is an input or textarea:

```<code>$(document).keypress(function (e) {
  var focussedTag = document.activeElement && document.activeElement.nodeName;
  if( focussedTag === 'INPUT' || focussedTag === 'TEXTAREA' ) {
    return;
  }
  if (e.which === 68 || e.which === 100) {
    doStuff();
  }
} );
</code>```

Fiddle: https://jsfiddle.net/e1qtapo6/

Body:
I'm using the code below :

$(document).keypress(function (e) {
    if (e.which === 68 || e.which === 100) {
        doStuff();
    }
});

What i want is to capture the key 'D' as a shortcut to a function in my page. Problem is , this page has inputs and textarea controls and when i'm'typing on this controls, the 'doStuff()' function is called.

How to avoid it ? I want the key 'D' capture only if the user is not typing anything in editable controls.

Thanks !

Body:
Alternatively to e.target, you could test if the current active element is an input or textarea:

$(document).keypress(function (e) {
  var focussedTag = document.activeElement && document.activeElement.nodeName;
  if( focussedTag === 'INPUT' || focussedTag === 'TEXTAREA' ) {
    return;
  }
  if (e.which === 68 || e.which === 100) {
    doStuff();
  }
} );

Fiddle: https://jsfiddle.net/e1qtapo6/


问:
Akka - creating remote actors
I am trying to create Akka Actors on a remote host.
Following the official documentation, I create a remote Actor System parsing the application.config file and then I create a new actor.
This is my code:

```<code>public static void main(String[] args) {

    Config config = ConfigFactory.parseFile(new File("application.conf"));
    ActorSystem system = ActorSystem.create("system",config);
    ActorRef actor = system.actorOf(Props.create(SampleActor.class), "sampleActor");
    System.out.println(actor.path());
    actor.tell("Hello", ActorRef.noSender());
}
</code>```

And this is how I set up the application.conf file:

akka {   actor {
      provider = remote   }   remote {
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "shielded-atoll-29637.herokuapp.com"
        port = 2552
      }  } }

Further details:

Akka protocol is provided by default by Akka

shielded-atoll-29637.herokuapp.com is the default domain of my server
hosted on heroku.

The point is: should I take another server or heroku is sufficient? In case Heroku is okay, am I supposed to write a server application that is listening on the port 2552 for incoming actor-creating requests? Because the documentation does not mention anything at all.

Thanks in advance,
Giacomo

答:
While you can start actors on a remote ActorSystem, you must have already deployed that ActorSystem with all the code you want to be able to trigger. This is usually used by different nodes that are all part of the same cluster. Your situation seems a little different.

I don't think deploying Akka on Heroku in this way will work: if I remember correctly Heroku is highly HTTP-centric, so I doubt it'll correctly make sure your Akka-based application is started when a connection is made to port 2552.

It might make more sense to deploy your server code on Heroku and trigger is though HTTP. That way you're playing more nicely with how Heroku is designed to work, and the implementation can still be either Akka-based (with akka-http) or something completely different.

Do consider that Heroku will want you to offload long-running processes to worker nodes, so it really depends on what you're trying to do whether that's a good solution.

Title: Akka - creating remote actors

Body:
I am trying to create Akka Actors on a remote host.
Following the official documentation, I create a remote Actor System parsing the application.config file and then I create a new actor.
This is my code:

public static void main(String[] args) {

    Config config = ConfigFactory.parseFile(new File("application.conf"));
    ActorSystem system = ActorSystem.create("system",config);
    ActorRef actor = system.actorOf(Props.create(SampleActor.class), "sampleActor");
    System.out.println(actor.path());
    actor.tell("Hello", ActorRef.noSender());
}

And this is how I set up the application.conf file:

akka {   actor {
      provider = remote   }   remote {
      enabled-transports = ["akka.remote.netty.tcp"]
      netty.tcp {
        hostname = "shielded-atoll-29637.herokuapp.com"
        port = 2552
      }  } }

Further details:

Akka protocol is provided by default by Akka

shielded-atoll-29637.herokuapp.com is the default domain of my server
hosted on heroku.

The point is: should I take another server or heroku is sufficient? In case Heroku is okay, am I supposed to write a server application that is listening on the port 2552 for incoming actor-creating requests? Because the documentation does not mention anything at all.

Thanks in advance,
Giacomo


问:
Reset the Value of a Select Box
I'm trying to reset the value of two select fields, structured like this,

```<code><select>
  <option></option>
  <option></option>
  <option></option>
</select>

<select>
  <option></option>
  <option></option>
  <option></option>
</select>
</code>```

jQuery,

```<code>$('select').each(function(idx, sel) {
  $(sel).find('option :eq(0)').attr('selected', true);
});
</code>```

Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anything with JS

EDIT:

I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have

```<code>$('p').click(function(){
  console.log('test');
});
</code>```

It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?

答:
What worked for me was:</p>

```<code>$('select option').each(function(){$(this).removeAttr('selected');});
</code>```

Title: Reset the Value of a Select Box

Body:
I'm trying to reset the value of two select fields, structured like this,

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

<select>
  <option></option>
  <option></option>
  <option></option>
</select>

jQuery,

$('select').each(function(idx, sel) {
  $(sel).find('option :eq(0)').attr('selected', true);
});

Unfortunately, no matter how many ways I try it, it just doesn't happen. Nothing in the console. I have no idea what's going on? I know there has to be a way to do this, you can do anything with JS

EDIT:

I figured out that the issue only occurs when I try to fire the code on the click of a dom element, however, I know that the code should be working, because when I have

$('p').click(function(){
  console.log('test');
});

It outputs 'test' to the console, but when I include the code in this function, nothing happens. Why is this?

Body:
What worked for me was:

$('select option').each(function(){$(this).removeAttr('selected');});


问:
MDX How to use CASE to check a level value
I'm new to BI and MDX and have a need to do this. I have a dimension that looks like this:

```<code><Dimension name="JobDim">
    <Hierarchy name="Job" hasAll="true" primaryKey="jobID">
        <Table name="JobDim" schema="dw"/>
        <Level name="Job Code" column="jobCode" type="String" uniqueMembers="false"/>
    </Hierarchy>
    <Hierarchy name="Job Status" hasAll="true" primaryKey="jobID">
        <Table name="JobDim" schema="dw"/>
        <Level name="Job Status" column="status" type="String" hideMemberIf="IfBlankName"/>
    </Hierarchy>
</Dimension>
</code>```

I have a calculated measure and I need to set the value of this measure depending on the 'job status', so if the job is 'complete', set the measure to 100, otherwise set its value to 200 (the value to be used is more complex but for this example purpose, this is good enough). I'm using something like this:

```<code>    <CalculatedMember name="Earned Revenue" dimension="Measures" formatString="$#,###.00;($#,###.00)" aggregator="sum">
        <Formula>case [JobDim.Job Status].CurrentMember
                    when [JobDim.Job Status].[Complete] then 100
                    else 200
                 end
        </Formula>
    </CalculatedMember>
</code>```

I've tried different variations of the code above, but none seem to work (some even cause a crash when I try to run the report). Anyone has done something like this in the past that can provide me an answer?

答:
You need to evaluate that tuple against some measure. Remember that in MDX evaluations are done against the level/aggregate results, not on a row by row basis.

From your description it looks like Job Status should be a property of the level Job Code, and not a level.

Try the following on your schema:

<Dimension name="JobDim">
    <Hierarchy name="Job" hasAll="true" primaryKey="jobID">

        <Level name="Job Code" column="jobCode" type="String" uniqueMembers="false">
            <Property name="Job Status" column="status" type="String"/>
        </Level>
    </Hierarchy>
</Dimension>

and on your calculated measure

<CalculatedMember name="Earned Revenue" dimension="Measures" formatString="$#,###.00;($#,###.00)" aggregator="sum">
        <Formula>case [JobDim.Job Status].CurrentMember.Properties("Job Status")
                    when "Complete" then 100
                    else 200
                 end
        </Formula>
</CalculatedMember>

Body:
I'm new to BI and MDX and have a need to do this. I have a dimension that looks like this:

<Dimension name="JobDim">
    <Hierarchy name="Job" hasAll="true" primaryKey="jobID">

        <Level name="Job Code" column="jobCode" type="String" uniqueMembers="false"/>
    </Hierarchy>
    <Hierarchy name="Job Status" hasAll="true" primaryKey="jobID">

        <Level name="Job Status" column="status" type="String" hideMemberIf="IfBlankName"/>
    </Hierarchy>
</Dimension>

I have a calculated measure and I need to set the value of this measure depending on the 'job status', so if the job is 'complete', set the measure to 100, otherwise set its value to 200 (the value to be used is more complex but for this example purpose, this is good enough). I'm using something like this:

    <CalculatedMember name="Earned Revenue" dimension="Measures" formatString="$#,###.00;($#,###.00)" aggregator="sum">
        <Formula>case [JobDim.Job Status].CurrentMember
                    when [JobDim.Job Status].[Complete] then 100
                    else 200
                 end
        </Formula>
    </CalculatedMember>

I've tried different variations of the code above, but none seem to work (some even cause a crash when I try to run the report). Anyone has done something like this in the past that can provide me an answer?

Body:
You need to evaluate that tuple against some measure. Remember that in MDX evaluations are done against the level/aggregate results, not on a row by row basis.

From your description it looks like Job Status should be a property of the level Job Code, and not a level.

Try the following on your schema:

<Dimension name="JobDim">
    <Hierarchy name="Job" hasAll="true" primaryKey="jobID">
        <Table name="JobDim" schema="dw"/>
        <Level name="Job Code" column="jobCode" type="String" uniqueMembers="false">
            <Property name="Job Status" column="status" type="String"/>
        </Level>
    </Hierarchy>
</Dimension>

and on your calculated measure

<CalculatedMember name="Earned Revenue" dimension="Measures" formatString="$#,###.00;($#,###.00)" aggregator="sum">
        <Formula>case [JobDim.Job Status].CurrentMember.Properties("Job Status")
                    when "Complete" then 100
                    else 200
                 end
        </Formula>
</CalculatedMember>