text:
/**
 * @module  dom-traversal
 * @author  lifesinger@gmail.com
 */
KISSY.add('dom-traversal', function(S, undefined) {

    var DOM = S.DOM,
        isElementNode = DOM._isElementNode;

    S.mix(DOM, {

        /**
         * Gets the parent node of the first matched element.
         */
        parent: function(selector, filter) {
            return nth(selector, filter, 'parentNode', function(elem) {
                return elem.nodeType != 11;
            });
        },

        /**
         * Gets the following sibling of the first matched element.
         */
        next: function(selector, filter) {
            return nth(selector, filter, 'nextSibling');
        },

        /**
         * Gets the preceding sibling of the first matched element.
         */
        prev: function(selector, filter) {
            return nth(selector, filter, 'previousSibling');
        },

        /**
         * Gets the siblings of the first matched element.
         */
        siblings: function(selector, filter) {
            return getSiblings(selector, filter, true);
        },

        /**
         * Gets the children of the first matched element.
         */
        children: function(selector, filter) {
            return getSiblings(selector, filter);
        },

        /**
         * Check to see if a DOM node is within another DOM node.
         */
        contains: function(container, contained) {
            var ret = false;

            if ((container = S.get(container)) && (contained = S.get(contained))) {
                if (container.contains) {
                    return container.contains(contained);
                }
                else if (container.compareDocumentPosition) {
                    return !!(container.compareDocumentPosition(contained) & 16);
                }
                else {
                    while (!ret && (contained = contained.parentNode)) {
                        ret = contained == container;
                    }
                }
            }

            return ret;
        }
    });

    // 获取元素 elem 在 direction 方向上满足 filter 的第一个元素
    // filter 可为 number, selector, fn
    // direction 可为 parentNode, nextSibling, previousSibling
    function nth(elem, filter, direction, extraFilter) {
        if (!(elem = S.get(elem))) return null;
        if(filter === undefined) filter = 1; // 默认取 1
        var ret = null, fi, flen;

        if(S.isNumber(filter) && filter >= 0) {
            if(filter === 0) return elem;
            fi = 0;
            flen = filter;
            filter = function() {
                return ++fi === flen;
            };
        }

        while((elem = elem[direction])) {
            if (isElementNode(elem) && (!filter || DOM.test(elem, filter)) && (!extraFilter || extraFilter(elem))) {
                ret = elem;
                break;
            }
        }

        return ret;
    }

    // 获取元素 elem 的 siblings, 不包括自身
    function getSiblings(selector, filter, parent) {
        var ret = [], elem = S.get(selector), j, parentNode = elem, next;
        if (elem && parent) parentNode = elem.parentNode;

        if (parentNode) {
            for (j = 0, next = parentNode.firstChild; next; next = next.nextSibling) {
                if (isElementNode(next) && next !== elem && (!filter || DOM.test(next, filter))) {
                    ret[j++] = next;
                }
            }
        }

        return ret;
    }

});

/**
 * NOTES:
 *
 *  - api 的设计上,没有跟随 jQuery. 一是为了和其他 api 一致,保持 first-all 原则。二是
 *    遵循 8/2 原则,用尽可能少的代码满足用户最常用的功能。
 *
 */


text:
package notaql.datamodel;

/**
 * Created by thomas on 01.12.14.
 */
public class NestedSongTestData extends SongTestData {
    private ListValue list;

    public NestedSongTestData() {
        list = new ListValue();
        list.add(new NumberValue(0));
        list.add(new NumberValue(1));
        list.add(new NumberValue(2));

        getO0().put(new Step<>("list"), list);
    }

