text:
Q: How to find consecutive positive, negative and zeroes in a numpy array? I use the following function in order to find the consecutive negative and positive numbers, now I also want to add a condition that gets the consecutive zeros as well.
How can I do that?
def consecutive_counts(arr):
    '''
    Returns number of consecutive negative and positive numbers
    arr = np.array
    negative = consecutive_counts()[0]
    positive = consecutive_counts()[1]
    '''
    pos = arr > 0
    # is used to Compute indices that are non-zero in the flattened version of arr
    idx = np.flatnonzero(pos[1:] != pos[:-1])
    count = np.concatenate(([idx[0]+1], idx[1:] - idx[:-1], [arr.size-1-idx[-1]]))
    negative = count[1::2], count[::2]
    positive = count[::2], count[1::2]
    if arr[0] < 0:
        return negative
    else:
        return positive

this is a pandas series:
In [221]: n.temp.p['50000']
Out[221]:
name
0         0.00
1       -92.87
2       -24.01
3       -92.87
4       -92.87
5       -92.87
...       ...

which i use it like this:
arr = n.temp.p['50000'].values #Will be a numpy array as the input

expected output:
In [225]: consecutive_counts(a)
Out[225]: (array([30, 29, 11, ...,  2,  1,  3]), array([19,  1,  1, ...,  1,  1,  2]))

Thanks :)

A: Since you tagged pandas here's one approach:
# random data
np.random.seed(1)
a = np.random.choice(range(-2,3), 1000)

# np.sign: + = 1, 0 = 0, - = -1
b = pd.Series(np.sign(a))

# b.head()
# 0    1
# 1    1
# 2   -1
# 3   -1
# 4    1
# dtype: int32

# sign blocks
blks = b.diff().ne(0).cumsum()

# blks.head()
# 0    1
# 1    1
# 2    2
# 3    2
# 4    3
# dtype: int32

# number of blocks:
blks.iloc[-1]
# 654

# block counts:
blks.value_counts()

# 1      2
# 2      2
# 3      1
# 4      3
# 5      2
# ...

A: Here is a numpy approach:
# create example
arr = np.random.randint(-2,3,(10))

# split into negative, zero, positive
*nzp, = map(np.flatnonzero,(arr<0,arr==0,arr>0))
# find block boundaries
*bb, = (np.flatnonzero(np.diff(x,prepend=-2,append=-2)-1) for x in nzp)
# compute block sizes
*bs, = map(np.diff,bb)

# show all
for data in (arr,nzp,bb,bs): print(data)
# [-1  1 -1  1  0  0  2 -1 -2  1]
# [array([0, 2, 7, 8]), array([4, 5]), array([1, 3, 6, 9])]
# [array([0, 1, 2, 4]), array([0, 2]), array([0, 1, 2, 3, 4])]
# [array([1, 1, 2]), array([2]), array([1, 1, 1, 1])]


text:
Q: Pytest django url's tests I saw some people writing url's test like this:
def test_sample_url():
    path = reverse('url_name', kwargs={'pk': 1})
    assert resolve(path).view_name == 'url_name'

As for me this test is not checking anything, because if I place 'url_name' in second line then in third it is obviously going to be equal to it.
Am I wrong or missing something?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why the laravel authentication view is not working, although i am able to use the login and register functionalities.? Output is showing like this.Output of default authentication functionality of laravel

A: It looks like you're using laravel/ui. Did you run npm install and npm run dev?


text:
Q: How to read & write a list to/from a file with vimscript I've got some configuration data that's stored in a list - I'd like to read and write it from an external file. Any suggestions on the best way to do this?

A: Try this:
let data = readfile('config')
...
if writefile(data, 'config')
    echomsg 'write error'
endif


text:
Q: Difference in behaviour between $x = undef and undef $x undef $x is different from $x = undef. I was under the impression that both would trigger garbage collection and free memory, but it seems $x = undef does not do so.
Is this a language bug? On doing $x = undef, shouldn't it free memory?

A: No and no. Perl favours speed over memory usage by not deallocating memory you're likely to need again. If you want the string buffer to be deallocated, use undef $x;.
$ perl -MDevel::Peek -e'
   Dump($x);
   $x='abc'; Dump($x);
   $x=undef; Dump($x);
   undef $x; Dump($x);
'
SV = NULL(0x0) at 0x1c39284       <-- No body allocated
  REFCNT = 1
  FLAGS = ()                      <-- Undefined
SV = PV(0x3e8d54) at 0x1c39284    <-- PV body allocated
  REFCNT = 1
  FLAGS = (POK,pPOK)              <-- Contains a string
  PV = 0x3eae7c "abc"\0
  CUR = 3
  LEN = 12
SV = PV(0x3e8d54) at 0x1c39284    <-- PV body allocated
  REFCNT = 1
  FLAGS = ()                      <-- Undefined
  PV = 0x3eae7c "abc"\0           <-- Currently unused string buffer
  CUR = 3
  LEN = 12
SV = PV(0x3e8d54) at 0x1c39284    <-- PV body allocated
  REFCNT = 1
  FLAGS = ()                      <-- Undefined
  PV = 0                          <-- No string buffer allocated


text:
Q: Flutter : Custom Radio Button How can I create a custom radio button group like this in flutter

A: Here is the full code
class CustomRadio extends StatefulWidget {
  @override
  createState() {
    return new CustomRadioState();
  }
}

class CustomRadioState extends State<CustomRadio> {
  List<RadioModel> sampleData = new List<RadioModel>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    sampleData.add(new RadioModel(false, 'A', 'April 18'));
    sampleData.add(new RadioModel(false, 'B', 'April 17'));
    sampleData.add(new RadioModel(false, 'C', 'April 16'));
    sampleData.add(new RadioModel(false, 'D', 'April 15'));
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("ListItem"),
      ),
      body: new ListView.builder(
        itemCount: sampleData.length,
        itemBuilder: (BuildContext context, int index) {
          return new InkWell(
            //highlightColor: Colors.red,
            splashColor: Colors.blueAccent,
            onTap: () {
              setState(() {
                sampleData.forEach((element) => element.isSelected = false);
                sampleData[index].isSelected = true;
              });
            },
            child: new RadioItem(sampleData[index]),
          );
        },
      ),
    );
  }
}

class RadioItem extends StatelessWidget {
  final RadioModel _item;
  RadioItem(this._item);
  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.all(15.0),
      child: new Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          new Container(
            height: 50.0,
            width: 50.0,
            child: new Center(
              child: new Text(_item.buttonText,
                  style: new TextStyle(
                      color:
                          _item.isSelected ? Colors.white : Colors.black,
                      //fontWeight: FontWeight.bold,
                      fontSize: 18.0)),
            ),
            decoration: new BoxDecoration(
              color: _item.isSelected
                  ? Colors.blueAccent
                  : Colors.transparent,
              border: new Border.all(
                  width: 1.0,
                  color: _item.isSelected
                      ? Colors.blueAccent
                      : Colors.grey),
              borderRadius: const BorderRadius.all(const Radius.circular(2.0)),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(left: 10.0),
            child: new Text(_item.text),
          )
        ],
      ),
    );
  }
}

class RadioModel {
  bool isSelected;
  final String buttonText;
  final String text;

  RadioModel(this.isSelected, this.buttonText, this.text);
}

To use :
void main() {
  runApp(new MaterialApp(
    home: new CustomRadio(),
  ));
}

Screenshot :

A: I achieved that with the following logic.
reply if you need a detailed explanation
    import 'package:flutter/material.dart';

    class Parent extends StatefulWidget {
      Parent({
        Key key,
      }) : super(key: key);

      @override
      _ParentState createState() => _ParentState();
    }

    class _ParentState extends State<Parent> {
      int _selectedItem = 0;

      selectItem(index) {
        setState(() {
          _selectedItem = index;
          print(selectItem.toString());
        });
      }

      @override
      Widget build(BuildContext context) {
        //...YOUR WIDGET TREE HERE

        return ListView.builder(
          shrinkWrap: true,
          itemCount: 5,
          itemBuilder: (context, index) {
            return CustomItem(
              selectItem, // callback function, setstate for parent
              index: index,
              isSelected: _selectedItem == index,
              title: index.toString(),
            );
          },
        );
      }
    }

    class CustomItem extends StatefulWidget {
      final String title;
      final int index;
      final bool isSelected;
      Function(int) selectItem;

      CustomItem(
        this.selectItem, {
        Key key,
        this.title,
        this.index,
        this.isSelected,
      }) : super(key: key);

      _CustomItemState createState() => _CustomItemState();
    }

    class _CustomItemState extends State<CustomItem> {
      @override
      Widget build(BuildContext context) {
        return Row(
          children: <Widget>[
            Text("${widget.isSelected ? "true" : "false"}"),
            RaisedButton(
              onPressed: () {
                widget.selectItem(widget.index);
              },
              child: Text("${widget.title}"),
            )
          ],
        );
      }
    }

A: Screenshot (Null safe)

Full code:

*

*Create this custom class.
class MyRadioListTile<T> extends StatelessWidget {
  final T value;
  final T groupValue;
  final String leading;
  final Widget? title;
  final ValueChanged<T?> onChanged;

  const MyRadioListTile({
    required this.value,
    required this.groupValue,
    required this.onChanged,
    required this.leading,
    this.title,
  });

  @override
  Widget build(BuildContext context) {
    final title = this.title;
    return InkWell(
      onTap: () => onChanged(value),
      child: Container(
        height: 56,
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: Row(
          children: [
            _customRadioButton,
            SizedBox(width: 12),
            if (title != null) title,
          ],
        ),
      ),
    );
  }

  Widget get _customRadioButton {
    final isSelected = value == groupValue;
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      decoration: BoxDecoration(
        color: isSelected ? Colors.blue : null,
        borderRadius: BorderRadius.circular(4),
        border: Border.all(
          color: isSelected ? Colors.blue : Colors.grey[300]!,
          width: 2,
        ),
      ),
      child: Text(
        leading,
        style: TextStyle(
          color: isSelected ? Colors.white : Colors.grey[600]!,
          fontWeight: FontWeight.bold,
          fontSize: 18,
        ),
      ),
    );
  }
}

*Use it in your widget like a regular RadioListTile.
class _MyPageState extends State<MyPage> {
  int _value = 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          MyRadioListTile<int>(
            value: 1,
            groupValue: _value,
            leading: 'A',
            title: Text('One'),
            onChanged: (value) => setState(() => _value = value!),
          ),
          MyRadioListTile<int>(
            value: 2,
            groupValue: _value,
            leading: 'B',
            title: Text('Two'),
            onChanged: (value) => setState(() => _value = value!),
          ),
          MyRadioListTile<int>(
            value: 3,
            groupValue: _value,
            leading: 'C',
            title: Text('Three'),
            onChanged: (value) => setState(() => _value = value!),
          ),
        ],
      ),
    );
  }
}

A: You can create it with ListView and List Item with one local variable to store the selected item. And you can render the selected the ListItem based on the variable.
P.S. Let me know if you need code snippet.
[EDIT]
As you have requested, Here is code snipper which will show you how you can maintain the state of each ListView item.
Now you can play with it and make it the way you want. If you want only one selected item you can write the logic that way.
void main() {
  runApp(new MaterialApp(
    home: new ListItemDemo(),
  ));
}

class ListItemDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("ListItem"),
      ),
      body: new ListView.builder(
          itemCount: 10,
          itemBuilder: (BuildContext context, int index) {
            return new MyListItem(
              title: "Hello ${index + 1}",
            );
          }),
    );
  }
}

class MyListItem extends StatefulWidget {
  final String title;

  MyListItem({this.title});

  @override
  _MyListItemState createState() => new _MyListItemState();
}

class _MyListItemState extends State<MyListItem> {
  bool isSelected;

  @override
  void initState() {
    super.initState();
    isSelected = false;
  }

  @override
  Widget build(BuildContext context) {
    return new Row(
      children: <Widget>[
        new Text("${widget.title} ${isSelected ? "true" : "false"}"),
        new RaisedButton(
          onPressed: () {
            if (isSelected) {
              setState(() {
                isSelected = false;
              });
            } else {
              setState(() {
                isSelected = true;
              });
            }
          },
          child: new Text("Select"),
        )
      ],
    );
  }
}

A: https://i.stack.imgur.com/Hq0O2.png
Here is Custom Radio Group Button Widget. You can easily customize all property as per your requirement. Use:
GroupRadioButton(
              label: [Text("A"), Text("B"), Text("C"), Text("D")],
              padding: EdgeInsets.symmetric(vertical: 10),
              spaceBetween: 5,
              radioRadius: 10,
              color: Const.mainColor,
              onChanged: (listIndex) {
                 print(listIndex);
              },
),

This is GroupRadioButton widget
import 'package:flutter/material.dart';

class GroupRadioButton extends StatefulWidget {
  GroupRadioButton({
    @required this.label,
    @required this.padding,
    @required this.onChanged,
    this.color = Colors.blue,
    this.radioRadius = 14.0,
    this.spaceBetween = 5.0,
    this.mainAxisAlignment = MainAxisAlignment.start,
    this.crossAxisAlignment = CrossAxisAlignment.start,
  });

  final Color color;
  final List<Widget> label;
  final EdgeInsets padding;
  final Function(int) onChanged;
  final double radioRadius;
  final double spaceBetween;
  final MainAxisAlignment mainAxisAlignment;
  final CrossAxisAlignment crossAxisAlignment;

  @override
  _GroupRadioButtonState createState() => _GroupRadioButtonState();
}

class _GroupRadioButtonState extends State<GroupRadioButton> {
  int selectedIndex = 0;
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        shrinkWrap: true,
        itemCount: widget.label != null ? widget.label.length : 0,
        itemBuilder: (context, index) {
          return LabeledRadio(
            selectedIndex: selectedIndex,
            color: widget.color,
            onChanged: (value) {
              setState(() {
                selectedIndex = value;
                widget.onChanged(value);
                // print(value);
              });
            },
            index: index,
            label: widget.label[index],
            crossAxisAlignment: widget.crossAxisAlignment,
            mainAxisAlignment: widget.mainAxisAlignment,
            radioRadius: widget.radioRadius,
            spaceBetween: widget.spaceBetween,
            padding: widget.padding,
          );
        });
  }
}

class LabeledRadio extends StatelessWidget {
  LabeledRadio({
    @required this.label,
    @required this.index,
    @required this.color,
    //@required this.groupValue,
    //@required this.value,
    @required this.onChanged,
    @required this.radioRadius,
    @required this.padding,
    @required this.spaceBetween,
    @required this.mainAxisAlignment,
    @required this.crossAxisAlignment,
    this.selectedIndex,
  });

  final Color color;
  final int selectedIndex;
  final Widget label;
  final index;
  final EdgeInsets padding;
  //final bool groupValue;
  //final bool value;
  final Function(int) onChanged;
  final double radioRadius;
  final double spaceBetween;
  final MainAxisAlignment mainAxisAlignment;
  final CrossAxisAlignment crossAxisAlignment;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        onChanged(index);
      },
      child: Padding(
        padding: padding,
        child: Row(
          mainAxisAlignment: mainAxisAlignment,
          crossAxisAlignment: crossAxisAlignment,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                //color: Const.mainColor,
                shape: BoxShape.circle,
                border: Border.all(color: color, width: 2),
              ),
              padding: EdgeInsets.all(2),
              child: selectedIndex == index
                  ? Container(
                      height: radioRadius,
                      width: radioRadius,
                      decoration: BoxDecoration(
                        color: color,
                        shape: BoxShape.circle,
                      ),
                    )
                  : Container(
                      height: radioRadius,
                      width: radioRadius,
                    ),
            ),
            SizedBox(
              width: spaceBetween,
            ),
            label,
          ],
        ),
      ),
    );
  }
}

A: My RadioButton is like the 'Radio' widget:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class RadioButton<T> extends StatefulWidget {
  RadioButton({
    Key key,
    @required this.value,
    @required this.caption,
    @required this.groupValue,
    @required this.onChanged,
  })  : assert(value != null),
        assert(caption != null),
        assert(groupValue != null),
        assert(onChanged != null),
        super(key: key);

  final T value;
  final T groupValue;
  final String caption;
  final Function onChanged;

  @override
  State<StatefulWidget> createState() => _RadioButtonState();
}

class _RadioButtonState extends State<RadioButton> {
  @override
  Widget build(BuildContext context) {
    final bool selected = widget.value == widget.groupValue;

    return GestureDetector(
      onTap: () {
        widget.onChanged(widget.value);
      },
      child: Container(
        width: double.maxFinite,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            color: selected ? Colors.red : Colors.white),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            widget.caption,
            textAlign: TextAlign.center,
            style: Theme.of(context)
                .textTheme
                .button
                .copyWith(color: selected ? Colors.white : Colors.red),
          ),
        ),
      ),
    );
  }
}

A: import 'package:flutter/material.dart';
class CustomRadio extends StatefulWidget {
  @override
  createState() {
    return new CustomRadioState();
  }
}

class CustomRadioState extends State<CustomRadio> {
  List<RadioModel> sampleData = new List<RadioModel>();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    sampleData.add(new RadioModel(true, 'A',0xffe6194B));
    sampleData.add(new RadioModel(false, 'B',0xfff58231));
    sampleData.add(new RadioModel(false, 'C',0xffffe119));
    sampleData.add(new RadioModel(false, 'D',0xffbfef45));
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("ListItem"),
      ),
      body: new ListView.builder(
        itemCount: sampleData.length,
        itemBuilder: (BuildContext context, int index) {
          return new InkWell(
            splashColor: Colors.blueAccent,
            onTap: () {
              setState(() {
                sampleData.forEach((element) => element.isSelected = false);
                sampleData[index].isSelected = true;
              });
            },
            child: new RadioItem(sampleData[index]),
          );
        },
      ),
    );
  }
}

class RadioItem extends StatelessWidget {
  final RadioModel _item;
  RadioItem(this._item);
  @override
  Widget build(BuildContext context) {
    return new Container(
      margin: new EdgeInsets.all(15.0),
      child: new Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          new Container(
            height: 25.0,
            width: 25.0,
            alignment: Alignment.center,
            child:Container(
            height: 15.0,
            width: 15.0,
              decoration: new BoxDecoration(
              color:Color(_item.colorCode),
              borderRadius: const BorderRadius.all(const Radius.circular(15)),
            )

            ),
            decoration: new BoxDecoration(
              color: Colors.transparent,
              border: new Border.all(
                  width: 3.0,
                  color: _item.isSelected
                      ? Color(_item.colorCode)
                      : Colors.transparent),
              borderRadius: const BorderRadius.all(const Radius.circular(25)),
            ),
          ),
          new Container(
            margin: new EdgeInsets.only(left: 10.0)
          )
        ],
      ),
    );
  }
}

class RadioModel {
  bool isSelected;
  final String buttonText;
  final int colorCode;

  RadioModel(this.isSelected, this.buttonText,this.colorCode);
}
void main() {
  runApp(new MaterialApp(
    home: new CustomRadio(),
  ));
}

Click here to check out put-> Here


text:
Q: Proving a function to be continuous in Topology I am trying exercises of section 1.7 of C. Wayne Patty and I am unable to think about solution of this question.

Note that I want to ask b part only.

My attempt -> The definition of continuity is inverse of the definition of open sets given here. So, I don't know how defination of continuity can be derived from definition of open sets here ?
Kindly help.

A: Let $U$ be an open subset of $Y$. You want to prove that $f^{-1}(U)$ is an open subset of $X$. But, by the definition of the topology on $X$, this is true indeed, since $A\in\mathcal T$ if and only if $A=f^{-1}(B)$ for some $B\in\mathcal U$.


text:
Q: Application.DoEvents() -> Equivalent function in java? I know that using threads is more efficient than using c# DoEvents(), but I was still wondering whether there is an equivalent function in java. I googled for it, but I couldn't find anything.

A: You can use Thread.yield(), which is the java counterpart to relinquish the control of the processors voluntarily.

A: You can use EventQueue.invokeLater() to append a Runnable after all pending events. This have a result similar to C#'s DoEvents() that comes before the code you put inside the Runnable.run() method.
See Java documentation for EventQueue.
For example, if you want to let all GUI controls to lose the focus and their lost focus events to be execute, you can use the following code:
@Override
public void windowClosing(WindowEvent e){
    // Clear the focus to allow last changes to be noted.
    KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
    // We want to let other events (e.g. lost focus) run before we start closing.
    EventQueue.invokeLater( new Runnable() {
        @Override public void run() {
            // Do actual closing...
        }
    });
}


text:
Q: React, текстовый редактор на сайте как правильно сделать кнопки редактора, чтобы при клике менялись стили следующих слов, а не всего текста? Помогите пожалуйста
вот код
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Folder from './folder';
import Text from './text';

export default class RichEditor extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      textName : '',
      textContent : '',

  }

  const contentValue = this.state.textContent;
}

  handleUserInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value});
  }
  handleSize(){
    this.setState({textContent});
  }

  handleClickB(){

  }

render() {
  return(

          <Folder />

          <Text />

        <input
          type="textName"
          placeholder="text-name"
          value={this.state.textName}
          name="textName"

          onChange={this.handleUserInput}
        />

            <button
              className="btn-bold"
              onClick={this.handleClickB}
            >B</button>
            <button className="btn-bold">I</button>
            <button className="btn-bold">U</button>
            <button className="btn-bold">fontName</button>
            <button className="btn-bold"
              onClick={this.handleSize}>
              16
            </button>
            <button className="btn-bold">color</button>
            <button className="btn-bold">unordered</button>
            <button className="btn-bold">ordered</button>
            <button className="btn-bold">Play</button>

          <textarea
            className="text-content"
            type="text"
            placeholder="text-content"
            value={this.contentValue}
            name="textContent"
            onChange={this.handleUserInput}
            >
            </textarea>

  );
}

}