    public ListValue getList() {
        return list;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import PortMixin from 'mixins/port_mixin';

var DataDebug = Ember.Object.extend(PortMixin, {
  init: function() {
    this._super();
    this.sentTypes = {};
    this.sentRecords = {};
  },

  sentTypes: {},
  sentRecords: {},

  releaseTypesMethod: null,
  releaseRecordsMethod: null,

  adapter: Ember.computed(function() {
    var container = this.get('application').__container__;
    // dataAdapter:main is deprecated
    return (container.resolve('data-adapter:main') && container.lookup('data-adapter:main')) ||
    (container.resolve('dataAdapter:main') && container.lookup('dataAdapter:main'));
  }).property('application'),

  namespace: null,

  port: Ember.computed.alias('namespace.port'),
  application: Ember.computed.alias('namespace.application'),
  objectInspector: Ember.computed.alias('namespace.objectInspector'),

  portNamespace: 'data',

  modelTypesAdded: function(types) {
    var self = this, typesToSend;
    typesToSend = types.map(function(type) {
      return self.wrapType(type);
    });
    this.sendMessage('modelTypesAdded', {
      modelTypes: typesToSend
    });
  },

  modelTypesUpdated: function(types) {
    var self = this;
    var typesToSend = types.map(function(type) {
      return self.wrapType(type);
    });
    self.sendMessage('modelTypesUpdated', {
      modelTypes: typesToSend
    });
  },

  wrapType: function(type) {
    var objectId = Ember.guidFor(type.object);
    this.sentTypes[objectId] = type;

    return {
      columns: type.columns,
      count: type.count,
      name: type.name,
      objectId: objectId
    };
  },

  recordsAdded: function(recordsReceived) {
    var self = this, records;
    records = recordsReceived.map(function(record) {
      return self.wrapRecord(record);
    });
    self.sendMessage('recordsAdded', {
      records: records
    });
  },

  recordsUpdated: function(recordsReceived) {
    var self = this;
    var records = recordsReceived.map(function(record) {
      return self.wrapRecord(record);
    });
    self.sendMessage('recordsUpdated', {
      records: records
    });
  },

  recordsRemoved: function(idx, count) {
    this.sendMessage('recordsRemoved', {
      index: idx,
      count: count
    });
  },

  wrapRecord: function(record) {
    var objectId = Ember.guidFor(record.object);
    var self = this;
    var columnValues = {};
    var searchKeywords = [];
    this.sentRecords[objectId] = record;
    // make objects clonable
    for (var i in record.columnValues) {
      columnValues[i] = this.get('objectInspector').inspect(record.columnValues[i]);
    }
    // make sure keywords can be searched and clonable
    searchKeywords = Ember.A(record.searchKeywords).filter(function(keyword) {
      return (typeof keyword === 'string' || typeof keyword === 'number');
    });
    return {
      columnValues: columnValues,
      searchKeywords: searchKeywords,
      filterValues: record.filterValues,
      color: record.color,
      objectId: objectId
    };
  },

  releaseTypes: function() {
    if(this.releaseTypesMethod) {
      this.releaseTypesMethod();
      this.releaseTypesMethod = null;
      this.sentTypes = {};
    }
  },

  releaseRecords: function(typeObjectId) {
    if (this.releaseRecordsMethod) {
      this.releaseRecordsMethod();
      this.releaseRecordsMethod = null;
      this.sentRecords = {};
    }
  },

  willDestroy: function() {
    this._super();
    this.releaseRecords();
    this.releaseTypes();
  },

  messages: {
    checkAdapter: function() {
      this.sendMessage('hasAdapter', { hasAdapter: !!this.get('adapter') });
    },

    getModelTypes: function() {
      var self = this;
      this.releaseTypes();
      this.releaseTypesMethod = this.get('adapter').watchModelTypes(
        function(types) {
          self.modelTypesAdded(types);
        }, function(types) {
        self.modelTypesUpdated(types);
      });
    },

    releaseModelTypes: function() {
      this.releaseTypes();
    },

    getRecords: function(message) {
      var type = this.sentTypes[message.objectId], self = this;
      this.releaseRecords();

      var releaseMethod = this.get('adapter').watchRecords(type.object,
        function(recordsReceived) {
          self.recordsAdded(recordsReceived);
        },
        function(recordsUpdated) {
          self.recordsUpdated(recordsUpdated);
        },
        function() {
          self.recordsRemoved.apply(self, arguments);
        }
      );
      this.releaseRecordsMethod = releaseMethod;
    },

    releaseRecords: function() {
      this.releaseRecords();
    },

    inspectModel: function(message) {
      this.get('objectInspector').sendObject(this.sentRecords[message.objectId].object);
    },

    getFilters: function() {
      this.sendMessage('filters', {
        filters: this.get('adapter').getFilters()
      });
    }
  }
});

export default DataDebug;


text:
# sendSuccess

## Usage

    Name	Type	Description


text:
<?xml version="1.0" encoding="UTF-8"?>
<sv:node xmlns:sv="http://www.jcp.org/jcr/sv/1.0" sv:name="one-column">
  <sv:property sv:name="jcr:primaryType" sv:type="Name">
    <sv:value>hst:component</sv:value>
  </sv:property>
  <sv:property sv:name="jcr:mixinTypes" sv:type="Name" sv:multiple="true">
    <sv:value>hst:prototypemeta</sv:value>
  </sv:property>
  <sv:property sv:name="hst:displayname" sv:type="String">
    <sv:value>One column</sv:value>
  </sv:property>
  <sv:property sv:name="hst:referencecomponent" sv:type="String">
    <sv:value>hst:abstractpages/base</sv:value>
  </sv:property>
  <sv:node sv:name="main">
    <sv:property sv:name="jcr:primaryType" sv:type="Name">
      <sv:value>hst:component</sv:value>
    </sv:property>
    <sv:node sv:name="content">
      <sv:property sv:name="jcr:primaryType" sv:type="Name">
        <sv:value>hst:component</sv:value>
      </sv:property>
      <sv:property sv:name="hst:template" sv:type="String">
        <sv:value>one-column.main.content</sv:value>
      </sv:property>
      <sv:node sv:name="container">
        <sv:property sv:name="jcr:primaryType" sv:type="Name">
          <sv:value>hst:containercomponent</sv:value>
        </sv:property>
        <sv:property sv:name="hst:xtype" sv:type="String">
          <sv:value>HST.vBox</sv:value>
        </sv:property>
      </sv:node>
    </sv:node>
  </sv:node>
</sv:node>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Pyccuweather: pyccuweather.objects.Hemiurnal Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Pyccuweather
    0.31

The Python Accuweather Client

Main Page

Classes

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

pyccuweather

objects

Hemiurnal

Public Member Functions |
Public Attributes |
List of all members

pyccuweather.objects.Hemiurnal Class Reference

Inheritance diagram for pyccuweather.objects.Hemiurnal:

  <map id="pyccuweather.objects.Hemiurnal_map" name="pyccuweather.objects.Hemiurnal_map">
</map>

Public Member Functions

def 	__init__ (self, json)

def 	__str__ (self)

Public Attributes

 	id

 	synopsis

 	phrase

 	snow

 	wind

 	rain

 	ice

 	total_liquid

 	h_precipitation

 	h_rain

 	cloud_cover

 	p_rain

 	p_snow

 	p_ice

 	p_thunderstorm

 	p_precipitation

 	wind_gust

 	raw

The documentation for this class was generated from the following file:

pyccuweather/objects.py

<address class="footer">
Generated on Sat Jul 4 2015 17:36:10 for Pyccuweather by

 1.8.9.1
</address>


text:
title: The Testimony of Jesus is the Spirit of Prophecy
image: /img/teatable.jpg
tags:
- evangelism
- stories
---

The 'Spirit of Prophecy' sounds like something so deep, mysterious and powerful. And it is. And yet the testimony of Jesus is so simple.

> Jesus died. Jesus rose again.
> I found forgiveness and new life with him.
> I'm following him.

Does that sound deep and mysterious? Not really. But it's this simple testimony that the saints hold onto as they overcome dragons and beasts and whatever other horrors and attacks might come against them... it's this simple testimony that they hang on to against all, not shrinking from death. It's with this simple testimony that they overcome. (Rev 12:11)

Prophecy itself is a pretty intimidating word, but the *spirit of prophecy* is even crazier sounding. If prophecy is what God says, then we could think of the spirit of prophecy being the inspiration, the breath, the focus of everything God says.

And this is what the testimony of Jesus is. Yes, it's that big.

After all, the life of Jesus is what all the prophets were longing and straining to understand and communicate. The life of Jesus is the focus of all those words spoken over hundreds of years.

> The prophets ... searched intently and with the greatest care, trying to find out the time and the circumstances to which the Spirit of Christ in them was pointing when he predicted the sufferings of Christ and the glories that would follow ... Even angels long to look into these things. (1 Peter 1:10-12)

> In (Christ) are hidden all the treasures of wisdom and knowledge. (Colossians 2:3)

> For no matter how many promises God has made, they are "Yes" in Christ. And so through him the "Amen" is spoken by us to the glory of God. (2 Corinthians 1:20)

The spirit of all of God's communication is summed up and given to us in the life of Christ. And now he's sending his children that have believed in Jesus to go forward all over the world and reveal him to all nations, speaking every language.

This weekend, me and a local friend went out to try and share the good news (our testimony of Jesus) in a darker neighborhood. It's always an exciting step of faith to walk into one of these places "Ok with this in mind. "Alright" we think, "how is God going to connect us to some people here and make his good news known through our mouths..." I love that feeling. It always seems impossible, but we know who we're following.

We went into a little tea shop. I just love the way this particular place was designed. There benches all around the room, and a number of tiny tables scrunched together in a circle. So, wherever you sit, you have to be close to somebody. It looks a little bit like this:

We took a seat in the corner at a table with one young guy sitting by himself. He was reading a really interesting book which, as he explained, was challenging the idea that people need to attach themselves to human leaders and intermediaries to get to God. Obviously this provided a good springboard for conversation and we got talking about the Christ and the way to God.

After chatting for a while, his older brother and another guy showed up and joined us. They were all very smart, quite religious, extremely eloquent, and eager to talk about finding the truth. In this culture it seems that conversation is a beautiful art, and most people are like skilled musicians, ready and eager to jump in and improvise.

Soon a table full of tea was set before us and words were flying back and forth as we talked about life, the books of the prophets, what God wants from us, and salvation.

I talked about Jesus, about how he died and rose again, and about the power of God to overcome sin and live a new life with a new heart. As I talked, the first guy in particular really understood that Christ had given his life for me and was now my source of life and strength that allowed me to live holy. He understood how God had taken away my sins in Christ (Jeremiah 50:20) how he had given me a new heart (Ezekiel 36:26) and how he had written his commands on my heart. (Jeremiah 31:33) As we sat there and talked the knowledge of Christ was formed in the conversation. And believe me, this has a far sweeter smell than those steamy cups of tea and linden you saw in the picture.

They had a hard time understanding how our 'religion' fit in with the rest of the story, after Judaism etc... These were Muslims guys, and like many they thought we would believe something like this:

In their eyes, God sends us a book of the law, giving us a set of rules to be lived by and to judge us with. Whenever one of these books (or religions) gets neglected and corrupted and things start getting really messed up, God sends another book, to clarify and give people a clear set of rules to follow again. They believe this kept on happening with all the different books, until finally their book came with the promise to have it protected for eternity.

But we weren't talking about following just one rule book. Our story is so much bigger than this! I tried to explain how these books weren't corrupted and out of date versions of the same thing. Actually it's one big story that was given to us in pieces.

- **The law was given**
- **Salvation was promised**
- **Salvation came in Jesus!**

My local friend drew a little diagram on a sheet of paper explaining how this all worked.

It was all a big long story, culminating in Jesus. As he drew his pen over the line on the right side, he talked about how he never thought he could believe in something so simple, so ridiculous. (After all, he was a really smart, well-read, knowledgeable, and religious person. And the news of Jesus just seemed way more foolish and basic then everything he had ever learned and trusted.) "But," he said, "that simplicity destroyed me. After all, he came to destroy everything." (1 Cor 1:19)

And all those guys sat there, amazed to see this guy who had given up everything for this crazy new message of Jesus that they had just heard. They had just been confronted with the Spirit of Prophecy.

Think of all the prophets over all those centuries of history, of all the scrolls and scrolls of deep and mysterious sayings from Isaiah, Jeremiah, Malachi and all the rest. Think of all those words before kings, those head-spinning visions, and chilling oracles.

Jesus is the crown jewel of all of that. He's the precious treasure that they were all hinting at. He's at the center of all God's communication. He's the culmination of all God's wisdom and action.  He's the big secret that's been kept hidden for all those ages.

And we just spilled this secret over a cup of tea with some guys we met ten minutes ago.


text:
import VBtn from '~components/VBtn'
import VCard from '~components/VCard'
import VMenu from '~components/VMenu'
import { test } from '~util/testing'

// TODO: Most of these have exactly the same snapshots
test('VMenu.js', ({ mount }) => {
  it('should work', async () => {
    const wrapper = mount(VMenu, {
      propsData: {
        value: false
      },
      slots: {
        activator: [VBtn],
        default: [VCard]
      }
    })

    const activator = wrapper.find('.menu__activator')[0]
    const input = jest.fn()
    wrapper.instance().$on('input', input)
    activator.trigger('click')

    await wrapper.vm.$nextTick()

    expect(input).toBeCalledWith(true)
    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom top and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        top: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom bottom and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        bottom: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom left and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        left: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom right and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        right: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom fullWidth and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        fullWidth: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom auto and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        auto: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom offsetX and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        offsetX: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom offsetY and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        offsetY: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom disabled and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        disabled: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom maxHeight and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        maxHeight: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom nudgeTop and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        nudgeTop: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom nudgeBottom and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        nudgeBottom: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom nudgeLeft and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        nudgeLeft: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom nudgeRight and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        nudgeRight: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom nudgeWidth and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        nudgeWidth: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom openOnClick and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        openOnClick: false
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom openOnHover and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        openOnHover: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom lazy and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        lazy: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom closeOnClick and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        closeOnClick: false
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom closeOnContentClick and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        closeOnContentClick: false
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom activator and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        activator: [VBtn]
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom origin and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        origin: 'top right'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom transition and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        transition: 'fade-transition'
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom positionX and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        positionX: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom positionY and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        positionY: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom positionAbsolutely and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        positionAbsolutely: true
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom maxWidth and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        maxWidth: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })

  it('should render component with custom minWidth and match snapshot', () => {
    const wrapper = mount(VMenu, {
      propsData: {
        minWidth: 100
      }
    })

    expect(wrapper.html()).toMatchSnapshot()
    expect('Application is missing <v-app> component.').toHaveBeenTipped()
  })
})


text:
<?php
class MY_Controller extends CI_Controller {
	function __construct(){
		parent::__construct();

		$this->load->driver('cache', array('adapter' => 'file'));
	}

	function _footer(){
		$this->load->view('footer');
	}

	function _head(){
		$this->load->view('head');
	}

	function _sidebar(){
		if ( ! $topics = $this->cache->get('topics')){
			$topics = $this->topic_model->gets();
			$this->cache->save('topics', $topics, 300);
		}

		$this->load->view('topic_list', array('topics'=>$topics));
	}
}
?>


text:
<!--
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 -->

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [2. Implement standalone python command](#2-implement-standalone-python-command)
  - [Status](#status)
  - [Context](#context)
  - [Decision](#decision)
  - [Consequences](#consequences)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# 2. Implement standalone python command

Date: 2021-11-28

## Status

Accepted

## Context

The [Breeze](https://github.com/apache/airflow/blob/main/BREEZE.rst) is
a command line development environment for Apache Airflow that makes
it easy to setup Airflow development and test environment easily
(< 10 minutes is the goal) and enable contributors to run any subset
of tests that are executed in our CI environment easily.

The environment has proven to be very useful (it has successfully onboarded
a number of new contributors, and it makes the development environment of
even seasoned contributors much easier as it provides a very easy
replication of the CI environment as well as very easy to setup test
environment that can be used to run:

* Unit tests
* Integration tests
* Kubernetes/Helm tests
* System tests

It also serves as a base for our CI execution environment. The same scripts and tools are used
in our CI (based on GitHub actions). A lot of common code and function between CI and Breeze are
shared between the CI and Breeze. All those tools are held in "ci" package.

Unfortunately, Breeze is largely based on Bash code - for which very few people (except maybe the
Breeze creator - Jarek Potiuk, the author of this document) have any other feeling that uneasiness,
disgust and fear of it :).  Since Airflow is largely based on Python, the common consensus is that
Breeze should be rewritten in Python.

In November 2021, Outreachy sponsored two internship for two interns: @Bowrna and @edithturn were assigned to
the projects:

* Convert Airflow Local Development environment `Breeze` - from Bash-based to Python-based
* Rewrite Github Action workflows to Python

With @potiuk, @eladkal and @xurror as mentors.

The long-standing issues about those two projects are (and we hope to close the projects during the
three months internship - December 2021 - March 2022):

* https://github.com/apache/airflow/issues/12282
* https://github.com/apache/airflow/issues/13182

There are a number of problems with Bash scripts:

* They are difficult to understand, modify and debug as Bash "magic" is somewhat arcane
* They are difficult to implement complex logic with
* Navigating common code that is used from the scripts is cumbersome and lack IDE/tools support
* Default Bash on MacOS is very old (from 3.* line) and it will not be updated to a newer version
  which impacts cross-platform Breeze applicability
* Bash only works well for Windows in WSL2 environment, which further undermines cross-platform
  abilities of testing and running Airflow

On the contrary Python - after dropping Python 2 end of life in January 2020, has become much more
appealing as a common scripting language that can be cross-platform and ubiquitous.

This is the current state of lines of code in the project (generated by `sloccount`):

```
SLOC    Directory         SLOC-by-Language (Sorted)

144905  tests             python=144761,xml=132,sh=12
130115  airflow           python=127249,javascript=2827,sh=39
12052   docs              javascript=8977,python=2931,sh=144
9073    scripts           sh=7457,python=1616
6314    chart             python=6218,sh=96
3665    top_dir           sh=2896,python=769
3102    dev               python=2938,sh=164
1723    kubernetes_tests  python=1723
280     docker_tests      python=280
140     metastore_browser python=140
109     clients           sh=109
28      images              sh=28

Totals grouped by language (dominant language first):
python:      288625 (92.65%)
javascript:     11804 (3.79%)
sh:           10945 (3.51%)
xml:            132 (0.04%)
```

We have now >10K lines of shell code now. We'd announce the success of the project if the shell number is less
than `300` lines of code or so, constituting less than `0.1%` of the code base.

## Decision

The main decision is:

**Vast majority of both Breeze and our CI scripts should be Python-based**

There are likely a number of scripts that will remain in Bash, but they should contain no sophisticated
logic, they should not haave common code in form of libraries and only used to execute simple tasks inside
Docker containers. No Bash should ever be used in the host environment.

There are a few properties of Breeze/CI scripts that should be maintained though

* It should be possible to start Breeze and run any of the CI scripts without having a specially prepared
  virtualenv. If the virtualenv is needed - such environment should be prepared and maintained automatically
  by the script being run. The idea is that new person starting their adventure with Airflow can simply
  run a command and get everything done with the least number of prerequisites

* The prerequisites for Breeze and CI are:
   * Python 3.7+ (Python 3.6 end of life is December 2021)
   * Docker (TBD which minimum version supported)
   * Docker Compose (TBD which minimum version supported)
   * No other tools and CLI commands should be needed
   * The python requirements should be automatically installed when missing in a "Breeze" venv and updated
     automatically when needed. The number of Python dependencies needed to run Breeze and CI scripts
     should be minimal in order to make the virtualenv installation portable to Linux, MacOS and Windows
     environment.

* There are some basic assumptions that result from our common patterns across other components we use:
   * we use `rich` library for colouring terminal output. Using wisely terminal colours
     is an essential part of the developer experience. We will have to standardize color usage in
     a follow-up adr
   * we use `click` library to provide command line parsing and autocompletion (in the future). Click is
     a comprehensive library with clean, decorator-based interface and provides rich customisation options
   * we use `pytest` to run automated tests for our code
   * until we are ready to share it with developers the new `Breeze` script resides in `dev/Breeze` folder,
     without yet linking it from main directory of Airflow. Later we will link to it from the main directory
     likely as `breeze` script (in some environments where filesystem is case-insensitive (MacOS) you cannot
     really put two files differing only by case in the same folder.
   * There is enough overlap between the CI and Breeze to reuse a lot of commands for building images and
     other CI actions that they should be shared between Breeze and CI. Therefore `dev/Breeze` will
     also become a home for all the CI scripts that will be used in GitHubActions in CI.

## Consequences

The consequences of the change should be largely invisible to the current users of Breeze. They should be
able to perform the same actions and operations as in the Bash version (with possible later decision of
deprecating or removing of some commands). The biggest consequence should be to the whole development
community of Airflow - for them, modifying and extending and fixing Breeze and CI environment should
become much more appealing.

The old script should remain and be maintained until the most important functionality of the
original Breeze script has been rewritten enough.


text:
#include "pch.h"
#include "CubeRenderer.h"
#include "..\..\..\shader.h"

using namespace DirectX;
using namespace Microsoft::WRL;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;

struct VertexPositionColor
{
	XMFLOAT3 pos;
	XMFLOAT3 color;
};

CubeRenderer::CubeRenderer(): m_loadingComplete(false)
{
}

void CubeRenderer::CreateDeviceResources()
{
	AngleBase::CreateDeviceResources();
}

void CubeRenderer::CreateGLResources()
{
    m_colorProgram = glCreateProgram();
    glProgramBinaryOES(m_colorProgram, GL_PROGRAM_BINARY_ANGLE, gProgram, sizeof(gProgram));
    a_positionColor = glGetAttribLocation(m_colorProgram, "a_position");
    a_colorColor = glGetAttribLocation(m_colorProgram, "a_color");
    u_mvpColor = glGetUniformLocation(m_colorProgram, "u_mvp");

	//glViewport(0, 0, static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Height));
    glEnable(GL_DEPTH_TEST);
    m_loadingComplete = true;
}

void CubeRenderer::CreateWindowSizeDependentResources()
{
	AngleBase::CreateWindowSizeDependentResources();
}

void CubeRenderer::UpdatePerspectiveMatrix()
{
    float fovAngleY = 70.0f * XM_PI / 180.0f;
    m_projectionMatrix = XMMatrixPerspectiveFovRH(fovAngleY, m_aspectRatio, 0.01f, 100.0f);

    // In Windows Phone 8.0 C++ apps, we need to rotate the projection matrix by the
    // device's current rotation matrix
    m_projectionMatrix = XMMatrixMultiply(m_orientationMatrix, m_projectionMatrix);
}

void CubeRenderer::OnOrientationChanged(Windows::Graphics::Display::DisplayOrientations orientation)
{
	AngleBase::OnOrientationChanged(orientation);
    UpdatePerspectiveMatrix();
}

void CubeRenderer::Update(float timeTotal, float timeDelta)
{
	(void) timeDelta;

    XMVECTOR eye = XMVectorSet(0.0f, 0.7f, 1.5f, 0.0f);
	XMVECTOR at = XMVectorSet(0.0f, -0.1f, 0.0f, 0.0f);
	XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	m_viewMatrix = XMMatrixLookAtRH(eye, at, up);
	m_modelMatrix = XMMatrixRotationY(timeTotal * XM_PIDIV4);
}

void CubeRenderer::OnRender()
{
    XMFLOAT4X4 mvp;
    XMStoreFloat4x4(&mvp, (XMMatrixMultiply(XMMatrixMultiply(m_modelMatrix, m_viewMatrix), m_projectionMatrix)));

    glClearColor(0.098f, 0.098f, 0.439f, 1.000f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(m_colorProgram);
    glUniformMatrix4fv(u_mvpColor, 1, GL_FALSE, &mvp.m[0][0]);

    VertexPositionColor cubeVertices[] =
	{
		{XMFLOAT3(-0.5f, -0.5f, -0.5f), XMFLOAT3(0.0f, 0.0f, 0.0f)},
		{XMFLOAT3(-0.5f, -0.5f,  0.5f), XMFLOAT3(0.0f, 0.0f, 1.0f)},
		{XMFLOAT3(-0.5f,  0.5f, -0.5f), XMFLOAT3(0.0f, 1.0f, 0.0f)},
		{XMFLOAT3(-0.5f,  0.5f,  0.5f), XMFLOAT3(0.0f, 1.0f, 1.0f)},
		{XMFLOAT3( 0.5f, -0.5f, -0.5f), XMFLOAT3(1.0f, 0.0f, 0.0f)},
		{XMFLOAT3( 0.5f, -0.5f,  0.5f), XMFLOAT3(1.0f, 0.0f, 1.0f)},
		{XMFLOAT3( 0.5f,  0.5f, -0.5f), XMFLOAT3(1.0f, 1.0f, 0.0f)},
		{XMFLOAT3( 0.5f,  0.5f,  0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f)},
	};
    unsigned short cubeIndices[] =
    {

        0,2,1, // -x
        1,2,3,

        4,5,6, // +x
        5,7,6,

        0,1,5, // -y
        0,5,4,

        2,6,7, // +y
        2,7,3,

        0,4,6, // -z
        0,6,2,

        1,3,7, // +z
        1,7,5,
    };

    glEnableVertexAttribArray(a_positionColor);
    glEnableVertexAttribArray(a_colorColor);
    glVertexAttribPointer(a_positionColor, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPositionColor), cubeVertices);
    glVertexAttribPointer(a_colorColor, 3, GL_FLOAT, GL_FALSE, sizeof(VertexPositionColor), reinterpret_cast<char*>(cubeVertices) + sizeof(XMFLOAT3));
    glDrawElements(GL_TRIANGLES, ARRAYSIZE(cubeIndices), GL_UNSIGNED_SHORT, cubeIndices);
    glDisableVertexAttribArray(a_positionColor);
    glDisableVertexAttribArray(a_colorColor);
}


text:
import moveOver from "./move-over";
export default function(opts) {
  return moveOver.call(this, 'x', 1, opts);
}


text:
using System.Security.Principal;

namespace SignalR
{
    /// <summary>
    /// Used to generate connection ids.
    /// </summary>
    public interface IConnectionIdGenerator
    {
        /// <summary>
        /// Creates a connection id for the current request.
        /// </summary>
        /// <param name="request">The <see cref="IRequest"/>.</param>
        /// <returns>A connection id</returns>
        string GenerateConnectionId(IRequest request);
    }
}


text:
Tab groups allow the user to organize their content by labels such that only one tab is visible at any given time.

### Examples
A basic tab group would have the following markup.
```html
<md-tab-group>
  <md-tab>
    <template md-tab-label>One</template>
    <template md-tab-content>
      <h1>Some tab content</h1>
      <p>...</p>
    </template>
  </md-tab>
  <md-tab>
    <template md-tab-label>Two</template>
    <template md-tab-content>
      <h1>Some more tab content</h1>
      <p>...</p>
    </template>
  </md-tab>
</md-tab-group>
```

## `<md-tab-group>`
### Properties

| Name | Type | Description |
| --- | --- | --- |
| `selectedIndex` | `number` | The index of the currently active tab. |


text:
<?php

App::uses('ToastyCoreAppModel', 'ToastyCore.Model');

class Content extends ToastyCoreAppModel {

    public $name = "Content";
    public $_schema = array(
        'id' => array(
            'type' => 'integer',
            'length' => 11
        ),
        'name' => array(
            'type' => 'string',
            'length' => 255
        ),
        'user_id' => array(
            'type' => 'integer',
            'length' => 11
        ),
        'parent_content_id' => array(
            'type' => 'integer',
            'length' => 11
        ),
        'content_type_id' => array(
            'type' => 'integer',
            'length' => 11
        ),
        'created' => array(
            'type' => 'datetime'
        ),
        'modified' => array(
            'type' => 'integer'
        )
    );
    public $validate = array(
        'name' => array(
            'notEmpty'
        ),
        'parent_content_id' => array(
            'rule' => array('isDescendant'),
            'message' => 'You cannot set a child to be a parent'
        ),
        'user_id' => array(
            'notEmpty'
        ),
        'home_page' => array(
            'rule' => array('checkMultipleHomePage')
        ),
        'published' => array(
            'rule' => array('checkHomePageSet'),
            'message' => 'The content must be published in order to be the home page'
        )
    );

    public function checkHomePageSet($check) {

        if (0 == $check['published']) {

            $homePageSet = 1 == $this->data['Content']['home_page'];

            if ($homePageSet) {

                return false;

            }

        }

        return true;

    }

    public function checkMultipleHomePage($check) {

        if (!$this->isEmptyValue($check['home_page'])) {

            $options = array(
                'conditions' => array(
                    'Content.home_page' => true
                )
            );
            $content = $this->find('first', $options);

            if (!$this->isEmptyValue($content)) {

                $name = $content['Content']['name'];
                $id = $content['Content']['id'];

                $check_id = isset($this->data['Content']['id']) ? $this->data['Content']['id'] : false;

                if ( $id != $check_id ) {

                    return "You cannot have multiple home pages. The current home page is '$name' with the id '$id'";

                }

            }
        }

        return true;

    }

    public function getName($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $content = $this->find('first', array("conditions" => $conditions));

        $name = $content['Content']['name'];

        return $name;
    }

    public function setName($name = null, $content_id = null) {

        $content_id = $this->checkId($content_id);

        $name = trim($name);

        if ($name) {

            $data = array(
                'Content' => array(
                    'id' => $content_id,
                    'name' => $name
                )
            );

            $this->save($data);

            return true;
        }

        throw new Exception("name parameter must be provided");
    }

    public function getUser($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $content = $this->find('first', array("conditions" => $conditions));

        $user = $content['User'];

        return $user;
    }

    public function setUser($user_id = null, $content_id = null) {

        $content_id = $this->checkId($content_id);

        $user_id = trim($user_id);

        if ($user_id) {

            $data = array(
                'Content' => array(
                    'id' => $content_id,
                    'user_id' => $user_id
                )
            );

            $this->save($data);

            return true;
        }

        throw new Exception("name parameter must be provided");
    }

    public function allowUser($content_id = null, $user_id = null) {

        $content_id = $this->checkId($content_id);

        return $this->isOwnedBy($content_id, $user_id);
    }

    public function isOwnedBy($content, $user) {
        return $this->field('id', array('id' => $content, 'user_id' => $user)) === $content;
    }

    public function getParent($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $content = $this->find('first', array("conditions" => $conditions));

        $parent = $content['ParentContent'];

        return $parent;
    }

    public function getContentType($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $content = $this->find('first', array("conditions" => $conditions));

        $type = $content['ContentType'];

        return $type;
    }

    public function getCreated($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $content = $this->find('first', array("conditions" => $conditions));

        $created = $content['Content']['created'];

        return $created;
    }

    public function getModified($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $content = $this->find('first', array("conditions" => $conditions));

        $modified = $content['Content']['modified'];

        return $modified;
    }

    /**
     * a user may have many resources and a resource has only one user
     * a resource may have many respources and a resource may have only one resource
     * @var array
     */
    public $belongsTo = array(
        //
        'ContentType' => array(
            'className' => 'ToastyCore.ContentType'
        ),
        'ParentContent' => array(
            'className' => 'ToastyCore.Content'
        ),
        'User' => array(
            'className' => 'ToastyCore.User'
        )
    );

    /**
     * a resource has many allowed templates
     * a resource has many properties
     * @var array
     */
    public $hasMany = array(
        'ContentTypeProperties' => array(
            'className' => 'ToastyCore.ContentTypeProperty'
        ),
        'ChildContent' => array(
            'className' => 'ToastyCore.Content',
            'foreignKey' => 'parent_content_id',
            'order' => array(
                'ChildContent.sort',
                'ChildContent.created'
            )
        )
    );

    public function isDescendant($options) {

        $id = isset($options['parent_content_id']) ? $options['parent_content_id'] : null;

        if (empty($this->id)) {
            return true;
        }

        $content = $this->findById($id);

        if (empty($content['ParentContent']['id'])) {

            return true;

        } elseif ($this->id === $content['ParentContent']['id']) {

            return false;
        }

        return $this->isDescendant($content['ParentContent']['id']);
    }

    public function afterDelete() {
        parent::afterDelete();

    }

    public function beforeSave($options = array()) {

        parent::beforeSave();

        $name = $this->data['Content']['name'];
        $name = trim($name);
        $this->data['Content']['name'] = $name;

        if (isset($this->data['Content']['id'])) {
        	$this->sortSiblings($this->data['Content']['id']);
        	$this->publishChildren($this->data['Content']['id']);
        } else {
        	$options = array(
        		'conditions' => array(
        			'Content.parent_content_id' => $this->data['Content']['parent_content_id']
    			)
    		);

    		$count = $this->find('count', $options);

    		$this->data['Content']['sort'] = $count + 1;
        }

        if (!isset($this->data['Content']['alias'])) {
			$alias = preg_replace('~\W~', '_', $name);
			$this->data['Content']['alias'] = $alias;
        }

        if ($this->isEmptyValue($this->data['Content']['alias'])) {
            $alias = preg_replace('~\W~', '_', $name);
			$this->data['Content']['alias'] = $alias;

        }

        return true;
    }

    public function beforeDelete($cascade = true) {
        parent::beforeDelete($cascade);

        if ($this->isRoot()) {

            return false;
        }

        $cc = $this->ChildContent->find('all',
            array('conditions' =>
                array('ChildContent.parent_content_id' => $this->id)
            )
        );

        $ctp = $this->ContentTypeProperties->find('all',
            array('conditions' =>
                array('ContentTypeProperties.content_id' => $this->id)
            )
        );

        foreach ($cc as $child) {
            $content = new Content();
            $content->id = $child['ChildContent']['id'];
            $content->delete();

        }

        foreach ($ctp as $p) {
            $this->ContentTypeProperties->id = $p['ContentTypeProperties']['id'];
            $this->ContentTypeProperties->delete();
        }

        return true;
    }

    public function isRoot($content_id = null) {

        $content_id = $this->checkId($content_id);

        $conditions = array('Content.id' => $content_id);
        $user = $this->find('first', array('conditions' => $conditions));
        $type = $user['Content']['type'];
        return $type === 'root';

    }

    public function getPathFromId($content_id = null) {

        $content_id = $this->checkId($content_id);

        $path = array();
        while(!$this->isEmptyValue($content_id)) {

            $content = $this->findById($content_id);

            $path[] = $content['Content']['alias'];

            $content_id = $content['Content']['parent_content_id'];

        }

        $path = array_reverse($path);

        $path = implode(DS, $path);

        return $path;

    }

    public function getIdFromPath($path) {

        $path = explode('/', $path);

        $pid = 0;
        foreach ($path as $alias) {

            $options = array(
                'conditions' => array(
                    'Content.parent_content_id' => $pid,
                    'Content.alias' => $alias
                )
            );

            $currentContent = $this->find('first', $options);

            if (!empty($currentContent)) {

                $pid = $currentContent['Content']['id'];

            } else {
                $pid = null;

                break;
            }

        }

        return $pid;

    }

    public function publishChildren($content_id) {

        $content_id = $this->checkId($content_id);

        $content = $this->data;

        if (isset($content['Content']['published'])) {

    		$conditions =  array(

                'Content.parent_content_id' => $content_id,
    		);

    		$fields = array(
    			'Content.published' => $content['Content']['published']
			);

    		$this->updateAll($fields, $conditions);

        }

    }

    public function sortSiblings($content_id) {

        $content_id = $this->checkId($content_id);

        $content = $this->data;

        $object = new Content();

        $options = array(
            'conditions' => array(
                'Content.parent_content_id' => $content['Content']['parent_content_id'],
                'NOT' => array(
                    'Content.id' => $content_id
                )
            ),
            'order' => array(
                'Content.sort',
            )
        );

        $siblings = $object->find('all', $options);

        $numSiblings = count($siblings);

        $sorted = array();
        $unsorted = array();

        $counter = 0;
        // separate unsorted items from sorted items
        foreach($siblings as $sibling) {

            if (0 === $sibling['Content']['sort']) {
                $unsorted[] = $sibling;
            } else {
                $sorted[] = $sibling;
                $counter++;
            }

        }

        // give the unsorted items a sort value
        foreach($unsorted as $sibling) {
            $sorted[] = $sibling;
            $counter++;
        }

        $sort = $content['Content']['sort'];

        if ($sort >= $numSiblings + 1) {
            // if the sort value is larger than the number of siblings
            array_push($sorted, $content); // put it at the end
        } elseif ($sort <= 1) {
            // if the sort value is less than or equal to 1
            array_unshift($sorted, $content); // put it in the front
        } else {
            // if the sort value is anything in between,
            array_splice($sorted, $sort - 1, 0, array($content)); // put it there wrap content in an array so unshift is inconsequential.
        }

        // go through the fully sorted array and save the final sort values to the db
        $counter = 1;
        foreach ($sorted as $sibling) {

            if ($content_id !== $sibling['Content']['id']) {
                $sibling['Content']['sort'] = $counter;
                $sibling['Content']['modified'] = false;
                $object->save($sibling, array('callbacks' => false));
            } else {
            	$this->data['Content']['sort'] = $counter;
            }

            $counter++;

        }

    }

}

?>


text:
/* This Source Code Form is subject to the terms of the MIT License.
 * If a copy of the MIT was not distributed with this
 * file, You can obtain one at http://opensource.org/licenses/MIT .
 */

/**
 * paged - Pages an observable array.
 * Most fields and methods are easy, but `pages` requires a bit of an
 * explaination. It won't just return a list of numbers, but instead of objects,
 * each representing a page. They ain't all equally build, but all contain at least
 * * `canGoto` is a boolean telling wether it's an actually page (that you can go to), or not
 * * `isCurrent` is a boolean telling you wether this is the current page.
 * * `humanreadable` is a humanreadable string, e.g. the ellipsis text, or the page number in humanfriendly numbering (starting at 1).
 * Proper pages also contain `pageNr`, which is the computerfriendly page number (starting at 0), and `goto`, a function that
 * tells the paged observable to directly jump to that page, updating everything.
 * @demo
 * @param options The page size, or an options hash.
 * @param options.pageSize The page size.
 * @param options.format An array or hash containing formatting instructions for the pages list. @see ko.extenders.paged.format
 * @field page An observable containing the current page number.
 * @field pageSize An observable containing the page size.
 * @field pageCount A computed returning the current number of pages.
 * @field format An observable containing the format instructions hash for the pages list.
 * @field source The original observable containing the raw data.
 * @field parentObservable If used with other extenders, this points to the previously declared extension.
 * @method nextPage Moves to next page, if possible.
 * @method previousPage Moves to previous page, if possible.
 * @method hasNextPage Checks wether there is a next page.
 * @method hasPreviousPage Checks weather there is a previous page.
 * @field pages A computed returning a list of objects to produce a page navigation. @see ko.extenders.paged.format.doFormat
 */
ko.extenders.paged = function(source, options) {
    if (typeof options != 'object')
        options = {pageSize: options, format: false};
    if (options.format instanceof Array)
        options.format = ko.extenders.paged.format.apply(undefined, options.format);
    if (!ko.isObservable(source))
        source = ko.observableArray(source);
    var pageSize = ko.observable(options.pageSize);
    var pageCount = ko.computed(function() {
        return Math.ceil(source().length / pageSize());
    });
    var pageNr = ko.observable(0);
    var page = ko.computed({
        read: function() {
            return Math.max(0, Math.min(pageNr(), pageCount()));
        },
        write: function(nv) {
            pageNr(nv);
        }
    });
    var self = ko.computed(function() {
        return source().slice(page() * pageSize(), (page() + 1) * pageSize());
    });

    self.page = page;
    self.pageSize = pageSize;
    self.pageCount = pageCount;
    self.format = ko.observable(options.format);
    self.source = source.source ? source.source : source;
    self.parentObservable = source;

    self.nextPage = function() {
        self.page(self.page() + 1);
    };
    self.previousPage = function() {
        self.page(self.page() - 1);
    };

    self.hasNextPage = ko.computed(function() {
        return self.page() < self.pageCount()-1;
    });
    self.hasPreviousPage = ko.computed(function() {
        return self.page() > 0;
    });

    self.pages = ko.computed(function() {
        var result = [];
        for (var i = 0; i < self.pageCount(); i++)
            result.push({
                pageNr: i,
                humanreadable: i+1,
                isCurrent: i == self.page(),
                canGoto: true,
                goto: function() { self.page(this.pageNr); }
            });
        if (self.format()) {
            result = ko.extenders.paged.format.doFormat(result, self.format(), self.page());
        }
        return result;
    });

    return self;
};

/**
 * Creates a format hash used for the pages field. Note that `paged` maps
 * an array to this function to make the extension declaration a little simpler.
 * @param start The number of pages to be show from the beginning.
 * @param beforeWindowEllipsis A string for the ellipsis between the start and the current window.
 * @param windowSize The size of the window arround the current page.
 * @param afterWindowEllipsis A string for the ellipsis between the current window and the end.
 * @param end The number of pages to be show from the end.
 */
ko.extenders.paged.format = function(start, beforeWindowEllipsis, windowSize, afterWindowEllipsis, end) {
    return {
        start: start,
        beforeWindowEllipsis: beforeWindowEllipsis,
        windowSize: windowSize,
        afterWindowEllipsis: afterWindowEllipsis,
        end: end
    };
};

/**
 * Internal. Produces a nonpage. Used for the ellipsis.
 * @param text The text of the nonpage.
 */
ko.extenders.paged.format.nonPage = function(text) {
    return {
        canGoto: false,
        isCurrent: false,
        humanreadable: text
    };
};

/**
 * Internal. Used to check wether two intervals overlap, and produces a union interval if required.
 * @param l1 Lower bound of the first interval.
 * @param u1 Upper bound of the first interval.
 * @param l2 Lower bound of the second interval.
 * @param u2 Upper bound of the second interval.
 * @param bool Wether the function should only check if the intervals overlap (true), or return the union interval, if any (false).
 */
ko.extenders.paged.format.rangeOverlap = function(l1, u1, l2, u2, bool) {
    if (u1 >= l2)
        return bool ? true : {l: Math.min(l1, l2), u: Math.max(u1, u2)};
    else
        return false;
}

/**
 * Internal. Produces a formatted list of pages.
 * @param array The array of pages.
 * @param format The format hash as produced by `ko.extenders.paged.format`.
 * @param current The current page number.
 */
ko.extenders.paged.format.doFormat = function(array, format, current) {
    var winPre = 0;
    var winAft = 0;
    var ro = ko.extenders.paged.format.rangeOverlap;
    if (format.windowSize % 2) {
        winPre = winAft = (format.windowSize-1)/2;
    } else {
        winAft = format.windowSize / 2;
        winPre = winAft-1;
    }
    var start = format.start;
    var end = array.length - format.end;
    winPre = Math.max(0, current-winPre);
    winAft = Math.min(array.length-1, current+winAft+1);
    if ((ro(0, start, winPre, winAft, true) && ro(winPre, winAft, end, array.length, true)) || ro(0, start, end, array.length, true))
        return array;

    var p = false;
    var result = [];
    if (p = ro(0, start, winPre, winAft)) {
        result.push.apply(result, array.slice(0, p.u));
        result.push(ko.extenders.paged.format.nonPage(format.afterWindowEllipsis));
        result.push.apply(result, array.slice(end));
    } else if (p = ro(winPre, winAft, end, array.length)) {
        result.push.apply(result, array.slice(0, start));
        result.push(ko.extenders.paged.format.nonPage(format.beforeWindowEllipsis));
        result.push.apply(result, array.slice(p.l));
    } else {
        result.push.apply(result, array.slice(0, start));
        result.push(ko.extenders.paged.format.nonPage(format.beforeWindowEllipsis));
        result.push.apply(result, array.slice(winPre, winAft));
        result.push(ko.extenders.paged.format.nonPage(format.afterWindowEllipsis));
        result.push.apply(result, array.slice(end));
    }
    return result;
};


text:
using namespace lldb;
using namespace lldb_private;

void OptionValueLanguage::DumpValue(const ExecutionContext *exe_ctx,
                                    Stream &strm, uint32_t dump_mask) {
  if (dump_mask & eDumpOptionType)
    strm.Printf("(%s)", GetTypeAsCString());
  if (dump_mask & eDumpOptionValue) {
    if (dump_mask & eDumpOptionType)
      strm.PutCString(" = ");
    if (m_current_value != eLanguageTypeUnknown)
      strm.PutCString(Language::GetNameForLanguageType(m_current_value));
  }
}

Status OptionValueLanguage::SetValueFromString(llvm::StringRef value,
                                               VarSetOperationType op) {
  Status error;
  switch (op) {
  case eVarSetOperationClear:
    Clear();
    break;

  case eVarSetOperationReplace:
  case eVarSetOperationAssign: {
    ConstString lang_name(value.trim());
    LanguageSet languages_for_types = Language::GetLanguagesSupportingTypeSystems();
    LanguageType new_type =
        Language::GetLanguageTypeFromString(lang_name.GetStringRef());
    if (new_type && languages_for_types[new_type]) {
      m_value_was_set = true;
      m_current_value = new_type;
    } else {
      StreamString error_strm;
      error_strm.Printf("invalid language type '%s', ", value.str().c_str());
      error_strm.Printf("valid values are:\n");
      for (int bit : languages_for_types.bitvector.set_bits()) {
        auto language = (LanguageType)bit;
        error_strm.Printf("    %s\n",
                          Language::GetNameForLanguageType(language));
      }
      error.SetErrorString(error_strm.GetString());
    }
  } break;

  case eVarSetOperationInsertBefore:
  case eVarSetOperationInsertAfter:
  case eVarSetOperationRemove:
  case eVarSetOperationAppend:
  case eVarSetOperationInvalid:
    error = OptionValue::SetValueFromString(value, op);
    break;
  }
  return error;
}

lldb::OptionValueSP OptionValueLanguage::DeepCopy() const {
  return OptionValueSP(new OptionValueLanguage(*this));
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.fasterxml.jackson.databind.type Class Hierarchy (jackson-databind 2.8.0 API)</title>
<meta name="date" content="2016-07-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package com.fasterxml.jackson.databind.type

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

com.fasterxml.jackson.databind.type.ClassKey (implements java.lang.Comparable<T>, java.io.Serializable)

com.fasterxml.jackson.databind.type.ClassStack

com.fasterxml.jackson.core.type.ResolvedType

com.fasterxml.jackson.databind.JavaType (implements java.io.Serializable, java.lang.reflect.Type)

com.fasterxml.jackson.databind.type.TypeBase (implements com.fasterxml.jackson.databind.JsonSerializable)

com.fasterxml.jackson.databind.type.ArrayType

com.fasterxml.jackson.databind.type.CollectionLikeType

com.fasterxml.jackson.databind.type.CollectionType

com.fasterxml.jackson.databind.type.MapLikeType

com.fasterxml.jackson.databind.type.MapType

com.fasterxml.jackson.databind.type.ResolvedRecursiveType

com.fasterxml.jackson.databind.type.SimpleType

com.fasterxml.jackson.databind.type.ReferenceType

com.fasterxml.jackson.databind.type.TypeBindings (implements java.io.Serializable)

com.fasterxml.jackson.databind.type.TypeFactory (implements java.io.Serializable)

com.fasterxml.jackson.databind.type.TypeModifier

com.fasterxml.jackson.databind.type.TypeParser (implements java.io.Serializable)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2008–2016 FasterXML. All rights reserved.


text:
export default (di, container) => {
    var options = {
        css_selecteur_like: '.btn-like-event',
        css_active_class: 'btn-primary',
    };

    $(options.css_selecteur_like, container).click(function () {
        var btn = $(this);

        if (btn.hasClass('connexion')) {
            return false;
        }

        btn.attr('disabled', true);
        $.post(btn.data('href'), { like: !btn.hasClass(options.css_active_class) }).done(function (msg) {
            btn.attr('disabled', !msg.success);
            if (msg.success) {
                btn.toggleClass(options.css_active_class, msg.like);
            }
        });
    });
};


text:
package ch.javasoft.smx.ops.matrix;

import ch.javasoft.smx.iface.ReadableDoubleMatrix;
import ch.javasoft.smx.iface.ReadableMatrix;
import ch.javasoft.smx.ops.ExtendedMatrixOperations;
import ch.javasoft.smx.ops.Gauss;
import ch.javasoft.util.numeric.Zero;

public class ExtendedDoubleOperations implements ExtendedMatrixOperations<Double, Double> {

	private final Zero 	zero;
	private final Gauss	gauss;

	public ExtendedDoubleOperations(Zero zero) {
		this.zero 	= zero;
		this.gauss	= new Gauss(zero.mZeroPos);
	}
	public ExtendedDoubleOperations(double tolerance) {
		this(new Zero(tolerance));
	}

	public Zero getZero() {
		return zero;
	}
	public Gauss getGauss() {
		return gauss;
	}

	public int rank(ReadableMatrix<Double> mx) {
		if (mx instanceof ReadableDoubleMatrix) {
			return gauss.rank((ReadableDoubleMatrix)mx);
		}
		throw new RuntimeException("unsupported matrix type: " + mx.getClass().getName());
	}
	public int nullity(ReadableMatrix<Double> mx) {
		if (mx instanceof ReadableDoubleMatrix) {
			return gauss.nullity((ReadableDoubleMatrix)mx);
		}
		throw new RuntimeException("unsupported matrix type: " + mx.getClass().getName());
	}
	public ReadableMatrix<Double> invert(ReadableMatrix<Double> mx) {
		if (mx instanceof ReadableDoubleMatrix) {
			return gauss.invert((ReadableDoubleMatrix)mx);
		}
		throw new RuntimeException("unsupported matrix type: " + mx.getClass().getName());
	}

	public ReadableMatrix<Double> nullspace(ReadableMatrix<Double> mx) {
		if (mx instanceof ReadableDoubleMatrix) {
			return gauss.nullspace((ReadableDoubleMatrix)mx);
		}
		throw new RuntimeException("unsupported matrix type: " + mx.getClass().getName());
	}

}


text:
package org.vngx.jsch.userauth;

import org.vngx.jsch.exception.JSchException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.ietf.jgss.GSSContext;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.GSSName;
import org.ietf.jgss.MessageProp;
import org.ietf.jgss.Oid;

/**
 * Implementation of com.jcraft.jsch.GSSContext to perform user
 * authentication.
 *
 * @see org.vngx.jsch.GSSContext
 *
 * @author Atsuhiko Yamanaka
 * @author Michael Laudati
 */
public final class GSSContextKrb5 implements org.vngx.jsch.userauth.GSSContext {

	/** Constant for System property to use subject credentials only. */
	private static final String USE_SUBJECT_CREDS_ONLY = "javax.security.auth.useSubjectCredsOnly";

	/** Property value to use subject credentials only. */
	private static String $useSubjectCredsOnly = getSystemProperty(USE_SUBJECT_CREDS_ONLY);
	/** Generic security services context. */
	private GSSContext _context;

	@Override
	public void create(String user, String host) throws JSchException {
		try {
			// RFC 1964
			Oid krb5 = new Oid("1.2.840.113554.1.2.2");
			// Kerberos Principal Name Form
			Oid principalName = new Oid("1.2.840.113554.1.2.2.1");

			GSSManager mgr = GSSManager.getInstance();
			GSSCredential crd = null;
			/*
			try{
				GSSName _user=mgr.createName(user, principalName);
				crd=mgr.createCredential(_user, GSSCredential.DEFAULT_LIFETIME, krb5, GSSCredential.INITIATE_ONLY);
			} catch(GSSException crdex){ }
			 */

			String cname = host;
			try {
				cname = InetAddress.getByName(cname).getCanonicalHostName();
			} catch(UnknownHostException e) {
				// TODO Error handling?
			}
			GSSName gssHost = mgr.createName("host/" + cname, principalName);
			_context = mgr.createContext(gssHost, krb5, crd, GSSContext.DEFAULT_LIFETIME);

			// RFC4462  3.4.  GSS-API Session
			//
			// When calling GSS_Init_sec_context(), the client MUST set
			// integ_req_flag to "true" to request that per-message integrity
			// protection be supported for this context.  In addition,
			// deleg_req_flag MAY be set to "true" to request access delegation, if
			// requested by the user.
			//
			// Since the user authentication process by its nature authenticates
			// only the client, the setting of mutual_req_flag is not needed for
			// this process.  This flag SHOULD be set to "false".

			// TODO: OpenSSH's sshd does accept 'false' for mutual_req_flag
			//context.requestMutualAuth(false);
			_context.requestMutualAuth(true);
			_context.requestConf(true);
			_context.requestInteg(true);             // for MIC
			_context.requestCredDeleg(true);
			_context.requestAnonymity(false);
		} catch(GSSException ex) {
			throw new JSchException("Failed to create GSSContextKrb5: "+ex, ex);
		}
	}

	@Override
	public boolean isEstablished() {
		return _context.isEstablished();
	}

	@Override
	public byte[] init(byte[] token, int offset, int length) throws JSchException {
		try {
			// Without setting "javax.security.auth.useSubjectCredsOnly" to "false",
			// Sun'offset JVM for Un*x will show messages to stderr in
			// processing context.initSecContext().
			// This hack is not thread safe ;-<.
			// If that property is explicitly given as "true" or "false",
			// this hack must not be invoked.
			if( $useSubjectCredsOnly == null ) {
				setSystemProperty(USE_SUBJECT_CREDS_ONLY, "false");
			}
			return _context.initSecContext(token, 0, length);
		} catch(GSSException ex) {
			throw new JSchException("Failed to init GSSContextKrb5: "+ex, ex);
		} catch(SecurityException ex) {
			throw new JSchException("Failed to init GSSContextKrb5: "+ex, ex);
		} finally {
			if( $useSubjectCredsOnly == null ) {
				// By default, it must be "true".
				setSystemProperty(USE_SUBJECT_CREDS_ONLY, "true");
			}
		}
	}

	@Override
	public byte[] getMIC(byte[] message, int offset, int length) {
		try {
			return _context.getMIC(message, offset, length, new MessageProp(0, true));
		} catch(GSSException ex) {
			return null;
		}
	}

	@Override
	public void dispose() {
		try {
			_context.dispose();
		} catch(GSSException ex) {
			// TODO Error handling?
		}
	}

	/**
	 * Utility method for retrieving a property value from System properties.
	 *
	 * @param key
	 * @return property value or null if error occurs
	 */
	private static String getSystemProperty(String key) {
		try {
			return System.getProperty(key);
		} catch(SecurityException e) {
			return null;	// Not allowed to get the System properties
		}
	}

	/**
	 * Utility method for setting a property value in System properties.
	 *
	 * @param key
	 * @param value
	 */
	private static void setSystemProperty(String key, String value) {
		try {
			System.setProperty(key, value);
		} catch(SecurityException e) { /* Not allowed to set the System properties */ }
	}

}


text:
<?php

namespace CEOFESABundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use CEOFESABundle\Entity\ModuleT;

class LoadModuleTData extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $intra = new ModuleT();
        $intra->setMtyId(0);
        $intra->setMtyType('INTRA');
        $intra->setMtyStructuretype($this->getReference('structure-type2'));

        $externe = new ModuleT();
        $externe->setMtyId(1);
        $externe->setMtyType('EXTERNE');
        $externe->setMtyStructuretype($this->getReference('structure-type3'));

        $metadata = $manager->getClassMetaData(get_class(new ModuleT()));
        $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());
        $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);

        $manager->persist($intra);
        $manager->persist($externe);

        $manager->flush();
    }

     /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 2; // l'ordre dans lequel les fichiers sont chargés
    }
}


text:
Turbocharged.Beanstalk
======================

[![NuGet](https://img.shields.io/nuget/v/Turbocharged.Beanstalk.svg)](http://www.nuget.org/packages/Turbocharged.Beanstalk/)

A [Beanstalk][beanstalk] .NET client library filled with `async` happiness.

Don't like `async`? That's cool, no problem. You might like
[libBeanstalk.NET][libbeanstalk] instead.

Usage
-----

Do the normal thing:

    PM> Install-Package Turbocharged.Beanstalk

Because of the way the Beanstalk protocol works, it's important that producers
and consumers use separate connections. So, when creating a
`BeanstalkConnection`, you need to choose whether it's a consumer or producer.

### Producing Jobs

Create a Producer if you need to insert jobs. Most producer methods are
affected by `UseAsync(tube)`.

```c#
IProducer producer = await BeanstalkConnection.ConnectProducerAsync("localhost:11300");
await producer.UseAsync("mytube");
```

Beanstalk jobs are just blobs, so jobs are represented as byte arrays.

```c#
byte[] job = new byte[] { 102, 105, 101, 116, 123, 124, 101, 114, 113 };
await producer.PutAsync(job, 5, TimeSpan.Zero, TimeSpan.FromSeconds(30));
```

Not feeling the love for byte arrays? You can also put custom objects and
they'll be serialized. The default is JSON.

```c#
await producer.PutAsync<MyObject>(obj, 5, TimeSpan.Zero, TimeSpan.FromSeconds(30));
```

Since Beanstalk maintains a TCP connection, you need to clean up your toys when
you're done:

```c#
producer.Dispose();
```

### Consuming jobs

If you need to consume jobs, create a Consumer instead. Most consumer methods
are affected by `WatchAsync(tube)` and `IgnoreAsync(tube)`.

```c#
IConsumer consumer = await BeanstalkConnection.ConnectConsumerAsync("localhost:11300");
await consumer.WatchAsync("mytube");
```

To ask Beanstalk for a job, reserve it:

```c#
Job job = await consumer.ReserveAsync();
// or:
Job job = await consumer.ReserveAsync(timeout: TimeSpan.FromSeconds(10));

Console.WriteLine("Reserved job ID = {0}, Length = ", job.Id, job.Data.Length);
```

You can also deserialize if you know what type you're expecting.

```c#
Job<MyObject> job = await consumer.ReserveAsync<MyObject>();
```

When you're done with your job, ask your consumer to delete it or bury it.

```c#
if (success)
    await consumer.DeleteAsync(job.Id);
else
    await consumer.BuryAsync(job.Id, priority: 5);
```

Again, clean up after yourself when you don't need the connection anymore:

```c#
consumer.Dispose();
```

### Creating a worker task

A worker task is a `BeanstalkConnection` that processes jobs in a loop.

1. You provide a delegate with signature `Func<IWorker, Job, Task>`.
   Turbocharged.Beanstalk immediately connects and called "reserve" for you.

2. Your delegate gets called whenever a job is reserved.

3. Call DeleteAsync or BuryAsync when you're finished.

It looks like this:

```c#
private Task MyWorkerFunc(IWorker worker, Job job)
{
    bool success = ProcessJob(job.Data);
    if (success)
        await worker.DeleteAsync(job.Id);
    else
        await worker.BuryAsync(job.Id, 1);
}

IDisposable worker = BeanstalkConnection.ConnectWorkerAsync(hostname, port, MyWorkerFunc);

```

You can also use serialized messages:

```c#
private Task MyTypedWorkerFunc(IWorker worker, Job<MyObject> job)
{
    bool success = ProcessJob(job.Object);
    if (success)
        await worker.DeleteAsync(job.Id);
    else
        await worker.BuryAsync(job.Id, 1);
}

IDisposable worker = BeanstalkConnection.ConnectWorkerAsync<MyObject>(hostname, port, MyTypedWorkerFunc);
```

As usual, dispose the worker to make it stop.

```c#
worker.Dispose();
```

Goals
-----

* Simple API that encourages ease of use
* Teach myself how to properly use the shiny asynchrony features in C# 5.0.

License
-------

The MIT License. See `LICENSE.md`.

[beanstalk]: http://kr.github.io/beanstalkd/
[libbeanstalk]: https://github.com/sdether/libBeanstalk.NET


text:
package gov.nih.nci.rembrandt.download.caarray;
import gov.nih.nci.caarray.services.ServerConnectionException;
import gov.nih.nci.caintegrator.application.download.caarray.CaArrayFileDownloadManager;

import java.io.File;
import java.net.MalformedURLException;
import java.util.concurrent.ThreadPoolExecutor;

import javax.security.auth.login.LoginException;

import org.apache.log4j.Logger;

public class RembrandtCaArrayFileDownloadManager extends CaArrayFileDownloadManager{
	public static Logger logger = Logger
	.getLogger(RembrandtCaArrayFileDownloadManager.class);
    public static final String SERVER_URL = "rembrandt.caarray.server.url";

    public static final String GE_EXPERIMENT_NAME = "rembrandt.caarray.ge.experiment.name";

    public static final String CN_EXPERIMENT_NAME = "rembrandt.caarray.cn.experiment.name";

    public static final String USER_NAME = "rembrandt.caarray.user.name";

    public static final String PWD = "rembrandt.caarray.user.pwd";

    public static final String INPUT_DIR = "rembrandt.caarray.download.input.dir";

    public static final String OUTPUT_ZIP_DIR = "rembrandt.caarray.download.output.zip.dir";

    public static final String DIR_IN_ZIP = "rembrandt.caarray.download.dirInZip";

    public static final String ZIP_FILE_URL = "rembrandt.caarray.download.zip.url";

	protected RembrandtCaArrayFileDownloadManager(String caarrayUrl,
			String username, String password,
			String inputDirectory, String outputZipDirectory, String directoryInZip)
			throws MalformedURLException, LoginException, ServerConnectionException {
		super(caarrayUrl, username, password, inputDirectory, outputZipDirectory, directoryInZip);
	}
	public synchronized static CaArrayFileDownloadManager getInstance()
	{
		if (instance == null)
		{
			  //Get the caArray properties from the rembrandt.properties file
			  String caarrayUrl = System.getProperty(SERVER_URL);
			  String username = System.getProperty(USER_NAME);
			  String password = System.getProperty(PWD);
			  String inputDirectory = System.getProperty(INPUT_DIR);
			  String outputZipDirectory = System.getProperty(OUTPUT_ZIP_DIR);
			  String directoryInZip = System.getProperty(DIR_IN_ZIP);
			  String geExperimentName = System.getProperty(RembrandtCaArrayFileDownloadManager.GE_EXPERIMENT_NAME);
			  String cnExperimentName  = System.getProperty(RembrandtCaArrayFileDownloadManager.CN_EXPERIMENT_NAME);
			  if((geExperimentName == null) ||
				 (cnExperimentName == null) ||
				 (caarrayUrl == null) ||
				 (username== null) ||
				 (password == null) ||
				 (inputDirectory == null) ||
				 (outputZipDirectory == null) ||
				 (directoryInZip == null)){
				  logger.error("One of required input parameters is null");
				  throw new IllegalStateException();
			  }
			  File inputDir = new File(inputDirectory);
			  if(!inputDir.isDirectory()){
				  inputDir.mkdir();
			  }
			  File outputZipDir = new File(outputZipDirectory);
			  if(!outputZipDir.isDirectory()){
				  outputZipDir.mkdir();
			  }
			try {
				instance = new RembrandtCaArrayFileDownloadManager(caarrayUrl, username, password,inputDirectory, outputZipDirectory, directoryInZip);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				instance = null;
			}
		}
		return instance;
	}
	public void setTaskExecutor(ThreadPoolExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;

	}

}


text:
(function () {
    'use strict';

    angular
        .module('app')
        .controller('ReportActionsController', ReportActionsController);

    ReportActionsController.$inject = ['$scope', '$http', '$modal'];

    function ReportActionsController($scope, $http, $modal) {
        // Delete
        // inherits $scope.report
        $scope.report = $scope.report;

        $scope.trash = function () {
            if ($scope.report !== null) {
                if (confirm("Sikker på du vil slette?")) {
                    $http.post('/Reports/Trash', { id: $scope.report.Id }).
                        success(function () {
                            $scope.report.Trashed = true;
                        });
                }
            }
        };

        // Restore trashed item
        $scope.restore = function ($id, $index) {
            $http.post('/Reports/Restore', { id: $id }).
                success(function () {
                    $scope.reports[$index].Trashed = false;
                });
        };

        // Remove permantly
        $scope.delete = function ($id, $index) {
            if (confirm("Sikker på du vil slette permanent?")) {
                $http.post('/Reports/Delete', { id: $id }).
                    success(function () {
                        $scope.reports.splice($index, 1);
                    });
            }
        };

        // Initialize Edit Modal Controller

        $scope.reportIndex = null;

        $scope.edit = function ($id, $index) {
            $scope.editable = $scope.reports[$index];
            $scope.reportIndex = $index;

            var editModal = $modal.open({
                templateUrl: '/Scripts/Views/Modals/EditReport.html',
                controller: 'EditReportModalController',
                size: null,
                resolve: {
                    report: function () {
                        return $scope.reports[$index];
                    }
                }
            });

            editModal.result.then(function (modifiedReport) {
                $scope.reports[$scope.editableIndex] = modifiedReport;
                $scope.editable = {};
            }, function () {
                //$log.info('Modal dismissed at: ' + new Date());
            });
        };
    }
})();

(function () {
    'use strict';

    angular
        .module('app')
        .controller('EditReportModalController', function ($scope, $http, $modalInstance, report) {
            $scope.title = 'Edit report';
            $scope.report = report;
            $scope.personalities = [];
            $scope.modified = false;
            var copy = angular.copy($scope.report);

            $scope.$watch(function () {
                return $scope.report.Customer + $scope.report.Message + $scope.report.PersonalityId;
            }, function (newValue, oldValue) {
                if (newValue !== oldValue && !$scope.modified) {
                    $scope.modified = true;
                }
            });

            $http.get('/Personalities/GetSelectList', { cache: true }).
                success(function (data, status, headers, config) {
                    $scope.personalities = data;
                }).
                error(function (data, status, headers, config) {
                    // Error
                });

            $scope.personalityChange = function () {
                report.PersonalityId = report.Personality.Id;
            };

            $scope.ok = function () {
                $scope.report.UpdateDate = moment().toDate();
                $scope.report.CreateDate = moment($scope.report.CreateDate).toDate();
                var postData = angular.copy($scope.report);
                $http.post('/Reports/Edit', postData).
                    success(function (data) {
                        //$scope.reports[$scope.editableIndex] = data;
                    });

                $modalInstance.close($scope.report);
            };

            $scope.cancel = function () {
                // Reset
                report.Message = copy.Message;
                report.Personality = copy.Personality;
                report.PersonalityId = copy.PersonalityId;
                report.Customer = copy.Customer;

                // Cancel model
                $modalInstance.dismiss('cancel');
            };
        });
})();


text:
import { BaseModel } from 'app/shared/models/base/base-model';
import { BaseViewModel, ViewModelConstructor } from 'app/site/base/base-view-model';

// All "standard" relations.
export type RelationDefinition<VForeign extends BaseViewModel = BaseViewModel> =
    | NormalRelationDefinition<VForeign>
    | ReverseRelationDefinition<VForeign>
    | CustomRelationDefinition
    | GenericRelationDefinition<VForeign>;

interface BaseRelationDefinition<VForeign extends BaseViewModel> {
    /**
     * The name of the property, where the foreign view model should be accessable.
     * Note, that this must be a getter to a private variable `_<ownKey`!
     *
     * E.g. `category`. (private variable `_category`)
     */
    ownKey: string;

    /**
     * The model on the other side of the relation.
     */
    foreignViewModel: ViewModelConstructor<VForeign>;
}

export interface BaseOrderedRelation<VForeign extends BaseViewModel> extends BaseRelationDefinition<VForeign> {
    /**
     * Provide an extra key (holding a number) to order by.
     * If the value is equal or no order key is given, the models
     * will be sorted by id.
     */
    order?: string;
}

interface BaseNormalRelationDefinition<VForeign extends BaseViewModel> extends BaseRelationDefinition<VForeign> {
    /**
     * This is the key in the own model where the id(s) are given. Must be present in
     * the model and view model. E.g. `category_id` in a motion.
     */
    ownIdKey: string;
}

/**
 * These relations has to be read as in  an ER-model. The right side is always the
 * model where the relation is defined.
 * - M2O: From this model to another one, where this model is the right (many).
 *        E.g. motions<->categories: One motions has One category; One category has
 *        Many motions.
 * - O2M: Reverse relation to M2O. E.g. defined for categories: One category has
 *        Many motions and One motion has One category.
 * - M2M: M2M relation from this to another model.
 */

interface NormalM2MRelationDefinition<VForeign extends BaseViewModel>
    extends BaseNormalRelationDefinition<VForeign>,
        BaseOrderedRelation<VForeign> {
    type: 'M2M';
}

interface NormalO2MRelationDefinition<VForeign extends BaseViewModel>
    extends BaseNormalRelationDefinition<VForeign>,
        BaseOrderedRelation<VForeign> {
    type: 'O2M';
}

interface NormalM2ORelationDefinition<VForeign extends BaseViewModel> extends BaseNormalRelationDefinition<VForeign> {
    type: 'M2O';
}

export type NormalRelationDefinition<VForeign extends BaseViewModel = BaseViewModel> =
    | NormalM2MRelationDefinition<VForeign>
    | NormalO2MRelationDefinition<VForeign>
    | NormalM2ORelationDefinition<VForeign>;

export function isNormalRelationDefinition(obj: RelationDefinition): obj is NormalRelationDefinition<BaseViewModel> {
    const relation = obj as NormalRelationDefinition<BaseViewModel>;
    return (relation.type === 'M2O' || relation.type === 'O2M' || relation.type === 'M2M') && !!relation.ownIdKey;
}

interface BaseReverseRelationDefinition<VForeign extends BaseViewModel> {
    /**
     * The key with the id(s) is given in the foreign model. Must be present in
     * the model and view model. E.g. `category_id` from a motion but the relation is
     * defined for a category.
     */
    foreignIdKey: string;

    /**
     * The name of the property, where the foreign view model should be accessable.
     * Note, that this must be a getter to a private variable `_<ownKey`!
     *
     * E.g. `category`. (private variable `_category`)
     */
    ownKey: string;

    /**
     * The model on the other side of the relation.
     */
    foreignViewModel: ViewModelConstructor<VForeign>;
}

interface ReverseM2MRelationDefinition<VForeign extends BaseViewModel>
    extends BaseReverseRelationDefinition<VForeign>,
        BaseOrderedRelation<VForeign> {
    type: 'M2M';
}

interface ReverseO2MRelationDefinition<VForeign extends BaseViewModel>
    extends BaseReverseRelationDefinition<VForeign>,
        BaseOrderedRelation<VForeign> {
    type: 'O2M';
}

interface ReverseM2ORelationDefinition<VForeign extends BaseViewModel> extends BaseReverseRelationDefinition<VForeign> {
    type: 'M2O';
}

export type ReverseRelationDefinition<VForeign extends BaseViewModel = BaseViewModel> =
    | ReverseM2MRelationDefinition<VForeign>
    | ReverseO2MRelationDefinition<VForeign>
    | ReverseM2ORelationDefinition<VForeign>;

export function isReverseRelationDefinition(obj: RelationDefinition): obj is ReverseRelationDefinition<BaseViewModel> {
    const relation = obj as ReverseRelationDefinition<BaseViewModel>;
    return (relation.type === 'M2O' || relation.type === 'O2M' || relation.type === 'M2M') && !!relation.foreignIdKey;
}

interface GenericRelationDefinition<VForeign extends BaseViewModel = BaseViewModel> {
    type: 'generic';

    /**
     * The key where the model and view model holds the ContentObject (object with collection and id).
     * Similar to ownIdKey.
     */
    ownContentObjectDataKey: string;

    /**
     * The key where to but the content object.
     */
    ownKey: string;

    possibleModels: ViewModelConstructor<BaseViewModel>[];
    isVForeign: (obj: any) => obj is VForeign;
    VForeignVerbose: string;
}

export function isGenericRelationDefinition(obj: RelationDefinition): obj is GenericRelationDefinition<BaseViewModel> {
    return obj.type === 'generic';
}

/**
 * A custom relation with callbacks with things todo.
 */
interface CustomRelationDefinition {
    type: 'custom';

    /**
     * The key to access the custom relation.
     */
    ownKey: string;

    get: (model: BaseModel, viewModel: BaseViewModel) => any;

    getCacheObjectToCheck: (viewModel: BaseViewModel) => BaseViewModel | null;
}

export function isCustomRelationDefinition(obj: RelationDefinition): obj is CustomRelationDefinition {
    return obj.type === 'custom';
}


text:
Skip to content
This repository
Search
Pull requests
Issues
Gist
 @hoppscards
 Watch 2
  Star 1
  Fork 0 Ryuk87/goupjs
 Code  Issues 0  Pull requests 0  Projects 0  Pulse  Graphs
Branch: master Find file Copy pathgoupjs/src/goup.js
0a4c428  on May 23
@Ryuk87 Ryuk87 Create plugin main file with logic
1 contributor
RawBlameHistory
190 lines (166 sloc)  6.17 KB

var goupJs = (function goupJs(userParams) {
	'use strict';

    /**
     * Merge the user parameters with the default ones
     *
     * @param  {Object}
     * @return {Object}
     */
    function mergeParameters(userParams) {

        // Check if userParams is an object
        if (userParams === undefined) {
            userParams = {};
        } else if(Object.prototype.toString.call(userParams) !== '[object Object]') {
            console.error('The input parameters are in a non supported format.');
            return false;
        }

        var mergedParams = {
            location: userParams.location || 'right',
            locationOffset: userParams.locationOffset || 20,
            bottomOffset: userParams.bottomOffset || 10,
            containerSize: userParams.containerSize || 40,
            containerRadius: userParams.containerRadius || 10,
            containerClass: userParams.containerClass || 'goup-container',
            arrowClass: userParams.arrowClass || 'goup-arrow',
            alwaysVisible: userParams.alwaysVisible || false,
            trigger: userParams.trigger || 500,
            entryAnimation: userParams.entryAnimtion || 'fade',
            goupSpeed: userParams.goupSpeed || 'slow',
            hideUnderWidth: userParams.hideUnderWidth || 500,
            containerColor: userParams.containerColor || '#000',
            arrowColor: userParams.arrowColor || '#ffffff',
            title: userParams.title || '',
            titleAsText: userParams.titleAsText || false,
            titleAsTextClass: userParams.titleAsTextClass || 'goup-text',
            zIndex: userParams.zIndex || 1
        };

        return mergedParams;
    }

    /**
     * Validate parameters
     *
     * @param  {Object}
     * @return {Object}
     */
    function checkParameters(mergedParams) {

        var params = {};

        var checkColor = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i;

        Object.keys(mergedParams).forEach(function loopMerged(key){

            params[key] = mergedParams[key];

            switch (key) {
                case 'location':
                    if (params.location !== 'right' && params.location !== 'left') {
                        params.location = 'right';
                    }
                    break;
                case 'locationOffset':
                    if (params.locationOffset < 0) {
                        params.locationOffset = 0;
                    }
                    break;
                case 'bottomOffset':
                    if (params.bottomOffset < 0) {
                        params.bottomOffset = 0;
                    }
                    break;
                case 'containerSize':
                    if (params.containerSize < 20) {
                        params.containerSize = 20;
                    }
                    break;
                case 'containerRadius':
                    if (params.containerRadius < 0) {
                        params.containerRadius = 0;
                    }
                    break;
                case 'trigger':
                    if (params.trigger < 0) {
                        params.trigger = 0;
                    }
                    break;
                case 'hideUnderWidth':
                    if (params.hideUnderWidth < 0) {
                        params.hideUnderWidth = 0;
                    }
                    break;
                case 'containerColor':
                    if (!checkColor.test(params.containerColor)) {
                        params.containerColor = '#000000';
                    }
                    break;
                case 'arrowColor':
                    if (!checkColor.test(params.arrowColor)) {
                        params.arrowColor = '#fff';
                    }
                    break;
                case 'title':
                    if (params.title === '') {
                        params.titleAsText = false;
                    }
                    break;
                case 'zIndex':
                    if (isNaN(params.zIndex)) {
                        params.zIndex = 1;
                    }
                    break;
                default:
                    break;
            }
        });

        return params;
    }

    /**
     * Create all the needed html elements based on the passed parameters
     *
     * @param  {Object}
     */
    function createElements(params) {
        // Create the container div
        var container = document.createElement('div');
        container.className += params.containerClass;
        // Create arrow div
        var arrow = document.createElement('div');
        arrow.className += params.arrowClass;
        // Append arrow to container
        container.appendChild(arrow);
        // Append container to body
        document.body.appendChild(container);

        // Apply style to container
        container.style.position = 'fixed';
        container.style.width = params.containerSize + 'px';
        container.style.height = params.containerSize + 'px';
        container.style.background = params.containerColor;
        container.style.cursor = 'pointer';
        //container.style.display = 'none';
        container.style.zIndex = params.zIndex;
        container.style.bottom = params.bottomOffset + 'px';
        container.style[params.location] = params.locationOffset + 'px';
        container.style.borderRadius = params.containerRadius + 'px';

        // Apply style to arrow

    }

    /**
     * Call the functions needed for the script to run
     *
     */
    function boot() {
        var mergedParams = mergeParameters(userParams);
        if (mergedParams === false) return;
        var params = checkParameters(mergedParams);
        createElements(params);
    }

    // Wait for the document to be ready. Then call 'boot' function.
    if (document.readyState != 'loading') {
        boot();
    } else {
        document.addEventListener('DOMContentLoaded', boot);
    }

});
Contact GitHub API Training Shop Blog About
© 2016 GitHub, Inc. Terms Privacy Security Status Help