A: Посмотри внимательно execCommand, функция обработчик будет иметь вид:
$('кнопка').on('mousedown', function (e) {
document.execCommand("bold");
e.preventDefault(); });

Там много чего есть для редактора. Если будут вопросы можешь обращаться, я уже написал свой редактор, включая работу с таблицами и связанными input. Связь как в Excel можно вписывать формулы.
Конкретно execCommand работает как с уже выделенным текстом так и с тем который еще будет вводиться. По моему то что тебе нужно.


text:
Q: With Jasmine-jQuery I tried to use fixture HTML but test doesn't pass I am newbie of Jasmine-jQuery. I tried to use fixture HTML but test doesn't pass.
fixture.html:
<html>
<body>
  <p id="0">
  </p>
</body>
</html>

fake_code_for_question_spec.coffee:
describe "FakeCodeForQuestion", ->
  describe "with HTML fixture", ->
    beforeEach ->
      loadFixtures "fixture.html"   ### Load Fixture
      @obj = new FakeCodeForQuestion

    describe "#addText", ->
      beforeEach ->
        @obj.addTextToParagraph0()   ### Change DOM

      it "should add text", ->
        expect($('p#0')).toHavaText "text"   ### Get Changed DOM

fake_code_for_question.coffee:
root = exports ? this
class root.FakeCodeForQuestion
  addTextToParagraph0: ->
    $('p0').text "text"

Jasmine Result:
FakeCodeForQuestion with HTML fixture #addText should add text.
TypeError: Object [object Object] has no method 'toHavaText'
TypeError: Object [object Object] has no method 'toHavaText'
    at null.<anonymous> (http://localhost:8888/__spec__/p130318_fake_code_for_question_spec.js:14:35)
    at jasmine.Block.execute (http://localhost:8888/__jasmine__/jasmine.js:1064:17)
    at jasmine.Queue.next_ (http://localhost:8888/__jasmine__/jasmine.js:2096:31)
    at goAgain (http://localhost:8888/__jasmine__/jasmine.js:2086:18)

Thank you for your kindness.

A: I think your folder structure is not in accordance with jasmine-jquery. The loadFixtures() uses this directory path spec/javascripts/fixtures. If you go into jasmin-jquery code base, look for fixturesPath, you'll see that all of them use spec/javascripts/fixtures. But you can override this by using jasmine.getFixtures().fixturesPath = "[your directory path here]";.
I hope this help, if I understand your question.

A: describe "FakeCodeForQuestion", ->
  describe "with HTML fixture", ->
    beforeEach ->
      loadFixtures "fixture.html"   ### Load Fixture
      @obj = new FakeCodeForQuestion

    describe "#addText", ->
       beforeEach ->
        @obj.addTextToParagraph0()   ### Change DOM

       it "should add text", ->
        expect($('p#0')).toHavaText "text"   ### Get Changed DOM

The result you got, no method 'toHavaText' gives you the indication, you want toHaveText instead


text:
Q: Why does the differential solid angle have a $\sin\theta$ term in integration in spherical coordinates? When you integrate in spherical coordinates, the differential element isn't just $ \mathrm d\theta \,\mathrm d\phi $.  No.  It's $\sin\theta \,\mathrm d\theta \,\mathrm d\phi$, where $\theta$ is the inclination angle and $\phi$ is the azimuthal angle.
For example, attempting to integrate the unit sphere without the $\sin\theta$ term:
$$
\int_0^{2\pi}\int_0^{\pi} \mathrm d\theta \,\mathrm d\phi = 2 \pi^2.
$$
With the $\sin\theta$ term you get
$$
\int_0^{2\pi}\int_0^{\pi} \sin\theta \,\mathrm d\theta \,\mathrm d\phi = 4 \pi.
$$
But I'm puzzled why you need to multiply the differential solid angle by $\sin\theta$.  It would seem it's because the chunks at the north/south pole are "worth less" than the chunks at the equator.  That kind of makes sense because they will be closer together.

A: You are right that higher chunks are worth less. This comes from the artifact of the horizontal radius getting smaller as you move toward either pole. Take the sphere at the origin and draw the radius going out horizontally on the x-y plane. Now move this radius upward along the z axis, keeping it parralel to the x-y plane. This is effectively in cylindrical coordinates now. Imagine we are now calculating the area of the sphere by adding up the horizontal circular slices as we go up  Notice that if you do one revolution in phi, you want to be tracing out the edge of the sphere, and the higher up you are, the smaller the radius. Basic trig tells you that at height z, the radius is $r\sin(\theta)$, where $r$ is the usual radius of the sphere (it looks like you have $r=1$). Without the sin factor you would be instead calculating the surface area of the side of a cylinder.

A: Zhen Lin explained the theory here. I try to recite this in the theory section and then show ways to plot things with different tools in the Getting Our Hands Dirty! section.
Theory

The square form i.e. the Jacobian is required for the change in
    coordinates because you need to know change in every direction. After
    this calculation, you need to calculate the determinant and take the
    square root as below
$$J = \begin{pmatrix} r \cos \theta \cos \phi & -r \sin \theta \sin  \phi \\ r \sin \theta \cos \phi &  r \cos \theta \sin \phi \\  -r \sin
 \phi & 0 \end{pmatrix}$$
for which the general formula
$$A = \int_S \sqrt{\det g} \, du \, dv.$$
I really recommend Zhen Lin's marvelous answer!

P.s. The only case when your first equation is correct is when $r=1$ and $\sin(\phi)=1$ for the integration -- probably not the integral
  you are trying to do! I use the same notation as Zhen Lin, Latitude is
  $\psi \in [0,\pi]$ and azimuth is $\theta \in[0,2\pi]$.
ALERT!

Please, notice that people use two different conventions for integration: Zhen Lin uses reading outer-most integral things first
    and you use reading things in parallel (I hope you know the difference
    or you are very confused!).

Now let's get our hands dirty!
Now how should we alter the parametrization to make it look like the integral? I don't know, thinking. Anyway, the below examples were provided by co-operation of people around Stackexchange such as Anon Mouse and eindandi. If you find them useful, give them some upvotes -- not me.

Mathematica

Manipulate[
 ParametricPlot3D[{Sin[theta] Cos[phi],
   Sin[theta] Sin[phi], Cos[theta]},
  {theta, 0, t}, {phi, 0, p},
  PlotRange -> {{-1, 1}, {-1, 1}, {-1, 1}}],
 {t, 0.1, Pi}, {p, 0.1, 2 Pi}]

Matlab

[f,t] = meshgrid(linspace(0,2*pi,361),linspace(0,pi,361));
x = sin(t)*cos(f);
y = sin(t)*sin(f);
z = cos(t);
surf(x,y,z)

A: To see this just draw a "square" somewhere  along the equator, with sides $d\phi$, $d\theta$. Now try and move this "square" upwards towards the poles: although the "height" ($d\theta$) stays the same, the "width" ($d\phi$) becomes smaller and smaller, until you reach the pole itself, where the width becomes zero. This is because the lines of constant $\phi$ are not parallel like in Cartesian coordinates, but rather "meet up" at the poles.

A: You can see need for the $\sin\phi$ factor by comparing the actual area on a globe with the apparent area in the Equirectangular projection.  Each square of the projection represents the same change in $\theta$ and in $\phi$ and maps to a curved quadrilateral on the globe.  The closer to the poles (where $\phi = 0, \pi$), the smaller the area on the globe; roughly it is proportional to $\sin\phi$, keeping in mind that the latitude measurement differs from $\phi$ by a right angle.

maps to

Equal changes in $\phi$ represent the same distance on a (spherical) globe, but equal changes in $\theta$ (longitude) represent distances proportional to $\sin\phi$, which you can prove by finding the radius of a circle of latitude that goes around around a pole (as pointed out by @Alex).

A: Actually what you meant to ask is like for differential solid pie element
$$
\int_0^{2\pi}\int_0^{\pi} \cos\phi \, d\phi \,d\theta \, = \int_0^{2\pi}\int_0^{\pi}  d (\sin \phi) \,d\theta \, =
\int_0^{2\pi}  \sin \phi \,d\theta \, = \int_0^{2\pi}  (1-(-1) \,d\theta \, $$
$$ = 2\, (2 \pi)  = 4 \pi$$
The earth is a sphere  not a cylinder, so $\cos \phi $ is shrinking to 0 at poles.


text:
Q: How to separately subplot a X*Y*Z (3D) matrix matlab? I'd like to create 4 subplots each containing 16 figures. Each figure is one dimension of the matrix GW. I.e. GW(:,:,1) is the first image.
Here is my for loop for the first 16 images in first subplot. How should I modify the for loop to get 3 more subplots?
The first subplot should contain first 16 images, second subplot should contain second 16 images and so on. With the following loop I'm getting first 16 images for all the four subplots.
for i=1:4
        figure(i);
        hold on;

        for jj = 1:16
              subplot (4,4,j)
              imshow (GW(:,:,j));
        end
end

A: You just need to modify how you access the 3rd dimension of GW. Try this:
num_figures = 4;  % because I dont like magic numbers in the code
subplots_per_figure = 16;  % same here
for i=1:num_figures
        figure(i);
        hold on;

        for j = 1:subplots_per_figure
              subplot (4,4,j)
              imshow (GW(:,:,j+(i-1)*subplots_per_figure));
        end
end


text:
Q: Problema con if anidados en python Hace un par de días empecé un pequeño curso de Python para familiarizarme con el lenguaje, y ya llegue a mi primer problema. Resulta que tenemos que armar nuestra propia red social, y hay un apartado al final donde el programa pregunta si el usuario quiere cambiar algo del perfil. Mi problema es el siguiente:

*

*Cada vez que escribo "1", se escriben todos los n1,n2,etc. ademas del mensaje continuar, quiero que cuando escriba "1" ya no me vuelva a repetir el mensaje de continuar

*Aunque me muestre los mensajes de n1,n2,etc. no me deja editarlos porque sigue en el loop con el mensaje de continuar.
Intente hacerlo con un bool y el resultado fue el mismo, ya no sé que más intentar, por favor ayuda jaja.
El código es el siguiente:
while continuar != 0:
   continuar = int(input("¿Desea cambiar algo del Perfil? Presione 1 para seguir o 0 para salir"))

   if continuar == 1:
    n1 = str(print("Para cambiar el nombre, escriba nombre:"))
    n2 = str(print("Para cambiar la edad, escriba edad:"))
    n3 = str(print("Para cambiar la cantidad de amigos, escriba amigos:"))
    n4 = str(print("Para salir, escriba 0:"))

    if n1 == "Nombre" or n1 == "nombre" or n1 == "NOMBRE":
          nombre = input("Nombre:")
          print()
    if n2 == "Edad" or n2 == "edad" or n2 == "EDAD":
          edad = input("Edad:")
          print()
    if n3 == "Amigos" or n3 == "amigos" or n3 == "AMIGOS":
          num_amigos = input("Cantidad de amigos:")
          print()
    if n4 == 0:
             print("Has decidido salir")

    elif continuar == 0:
       print("Has dedicido salir")

A: le hice un par de cambios:
#-*- coding: utf -8 -*-

while True:
    continuar = int(input("¿Desea cambiar algo del Perfil? Presione 1 para seguir,
    0 para salir: "))

if continuar == 1:
    print("""
    Para cambiar el nombre, escriba nombre
    Para cambiar la edad, escriba edad
    Para cambiar la cantidad de amigos, escriba amigos
    Para salir, escriba 0:""")
    opcion= input("Cambiar: ").lower() #para que lea siempre en minúsculas
    if  opcion == "nombre" :
        nombre = input("Nombre:")
        print()
    elif opcion == "edad":
        edad = input("Edad:")
        print()
    elif opcion == "amigos" :
        num_amigos = input("Cantidad de amigos:")
        print()
    elif opcion == "0":
        print("Has decidido salir")

elif continuar == 0:
    print("Has dedicido salir")
    break
else:print("Opción incorrecta")


text:
Q: IBM Db2 on Cloud: Results not shown in SQL editor I have uploaded the tables and created them in IBM Db2 on Cloud.
However, when I run queries in the SQL editor, the results are not being displayed.

So I am unable to verify if the results are correct.
How do I go about it?
Thanks.

A: Click on the arrow on the right. It will open a new window and display the result.


text:
Q: BMI Category is qualitative or quantitative I know for sure that BMI(Body Mass Index) is a quantitative variable as it is a continuous variable. But is that BMI Category derived from the BMI a qualitative variable or a quantitative variable? (Underweight, Normal Weight, Overweight. Thanks

A: Usually we think of this type of data as a special form of categorical data called "ordinal", that is, ordered-categorical. This is because there is a natural ordering in the data: Underweight < Normal < Overweight.
While it is sometimes useful to create categories such as these, there is a great loss of information by doing so.
Edit:  Based on comments in the question, it would be a good idea to consider a regression based model, where you do not categorise BMI but rather use it as the outcome/response. Since you seem to have a just one independent variable, which is categorical, this would be a one-way ANOVA.


text:
Q: How can I pause the execution of a pthread program, so that I can check the pid and tgid of the threads? I am trying with a small program from Distinction between processes and threads in Linux
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>

void* threadMethod(void* arg)
{
    int intArg = (int) *((int*) arg);

    int32_t pid = getpid();
    uint64_t pti = pthread_self();

    printf("[Thread %d] getpid() = %d\n", intArg, pid);
    printf("[Thread %d] pthread_self() = %lu\n", intArg, pti);
}

int main()
{
    pthread_t threads[2];

    int thread1 = 1;

    if ((pthread_create(&threads[0], NULL, threadMethod, (void*) &thread1))
         != 0)
    {
        fprintf(stderr, "pthread_create: error\n");
        exit(EXIT_FAILURE);
    }

    int thread2 = 2;

    if ((pthread_create(&threads[1], NULL, threadMethod, (void*) &thread2))
         != 0)
    {
        fprintf(stderr, "pthread_create: error\n");
        exit(EXIT_FAILURE);
    }

    int32_t pid = getpid();
    uint64_t pti = pthread_self();

    printf("[Process] getpid() = %d\n", pid);
    printf("[Process] pthread_self() = %lu\n", pti);

    if ((pthread_join(threads[0], NULL)) != 0)
    {
        fprintf(stderr, "Could not join thread 1\n");
        exit(EXIT_FAILURE);
    }

    if ((pthread_join(threads[1], NULL)) != 0)
    {
        fprintf(stderr, "Could not join thread 2\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}

On 64 bit Lubuntu 18.04, I compile it by the same command from the post:
$ gcc -pthread -o thread_test thread_test.c

I also try to follow what the post says:

By using scheduler locking in gdb, I can keep the program and its threads alive so I can capture what top

but because I am not familiar with gdb,  the program runs to finish without pausing (see below). I also tried to set up breakpoint by break 43, but gdb says No line 40 in the current file. What shall I do to pause the execution, so that I can use top or ps to examine the threads' pid and tgid?
$ gdb thread_test
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from thread_test...(no debugging symbols found)...done.
(gdb) set scheduler-locking
Requires an argument. Valid arguments are off, on, step, replay.
(gdb) set scheduler-locking on
Target 'exec' cannot support this command.
(gdb) run
Starting program: /tmp/test/pthreads/thread_test
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff77c4700 (LWP 4711)]
[New Thread 0x7ffff6fc3700 (LWP 4712)]
[Thread 1] getpid() = 4707
[Thread 1] pthread_self() = 140737345505024
[Process] getpid() = 4707
[Process] pthread_self() = 140737353951040
[Thread 0x7ffff77c4700 (LWP 4711) exited]
[Thread 2] getpid() = 4707
[Thread 2] pthread_self() = 140737337112320
[Thread 0x7ffff6fc3700 (LWP 4712) exited]
[Inferior 1 (process 4707) exited normally]
(gdb)

A: You have two problems:

*

*you built your program without debugging info (add -g flag), and

*you are trying to set scheduler-locking on before the program started (that doesn't work).

This should work:
 gcc -g -pthread -o thread_test thread_test.c
 gdb -q ./thread_test
 (gdb) start
 (gdb) set scheduler-locking on

However, you must be extra careful with this setting -- simply continuing from this point will get your program to block in pthread_join, as only the main thread will keep running.

A: the following is an example of using gdb with the posted code to pause everything:
note: this was compiled to find/fix compile problems via:
gcc -ggdb -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c untitled.c

this was finally compiled/linked via:
gcc -ggdb -Wall -o untitled untitled.c   -lpthread

then using the debugger: gdb, thereby showing my inputs and the gdb outputs:
$ gdb untitled
GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from untitled...done.
(gdb) br main
Breakpoint 1 at 0x9a5: file untitled.c, line 20.
(gdb) br threadMethod
Breakpoint 2 at 0x946: file untitled.c, line 9.
(gdb) r
Starting program: /home/richard/Documents/forum/untitled
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Breakpoint 1, main () at untitled.c:20
20  {
(gdb) c
Continuing.
[New Thread 0x7ffff77c4700 (LWP 8645)]
[New Thread 0x7ffff6fc3700 (LWP 8646)]
[Switching to Thread 0x7ffff77c4700 (LWP 8645)]

Thread 2 "untitled" hit Breakpoint 2, threadMethod (arg=0x7fffffffdf4c)
    at untitled.c:9
9       int intArg = (int) *((int*) arg);
(gdb)

then you can (in another terminal window) use ps etc to display info.  However, the thread function will output (to stdout the information you might be interested in.
or you can (in gdb enter commands like:
(gdb) c
[Process] getpid() = 8641
[Process] pthread_self() = 140737353992000
[Switching to Thread 0x7ffff6fc3700 (LWP 8646)]

Thread 3 "untitled" hit Breakpoint 2, threadMethod (arg=0x7fffffffdf50)
at untitled.c:9
9       int intArg = (int) *((int*) arg);
(gdb) c
....
[Thread 1] getpid() = 8641
[Thread 1] pthread_self() = 140737345505024
....
[Thread 2] getpid() = 8641
[Thread 2] pthread_self() = 140737337112320


text:
Q: Is there any API to implement flow visualization like google flow visualization I am trying to implement flow visualization diagram like google flow visualization. Please suggest any API for this type of implementation. Any help will be appreciated.
EDIT : I used sankey diagrams to achieve this requirement. Below is my code:
$(document).ready(function() {

    var dataArray = [["India \n 40","United States \n 25","Canada \n 20","Hong Kong \n 15"],
                     ["page1 \n 50","page2 \n 30","about_us.htm \n 20"],
                     ["page2 \n 50","contactus.htm \n 15"],
                     ["page1 \n 50"]];

    var sankey = new Sankey();

    for(var i=0; i< dataArray.length; i++)
    sankey.stack(i,dataArray[i]);

    sankey.setData([["India \n 40",20,"page1 \n 50"],["United States \n 25",10,"page1 \n 50"],["Canada \n 20",10,"page1 \n 50"],["Hong Kong \n 15",10,"page1 \n 50"],["India \n 40",10,"page2 \n 30"],["United States \n 25",10,"page2 \n 30"],["Canada \n 20",5,"page2 \n 30"],["Hong Kong \n 15",5,"page2 \n 30"],["India \n 40",10,"about_us.htm \n 20"],["United States \n 25",5,"about_us.htm \n 20"],["Canada \n 20",5,"about_us.htm \n 20"],
                    ["page1 \n 50",35,"page2 \n 50"],["page2 \n 30",15,"page2 \n 50"],["page1 \n 50",10,"contactus.htm \n 15"],["page2 \n 30",5,"contactus.htm \n 15"],
                    ["page2 \n 50",40,"page1 \n 50"]
                    ]);

    sankey.setBubbles([["page1 \n 50", 5],["page2 \n 30",10],["about_us.htm \n 20",20],["contactus.htm \n 15",15],["page2 \n 50",10]]);

    sankey.bubbleColor = "#F37126";
    sankey.bubbleLabelColor = "#FFF";
    sankey.draw();
});

In the above example, I have "page1 \n 50" in first and third interaction. For this it will created only one node in third interaction. How to overcome this problem. Please help me out.
Thanks in advance

A: It looks like what you want is a Sankey diagram.

A: The thing is you can't do that with sankey. You can add some other data such as stack number to the data so you can reduce duplication. This is how i am doing with it. It simply means none of my objects have same name in sankey chart.


text:
Q: Can you skip a record on bulk import when a duplicate record shows up? I'm diving into some code written by others and I'm running into a duplicate record issue. I understand why the duplicate issue is popping up (I added the unique_together constraint). This code below is wrapped with the @transaction.atomic decorator so if any part fails it rolls back. I want to have the serializer is_valid() function skip over the duplicates, just move on, and not raise the ValidationError. How can I do this and is this the best practice?
The code makes use of the Django Rest Framework serializers and validators.
serializer_class = globals().get(table + 'Serializer')
if serializer_class is None:
    raise SerializerNotFound(table)
serializer = serializer_class(data=data, many=True)
serializer.is_valid(raise_exception=True)
serializer.save()

I also added this code to the Serializer class:
class Meta:
    model = CoolModelName
    validators = [
        validators.UniqueTogetherValidator(
            queryset=CoolModelName.objects.all(),
            fields=('field', 'list', 'names', 'here')
        )
    ]


text:
Q: Route user to another HTML page using $state.go in Ionic I am creating a simple 'phonebook' test application and am running into an issue when attempting to navigate the user to a new page when clicking on an ion-item in and ion-list.
To give a brief overview of what I am trying to accomplish:
I have a SQLite DB that consists of information of users (name, phone number, etc)
I have created a ion-list to display all the users. When a user is clicked, it must direct the user to a new page that will go into a more in-depth description of all the users' information. Going from the 'home' page to the 'detail' page is where my problem lies. There is no error being thrown when clicking on the ion-item that contains the 'short description' of the user's information.
In my app.js file I have the following config:
app.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider.state('home', {
          url: "/home",
          templateUrl: "index.html",
          controller: "HomeCtrl"
    })
    $stateProvider.state('detail', {
          url: "/detail",
          templateUrl: "dummy.html",
          controller: "DetailCtrl"
     })
   $urlRouterProvider.otherwise("/home");
 })

 .controller('HomeCtrl', function($scope, $state) {
    $scope.changeState = function () {
        console.log("home");
        $state.go('home');
    }
 })
 .controller('DetailCtrl', function($scope, $state) {
    $scope.changeState = function () {
        console.log("detail");
        $state.go('detail');
    }

 })

In my index.html, I have the following body:

  <ion-nav-view name="home" ui-sref="home">
    <ion-pane>
        <ion-header-bar class="bar-assertive">

Contacts

        </ion-header-bar>

        <ion-content class="scroll-content" ng-controller="HomeScreenController" padding="true">

            <ion-list>
                <ion-item
                    class="ion-item-content"
                    ng-repeat="employee in allEmployeeInformation | orderBy:'lastName'"
                    ng-controller="DetailCtrl"
                    ng-click="changeState()">

{{employee.userCN}}

{{employee.title}}

{{employee.town}}

                </ion-item>
            </ion-list>
        </ion-content>
    </ion-pane>
 </ion-nav-view>

Not that this applies but just to be as thorough as possible, I'm currently just using a filler for the 'detail' page until I get this working. This contains the following:

  <ion-nav-view name="detail" ui-sref="detail">

John Doe

Developer

 </ion-nav-view>

What would cause the click on the ion-item to (what appears to) not do anything? What am I missing that would make the user able to click the ion-item to navigate to the 'detail' HTML page?
I can provide any further information needed. I'm not sure how to continue at this point.
Thanks in advance for the help, guys.
Cheers,
-Mike

A: @Michael I am working on ionic app that deals with routing using $state.go()

*

*Inject $state service in your controller.

Sample App.js
.state('tab.chats', {
      url: '/chats',
      views: {
        'tab-chats': {
          templateUrl: 'templates/tab-chats.html',
          controller: 'ChatsCtrl'
        }
      }
    })

Controller redirection logic
$state.go('tab.chats');

Update - 4/2/2016
Hey Michael thanks to your question now even i know how tab project is wired.. :)
This is working code. In your code you forgot to add abstract state which is parent state. see in my code tab state. where tab is parent state and [Parent]tab.home[child] and [Parent]tab.detail[child] states.
Create tabs project so you dont have to create all files from scratch. Tabs projects will allow you to create very structured project.
Tabs.html
<ion-tabs class="tabs-icon-top tabs-color-active-positive">

  <ion-tab title="Status" icon-off="ion-ios-pulse" icon-on="ion-ios-pulse-strong" href="#/tab/home">
    <ion-nav-view name="tab-home"></ion-nav-view>
  </ion-tab>

  <ion-tab title="Chats" icon-off="ion-ios-chatboxes-outline" icon-on="ion-ios-chatboxes" href="#/tab/detail">
    <ion-nav-view name="tab-detail"></ion-nav-view>
  </ion-tab>
</ion-tabs>

App.js
// setup an abstract state for the tabs directive
 .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'templates/tabs.html'
  })

.state('tab.home', {
    url: '/home',
    views: {
      'tab-home': {
        templateUrl: 'templates/tab-home.html',
        controller: 'HomeCtrl'
      }
    }
  })

  .state('tab.detail', {
    url: '/detail',
    views: {
      'tab-detail': {
        templateUrl: 'templates/tab-detail.html',
        controller: 'DetailCtrl'
      }
    }
  });

Controller.js
.controller('HomeCtrl', function($scope) {})

.controller('DetailCtrl', function($scope) {})

Create 2 html pages in template folder tab-home.html and tab-detail.html
I hope it resolves your bug.


text:
Q: Allow all JQuery accordion sections to be open I have a fully working JQuery accordion except for the fact that I want to have the ability to have all the sections open. To achieve this an user must be able to open a section without the other one's collapsing.
This is a bit counterintuitive, but a real-life accordion can also be expanded to it's full extend.

$(document).ready(function() {
  $("#accordion").accordion({
    heightStyle: 'content',
    collapsible: true,
    toggle: false
  });
});

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Section 1

    A

Section 2

    B

Section 3

    C

Section 4

    D

JS Fiddle: https://jsfiddle.net/xu9d53ta/
How would I achieve this?

A: Try this:

var headers = $('#accordion .accordion-header');
var contentAreas = $('#accordion .ui-accordion-content ').hide();
var expandLink = $('.accordion-expand-all');

// add the accordion functionality
headers.click(function() {
    var panel = $(this).next();
    var isOpen = panel.is(':visible');

    // open or close as necessary
    panel[isOpen? 'slideUp': 'slideDown']()
        // trigger the correct custom event
        .trigger(isOpen? 'hide': 'show');

    // stop the link from causing a pagescroll
    return false;
});

// hook up the expand/collapse all
expandLink.click(function(){
    $(".ui-accordion-content").show();
});
body {
    font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
    font-size: 62.5%;
}

.accordion-expand-holder {
    text-align: center;
    padding: 10px;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

    Expand all

        Section 1

            Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
            ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
            amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
            odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

        Section 2

            Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
            ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
            amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
            odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

        Section 3

            Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
            ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
            amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
            odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Fiddle link:
https://jsfiddle.net/s5hAw/1091/
Credits: https://stackoverflow.com/a/43445385/13695248


text:
Q: Distance between orthocenter and circumcenter.
Let $O$ and $H$ be respectively the circumcenter and the orthocenter of triangle $ABC$. Let $a$, $b$ and $c$ denote the side lengths. We are given that $a^2+b^2+c^2=29$ and the circumradius is $R=9$. We need to find $OH^2$.
I know that there is formula $OH^2=9R^2-(a^2+b^2+c^2)$, but I cannot use it unless I prove it.

I tried placing ABC triangle in a Cartesian plane and found coordinates of $O$ and $H$, but the expressions are not nice and I didn't manage to simplify them to required result.
Maybe vectors can be used? Please, note that I cannot use sophisticated vector knowledge in the solution. Any suggestions or ideas would be appreciated.

A:
since
$$\angle HAO=|B-C|.OA=R,AH=2R\cos{A}$$
use cosin theorem we have
\begin{align*}
OH^2&=AH^2+AO^2-2AH\cdot AO\cos{|B-C|}
=4R^2\cos^2{A}+R^2-4R^2\cos{A}\cos{(B-C)}\\
&=5R^2-4R^2\sin^2{A}+4R^2\cos{(B+C)}\cos{(B-C)}\\
&=9R^2-4R^2(\sin^2{A}+\sin^2{B}+\sin^2{C})\\
&=9R^2-(a^2+b^2+c^2)
\end{align*}

A: Take the circumcenter as the origin. Then vertices $A, B ,C$ become $\vec A,\vec B$ and $\vec C$ respectively, where $|\vec A|=|\vec B|=|\vec C|$. Also, let the circumcenter be $O$, centroid $G$, and orthocenter $H$.
Now, the centroid $G$ can be written as: $$G=\dfrac {\vec A+\vec B+\vec C}3\,.$$ Also we know that $\dfrac {HG}{GO}=\dfrac 21$, which means $$HO=3\cdot GO\implies HO=3\cdot\left( \dfrac {\vec A+\vec B+\vec C}3\right)={\vec A+\vec B+\vec C}\,.$$ Therefore, $$OH^2=(\vec A+\vec B+\vec C)\cdot(\vec A+\vec B+\vec C)=3R^2+2(\vec A\cdot\vec B+\vec B\cdot\vec C+\vec C\cdot\vec A)$$ Note that $$\begin{align}\vec A\cdot\vec B+\vec B\cdot\vec C+\vec C\cdot\vec A&=R^2(\cos {2A}+\cos {2B}+\cos {2C})\\&=3R^2-2R^2(\sin^2 A+\sin^2 B+\sin^2 C)\,.\end{align}$$ Finally, using the sine rule, we get $$OH^2=9R^2-(a^2+b^2+c^2)\,.$$
The result used above is the $\textit {Euler Line Theorem}$.
$\textbf {Proof:}$
Let $O$ the circumcenter of $\triangle ABC$ and $G$ its centroid. Extend $OG$ until  a point $P$ such that $OG/GP=1/2$. We'll prove that $P$ is the orthocenter $H$.
Draw the median $AA'$ where $A'$ is the midpoint of $BC$. Triangles $OGA'$ and $PGA$ are similar, since $GP=2GO$, $AG=2A'G$ and $\angle OGA'=\angle PGA$. Then $\angle OA'G =\angle PGA$ and $OA'\parallel AP$. But $OA'\perp BC$ so $AP\perp BC$, that is, $AP$ is a height of the triangle.
Repeating the same argument for the other medians proves that $P$ lies on the three heights and therefore it must be the orthocenter $H$.
The ratio is $OG/GH=1/2$ since we constructed it that way.


text:
Q: SVG transform="rotate(x,x,x)" not working on iOS I've created a Greensock animation with a circle that draws 90% and rotates so that text can be placed in the gap of the circle.  It works everywhere but on iOS devices. (see codepen below)
http://codepen.io/sumnercreations/pen/KgRJzZ
I know that iOS still requires the -webkit prefix, as stated in this question Transform not Working on IOS, so I added that in the svg code, but it still doesn't work.
CSS Tricks says that this should work everywhere but I can't get it to work for me. https://css-tricks.com/transforms-on-svg-elements/
<!-- works everywhere -->
<rect x='65' y='65' width='150' height='80' transform='rotate(45)' />

Any ideas how to accomplish this on iOS devices?

A: Greensock replied to my tweet and explained that iOS draws circles in the opposite direction and so one solution would be to use <path> instead of <circle>.  (they also mentioned that MorphSVGPlugin.convertToPath() http://greensock.com/morphSVG`) could also do it.
They included a codepen that worked perfectly.
http://codepen.io/sumnercreations/pen/EgRovE

A: One possible issue is a bug in iOS that seems to ignore rotations by multiples of 90 degrees. I found it was fixable by simply using a value that was just fractionally off (eg. 89.9 degrees).
This might not have been the issue for you, but thought this would be worth posting here because it is one possible reason for rotations not working in iOS.


text:
Q: Searchable Dropdown spinner xamarin Android Searchable Dropdown spinner
hi ,, I have spinner full by sqlite database I want can search in it
how can i do that
 I try used Autocomplete text but not worked well
this my spinner.aXml
 <Spinner
       android:layout_width="match_parent"
        android:layout_height="35dp"
        android:id="@+id/SpinnerHotel"
        android:paddingLeft="10dp"
        android:background="@drawable/Spinner_Style"
        android:spinnerMode="dropdown"
        android:gravity="center"
        android:visibility="visible"
        android:layout_marginRight="10dp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp" />

 and text_View.axml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="20dp"
                      android:id="@+id/autoCompleteTextView1"
    android:textColor="#68767A"
    android:text="Select a Hotel .. "
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:textSize="18dp" />

and this my Activity
  async    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.GoShow_layout);

        Agent = FindViewById<Spinner>(Resource.Id.SpinnerAgentt);

        List<string> my_array = new List<string>();
          my_array = await login.Get_Hotel();
        ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Resource.Layout.Text_View, my_array);
        adapter.SetDropDownViewResource(Resource.Layout.Text_View);
        Hotel.Adapter = adapter;
        Hotel.ItemSelected += Hotel_ItemSelected;

    }

private void Agent_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
    var Spinner = sender as Spinner;
    string Agentt = Spinner.GetItemAtPosition(e.Position).ToString();

    Toast.MakeText(this, Agentt , ToastLength.Short).Show();
}

A: I think you have to combine Spinner with AutoCompleteTextView, like here Combine Spinner and AutoCompleteTextView


text:
Q: (Lift) Ajax submit using SHtml.select onchange event I'm tring to implement the classic functionality of this select:elements depends on this other select:selection using Lift, E.g. select the country and get the possible states for the selected country.
The problem that I'm facing is that the "this.myForm.submit()" that I have inside the onchange of the select element is not firing the ajax request. If I use an input type"submit" it works perfectly.
Is this behaivior related with Lift framework? Is there a better way of implementing this kind of functionality using Lift libraries?
The relevant snipped code:
"name=distributionPoints" #> SHtml.select(distributionPoints, Empty, selectedDistributionPoint = _, "id" -> "the_distributionPoints") &
        "name=devices" #> (SHtml.select(devices, Empty, selectedDevice = _, "id" -> "the_devices")  ++ SHtml.hidden(process))

The view html:
<form class="lift:form.ajax">
<select name="distributionPoints" id="the_distributionPoints" onchange="submit()">
                    <option></option>
                </select>

                Device:
                <select name="devices" id="the_devices">
                    <option></option>
                </select>
</form>

The rendered HTML:
    <form id="F391649920812YBACEZ" action="javascript://" onsubmit="liftAjax.lift_ajaxHandler(jQuery('#'+"F391649920812YBACEZ").serialize(), null, null, "javascript");return false;">

Punto de distribución:
                <select onchange="submit()" id="the_distributionPoints" name="F630704816482OLP514"></select>

                    Equipo:
                    <select name="F391649920817BLRJW5" id="the_devices"></select><input type="hidden" name="F391649920818HPS35E" value="true" />

            </form>

[edit]
I finally got the solution. Like Chris mentioned I used ajaxSelect instead of just selects and instead of using setHtml there's a method called JsCmds.ReplaceOptions that does exactly what I was looking for.

A: You should understand that when using Ajax submit the page is not reloaded. So I would suggest you to use JsCmds.setHtml on server side to "reset" the second select element.
So, in fact the first select is an ajaxSelect which is meant to modify the second one (so it is not concerned by the hidden submit in my opinion). The second select is updated when the first one is changed, using 'selectPoint(s)'
Piece of Scala code
def selectPoint(s):JsCmd = {
  selectedDistributionPoint = s;
  newDevices:List[String] = findCorrespondingDevices(s);
  JsCmds.setHtml("name=devices", SHtml.select(newDevices, Empty, selectedDevice = _, "id" -> "the_devices")) ++ SHtml.hidden(process))
}

"name=distributionPoints" #> SHtml.AjaxSelect(distributionPoints, Empty, s=> selectPoint(s), "id" -> "the_distributionPoints") &
"name=devices" #> (SHtml.select(Nil, Empty, selectedDevice = _, "id" -> "the_devices")  ++ SHtml.hidden(process))

Piece of template code
<input name="distributionPoints" id="the_distributionPoints" onchange="submit()"/>
<input name="devices" id="the_devices"/>


text:
Q: Setting Matplotlib Ytick labels with matplotlib.ticker yields key error I would like to set y-ticker labels, but still have them bound to the data. Via this question, matplotlib: change yaxis tick labels, I am trying to do this with matplotlib.ticker.
I currently just want tick marks at three positions: [.25, .5, .75]. The graph generates correctly, but with the print statements, I can see it iterates over each label twice and some other random values that are not in my dictionary and thus generate key errors on this line: return label_lookup[x]. The values do not appear to be the same it's run each time. What is causing this issue?
import matplotlib as mpl
import matplotlib.pyplot as plt

label_lookup = {.25: 'Label 1',
                .5: 'Label 2',
                .75: 'Label 3'}

def mjrFormatter(x, pos):
    print x, pos
    return label_lookup[x]

ax = plt.gca()
ax.set_yticks([.25,.5,.75], minor=False)
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))
plt.draw()
plt.show()

A: I'm not an expert at matplotlib myself, but it looks like you want to be using a FixedFormatter instead of a FuncFormatter.  The FixedFormatter just takes a sequence of strings instead of a function, and emits the appropriate label.  By using a FixedFormatter, you only need your 3 labels, while with a FuncFormatter, you have to have valid values for all x's passed in.
Simply replace
ax.yaxis.set_major_formatter(mpl.ticker.FuncFormatter(mjrFormatter))

with
ax.yaxis.set_major_formatter(mpl.ticker.FixedFormatter(['Label 1', 'Label 2', 'Label 3']))

and you'll get the same results without the KeyErrors.  You can also then get rid of mjrFormatter, since you're no longer using it.
Alternatively, if you really want to use FuncFormatter, you have to be able to accept any x, not just the exact values of 0.25, 0.5, and 0.75.  You could rewrite mjrFormatter as follows:
def mjrFormatter(x, pos):
    print x, pos
    if x <= .25:
         return 'Label 1'
    if x <= .5:
         return 'Label 2'
    return 'Label 3'

Your dictionary label_lookup doesn't strike me as the ideal way to do things.  You could make it work with enough effort, but the unordered nature of the dictionary makes it hard to have a simple chain of inequality checks, which is why I hardcoded the values.


text:
Q: How can i fix this playbook how can i use service_name in the condition, i tryed with set_fact but it doesn't work.
    - name: "create systemd service"
      template:
        src: "service.j2"
        dest: "/etc/systemd/system/{{ systemd_service[item].service_name | default(item) }}.service"
        set_fact: service_name= "{{ systemd_service[item].service_name }}"
      with_items: "{{ systemd_service | list }}"
      when:
        - service_name == "oracle"

A: set_fact is the name of a module; it's not an argument to the template module. Fortunately, you don't need it; you can just write:
    - name: "create systemd service"
      template:
        src: "service.j2"
        dest: "/etc/systemd/system/{{ systemd_service[item].service_name | default(item) }}.service"
      with_items: "{{ systemd_service | list }}"
      when:
        - systemd_service[item].service_name == "oracle"
        - env_vars.stdout.find('ORACLE=True') != -1


text:
Q: An internal Exception occurred during push: cannot store objects Hello I am new to Git and trying to setup server part and client part.
On a Server side I have ssh access and Git version 1.5
On a Client side I have eclipse with eGit.
I created git repo on a server side via usual means: git init and added simple html file.
Using eGit I checkout the repo and everything seems to be going well. I made changes on a client side, committed it and decided to push back to the server.
Now I have all permissions set but still get following error:

I don't know how to fix it and error message doesn't provide much details.
Please help.
Thank you!

A: For me, on Windows eclipse, I had an error like this:
An internal Exception occurred during push: github.com/***/***/service=git-receive-pack not found

I just reconfigured the eclipse and added my github account information and store it. Then it worked. Team->Remove->Configure push to upstream->URI, Change->Add authentication details

A: Ok, I resolved my issue following way:
1) I changed configuration for remote fetch and pull from sftp to ssh
2) Once I did step 1. I got different error:

When I tried to push changes from Terminal I got following:

git push origin
      Password:
      bash: git-receive-pack: command not found
      fatal: The remote end hung up unexpectedly

3) Found answer to the above error: git-upload-pack: command not found, how to fix this correctly
4) On my old server path to the git is: "/usr/local/git/bin" So I added it to .bashrc file.
Once I done that, everything started to work:

A: The possible issues are:
1. The source code might not be committed in the first place. Please try committing and see.
2. There is some issue with github authentication. Please re authenticate the credentials and try using: Team->Remove->Configure push to upstream->URI, Change->Add authentication


text:
Q: Joining two MySQL tables by 1 single column in common did quite a bit of looking online, still stumped.  Not sure how to join these two tables.
So here's the data (apologizes, still figuring this wonderful site out)
Table 1:people

*

*peopleID

*firstname

*lastname

Table 2: locationMember

*

*locationID

*peopleID

*notes

My goal:  Join these tables at the userID and select and output all the data returned.  I want to SELECT every row in Table 2 that has a specific LocationID, and pull the name of the users from the Table 1.
Most recent attempt that failed:
SELECT m.peopleID, m.notes, p.nameFirst, p.nameLast
FROM locationMember AS m, people AS p
JOIN locationMember ON m.peopleID = p.peopleID
WHERE m.locationID='".ID."'

A: I think your JOIN is a bit off. You need to declare the table after the JOIN. You also don't need AS in the aliasing
SELECT m.peopleID, m.notes, p.nameFirst, p.nameLast
FROM locationMember m
    INNER JOIN people p ON m.peopleID = p.peopleID
WHERE m.locationID='".ID."'

A: I figured it out, hope this helps others
SELECT
locationMember.peopleID,
locationMember.notes,
people.nameFirst,
people.nameLast
FROM locationMember
INNER JOIN people ON locationMember.peopleID=people.peopleID
WHERE locationMember.locationID='id here'


text:
Q: Adding a node with jQuery in a Firefox extension I suspect that jQuery is not working ok in my extension...
I'm using version 1.3.2, loaded with the following rows:
var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
              .getService(Components.interfaces.mozIJSSubScriptLoader);
loader.loadSubScript("chrome://myext/content/lib/jquery.js", myext);

My problem is that, when running the following rows, the one tagged as 1 works, the 2 raises a misterious error "L is null" related to jQuery:
jQuery.noConflict();
$ = function(selector,context){ return new jQuery.fn.init(selector,myext.doc); };
$.fn = $.prototype = jQuery.fn;
$().ready(function() {
   $("menuitem#a").attr("label","Value set by jQuery!");             // 1
   $("menupopup#listacorsi").append("<menuitem label='newnode!'/>"); // 2

});

I supposed that second row should be good to add a child node to element #listacorsi. menuitem#a is a child of #listacorsi.
Could you please help me to understand what's wrong with my coding?
Thanks and best regards,
Livio

A: You should be referencing $ variable like this:
$("body",window.content)

Also I have also used jQuery in my firefox extension it works seamlessly with no issues at all.


text:
Q: Accessing the content of the file //Introduction
Hey, Welcome.....
This is the tutorial
//EndIntro

//Help1
Select a Stock
To use this software you first need to select the stock. To do that, simply enter the stock symbol in the stock text-box (such as "MSFT").
To continue enter "MSFT" in the stock symbol box.
//EndHelp1

//Help2

Download Stock Data
Next step is to to download the stock data from the online servers. To start the process simply press the "Update" button or hit the <ENTER> key.
After stock data is downloaded the "Refresh" button will appear instead. Press it when you want to refresh the data with the latest quote.
To continue make sure you are online and press the "Update" button
//EndHelp2

First time I want to display the content between //Introduction and //EndIntro then second time the content between //Help1 and //EndHelp1 and so on.

A: That's a very open-ended question - what sort of file? To read binary data from it you'd usually use:
using (Stream stream = File.OpenRead(filename))
{
    // Read from the stream here
}

or
byte[] data = File.ReadAllBytes(filename);

To read text you could use any of:
using (TextReader reader = File.OpenText(filename))
{
    // Read from the reader
}

or
string text = File.ReadAllText(filename);

or
string[] lines = File.ReadAllLines(filename);

If you could give more details about the kind of file you want to read, we could help you with more specific advice.
EDIT: To display content from an RTF file, I suggest you load it as text (but be careful of the encoding - I don't know what encoding RTF files use) and then display it in a RichTextBox control by setting the Rtf property. Make the control read-only to avoid the user editing the control (although if the user does edit the control, that wouldn't alter the file anyway).
If you only want to display part of the file, I suggest you load the file, find the relevant bit of text, and use it appropriately with the Rtf property. If you load the whole file as a single string you can use IndexOf and Substring to find the relevant start/end markers and take the substring between them; if you read the file as multiple lines you can look for the individual lines as start/end markers and then concatenate the content between them.
(I also suggest that next time you ask a question, you include this sort of detail to start with rather than us having to tease it out of you.)
EDIT: As Mark pointed out in a comment, RTF files should have a header section. What you've shown isn't really an RTF file in the first place - it's just plain text. If you really want RTF, you could have a header section and then the individual sections. A better alternative would probably be to have separate files for each section - it would be cleaner that way.

A: Not sure I understand your question correctly. But you can read and write content using System.IO.StreamReader and StreamWriter classes
string content = string.Empty;
using (StreamReader sr = new StreamReader("C:\\sample.txt"))
{
    content = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter("C:\\Sample1.txt"))
{
    sw.Write(content);
}

A: Your question needs more clarification. Look at System.IO.File for many ways to read data.
The easiest way of reading a text file is probably this:
string[] lines = File.ReadAllLines("filename.txt");

Note that this automatically handles closing the file so no using statement is need.
If the file is large or you don't need all lines you might prefer to reading the text file in a streaming manner:
using (StreamReader streamReader = File.OpenText(path))
{
     while (true)
     {
         string line = streamReader.ReadLine();
         if (line == null)
         {
             break;
         }
         // Do something with line...
     }
}

If the file contains XML data you might want to open it using an XML parser:
XDocument doc = XDocument.Load("input.xml");
var nodes = doc.Descendants();

There are many, many other ways to read data from a file. Could you be more specific about what the file contains and what information you need to read?
Update: To read an RTF file and display it:
richTextBox.Rtf = File.ReadAllText("input.rtf");


text:
Q: Eclipse cannot import package which is defined as dependency in maven I have checked out a maven project into eclipse using subclipse.
I try to use the spring framework in my project, and have defined it as a required dependency:
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>3.0.5.RELEASE</version>
  </dependency>

I have added the maven repo by adding the M2_REPO to my CLASS_PATH. I did that by executing this command on the cmd prompt:
mvn -Declipse.workspace="your Eclipse Workspace" eclipse:configure-workspace

I verified in Eclipse preferences that the M2_REPO variable is in my Classpath variable, and that the path refers to the repository directory of Maven.
However, a import statement like this:
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

does not work.
What can be the problem here?
EDIT:
Since this was a module under the root, i figured that i did not need to define the dependency on Spring once more in this module. However, including (copy paste the list from the root :s) solved the issue. But this can't be right since the POM.xml in the root already requieres that this module is included.

A: Try adding M2_REPO to your class path variables in eclipse if you are not using m2eclipse and mvn eclipse:configure-workspace didn't work..

Windows-> Preferences ->  Java -> Build Path ->  ClassPath Variables
  -> new -> M2_REPO or MAVEN_REPO and your Repo location


text:
Q: Changing the parallax image in parallax.js Is there a way that I can change my parallax image when an event is fired? I am using parallax.js and I cannot seem to figure out a way.
Here's the HTML:

  img_link_1

  img_link_2

  img_link_3

JS:
$(".color").click(function() {

      var indexNum = $(".product-color-list .color").index(this);

      sliderInit(indexNum);

});

var   $hero  = $("#hero"),
      $bg_index = $(".bg-page-index"),
      bg_init = $bg_index.eq(indexNum).html();

$hero.parallax({
  imageSrc: bg_init,
  speed: 0.7
});

This works the first time, but it won't work a second time because the parallax.js library changes things around with the element. Does anyone know a better way of doing this, or how to reinitiate the library?

A: I found a solution that works.  Rather than re-initiate the plugin every time I want to change the background I simply changed the image src within the element this plugin creates:
$('.parallax-slider').attr('src', background);


text:
Q: Cannot get past password section of login. Can do guest session though When switching on my PC I get to password and background photo. No icons or anything. I have attempted the Ctrl+Alt+F1 route, but this did not work.  How can I fix this?

A: Which Desktop are you using? What's your graphic hardware specs?
If you are using Unity Desktop, check this link  Unity doesn't load, no launcher no dash appears
Where, as @Oli says (Answer taken directly)

1. Try to open a terminal with Ctrl+Alt+T.
This may not work but you can try right clicking on the desktop and selecting "Open terminal here." Otherwise, you may need to change to a "hard" terminal by pressing Ctrl+Alt+F1 and log in.

2. Install compizconfig-settings-manager by running

    sudo apt-get install compizconfig-settings-manager

3. Then run it with this:

    DISPLAY=:0 ccsm &

 The first part tells the terminal which display you want it to load on (otherwise it won't have a clue).

4. If you switched to a TTY in step 1, switch back to the graphical server by pressing Ctrl +Alt+F7 (or Ctrl+Alt+F8 sometimes).
There there should be a CompizConfig Settings Manager waiting for you.

5. Find the Unity plugin. Enable it. You will be asked "Ubuntu Unity Plugin requires the plugin OpenGL. Enable Ubuntu Unity Plugin / Enable OpenGL"
6. Everything should spring into life but if it doesn't, you might have to restart. You can do that by going back to the terminal and running sudo reboot.


text:
Q: Change object type between implemented traits What I want to do:
I want to create a small parser in rust that can decode several types -> numbers, strings, lists, etc. For instance the lists can contain any type -> other lists, numbers, etc
How I'm trying to do it:
I have a super trait 'Element' which will be the base for all my types. Then I have a a trait per type,  which all require the 'Element' trait. Those traits are backed by some concrete structs. Because the lists can contain (mixed) any type, I try to store the values as Vec<Box<dyn Element>>. The issue is that when later I try to convert the dyn Element to another trait, I hit a wall:
The error:
error[E0161]: cannot move a value of type dyn Element: the size of dyn Element cannot be statically determined
  --> src/main.rs:94:27
   |
94 |     let boxed_as_number = num_as_element.to_boxed_number();
   |                           ^^^^^^^^^^^^^^

MCVE
use std::fmt;

pub enum ElementType {
    Number,
    Text,
}

pub trait Element: fmt::Debug {
    fn element_type(&self) -> ElementType;

    // Works, but I do not want a reference -> I want to change the "type"
    fn to_number_ref(&self) -> Option<&dyn Number>;

    fn to_boxed_number(self) -> Option<Box<dyn Number>>;
}

pub trait Number: Element {
    fn value(&self) -> i64;
}

pub trait Text: Element {
    fn value(&self) -> &str;
}

#[derive(Debug)]
pub struct SignedNumber {
    value: i64
}

impl SignedNumber {
    fn new(value: i64) -> SignedNumber {
        return SignedNumber { value };
    }
}

impl Element for SignedNumber {
    fn element_type(&self) -> ElementType {
        return ElementType::Number;
    }

    fn to_number_ref(&self) -> Option<&dyn Number> {
        return Some(self);
    }

    fn to_boxed_number(self) -> Option<Box<Number>> {
        return Some(Box::new(self));
    }
}

impl Number for SignedNumber {
    fn value(&self) -> i64 {
        return self.value;
    }
}

#[derive(Debug)]
pub struct StringWrapper {
    value: String
}

impl StringWrapper {
    fn new<T: Into<String>>(value: T) -> StringWrapper {
        return StringWrapper { value: value.into() };
    }
}

impl Element for StringWrapper {
    fn element_type(&self) -> ElementType {
        return ElementType::Text;
    }

    fn to_number_ref(&self) -> Option<&dyn Number> {
        return None;
    }

    fn to_boxed_number(self) -> Option<Box<Number>> {
       return None;
    }
}

impl Text for StringWrapper {
    fn value(&self) -> &str {
        return &self.value;
    }
}

fn main() {
    let num = SignedNumber::new(1);
    let num_as_element: Box<dyn Element> = Box::new(num);
    let borrowed_as_num = num_as_element.to_number_ref().unwrap();

    let num = SignedNumber::new(2);
    let num_as_element: Box<dyn Element> = Box::new(num);
    let boxed_as_number = num_as_element.to_boxed_number();
}

Why
Shouldn't self be SignedNumber in that case ? Why does rustc thinks it's dyn Element ?
impl Element for SignedNumber {
    fn to_boxed_number(self) -> Option<Box<Number>> {
        return Some(Box::new(self));
    }
}

Is there a way to do such type conversion or should I stick with references ?


text:
Q: Why I am getting this screen when I checked the size of the uploaded file in this file upload function? In the file upload function that I am working on it, one important issue is to check the size of the uploaded file. If it is larger than the default size I should get an error message. However, I am getting this screen and I don't know why. Also, I tried to debug the code but debugging did not work at all. It did not go though any line of code and I don't know why

protected void UploadFile(object sender, EventArgs e)
{
    if(FileUpload1.HasFile)
    {
        try
        {
            string[] validTypes = { "bmp", "gif"};
            string ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName);
            int size = FileUpload1.PostedFile.ContentLength;
            int limit = 84304;

            if (size < limit)
            {
                .....................................
            }
            else
            {
                Label2.ForeColor = System.Drawing.Color.Red;
                Label2.Text = "file is heavy";
            }
        }
        catch (Exception ex)
        {
            Label2.Text = "The file could not be uploaded." + ex.Message;
        }
    }
}

A: you are getting that error message because the file you chose is larger than 4Mb, which is the default . If you want to increase the size of the files you want to upload you need to change it in web.config.
inside system.web tag add a line like this:

<httpRuntime executionTimeout="600" maxRequestLength="512000" />

where 600 is the number of seconds and 512000 is the max size of the file in Kb


text:
Q: Adding file extensions to files without them in Windows I am trying to add file extensions to a large number of files located in a series of folders and subfolders in Windows. For some reason, these files do not have a file extension on them and I need them to have the extension .ddd so I can convert them to PDFs using a separate program.
cd R:\PRODUCTION\92
ren *. *.ddd

Note that this command does indeed work but only on folders that actually contain the files I need, and no subfolders. What could I add or change to hit all files in all subfolders? Thanks in advance.

A: Please try the following command. If it looks like it will do the correct rename, remove the ECHO from the REN command line.
CD /D R:\PRODUCTION\92
FOR /F "delims=" %f IN ('DIR /S /B /A:-D "*."') DO (ECHO REN "%~f" "%~nf.ddd")

In a .bat file script, double the percent character on the variable.
CD /D R:\PRODUCTION\92
FOR /F "delims=" %%f IN ('DIR /S /B /A:-D "*."') DO (ECHO REN "%%~f" "%%~nf.ddd")


text:
Q: update: libsdl1.2-dev on ubuntu12.4 I need to install libsdl1.2-dev for doing some graphics, but it is not allowed.
The reason is:
Die folgenden Pakete haben unerfüllte Abhängigkeiten:
 libsdl1.2-dev : Hängt ab von: libx11-dev soll aber nicht installiert werden
                 Hängt ab von: libglu1-mesa-dev soll aber nicht installiert werden
                 Hängt ab von: libpulse-dev soll aber nicht installiert werden
                 Hängt ab von: libxt-dev soll aber nicht installiert werden
                 Hängt ab von: libxext-dev soll aber nicht installiert werden
E: Probleme können nicht korrigiert werden, Sie haben zurückgehaltene defekte Pakete.

Update: Einige Pakete konnten nicht installiert werden. Das kann bedeuten, dass
Sie eine unmögliche Situation angefordert haben oder, wenn Sie die
Unstable-Distribution verwenden, dass einige erforderliche Pakete noch
nicht erstellt wurden oder Incoming noch nicht verlassen haben.
Die folgenden Informationen helfen Ihnen vielleicht, die Situation zu lösen:

Die folgenden Pakete haben unerfüllte Abhängigkeiten:
 libpulse-dev : Hängt ab von: libpulse0 (= 1:1.1-0ubuntu15) aber 1:1.1-0ubuntu15.4 soll installiert werden
                Hängt ab von: libpulse-mainloop-glib0 (= 1:1.1-0ubuntu15) aber 1:1.1-0ubuntu15.4 soll installiert werden
                Hängt ab von: libglib2.0-dev soll aber nicht installiert werden
 libx11-dev : Hängt ab von: libx11-6 (= 2:1.4.99.1-0ubuntu2.1) aber 2:1.4.99.1-0ubuntu2.2 soll installiert werden
              Empfiehlt: libx11-doc soll aber nicht installiert werden
E: Probleme können nicht korrigiert werden, Sie haben zurückgehaltene defekte Pakete.

mp@ubuntu:~$ sudo apt-get install libsdl1.2-dev libx11-dev libglu1-mesa-dev libpulse-dev libxt-dev libxext-dev
Paketlisten werden gelesen... Fertig
Abhängigkeitsbaum wird aufgebaut
Statusinformationen werden eingelesen... Fertig
Einige Pakete konnten nicht installiert werden. Das kann bedeuten, dass
Sie eine unmögliche Situation angefordert haben oder, wenn Sie die
Unstable-Distribution verwenden, dass einige erforderliche Pakete noch
nicht erstellt wurden oder Incoming noch nicht verlassen haben.
Die folgenden Informationen helfen Ihnen vielleicht, die Situation zu lösen:

Die folgenden Pakete haben unerfüllte Abhängigkeiten:
 libpulse-dev : Hängt ab von: libpulse0 (= 1:1.1-0ubuntu15) aber 1:1.1-0ubuntu15.4 soll installiert werden
                Hängt ab von: libpulse-mainloop-glib0 (= 1:1.1-0ubuntu15) aber 1:1.1-0ubuntu15.4 soll installiert werden
                Hängt ab von: libglib2.0-dev soll aber nicht installiert werden
 libx11-dev : Hängt ab von: libx11-6 (= 2:1.4.99.1-0ubuntu2.1) aber 2:1.4.99.1-0ubuntu2.2 soll installiert werden
              Empfiehlt: libx11-doc soll aber nicht installiert werden
E: Probleme können nicht korrigiert werden, Sie haben zurückgehaltene defekte Pakete.

A: Try explicitly requesting the installation of all those packages, like so:
sudo apt-get install libsdl1.2-dev libx11-dev libglu1-mesa-dev libpulse-dev libxt-dev libxext-dev

That will either work or give you another error. In the latter case, please update your post with the details on that error using the edit function.


text:
Q: @NaturalId only valid on root entity (or its @MappedSuperclasses), using Natural Id in Joined, Multiple Table Inheritance basically I cant find in google some similar problems by just pasting the root exception "@NaturalId only valid on root entity (or its @MappedSuperclasses)" in the search tab. I'm using a Joined, Multiple Table inheritance strategy to map my concrete/children Entities(Student,Employee) including their Abstract Parent (Person) to the three tables in my database, so far I never had a problem, Until I realize I need to implement a custom query for my Student Entity, using the Student's studentId. I manage to extract the underlying Hibernate-session from the Entity-manager and now I can clearly see and use the methods I need from my beloved HibernateSession, (we all know Hibernate has methods for naturalIds such as (byId, byNaturalId etc..)), and these kinds of methods are really really REALLY useful for querying entities. So I just annotate my studentId data member with @NaturalId until.. I performed some operation (save/create) and then multiple lines of exception are thrown to me. And the root cause is..
 org.hibernate.AnnotationException: @NaturalId only valid on root entity (or its @MappedSuperclasses)

I will paste the codes of my entities for added information
The Parent abstract base class
Person class
@Entity
@Inheritance(strategy=InheritanceType.JOINED)
@DiscriminatorColumn(name="PERSON_TYPE")
@Table(name="PERSON")
public abstract class Person {

@Id
@GeneratedValue
@Column(name="person_ent_id", insertable = false)
private int personId;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "age")
private int age;

@Column(name = "postal_id")
private String postalId;

.. getter and setter methods declarations

The Entity sub-class
Student class
@Entity
@Table(name = "STUDENT")
@DiscriminatorValue("S")
@PrimaryKeyJoinColumn(name = "student_ent_id", referencedColumnName = "person_ent_id")
public class Student extends Person {

@Column (name = "student_ent_id", insertable=false, updatable=false)
private int studentEntId;

@NaturalId
@Column(name = "school_id")
private String schoolId;

@Column(name = "school_name")
private String shoolName;

public Student() {
    super();
}

...getter and setter methods declarations

Questions:
  Is there a anything I can do to make a unique query for different student entities? because Hibernate's  naturalId methods are really useful to perform operations with entities such as get or
update
Is there any work-around to accomplish what I want without sacrificing my Design with the Entities and the database table? I want the studentId to act as a naturalId IF it would be possible. Any suggestions/help/comments please. Any thing will be greatly appreciated.

A: No, unfortunately this is not possible. I think it's because you can make NaturalId queries only on the whole table, so it needs to be on a root Entity. But if you only want to make sure that schoolId is unique for all Students you can use @Column(name = "school_id", unique = true).


text:
Q: Is there a more idiomatic way of replacing a pointer? Consider the following code:
#include <memory>
#include <stdio.h>
#include <stdexcept>

class Foo {
    public:
        Foo(int n) { val =n; printf("Hi %d\n", val); };
        ~Foo() { printf("Bye %d\n", val); };
    private:
        int val;
};

int main()
{
    std::shared_ptr<Foo> p = nullptr;  // I don't know what I want yet
    p = std::make_shared<Foo>(1); // OK, I've decided

    // I've changed my mind, it needs to be something else
    p = nullptr;
    p = std::make_shared<Foo>(2);

    return 0;
}

Its output is:
Hi 1
Bye 1
Hi 2
Bye 2

It's a contrived example. Foo is a fairly uninteresting. It just prints out info regarding its lifetime.
The logic behind the code is: I declare p, but I don't know what it should be initially. I then decide that I know what it is: it should take the value 1. In my real code, this value might last a long time.
Some time later, I decide that it shouldn't be 1, it should be 2. So whatever it was before should be destroyed, and be replaced by something else.
So far, my understanding is that the code above is good in terms of memory  management and is robust under exceptions.
Is there a more idiomatic way of saying:
p = nullptr;
p = std::make_shared<Foo>(2);

I can't just write the last line, because I want to say that what I had before needs to be destroyed.

A: Just assigning to the pointer is enough to inform you don't need the previous value. You don't get to say whether it should be destroyed since it's a shared pointer and may have other owners.
In my opinion just assigning is enough but you may prefer to use shared_ptr::reset().

A: Since you want idiomatic (good!), let's be idiomatic:
#include <memory>
#include <stdexcept>
#include <iostream>

class Foo {
public:
    Foo(int n)
    : val(n)
    {
        std::cout << "Hi " << val << "\n";
    };
    ~Foo() {
        std::cout << "bye " << val << "\n";
    };
private:
    int val;
};

int main()
{
    auto p = std::shared_ptr<Foo>();  // I don't know what I want yet
    p = std::make_shared<Foo>(1); // OK, I've decided

    // I've changed my mind, it needs to be something else
    p = std::make_shared<Foo>(2);

    return 0;
}

A: There is nothing else you need to do here
p = std::make_shared<Foo>(2);

This line destroys previous object in p if it was the last reference to this object. Then it assigns new shared_ptr to p with new value


text:
Q: Facebook Graph API Request for only todays photos I want to get all the uploaded photos of the logged in user that was uploaded today. I could fetch all the photos and filter it with the created_time field. But I would like to make the request to Facebook api to just send me todays photos.
This is the code I am using to get users uploaded photos
    fun getAllPhotos() {
        val bundle =Bundle()
        bundle.putString(
            "fields",
            "album,alt_text,created_time,event,place,alt_text_custom,name,name_tags,target,source"
        )

        tempPhotos.clear()
        val request = GraphRequest.newGraphPathRequest(
            AccessToken.getCurrentAccessToken(),
            "/me/photos/uploaded",
            object : GraphRequest.Callback {
                override fun onCompleted(response: GraphResponse) {
                    val type = object : TypeToken<ApiResponseObject>() {}.type
                    val respJSON = response.getJSONObject()
                    val item: ApiResponseObject = Gson().fromJson(respJSON.toString(), type)
                    item.data.forEach {
                        if (UtilityFunctions.checkIfToday(it.createdTime)) {
                            tempPhotos.add(it)
                        } else {
                            return@forEach
                        }
                    }
                }
            })
        request.parameters = bundle
        request.executeAsync()
    }

As you can see I request for all photos to "/me/photos/uploaded/" I would like to only request for photos on a certain date ( or just today )
I saw that the response came sorted by created time so I returned from the loop whenever I saw some picture that was out of date.

A: Hey can you provide some more information regarding the issue you are facing with your code.
eg. some examples of how facebook api response structure is, some code snippets etc.

Edited response:

I crawled a while for the internet to search for your problem as it is difficult to create custom query in graph api and I have never used it before. What you are doing in your code is not bad either but if you insist on creating a custom query to api then I have found a github repository that might help you
Facebook Graph API query builder

A: I found the solution. I just needed to look into the pagination documentation
I found that just as fields I could also send since and a unix timestamp and it would return the photos uploaded since that timestamp