text:
ModernPropertyContext::ModernPropertyContext(RootProperty* root_, DAVA::ContextAccessor* accessor_, DAVA::OperationInvoker* invoker_, QWidget* parent_)
    : accessor(accessor_)
    , invoker(invoker_)
    , parent(parent_)
{
    root = root_;
}

ModernPropertyContext::~ModernPropertyContext()
{
}

RootProperty* ModernPropertyContext::GetRoot() const
{
    return root.Get();
}

DAVA::ContextAccessor* ModernPropertyContext::GetAccessor() const
{
    return accessor;
}

DAVA::OperationInvoker* ModernPropertyContext::GetInvoker() const
{
    return invoker;
}

QWidget* ModernPropertyContext::GetParent() const
{
    return parent;
}

ModernPropertyEditor::ModernPropertyEditor(const std::shared_ptr<ModernPropertyContext>& context_, ValueProperty* property_)
    : QObject(context_->GetParent())
    , context(context_)
{
    property = property_;

    isLayoutSensitive = property->GetName() == "size" || property->GetName() == "position";

    resetAction = new QAction("Reset", context->GetParent());
    QObject::connect(resetAction, &QAction::triggered, this, &ModernPropertyEditor::ResetProperty);

    forceOverrideAction = new QAction("Force Override", context->GetParent());
    QObject::connect(forceOverrideAction, &QAction::triggered, this, &ModernPropertyEditor::ForceOverride);

    bindAction = new QAction("Bind", context->GetParent());
    QObject::connect(bindAction, &QAction::triggered, this, &ModernPropertyEditor::BindProperty);

    GetRootProperty()->propertyChanged.Connect(this, &ModernPropertyEditor::PropertyChanged);
    DAVA::GetEngineContext()->uiControlSystem->GetStyleSheetSystem()->stylePropertiesChanged.Connect(this, &ModernPropertyEditor::OnStylePropertiesChanged);
    DAVA::GetEngineContext()->uiControlSystem->GetLayoutSystem()->controlLayouted.Connect(this, &ModernPropertyEditor::OnControlLayouted);
}

ModernPropertyEditor::~ModernPropertyEditor()
{
    GetRootProperty()->propertyChanged.Disconnect(this);
    DAVA::GetEngineContext()->uiControlSystem->GetStyleSheetSystem()->stylePropertiesChanged.Disconnect(this);
    DAVA::GetEngineContext()->uiControlSystem->GetLayoutSystem()->controlLayouted.Disconnect(this);
}

bool ModernPropertyEditor::IsBindingEditor() const
{
    return false;
}

ValueProperty* ModernPropertyEditor::GetProperty() const
{
    return property.Get();
}

void ModernPropertyEditor::ChangeProperty(const DAVA::Any& value)
{
    if (!property->IsReadOnly())
    {
        DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
        if (activeContext)
        {
            DocumentData* documentData = activeContext->GetData<DocumentData>();
            DVASSERT(documentData != nullptr);

            RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
            documentData->ExecCommand<ChangePropertyValueCommand>(root->GetControlNode(), property.Get(), value);
        }
    }
}

void ModernPropertyEditor::ChangeBinding(const DAVA::String& expr, DAVA::int32 mode)
{
    if (!property->IsReadOnly())
    {
        DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
        if (activeContext)
        {
            DocumentData* documentData = activeContext->GetData<DocumentData>();
            DVASSERT(documentData != nullptr);

            RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
            documentData->ExecCommand<ChangeBindingCommand>(root->GetControlNode(), property.Get(), expr, mode);
        }
    }
}

void ModernPropertyEditor::ApplyStyleToWidget(QWidget* widget)
{
    widget->setProperty("overriden", overriden);
    widget->setProperty("setByStyle", setByStyle);
    widget->setProperty("inherited", inherited);

    widget->style()->unpolish(widget);
    widget->style()->polish(widget);
}

void ModernPropertyEditor::OnPropertyChanged()
{
    overriden = property->IsOverriddenLocally();

    setByStyle = false;
    DAVA::int32 propertyIndex = property->GetStylePropertyIndex();
    DAVA::UIControl* control = context->GetRoot()->GetControlNode()->GetControl();
    if (propertyIndex != -1 && !control->GetLocalPropertySet().test(propertyIndex))
    {
        setByStyle = control->GetStyledPropertySet().test(propertyIndex);
    }

    inherited = property->GetFlags() & AbstractProperty::EF_INHERITED;
}

RootProperty* ModernPropertyEditor::GetRootProperty() const
{
    return context->GetRoot();
}

DAVA::ContextAccessor* ModernPropertyEditor::GetAccessor() const
{
    return context->GetAccessor();
}

DAVA::OperationInvoker* ModernPropertyEditor::GetInvoker() const
{
    return context->GetInvoker();
}

QWidget* ModernPropertyEditor::GetParentWidget() const
{
    return context->GetParent();
}

void ModernPropertyEditor::PropertyChanged(AbstractProperty* property_)
{
    if (property.Get() == property_)
    {
        OnPropertyChanged();
    }
}

void ModernPropertyEditor::OnStylePropertiesChanged(DAVA::UIControl* control, const DAVA::UIStyleSheetPropertySet& properties)
{
    DAVA::int32 propertyIndex = property->GetStylePropertyIndex();
    if (propertyIndex != -1 &&
        properties.test(propertyIndex) &&
        control == context->GetRoot()->GetControlNode()->GetControl())
    {
        OnPropertyChanged();
    }
}

void ModernPropertyEditor::OnControlLayouted(DAVA::UIControl* control)
{
    DAVA::UIControl* propertyControl = GetRootProperty()->GetControlNode()->GetControl();
    if (isLayoutSensitive)
    {
        for (DAVA::UIControl* p = propertyControl; p != nullptr; p = p->GetParent())
        {
            if (p == control)
            {
                OnPropertyChanged();
                break;
            }
            if (p->GetComponent<DAVA::UILayoutIsolationComponent>() != nullptr)
            {
                break;
            }
        }
    }
}

void ModernPropertyEditor::ResetProperty()
{
    if (!property->IsReadOnly())
    {
        DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
        DVASSERT(activeContext != nullptr);
        DocumentData* documentData = activeContext->GetData<DocumentData>();
        DVASSERT(documentData != nullptr);

        RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
        documentData->ExecCommand<ChangePropertyValueCommand>(root->GetControlNode(), property.Get(), DAVA::Any());
    }
}

void ModernPropertyEditor::BindProperty()
{
    if (!property->IsReadOnly())
    {
        DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
        DVASSERT(activeContext != nullptr);
        DocumentData* documentData = activeContext->GetData<DocumentData>();
        DVASSERT(documentData != nullptr);

        RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
        documentData->ExecCommand<ChangeBindingCommand>(root->GetControlNode(), property.Get(), "", 0);
    }
}

void ModernPropertyEditor::ShowActionsMenu(const QPoint& pos)
{
    QMenu menu;
    menu.addAction(resetAction);
    menu.addAction(forceOverrideAction);
    if (property->IsBindable() && !property->IsBound())
    {
        menu.addAction(bindAction);
    }
    menu.exec(pos);
}

void ModernPropertyEditor::ForceOverride()
{
    if (!property->IsReadOnly())
    {
        DAVA::DataContext* activeContext = context->GetAccessor()->GetActiveContext();
        DVASSERT(activeContext != nullptr);
        DocumentData* documentData = activeContext->GetData<DocumentData>();
        DVASSERT(documentData != nullptr);

        RootProperty* root = DAVA::DynamicTypeCheck<RootProperty*>(property->GetRootProperty());
        documentData->ExecCommand<ChangePropertyForceOverrideCommand>(root->GetControlNode(), property.Get());
    }
}

bool ModernPropertyEditor::eventFilter(QObject* o, QEvent* e)
{
    if (e->type() == QEvent::Wheel)
    {
        e->ignore();
        return true;
    }
    return QObject::eventFilter(o, e);
}


text:
package ge.edu.freeuni.sdp.xo.achiev.data;

import com.microsoft.azure.storage.StorageException;

public interface Repository {

	public void insertOrUpdate(AchievEntity achiev) throws StorageException;

	public AchievEntity get(String id) throws Exception;
}

redpajama_set_name: RedPajamaGithub


text:
using AudioSwitcher.AudioApi.CoreAudio;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AlarmApp
{
    public partial class MainForm : Form
    {
        WMPLib.WindowsMediaPlayer wmPlayer;
        CoreAudioDevice defaultPlaybackDevice;
        Challenge challengeForm;

        public MainForm()
        {
            InitializeComponent();
            soundFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
            challengeFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            wmPlayer = new WMPLib.WindowsMediaPlayer();
            defaultPlaybackDevice = new CoreAudioController().DefaultPlaybackDevice;
        }

        private void alarmTimer_Tick(object sender, EventArgs e)
        {
            alarmTimer.Stop();
            PlaySound();
            lbl_AlarmSet.Visible = false;
        }

        private void btn_SetAlarm_Click(object sender, EventArgs e)
        {
            SetAlarm();
        }

        private void btn_BrowseSoundFile_Click(object sender, EventArgs e)
        {
            soundFileDialog.ShowDialog();
        }

        private void btn_BrowseChallengeFile_Click(object sender, EventArgs e)
        {
            challengeFileDialog.ShowDialog();
        }

        private void btn_TryChallenge_Click(object sender, EventArgs e)
        {
            PlaySound();
        }

        private void challenge_Completed(object sender, EventArgs e)
        {
            StopSound();
        }

        private void challengeFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            tbx_ChallengeFileName.Text = challengeFileDialog.FileName;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
                e.Cancel = true;
        }

        private void radMathPuzzle_CheckedChanged(object sender, EventArgs e)
        {
            UpdateChallengeFileEnabled();
        }

        private void radTextFile_CheckedChanged(object sender, EventArgs e)
        {
            UpdateChallengeFileEnabled();
        }

        private void soundFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            tbx_SoundFileName.Text = soundFileDialog.FileName;
        }

        private TimeSpan IntervalToEndTime()
        {
            DateTime endTime = endTimePicker.Value;
            TimeSpan interval;
            if (DateTime.Now.TimeOfDay < endTime.TimeOfDay)
            {
                interval = endTime.TimeOfDay - DateTime.Now.TimeOfDay;
            }
            else
            {
                interval = (DateTime.Now.Date.AddDays(1) + endTime.TimeOfDay) - DateTime.Now;
            }
            return interval;
        }

        private void LoopSound(int newState)
        {
            wmPlayer.controls.play();
        }

        private void PlaySound()
        {
            if (radTextFile.Checked)
            {
                challengeForm = new TextFileChallenge(tbx_ChallengeFileName.Text);
            }
            else if (radMathPuzzle.Checked)
            {
                challengeForm = new ArithmeticChallenge(DifficultyLevel.MEDIUM, 5);
            }
            else
            {
                return;
            }
            wmPlayer.URL = tbx_SoundFileName.Text;
            wmPlayer.controls.play();
            wmPlayer.PlayStateChange += LoopSound;
            volumeUpTimer.Enabled = true;
            updn_Volume.Enabled = false;
            this.FormClosing += MainForm_FormClosing;
            challengeForm.ChallengeCompleted += challenge_Completed;
            challengeForm.ShowDialog(this);
        }

        private void SetAlarm()
        {
            alarmTimer.Interval = (int)IntervalToEndTime().TotalMilliseconds;
            alarmTimer.Start();
            lbl_AlarmSet.Visible = true;
        }

        private void StopSound()
        {
            wmPlayer.PlayStateChange -= LoopSound;
            wmPlayer.controls.stop();
            this.FormClosing -= MainForm_FormClosing;
            volumeUpTimer.Enabled = false;
            updn_Volume.Enabled = true;
        }

        private void UpdateChallengeFileEnabled()
        {
            tbx_ChallengeFileName.Enabled = radTextFile.Checked;
            btn_BrowseChallengeFile.Enabled = radTextFile.Checked;
        }

        private void volumeUpTimer_Tick(object sender, EventArgs e)
        {
            defaultPlaybackDevice.Volume = (double)updn_Volume.Value;
        }
    }
}


text:
package com.ehret.mixit.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.ehret.mixit.HomeActivity;
import com.ehret.mixit.R;
import com.ehret.mixit.adapter.ListTalkForFilAdapter;
import com.ehret.mixit.domain.TypeFile;
import com.ehret.mixit.domain.talk.Talk;
import com.ehret.mixit.model.ConferenceFacade;

public class FilDeLeauFragment extends Fragment {

    private ListView liste;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_datalist, container, false);

        //Handle with layout
        this.liste = (ListView) rootView.findViewById(R.id.liste_content);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((HomeActivity) activity).onSectionAttached("title_fildeleau","color_planning");
    }

    /**
     * Recuperation des marques de la partie en cours
     */
    @Override
    public void onResume() {
        super.onResume();
        Context context = getActivity().getBaseContext();
        liste.setClickable(true);

        liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Talk conf = (Talk) liste.getItemAtPosition(position);

                if("Workshop".equals(conf.getFormat())){
                    ((HomeActivity) getActivity()).changeCurrentFragment(
                            SessionDetailFragment.newInstance(TypeFile.workshops.toString(), conf.getId(),4), TypeFile.workshops.toString());
                }
                else if("Talk".equals(conf.getFormat()) || "Keynote".equals(conf.getFormat())){
                    ((HomeActivity) getActivity()).changeCurrentFragment(
                            SessionDetailFragment.newInstance(TypeFile.talks.toString(), conf.getId(),3), TypeFile.talks.toString());
                }
            }
        });

        ListTalkForFilAdapter adapter = new ListTalkForFilAdapter(context, ConferenceFacade.getInstance().getWorkshopsAndTalks(context));
        liste.setAdapter(adapter);

        liste.setSelection(adapter.getCurrentSelection());
    }
}


text:
import copy
import logging

from collections import OrderedDict

from atpbar import atpbar

from alphatwirl.misc.deprecation import _deprecated
from alphatwirl.misc.deprecation import _deprecated_class_method_option

from .EventLoop import EventLoop
from .merge import merge_in_order

##__________________________________________________________________||
@_deprecated(msg='replaced with alphatwirl.datasetloop.CollectorComposite')
class CollectorComposite:

    """A composite of collectors.

    This class is a composite in the composite pattern.

    Examples of collectors are instances of `Collector`,
    `NullCollector`, and this class.

    """

    @_deprecated_class_method_option('progressReporter')
    def __init__(self, progressReporter=None):

        self.components = [ ]

    def __repr__(self):
        name_value_pairs = (
            ('components',       self.components),
        )
        return '{}({})'.format(
            self.__class__.__name__,
            ', '.join(['{}={!r}'.format(n, v) for n, v in name_value_pairs]),
        )

    def add(self, collector):
        """add a collector

        Args:
            collector: the collector to be added

        """
        self.components.append(collector)

    def collect(self, dataset_readers_list):
        """collect results

        Returns:
            a list of results

        """

        ret = [ ]
        for i, collector in enumerate(atpbar(self.components, name='collecting results')):
            ret.append(collector.collect([(dataset, tuple(r.readers[i] for r in readerComposites))
                                          for dataset, readerComposites in dataset_readers_list]))
        return ret

        ## in one line without the progress bar
        #return [collector.collect([(dataset, tuple(r.readers[i] for r in readerComposites))
        #                           for dataset, readerComposites in dataset_readers_list])
        #        for i, collector in enumerate(self.components)]

##__________________________________________________________________||
@_deprecated(msg='replaced with alphatwirl.datasetloop.EventDatasetReader')
class EventDatasetReader:
    """This class manages objects involved in reading events in data sets.

    On receiving a data set, this class calls the function
    split_into_build_events(), which splits the data set into chunks,
    creates the function build_events() for each chunk, and returns a
    list of the functions. Then, for each build_events(), This class
    creates a copy of the reader, creates an event loop, and send it
    to the event loop runner.

    At the end, this class receives results from the event loop runner
    and have the collector collect them.

    """
    def __init__(self, eventLoopRunner, reader, collector,
                 split_into_build_events):

        self.eventLoopRunner = eventLoopRunner
        self.reader = reader
        self.collector = collector
        self.split_into_build_events = split_into_build_events

        self.EventLoop = EventLoop

        self.runids = [ ]
        self.runid_dataset_map = { }
        self.dataset_runid_reader_map = OrderedDict()

        name_value_pairs = (
            ('eventLoopRunner', self.eventLoopRunner),
            ('reader', self.reader),
            ('collector', self.collector),
            ('split_into_build_events', self.split_into_build_events),
        )
        self._repr = '{}({})'.format(
            self.__class__.__name__,
            ', '.join(['{}={!r}'.format(n, v) for n, v in name_value_pairs]),
        )

    def __repr__(self):
        return self._repr

    def begin(self):
        self.eventLoopRunner.begin()

        self.runids = [ ]
        self.runid_dataset_map = { }
        self.dataset_runid_reader_map = OrderedDict()

    def read(self, dataset):
        build_events_list = self.split_into_build_events(dataset)
        eventLoops = [ ]
        for build_events in build_events_list:
            reader = copy.deepcopy(self.reader)
            eventLoop = self.EventLoop(build_events, reader, dataset.name)
            eventLoops.append(eventLoop)
        runids = self.eventLoopRunner.run_multiple(eventLoops)

        self.runids.extend(runids)
        # e.g., [0, 1, 2]

        self.runid_dataset_map.update({i: dataset.name for i in runids})
        # e.g., {0: 'dataset1', 1: 'dataset1', 2: 'dataset1', 3: 'dataset3'}

        self.dataset_runid_reader_map[dataset.name] = self.dataset_runid_reader_map.get(dataset.name, OrderedDict())
        self.dataset_runid_reader_map[dataset.name].update(((i, None) for i in runids))
        # e.g.,
        # OrderedDict(
        #     [
        #         ('dataset1', OrderedDict([(0, None), (1, None), (2, None)])),
        #         ('dataset2', OrderedDict()),
        #         ('dataset3', OrderedDict([(3, None)]))
        #     ])

    def end(self):

        runids_towait = self.runids[:]
        while runids_towait:
            runid, reader = self.eventLoopRunner.receive_one()
            self._merge(runid, reader)
            runids_towait.remove(runid)

        dataset_readers_list = [(d, list(rr.values())) for d, rr in self.dataset_runid_reader_map.items()]
        # e.g.,
        # [('dataset1', reader), ('dataset2', []), ('dataset3', reader)]

        return self.collector.collect(dataset_readers_list)

    def _merge(self, runid, reader):
        dataset = self.runid_dataset_map[runid]
        runid_reader_map = self.dataset_runid_reader_map[dataset]
        merge_in_order(runid_reader_map, runid, reader)

##__________________________________________________________________||


text:
<!DOCTYPE html>

    <meta charset="utf-8">

	<title>Tiny editable jQuery Bootstrap spreadsheet from MindMup</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="keywords" content="opensource jquery bootstrap editable table spreadsheet" />
    <meta name="description" content="This tiny jQuery bootstrap plugin turns any table into an editable spreadsheet" />
    <link rel="apple-touch-icon" href="http://static.mindmup.com/img/apple-touch-icon.png" />
    <link rel="shortcut icon" href="http://static.mindmup.com/img/favicon.ico" >
    <link href="external/google-code-prettify/prettify.css" rel="stylesheet">
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
    <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-responsive.min.css" rel="stylesheet">
		<link href="http://netdna.bootstrapcdn.com/font-awesome/3.0.2/css/font-awesome.css" rel="stylesheet">

		<link href="index.css" rel="stylesheet">

    Follow @mindmup

editableTableWidget
 tiny editable jQuery Bootstrap spreadsheet

			That would cost too much

Name	Cost	Profit	Fun

Car	100	200	0

Bike	330	240	1

Plane	430	540	3

Yacht	100	200	0

Segway	330	240	1

TOTAL

just start typing to edit, or move around with arrow keys or mouse clicks!

About

		  This tiny (3KB, < 120 lines) jQuery plugin turns any
		  table into an editable spreadsheet.
          Here are the key features:

No magic - works on a normal HTML table (so you can plug it in into any web table, and apply any JS function to calculate values)

Supports validation and change events (so you can warn about invalid input or prevent invalid changes)

Uses standard DOM focus for selection (so does not interrupt scrolling or tabbing outside the table)

Input automatically copies underlying table cell styling

Native copy/paste support

Does not force any styling (so you can style it any way you want, using normal CSS)

Works well with Bootstrap

Depends only on jQuery

Tested in Chrome 32, Firefox 26, IE 10, Safari 7, Android Chrome and iOS 7 Safari

Usage

$('#table').editableTableWidget();

Use a text area instead of input field to input (or supply a custom editor element)

$('#table').editableTableWidget({editor: $('<textarea>')});

Make sure that the editor clones some specific CSS properties of the underlying cell

$('#table').editableTableWidget({
	cloneProperties: ['background', 'border', 'outline']
});

Mark content as invalid during editing (for example, change one of the item names above to blank or try to enter a non-numeric cost)

$('table td').on('validate', function(evt, newValue) {
	if (....) {
		return false; // mark cell as invalid
	}
});

Act on a change (or even reject it). This is how the numbers above recalculate. Also, try to increase total cost over 5000!

$('table td').on('change', function(evt, newValue) {
	// do something with the new cell value
	if (....) {
		return false; // reject change
	}
});

Why?

		We built a tabular data editor for MindMup. Yes, there are plenty of existing widgets such as this, but
		the ones we could find were either too magic (automatically generated tables with custom styles, interrupting normal focus flow, faking selection with background styles, flash-based copy-paste)
		or too big (good ones start at 200KB).

MindMup targets recent browsers, so with HTML5, everything we need can fit into less than 3K. We built this tiny tiny
		editor that does everything we need, does not impose
          any particular additional CSS, does not fight DOM but uses it as normal, works well with Bootstrap styling, and fits nicely into jQuery event processing.

It's released under the MIT license, so fork and enjoy!

FAQ

Can the widget insert rows and columns?

It works on your HTML table. Just use normal DOM manipulation to insert rows and cells. You don't need to extend the widget for that. You can bind a keystroke to the table or some buttons to do that, for example.

Can the widget apply numeric functions?

It works on your HTML table. Just use normal javascript/DOM manipulation to calculate stuff. Listen to the change event and recalculate (see an example).

Can the widget sync with a background data model?

It works on your HTML table, so just use HTML5 data binding or whatever you would normally use to sync with the DOM, and normal javascript/DOM manipulation to update. You don't need to tell the widget about updates.
		To sync in the other direction, subscribe to the change event.

How do I post data to my server?

It works on your HTML table, so use standard DOM functions to pull the data from the table, and use jQuery to post to the server

What other widgets are there?

This widget is intentionally minimalistic. If you need more magic and "it works on your HTML table" is not a good answer for you, then check out HandsonTable or SlickGrid.

				View project on Github


text:
layout: post
title:  Non-Teaching posts in IIIT Allahabad  last date 31st July-2015
date: 2015-06-11 11:10
comments: true
tags: Accountant Assistant Engineer IIIT Institute IT(Computer) Librarian Medical Officer Programmer Registrar Steno UP
archive: true
---
Indian  Institute  of  Information  Technology,  Allahabad  has  been  in  the  forefront  of  Technology  Education,  Research  &  Development.  The  Institute  invites  applications  in  the  prescribed  format  for appointment on regular/ contract/ deputation basis on the following posts  upto 31/07/2015  :

Group-A

1. Registrar : 01 post
2. Deputy Registrar : 02 posts
3. Deputy Librarian : 01 post
4. System Analyst : 01 post
5. Executive Engineer (Civil) : 01 post
6. Assistant Registrar : 02 posts
7. Senior Programmer : 02 posts
8. Medical Officer : 02 posts

Group-B

1. Programmer cum computer Asstt : 01 post
2. Senior Steno : 01 post
3. Accountant : 01 post
4. Personal Assistant : 02 posts
5. Librarian Information Assistant : 01 post
6. Technical Assistant : 03 posts
7. Assistant Engineer (Elect+Civil) : 02 posts
8. Junior Engineer : 01 post

Group-C

1. Junior Steno : 02 posts
2. Caretaker-cum-Manager : 01 post

**How to Apply** : The complete application form in prescribed format in all respect  should  be sent to Deputy  Registrar (E),  IIIT-Allahabad, Deoghat, Jhalwa, Allahabad-211012, U.P. on or before 31/07/2015.

The complete detail and application format is available at  <http://www.iiita.ac.in/announcements.php>


text:
@implementation HTTPConnection
@synthesize delegate;

static HTTPConnection* instance;

+ (HTTPConnection *)getInstance {
    @synchronized(self) {
        if (instance == NULL)
            instance = [[HTTPConnection alloc] init];
        return instance;
    }
}

#pragma mark - send frame

+ (NSString *)removeSpacesFromString:(NSString*)str {
    NSMutableString* result = [[NSMutableString alloc] initWithString:str];
    [result replaceOccurrencesOfString:@" " withString:@"%20" options:NSLiteralSearch range:NSMakeRange(0, [str length])];
    return result;
}

+ (NSString *)generateURL {
    NSString* salt = @"a dzwony bily wciaz...";
    NSString* md = [[NSString alloc] initWithFormat:@"%@%d%@", PLAYER_NAME, SCORE, salt];

    NSLog(@"str to md: %@", md);

    md = [HashFunctions calculateMD5:md];
    NSString* result = [NSString stringWithFormat:@"%@/~tomek/?name=%@&score=%d&h=%@&n=%d", [Util getServerAddress], [HTTPConnection removeSpacesFromString:PLAYER_NAME], SCORE, md, HIGHSCORE_LIST_LENGTH];

    NSLog(@"generated url: %@", result);
    return result;
}

+ (void)sendSimplePostRequest {
    HTTPConnection* conn = [HTTPConnection getInstance];

    NSURL* url = [NSURL URLWithString:[HTTPConnection generateURL]];

    NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kNetwork_httpConnectionTimeout];
    [req setHTTPMethod:@"POST"];

    //NSData* data = [NSData data];
    //[req setHTTPBody:data];

    NSURLConnection* connection = [NSURLConnection connectionWithRequest:req delegate:conn];
    [connection start];

}

#pragma mark - manager lifecycle

- (id)init {
    if ((self = [super init])) {
        receivedData = [[NSMutableData data] retain];
    }
    return self;
}

- (void)dealloc {
    [delegate release];
    [receivedData release];
    [super dealloc];
}

#pragma mark - NSConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.

    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.

    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);

    NSString* strResponse = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
    NSLog(@"Received msg: %@", strResponse);

    // parse string
    NSMutableArray* result = [NSMutableArray array];;

    NSArray* rows = [strResponse componentsSeparatedByString:@";;||;;"];
    for (NSString* row in rows) {
        NSArray* elements = [row componentsSeparatedByString:@";;;"];
        if ([elements count] == 2) {
            NSLog(@"[%@, %@], ", [elements objectAtIndex:0], [elements objectAtIndex:1]);

            [result addObject:[elements objectAtIndex:0]];
            [result addObject:[elements objectAtIndex:1]];
        }
    }
    [strResponse release];

    [self.delegate updateWithHighscores:result];
}

@end


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
define(["require", "exports", "aurelia-framework", "./../../config"], function (require, exports, aurelia_framework_1, config_1) {
    "use strict";
    var ModelContentElement = (function () {
        function ModelContentElement() {
        }
        __decorate([
            aurelia_framework_1.bindable,
            __metadata('design:type', String)
        ], ModelContentElement.prototype, "class", void 0);
        ModelContentElement = __decorate([
            aurelia_framework_1.customElement(config_1.config.modalContent),
            aurelia_framework_1.containerless,
            aurelia_framework_1.inlineView("<template>
<slot></slot>
</template>"),
            __metadata('design:paramtypes', [])
        ], ModelContentElement);
        return ModelContentElement;
    }());
    exports.ModelContentElement = ModelContentElement;
});

//# sourceMappingURL=modalContentElement.js.map


text:
	<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/blueStatus"
            android:minHeight="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:navigationIcon="?attr/homeAsUpIndicator"
            app:theme="@style/Theme.AppCompat.NoActionBar"/>

    </android.support.design.widget.AppBarLayout>

	setSupportActionBar(mToolbar);

	  ActionBar actionBar = getSupportActionBar();
	  if (actionBar != null) {
	      //设置显示Home键
	      actionBar.setDisplayHomeAsUpEnabled(true);
	  }

监听Toolbar左上角按钮的点击事件
覆写Activity的onOptionsItemSelected()方法,那个按钮的id一直是android.R.id.home

	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:   //Toolbar左上角的按钮
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

## 2.添加了这个之后左上角的图标就变了

	//添加抽屉监听 ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
	mToolbar, R.string.open_drawer, R.string .close_drawer);
	mDrawerLayout.addDrawerListener(actionBarDrawerToggle);
	//同步状态
	actionBarDrawerToggle.syncState();


text:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from mainWindow import Ui_MainWindow
from converter import UgScriptConverter

class Main(QtGui.QMainWindow):
	input_file = '' # Menbe hujjiti
	output_file = '' # Nishah hujjiti
	isSetFile = False # Ensure the input file is selected

	def __init__(self):
		QtGui.QMainWindow.__init__(self)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)
		self.ui.btnConvert.clicked.connect(self.btnConvert_clicked)
		# self.ui.btnDefault.clicked.connect(self.btnDefault_clicked)
		self.ui.actionInput_File.triggered.connect(self.selectInputFile)
		self.ui.actionOutput_File.triggered.connect(self.setOutputFile)

	def btnConvert_clicked(self):
		if self.isSetFile == False:
			src_txt =  unicode (self.ui.te_src.toPlainText().toUtf8(), "utf-8")
			opt_txt =  unicode (self.ui.te_opt.toPlainText().toUtf8(), "utf-8")
		else:
			# This part should change to status bar
			msgBox = QtGui.QMessageBox()
 			msgBox.setText("Converting the source file. \n Menbe hujitini aylandurwatimiz.")
 			msgBox.exec_()
 			inf = open(self.input_file, 'r')
 			src_txt = unicode (inf.read(), "utf-8")
 			inf.close()

		from_val =  self.ui.cb_src.currentIndex()
		to_val =  self.ui.cb_opt.currentIndex()

		usc = UgScriptConverter()

		# 0 Uyghur, 1 Latin, 2 Common Turkish
		if from_val == to_val:
			opt_txt = src_txt
		# Uyghur Arabic
		elif from_val == 0:
			if to_val == 1:
				# Uyghur to Latin
				opt_txt = usc.UA2LA(src_txt)
			elif to_val == 2:
				# Uyghur to Common Turkish
				opt_txt = usc.UA2CT(src_txt)
			elif to_val == 3:
				# Uyghur to Cyrilik Turkish
				opt_txt = usc.UA2CC(src_txt)
		# Latin
		elif from_val == 1:
			if to_val == 0:
				# Latin to Uyghur
				opt_txt = usc.LA2UA(src_txt)
			elif to_val == 2:
				# Latin to Common Turkish
				opt_txt = usc.LA2CT(src_txt)
			elif to_val == 3:
				# Latin to Cyrilik
				opt_txt = usc.LA2CC(src_txt)
		# Common TUrkish
		elif from_val == 2:
			if to_val == 0:
				# Common Turkish to Uyghur
				opt_txt = usc.CT2UA(src_txt)
			elif to_val == 1:
				# Common Turkish to Latin
				opt_txt = usc.CT2LA(src_txt)
			elif to_val == 3:
				# Common Turkish to Cyrilik
				opt_txt = usc.CT2CC(src_txt)
		# Cyrilik
		elif from_val == 3:
			if to_val == 0:
				# Common Turkish to Uyghur
				opt_txt = usc.CC2UA(src_txt)
			elif to_val == 1:
				# Common Turkish to Latin
				opt_txt = usc.CC2LA(src_txt)
			elif to_val == 2:
				# Common Turkish to Cyrilik
				opt_txt = usc.CT2CC(src_txt)

		if self.isSetFile == False:
			self.ui.te_opt.setText(opt_txt)
		else:
			of = open(self.output_file, 'w')
			of.write(opt_txt.encode('utf8'))
			of.close()

		isSetFile = False

		print "Converting is done."
		# print from_val
		# print to_val

		# text = u"ھەممە ئادەم تۇغۇلۇشىدىنلا ئەركىن، ئىززەت-ھۆرمەت ۋە ھوقۇقتا باب-باراۋەر بولۇپ تۇغۇلغان."+\
		# u' ئۇلار ئەقىلگە ۋە ۋىجدانغا ئىگە ھەمدە بىر-بىرىگە قېرىنداشلىق مۇناسىۋىتىگە'+\
		# u" خاس روھ بىلەن مۇئامىلە قىلىشى كېرەك."

		# latin_text = u"Hemme adem tughulushidinla erkin, izzet-hörmet we hoquqta bab-barawer "+\
		# u"bolup tughulghan. Ular eqilge we wijdan'gha ige hemde bir-birige qérindashliq munasiwitige "+\
		# u"xas roh bilen muamile qilishi kérek."

		# ct_text = u"Hemme adem tuğuluşidinla erkin, izzet-hörmet ve hoquqta bab-baraver bolup tuğulğan."+\
		# u" Ular eqilge ve vijdanğa ige hemde bir-birige qérindaşliq munasivitige xas roh bilen mu'amile qilişi kérek. ? <<>>"

		# # latin_text = "adem adem"
		# self.ui.te_src.setText(ct_text)
		# usc = UgScriptConverter()

		# # ug_text = usc.CT2UA(ct_text)
		# # self.ui.textEdit_2.setText(ug_text)

		# # sys.exit()

		# ug_text = usc.LA2UA(latin_text)
		# self.ui.te_opt.setText(ug_text)

		# ct_text= usc.LA2CT(latin_text)
		# self.ui.te_opt.setText(ct_text)

	# This function for testing
	def btnDefault_clicked(self):

		inf = open('default.txt', 'r')
		ug_text = unicode (inf.read(), "utf-8")
		inf.close()

		from_val =  self.ui.cb_src.currentIndex()

		if from_val == 0:
			self.ui.te_src.setText(ug_text)
		elif from_val == 1:
			pass
		elif from_val == 1:
			pass
		elif from_val == 1:
			pass
		elif from_val == 1:
			pass
		else:
			pass

	def selectFile(self):
		tmp_file = (QtGui.QFileDialog.getOpenFileName())
		return tmp_file

	def selectInputFile(self):
		self.input_file = self.selectFile()
		self.output_file = self.input_file + '_convert.txt'
		print "Input file is selected."
		print 'Input: ', self.input_file
		print 'Output: ', self.output_file
		self.isSetFile = True

	def setOutputFile(self):
		if self.isSetFile == False:
			 msgBox = QtGui.QMessageBox()
 			 msgBox.setText("Please choose the source file. \n Menbe hujitini tallang.")
 			 msgBox.exec_()
 			 return
		self.output_file = self.selectFile()
		print 'Input: ', self.input_file
		print 'Output: ', self.output_file

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())


text:
module Temple
  module ERB
    # Example ERB engine implementation
    #
    # @api public
    class Engine < Temple::Engine
      use Temple::ERB::Parser
      use Temple::ERB::Trimming
      filter :Escapable
      filter :MultiFlattener
      filter :StaticMerger
      generator :ArrayBuffer
    end
  end
end


text:
package opennlp.tools.coref.mention;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.didion.jwnl.JWNLException;
import net.didion.jwnl.data.Adjective;
import net.didion.jwnl.data.FileDictionaryElementFactory;
import net.didion.jwnl.data.IndexWord;
import net.didion.jwnl.data.POS;
import net.didion.jwnl.data.Pointer;
import net.didion.jwnl.data.PointerType;
import net.didion.jwnl.data.Synset;
import net.didion.jwnl.data.VerbFrame;
import net.didion.jwnl.dictionary.FileBackedDictionary;
import net.didion.jwnl.dictionary.MorphologicalProcessor;
import net.didion.jwnl.dictionary.file_manager.FileManager;
import net.didion.jwnl.dictionary.file_manager.FileManagerImpl;
import net.didion.jwnl.dictionary.morph.DefaultMorphologicalProcessor;
import net.didion.jwnl.dictionary.morph.DetachSuffixesOperation;
import net.didion.jwnl.dictionary.morph.LookupExceptionsOperation;
import net.didion.jwnl.dictionary.morph.LookupIndexWordOperation;
import net.didion.jwnl.dictionary.morph.Operation;
import net.didion.jwnl.dictionary.morph.TokenizerOperation;
import net.didion.jwnl.princeton.data.PrincetonWN17FileDictionaryElementFactory;
import net.didion.jwnl.princeton.file.PrincetonRandomAccessDictionaryFile;

/**
 * An implementation of the Dictionary interface using the JWNL library.
 */
public class JWNLDictionary implements Dictionary {

  private net.didion.jwnl.dictionary.Dictionary dict;
  private MorphologicalProcessor morphy;
  private static String[] empty = new String[0];

  public JWNLDictionary(String searchDirectory) throws IOException, JWNLException {
    PointerType.initialize();
	Adjective.initialize();
	VerbFrame.initialize();
    Map<POS, String[][]> suffixMap = new HashMap<POS, String[][]>();
    suffixMap.put(POS.NOUN,new String[][] {{"s",""},{"ses","s"},{"xes","x"},{"zes","z"},{"ches","ch"},{"shes","sh"},{"men","man"},{"ies","y"}});
    suffixMap.put(POS.VERB,new String[][] {{"s",""},{"ies","y"},{"es","e"},{"es",""},{"ed","e"},{"ed",""},{"ing","e"},{"ing",""}});
    suffixMap.put(POS.ADJECTIVE,new String[][] {{"er",""},{"est",""},{"er","e"},{"est","e"}});
    DetachSuffixesOperation tokDso = new DetachSuffixesOperation(suffixMap);
    tokDso.addDelegate(DetachSuffixesOperation.OPERATIONS,new Operation[] {new LookupIndexWordOperation(),new LookupExceptionsOperation()});
    TokenizerOperation tokOp = new TokenizerOperation(new String[] {" ","-"});
    tokOp.addDelegate(TokenizerOperation.TOKEN_OPERATIONS,new Operation[] {new LookupIndexWordOperation(),new LookupExceptionsOperation(),tokDso});
    DetachSuffixesOperation morphDso = new DetachSuffixesOperation(suffixMap);
    morphDso.addDelegate(DetachSuffixesOperation.OPERATIONS,new Operation[] {new LookupIndexWordOperation(),new LookupExceptionsOperation()});
    Operation[] operations = {new LookupExceptionsOperation(), morphDso , tokOp};
    morphy = new DefaultMorphologicalProcessor(operations);
    FileManager manager = new FileManagerImpl(searchDirectory,PrincetonRandomAccessDictionaryFile.class);
    FileDictionaryElementFactory factory = new PrincetonWN17FileDictionaryElementFactory();
    FileBackedDictionary.install(manager, morphy,factory,true);
    dict = net.didion.jwnl.dictionary.Dictionary.getInstance();
    morphy = dict.getMorphologicalProcessor();
  }

  @SuppressWarnings("unchecked")
  public String[] getLemmas(String word, String tag) {
    try {
      POS pos;
      if (tag.startsWith("N") || tag.startsWith("n")) {
        pos = POS.NOUN;
      }
      else if (tag.startsWith("V") || tag.startsWith("v")) {
        pos = POS.VERB;
      }
      else if (tag.startsWith("J") || tag.startsWith("a")) {
        pos = POS.ADJECTIVE;
      }
      else if (tag.startsWith("R") || tag.startsWith("r")) {
        pos = POS.ADVERB;
      }
      else {
        pos = POS.NOUN;
      }
      List<String> lemmas = morphy.lookupAllBaseForms(pos,word);
      return lemmas.toArray(new String[lemmas.size()]);
    }
    catch (JWNLException e) {
      e.printStackTrace();
      return null;
    }
  }

  public String getSenseKey(String lemma, String pos,int sense) {
    try {
      IndexWord iw = dict.getIndexWord(POS.NOUN,lemma);
      if (iw == null) {
        return null;
      }
      return String.valueOf(iw.getSynsetOffsets()[sense]);
    }
    catch (JWNLException e) {
      e.printStackTrace();
      return null;
    }

  }

  public int getNumSenses(String lemma, String pos) {
    try {
      IndexWord iw = dict.getIndexWord(POS.NOUN,lemma);
      if (iw == null){
        return 0;
      }
      return iw.getSenseCount();
    }
    catch (JWNLException e) {
      return 0;
    }
  }

  private void getParents(Synset synset, List<String> parents) throws JWNLException {
    Pointer[] pointers = synset.getPointers();
    for (int pi=0,pn=pointers.length;pi<pn;pi++) {
      if (pointers[pi].getType() == PointerType.HYPERNYM) {
        Synset parent = pointers[pi].getTargetSynset();
        parents.add(String.valueOf(parent.getOffset()));
        getParents(parent,parents);
      }
    }
  }

  public String[] getParentSenseKeys(String lemma, String pos, int sense) {
    //System.err.println("JWNLDictionary.getParentSenseKeys: lemma="+lemma);
    try {
      IndexWord iw = dict.getIndexWord(POS.NOUN,lemma);
      if (iw != null) {
        Synset synset = iw.getSense(sense+1);
        List<String> parents = new ArrayList<String>();
        getParents(synset,parents);
        return parents.toArray(new String[parents.size()]);
      }
      else {
        return empty;
      }
    }
    catch (JWNLException e) {
      e.printStackTrace();
      return null;
    }
  }

  public static void main(String[] args) throws IOException, JWNLException {
    String searchDir = System.getProperty("WNSEARCHDIR");
    System.err.println("searchDir="+searchDir);
    if (searchDir != null) {
      Dictionary dict = new JWNLDictionary(System.getProperty("WNSEARCHDIR"));
      String word = args[0];
      String[] lemmas = dict.getLemmas(word,"NN");
      for (int li=0,ln=lemmas.length;li<ln;li++) {
        for (int si=0,sn=dict.getNumSenses(lemmas[li],"NN");si<sn;si++) {
          System.out.println(lemmas[li]+" ("+si+")\t"+java.util.Arrays.asList(dict.getParentSenseKeys(lemmas[li],"NN",si)));
        }
      }
    }
  }
}


text:
package poly.io

/**
 * Represents a writable file system.
 *
 * A file system can either be your local file system,
 * a zip archive, or a file system on a remote server.
 * @since 0.2.0
 * @author Tongfei Chen
 */
trait WritableFileSystem extends ReadOnlyFileSystem { self =>

  type Path <: WritablePath[this.type]

  type Directory <: WritableDirectory[this.type] with Path

  type File <: WritableFile[this.type] with Path

  type SymLink <: ReadOnlySymLink[this.type] with Path

  implicit def copying: Copying[this.type, this.type]

}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Glimpse.Server.Internal.Extensions
{
    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class ParameterExtensions
    {
        public static IEnumerable<string> ParseEnumerable(this IDictionary<string, string> parameters, string name)
        {
            if (parameters.ContainsKey(name) && !string.IsNullOrWhiteSpace(parameters[name]))
                return parameters[name].Split(',');

            return Enumerable.Empty<string>();
        }

        public static string ParseString(this IDictionary<string, string> parameters, string name)
        {
            if (parameters.ContainsKey(name))
                return parameters[name];

            return null;
        }

        public static float? ParseFloat(this IDictionary<string, string> parameters, string name)
        {
            float result;
            if (parameters.ContainsKey(name) && float.TryParse(parameters[name], out result))
                return result;

            return null;
        }

        public static int? ParseInt(this IDictionary<string, string> parameters, string name)
        {
            int result;
            if (parameters.ContainsKey(name) && int.TryParse(parameters[name], out result))
                return result;

            return null;
        }

        public static DateTime? ParseDateTime(this IDictionary<string, string> parameters, string name)
        {
            DateTime result;
            if (parameters.ContainsKey(name) && DateTime.TryParse(parameters[name], out result))
                return result;

            return null;
        }

        public static Guid? ParseGuid(this IDictionary<string, string> parameters, string name)
        {
            Guid result;
            if (parameters.ContainsKey(name) && Guid.TryParseExact(parameters[name], "N", out result))
                return result;

            return null;
        }
    }
}


text:
require 'spec_helper'

RSpec.describe WebShield do
  it 'has a version number' do
    expect(WebShield::VERSION).not_to be nil
  end
end


text:
import { NgModule } from '@angular/core';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';

import { HttpClientInMemoryWebApiModule, InMemoryDbService } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './core';

@NgModule({
  imports: [
    AppModule,
    // The HttpClientInMemoryWebApiModule module intercepts HTTP requests
    // and returns simulated server responses.
    HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {
      dataEncapsulation: false,
      delay: 300,
      passThruUnknownUrl: true
    })
  ],
  providers: [{ provide: InMemoryDataService, useExisting: InMemoryDbService }],
  bootstrap: [AppComponent]
})
export class AppDevModule {}


text:
package main

import (
	"fmt"
	"os"
	"regexp"
	"sort"
	"strings"
	"text/tabwriter"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/ec2/ec2iface"
)

// EC2Client -
type EC2Client interface {
	ListInstances(string) (Ec2Instances, error)
}

// ec2Client -
type ec2Client struct {
	client ec2iface.EC2API
}

// NewEC2Client is construct of ec2 object.
func NewEC2Client(svc ec2iface.EC2API) EC2Client {
	return &ec2Client{
		client: svc,
	}
}

// Ec2Instances is list of EC2 instance.
type Ec2Instances []*ec2.Instance

func (instance Ec2Instances) Len() int {
	return len(instance)
}

func (instance Ec2Instances) Swap(i, j int) {
	instance[i], instance[j] = instance[j], instance[i]
}

func (instance Ec2Instances) Less(i, j int) bool {
	return GetTagValue(instance[i], "Name") < GetTagValue(instance[j], "Name")
}

// ParseFilter parse filter option.
func ParseFilter(filters string) []*ec2.Filter {

	// filters e.g. "Name=tag:Foo,Values=Bar Name=instance-type,Values=m1.small"
	var ec2Filter []*ec2.Filter

	re := regexp.MustCompile(`Name=(.+),Values=(.+)`)
	for _, i := range strings.Fields(filters) {
		matches := re.FindAllStringSubmatch(i, -1)
		ec2Filter = append(ec2Filter, &ec2.Filter{
			Name: aws.String(matches[0][1]),
			Values: []*string{
				aws.String(matches[0][2]),
			},
		})
	}
	return ec2Filter
}

// GenerateSession generate session.
func GenerateSession(region, profile string) (*session.Session, error) {

	sessOpt := session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}
	if len(region) != 0 {
		sessOpt.Config = aws.Config{Region: aws.String(region)}
	}
	if len(profile) != 0 {
		sessOpt.Profile = profile
	}
	return session.NewSessionWithOptions(sessOpt)
}

// ListInstances lists one or more of your instances.
func (svc *ec2Client) ListInstances(filters string) (Ec2Instances, error) {

	var instances Ec2Instances
	params := &ec2.DescribeInstancesInput{}
	if len(filters) != 0 {
		params = &ec2.DescribeInstancesInput{
			Filters: ParseFilter(filters),
		}
	}
	resp, err := svc.client.DescribeInstances(params)
	if err != nil {
		return nil, err
	}
	if len(resp.Reservations) == 0 {
		return Ec2Instances{}, nil
	}
	for _, res := range resp.Reservations {
		for _, instance := range res.Instances {
			instances = append(instances, instance)
		}
	}
	sort.Sort(instances)
	return instances, nil
}

// PrintInstances is output stdout.
func PrintInstances(instances Ec2Instances) {
	w := new(tabwriter.Writer)
	w.Init(os.Stdout, 2, 8, 2, ' ', 0)
	for _, instance := range instances {
		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
			GetTagValue(instance, "Name"),
			GetPrivateIPAddress(instance),
			GetPublicIPAddress(instance),
			*instance.InstanceId,
			*instance.InstanceType,
			*instance.Placement.AvailabilityZone,
			*instance.State.Name,
			GetPlatform(instance),
		)
	}
	w.Flush()
}

// GetTagValue returns values of EC2 tag.
func GetTagValue(instance *ec2.Instance, tagName string) string {
	for _, t := range instance.Tags {
		if *t.Key == tagName {
			return *t.Value
		}
	}
	return ""
}

// GetPrivateIPAddress returns value of EC2 private ip address, if there is a value.
func GetPrivateIPAddress(instance *ec2.Instance) string {
	if instance.PrivateIpAddress != nil {
		return *instance.PrivateIpAddress
	}
	return ""
}

// GetPublicIPAddress returns value of EC2 public ip address, if there is a value.
func GetPublicIPAddress(instance *ec2.Instance) string {
	if instance.PublicIpAddress != nil {
		return *instance.PublicIpAddress
	}
	return ""
}

// GetPlatform returns platform name(linux or windows).
func GetPlatform(instance *ec2.Instance) string {
	if instance.Platform != nil {
		return *instance.Platform
	}
	return "linux"
}


text:
layout: relation
title: 'compound:prt'
shortdef: 'compound:prt'
---

This document is a placeholder for the language-specific documentation
for `compound:prt`.


text:
<?php

namespace Umc\Base\Controller\Adminhtml;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

abstract class Module extends Action
{
    /**
     * page factory reference
     *
     * @var PageFactory
     */
    protected $resultPageFactory;

    /**
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
}


text:
using Microsoft.CodeAnalysis;
using System;
using System.Linq.Expressions;
using Z3.ObjectTheorem.EF.Metamodel;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp;

namespace Z3.ObjectTheorem.EF.RoslynIntegration.Assumptions
{
    public class DatabaseGeneratedAttributePropertyAssumption : PropertyAssumption<ValueField, DatabaseGeneratedAttribute>
    {
        public DatabaseGeneratedAttributePropertyAssumption(IPropertySymbol property, Expression<Func<bool>> assumption, ValueField valueField)
            : base(property, assumption, valueField)
        { }

        public override Expression<Func<ValueField, DatabaseGeneratedAttribute>> PropertyExpression => vf => vf.DatabaseGeneratedAttribute;

        public override int Rank
        {
            get
            {
                return 2;
            }
        }

        protected override IEnumerable<AttributeSyntax> GetAttributeSyntaxesToAdd(DatabaseGeneratedAttribute result)
        {
            if (result != DatabaseGeneratedAttribute.None)
            {
                yield return SyntaxFactory.Attribute(
                    SyntaxFactory.IdentifierName("DatabaseGenerated"),
                    SyntaxFactory.AttributeArgumentList(
                        SyntaxFactory.SingletonSeparatedList(
                            SyntaxFactory.AttributeArgument(
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.IdentifierName(
                                        "DatabaseGeneratedOption"),
                                    SyntaxFactory.IdentifierName(
                                        result.ToString()))
                            )
                        )
                    )
                );
            }
        }

        protected override IEnumerable<string> GetAttributesToDelete(DatabaseGeneratedAttribute result)
        {
            if (result == DatabaseGeneratedAttribute.None)
            {
                yield return "DatabaseGenerated";
            }
        }
    }
}


text:
layout: page
title: Spears Aerospace Party
date: 2016-05-24
author: Natalie Blankenship
tags: weekly links, java
status: published
summary: Integer vehicula purus et porttitor varius. Quisque viverra laoreet.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/31/2018
  endDate: 08/04/2018
  ctyhocn: SHMTXHX
  groupCode: SAP
published: true
---
Integer et porta urna. Etiam ut condimentum ante. Praesent iaculis congue condimentum. Donec libero orci, placerat at sodales id, rhoncus sit amet justo. Fusce vitae ex quis dui faucibus pretium at at nisl. Fusce vulputate, elit in viverra viverra, nisi lectus aliquam mi, et blandit felis lacus faucibus massa. Phasellus elementum non urna ut mollis. Cras a purus vel felis dictum tempor non id lacus. Duis scelerisque justo nisi, id eleifend orci viverra a. Etiam imperdiet, arcu eget interdum pretium, enim neque sagittis nibh, vitae tempus risus mauris a ipsum. Ut iaculis sed magna a sollicitudin. Mauris rhoncus neque nec ullamcorper bibendum. Maecenas tincidunt nulla in leo faucibus, luctus imperdiet enim tempor. Nam eu purus sit amet diam accumsan ultrices. Curabitur faucibus erat iaculis, imperdiet leo eu, commodo augue.
Donec lacinia at felis vitae imperdiet. Interdum et malesuada fames ac ante ipsum primis in faucibus. Nulla id euismod mi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum sit amet sem eleifend, pharetra magna ac, rutrum orci. Curabitur tincidunt, turpis quis iaculis efficitur, massa elit fermentum leo, ac sollicitudin tortor odio eget nisl. Donec sit amet consectetur purus, eu dictum felis. Proin sit amet porta augue. Nam sagittis condimentum sapien, nec iaculis eros aliquet sed.

1 Vivamus varius ipsum ac nulla pulvinar luctus
1 Morbi sed arcu accumsan, rutrum elit sed, vulputate mi
1 Sed viverra tellus a sem dictum dapibus
1 Ut id neque id orci accumsan accumsan non placerat orci
1 Nunc non magna sed neque placerat maximus id vitae nisl
1 Sed non sapien placerat sem porttitor fringilla.

Proin tincidunt, sem ut volutpat laoreet, eros magna aliquam erat, id eleifend nisl mauris in odio. Suspendisse commodo est at risus dictum facilisis. Suspendisse sed lobortis ex. Curabitur ultrices euismod nulla. In hac habitasse platea dictumst. Mauris eu quam tincidunt, imperdiet dolor quis, placerat quam. Mauris imperdiet justo a ex sollicitudin, quis pharetra nunc semper.


text:
class Question < ActiveRecord::Base
    has_many :answers

    validates :title, presence: true
    validates :content, presence: true

    def upvote
        self.votes += 1
        self.save
    end

    def downvote
        self.votes -= 1
        self.save
    end
end


text:
const
  helper = require('../../helper'),
  chai = require('chai')
chai.should()

const types = require(helper.requirePath('data/types'))

describe('data.types.Double', () => {
  it('Creates a Double (single value) instance from a string value', () => {
    const double = types.make(types.MKT_DOUBLE_VALUE, undefined, '0.00000005')
    double.constructor.name.should.equal('Double')
    double.toString().should.equal('5e-8')
    double.valueOf().should.equal('5e-8')
  })
  it('Creates a Double (single value) instance from a number value', () => {
    const double = types.make(types.MKT_DOUBLE_VALUE, undefined, 0.00000005)
    double.constructor.name.should.equal('Double')
    double.toString().should.equal('5e-8')
    double.valueOf().should.equal('5e-8')
  })
})


text:
app.controller('personaldataCtrl', ['$scope', '$routeParams', '$http', '$location', '$filter', '$q', 'ngTableParams', 'ngDialog', 'toaster', 'enums', function($scope, $routeParams, $http, $location, $filter, $q, ngTableParams, ngDialog, toaster, enums) {
    $scope.allomanymodok = enums.allomanymodok;
    $scope.nemek = enums.nemek;
    $scope.kozteruletTipusok = enums.kozteruletTipusok;
    $scope.munkakorJellegek = enums.munkakorJellegek;
    $scope.jogviszonyMegszunesenekModjai = enums.jogviszonyMegszunesenekModjai;
    $scope.csaladiAllapotok = enums.csaladiAllapotok;

    $scope.calculateNextMedicalExaminationDate = function() {
        if ($scope.selectedPersonaldata) {
            var utolsoOrvosiVizsgalatIdopontjaAsDate = $scope.selectedPersonaldata.orvosiVizsgalat.utolsoOrvosiVizsgalatIdopontja;
            var kovetkezoOrvosiVizsgalatIdopontjaAsDate = addMonths(utolsoOrvosiVizsgalatIdopontjaAsDate, $scope.selectedPersonaldata.orvosiVizsgalat.gyakorisag);
            $scope.selectedPersonaldata.orvosiVizsgalat.kovetkezoOrvosiVizsgalatIdopontja = kovetkezoOrvosiVizsgalatIdopontjaAsDate;
        }
    };

    var healthAssessmentAttributesToWatch = ['selectedPersonaldata.orvosiVizsgalat.utolsoOrvosiVizsgalatIdopontja', 'selectedPersonaldata.orvosiVizsgalat.gyakorisag'];
    for (var i=0;i<healthAssessmentAttributesToWatch.length;++i) {
        $scope.$watch(healthAssessmentAttributesToWatch[i], $scope.calculateNextMedicalExaminationDate);
    }
}]);

app.directive('personaldataBodyCreate', function() {
    return {
        restrict: 'E',
        templateUrl: 'module/personaldata/personaldata-body-create.html',
        controller: 'personaldataCtrl'
    };
});

app.directive('personaldataBodyEdit', function() {
    return {
        restrict: 'E',
        templateUrl: 'module/personaldata/personaldata-body-edit.html',
        controller: 'personaldataCtrl'
    };
});

app.directive('tabPersonalDetailsCreate', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-personal-details-create.html'
    };
});

app.directive('tabPersonalDetailsEdit', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-personal-details-edit.html'
    };
});

app.directive('tabJobClassification', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-job-classification.html'
    };
});

app.directive('tabEmploymentStatus', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-employment-status.html'
    };
});

app.directive('tabQualification', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-qualification.html'
    };
});

app.directive('tabReceivedItems', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-received-items.html'
    };
});

app.directive('tabFamily', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-family.html'
    };
});

app.directive('tabHealthAssessment', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-health-assessment.html'
    };
});

app.directive('tabVacation', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-vacation.html',
        controller: 'vacationsCtrl'
    };
});

app.directive('tabTimeAndAttendance', function() {
    return {
        require: '^personaldataBody',
        restrict: 'E',
        templateUrl: 'module/personaldata/tab-time-and-attendance.html',
        controller: 'timeandattendanceCtrl'
    };
});

app.directive('jobhistoryTable', function() {
    return {
        scope: true,
        restrict: 'E',
        templateUrl: 'module/personaldata/jobhistory/jobhistory-table.html',
        controller: 'jobhistoryCtrl'
    };
});

app.directive('qualificationsTable', function() {
    return {
        scope: true,
        restrict: 'E',
        templateUrl: 'module/personaldata/qualifications/qualifications-table.html',
        controller: 'qualificationsCtrl'
    };
});

app.directive('receiveditemsTable', function() {
    return {
        scope: true,
        restrict: 'E',
        templateUrl: 'module/personaldata/receiveditems/receiveditems-table.html',
        controller: 'receiveditemsCtrl'
    };
});

app.directive('familymembersTable', function() {
    return {
        scope: true,
        restrict: 'E',
        templateUrl: 'module/personaldata/familymembers/familymembers-table.html',
        controller: 'familymembersCtrl'
    };
});


text:
namespace StudentsAndCourses
{

    using System.Collections.Generic;

    using CoursesEnum;

    public class Course
    {
        private ICollection<Student> programmingList;
        private ICollection<Student> mathList;
        private ICollection<Student> algorithms;

        public Course()
        {
            programmingList = new List<Student>();
            mathList = new List<Student>();
            algorithms = new List<Student>();

            //AddStudentToCourse(new Student("Pesho"), CourseName.math);
            //AddStudentToCourse(new Student("Ivan"), CourseName.math);
            //AddStudentToCourse(new Student("Dragan"), CourseName.math);

        }

        public void AddStudentToCourse(Student student, CourseName course)
        {
            switch (course)
            {
                case CourseName.programming:
                    if (GetCountOfStudents(CourseName.programming) < 30)
                    {
                        programmingList.Add(student);
                    }
                    break;
                case CourseName.math:
                    if (GetCountOfStudents(CourseName.math) < 30)
                    {
                        mathList.Add(student);
                    }
                    break;
                case CourseName.algorithms:
                    if (GetCountOfStudents(CourseName.algorithms) < 30)
                    {
                        algorithms.Add(student);
                    }
                    break;
            }
        }

        public void RemoveStudentFromCourse(Student student, CourseName course)
        {
            switch (course)
            {
                case CourseName.programming:
                    programmingList.Remove(student);
                    break;
                case CourseName.math:
                    mathList.Remove(student);
                    break;
                case CourseName.algorithms:
                    algorithms.Remove(student);
                    break;
            }

        }

        public int GetCountOfStudents(CourseName course)
        {
            int count = 0;
            switch (course)
            {
                case CourseName.programming:
                    count = programmingList.Count;
                    break;
                case CourseName.math:
                    count = mathList.Count;
                    break;
                case CourseName.algorithms:
                    count = algorithms.Count;
                    break;
            }

            return count;
        }
    }
}


text:
@import CoreData;

#import "STKTableViewDataSource.h"

@interface STKTableViewDataSource () <ASTableViewDataSource>

@property (strong, nonatomic) NSMutableOrderedSet *mutableObjects;
@property (strong, nonatomic) NSOperationQueue *queue;

@property (copy, nonatomic) NSArray *sortDescriptors;
@property (copy, nonatomic) NSString *entityName;

@property (weak, nonatomic, readwrite) ASTableView *tableView;
@property (weak, nonatomic, readwrite) id <STKTableViewDataSourceDelegate> delegate;

@end

@implementation STKTableViewDataSource

#pragma mark - Lifecycle

- (instancetype)initWithTableView:(ASTableView *)tableView
                          objects:(NSArray *)objects
                  sortDescriptors:(NSArray *)sortDescriptors
                         delegate:(id<STKTableViewDataSourceDelegate>)delegate {
    self = [super init];

    if (self) {
        self.animateChanges = YES;

        self.queue = [NSOperationQueue mainQueue];
        self.queue.maxConcurrentOperationCount = 1;

        self.tableView = tableView;
        tableView.asyncDataSource = nil;
        tableView.asyncDataSource = self;

        self.mutableObjects = [NSMutableOrderedSet orderedSetWithArray:objects];
        self.sortDescriptors = sortDescriptors;
        [self.mutableObjects sortUsingDescriptors:sortDescriptors];

        self.delegate = delegate;
    }

    return self;
}

- (void)dealloc {
    [self.queue cancelAllOperations];

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (NSArray *)objects {
    return self.mutableObjects.array;
}

#pragma mark - Actions

- (void)registerForChangeNotificationsForContext:(NSManagedObjectContext *)context entityName:(NSString *)entityName {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeNSManagedObjectContext:) name:NSManagedObjectContextObjectsDidChangeNotification object:context];
    self.entityName = entityName;
}

- (void)unregisterForChangeNotificationsForContext:(NSManagedObjectContext *)context {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextObjectsDidChangeNotification object:context];
}

- (void)didChangeNSManagedObjectContext:(NSNotification *)notification {
    NSSet *deletedObjects = notification.userInfo[NSDeletedObjectsKey];

    if (self.entityName.length > 0) {
        NSManagedObjectContext *context = notification.object;
        NSDictionary *entitiesByName = context.persistentStoreCoordinator.managedObjectModel.entitiesByName;
        NSEntityDescription *entity = entitiesByName[self.entityName];

        if (entity) {
            NSSet *deletedEntities = [deletedObjects objectsPassingTest:^BOOL(id  _Nonnull obj, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:[NSManagedObject class]]) {
                    return [[obj entity] isKindOfEntity:entity];
                }
                else {
                    return NO;
                }
            }];

            if (deletedEntities.count > 0) {
                [self removeObjects:deletedEntities.allObjects completion:nil];
            }
        }
    }
}

#pragma mark - Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (NSInteger)self.mutableObjects.count;
}

- (ASCellNode *)tableView:(ASTableView *)tableView nodeForRowAtIndexPath:(NSIndexPath *)indexPath {
    id object = [self.mutableObjects objectAtIndex:(NSUInteger)indexPath.row];

    return [self.delegate tableView:tableView nodeForObject:object atIndexPath:indexPath];
}

- (void)tableViewLockDataSource:(ASTableView *)tableView {
    self.queue.suspended = YES;
}

- (void)tableViewUnlockDataSource:(ASTableView *)tableView {
    self.queue.suspended = NO;
}

- (void)addObjects:(NSArray *)objects completion:(void (^)(NSArray *))completion {
    if (objects.count > 0) {
        __weak __typeof(self) wself = self;

        [self.queue addOperationWithBlock:^{
            NSMutableOrderedSet *newObjects = [NSMutableOrderedSet orderedSetWithArray:objects];
            [newObjects minusOrderedSet:wself.mutableObjects];

            NSMutableOrderedSet *updatedObjects = [NSMutableOrderedSet orderedSetWithArray:objects];
            [updatedObjects intersectOrderedSet:wself.mutableObjects];

            [wself.mutableObjects unionOrderedSet:newObjects];
            [wself.mutableObjects sortUsingDescriptors:wself.sortDescriptors];

            NSIndexSet *newIndexes = [wself.mutableObjects indexesOfObjectsPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                return [newObjects containsObject:obj];
            }];

            NSIndexSet *updatedIndexes = [wself.mutableObjects indexesOfObjectsPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                return [updatedObjects containsObject:obj];
            }];

            NSMutableArray *newIndexPaths = [NSMutableArray array];
            [newIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
                [newIndexPaths addObject:[NSIndexPath indexPathForRow:(NSInteger)idx inSection:0]];
            }];

            NSMutableArray *updatedIndexPaths = [NSMutableArray array];
            [updatedIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
                [updatedIndexPaths addObject:[NSIndexPath indexPathForRow:(NSInteger)idx inSection:0]];
            }];

            [wself.tableView beginUpdates];

            [wself.tableView insertRowsAtIndexPaths:newIndexPaths withRowAnimation:UITableViewRowAnimationNone];

            [wself.tableView endUpdatesAnimated:wself.animateChanges completion:^(BOOL completed) {
                for (NSIndexPath *indexPath in updatedIndexPaths) {
                    if ([wself tableView:wself.tableView containsIndexPath:indexPath]) {
                        ASCellNode *node = [wself.tableView nodeForRowAtIndexPath:indexPath];
                        id object = [wself.mutableObjects objectAtIndex:(NSUInteger)indexPath.row];

                        if (node) {
                            [wself.delegate tableView:wself.tableView updateNode:node forObject:object atIndexPath:indexPath];
                        }
                    }
                }

                [wself.delegate tableViewDidChangeContent:wself.tableView];

                if (completion) {
                    completion(newIndexPaths);
                }
            }];
        }];
    }
    else {
        __weak __typeof(self) wself = self;

        [self.queue addOperationWithBlock:^{
            [wself.delegate tableViewDidChangeContent:wself.tableView];

            if (completion) {
                completion(nil);
            }
        }];
    }
}

- (void)removeObjects:(NSArray *)objects completion:(void (^)(NSArray *))completion {
    if (objects.count > 0) {
        __weak __typeof(self) wself = self;

        [self.queue addOperationWithBlock:^{
            NSMutableOrderedSet *removedObjects = [NSMutableOrderedSet orderedSetWithArray:objects];

            NSIndexSet *removedIndexes = [self.mutableObjects indexesOfObjectsPassingTest:^BOOL(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                return [removedObjects containsObject:obj];
            }];

            NSMutableArray *removedIndexPaths = [NSMutableArray array];
            [removedIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
                [removedIndexPaths addObject:[NSIndexPath indexPathForRow:(NSInteger)idx inSection:0]];
            }];

            [wself.mutableObjects minusOrderedSet:removedObjects];
            [wself.mutableObjects sortUsingDescriptors:wself.sortDescriptors];

            [wself.tableView beginUpdates];

            [wself.tableView deleteRowsAtIndexPaths:removedIndexPaths withRowAnimation:UITableViewRowAnimationNone];

            [wself.tableView endUpdatesAnimated:wself.animateChanges completion:^(BOOL completed) {
                [wself.delegate tableViewDidChangeContent:wself.tableView];

                if (completion) {
                    completion([removedIndexPaths copy]);
                }
            }];
        }];
    }
    else {
        __weak __typeof(self) wself = self;

        [self.queue addOperationWithBlock:^{
            [wself.delegate tableViewDidChangeContent:wself.tableView];

            if (completion) {
                completion(nil);
            }
        }];
    }
}

- (void)replaceAllObjectsWithObjects:(NSArray *)objects completion:(void (^)())completion {
    __weak __typeof(self) wself = self;

    [self.queue addOperationWithBlock:^{
        [wself.mutableObjects removeAllObjects];
        [wself.mutableObjects addObjectsFromArray:objects];

        [wself.tableView beginUpdates];

        [wself.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];

        [wself.tableView endUpdatesAnimated:wself.animateChanges completion:^(BOOL completed) {
            [wself.delegate tableViewDidChangeContent:wself.tableView];

            if (completion) {
                completion();
            }
        }];
    }];
}

#pragma mark - Helpers

- (BOOL)tableView:(ASTableView *)tableView containsIndexPath:(NSIndexPath *)indexPath {
    BOOL containsIndexPath = NO;

    if (indexPath.section < tableView.numberOfSections &&
        indexPath.row < [tableView numberOfRowsInSection:indexPath.section]) {
        containsIndexPath = YES;
    }

    return containsIndexPath;
}

@end


text: Code for the Enigma 2016 Making an Instrument group at CCGS


text:
title: Using Volumes with Docker can Cause Problems with SELinux
author: dwalsh
date: 2015-06-15 17:52:00 UTC
tags: SELinux, Volumes, Docker
comments: true
published: true
---

When using SELinux for controlling processes within a container, you need to make sure any content that gets volume mounted into the container is readable, and potentially writable, depending on the use case.

By default, Docker container processes run with the `system_u:system_r:svirt_lxc_net_t:s0` label.  The `svirt_lxc_net_t` type is allowed to read/execute most content under /usr, but it is not allowed to use most other types on the system.

READMORE

If you want to volume mount content under `/var`, for example, into a container you need to set the labels on this content.  In the `docker run` man page we mention this.

```
man docker-run
...
When  using  SELinux,  be  aware that the host has no knowledge of container SELinux policy. Therefore, in the above example, if SELinux policy  is enforced,  the /var/db directory is not  writable to the container. A "Permission Denied" message will occur and an avc: message in the host's syslog.

To  work  around  this, at time of writing this man page, the following command needs to be run in order for the  proper  SELinux  policy  type label to be attached to the host directory:

# chcon -Rt svirt_sandbox_file_t /var/db
```

This got easier recently since Docker finally merged a patch which will be showing up in docker-1.7 (We have been carrying the patch in docker-1.6 on RHEL, CentOS, and Fedora).

This patch adds support for "z" and "Z" as options on the volume mounts (-v).

For example:

```
  docker run -v /var/db:/var/db:z rhel7 /bin/sh
```
Will automatically do the `chcon -Rt svirt_sandbox_file_t /var/db` described in the man page.

Even better, you can use `Z`.

```
  docker run -v /var/db:/var/db:Z rhel7 /bin/sh
```

This will label the content inside the container with the exact MCS label that the container will run with, basically it runs `chcon -Rt svirt_sandbox_file_t -l s0:c1,c2 /var/db` where `s0:c1,c2` differs for each container.

I have a [bug](https://bugzilla.redhat.com/show_bug.cgi?id=1230098)
 that was reported to me, that might become common. The user got AVC's that looked like the following.

Raw Audit Messages

_type=AVC msg=audit(1433926625.524:1347): avc:  denied  { write } for  pid=29280 comm="launch" name="addons" dev="dm-2" ino=2491404 scontext=system_u:system_r:svirt_lxc_net_t:**s0:c147,c266** tcontext=system_u:object_r:svirt_sandbox_file_t:**s0:c372,c410** tclass=dir permissive=0_

Notice the bolded MCS labels.

The problem here was the user created a volume and labeled it from one container with the "Z" for one container, then attempted to share it in another container.  Which SELinux denied since the Multi-Category Security (MCS) labels differed.

I told the reporter that he needs to mount it using Z or z, since at some point the volume got a different containers labels on it.

Your container processes are running with this label, `system_u:system_r:svirt_lxc_net_t:s0:c147,c266` Notice the `s0:c147,c266`
The volume mount is labeled `system_u:object_r:svirt_sandbox_file_t:s0:c372,c410` Notice the MCS label `s0:c372,c410` MCS Security prevents read/write of content with different MCS labels. However it will allow read/write of content labeled with an s0 label.

If you volume mount a image with `-v /SOURCE:/DESTINATION:z` docker will automatically  relabel the content for you to s0. If you volume mount with a "Z", then the label will be specific to the container, and not be able to be shared between containers.


text:
Johns-Hopkins-600.107
=====================

Game created as part of 600.107 Java course at Johns Hopkins under open-sourced MIT License


text:
package com.lqldev.spadgerweather;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    private static Context appContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        appContext = getApplicationContext();
        setContentView(R.layout.activity_main);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (preferences.getString("weather",null) != null) {
            Intent intent = new Intent(this,WeatherActivity.class);
            startActivity(intent);
            finish();
        }
    }
    public static Context getAppContext(){
        return appContext;
    }
}


text: sudo apt-get -y install wfuzz


text:
package org.apache.drill.exec.planner.logical;

import org.eigenbase.rel.FilterRel;
import org.eigenbase.rel.RelNode;
import org.eigenbase.relopt.Convention;
import org.eigenbase.relopt.RelOptRule;
import org.eigenbase.relopt.RelOptRuleCall;

/**
 * Rule that converts a {@link org.eigenbase.rel.FilterRel} to a Drill "filter" operation.
 */
public class DrillFilterRule extends RelOptRule {
  public static final RelOptRule INSTANCE = new DrillFilterRule();

  private DrillFilterRule() {
    super(RelOptHelper.any(FilterRel.class, Convention.NONE), "DrillFilterRule");
  }

  @Override
  public void onMatch(RelOptRuleCall call) {
    final FilterRel filter = (FilterRel) call.rel(0);
    final RelNode input = filter.getChild();
    //final RelTraitSet traits = filter.getTraitSet().plus(DrillRel.DRILL_LOGICAL);
    final RelNode convertedInput = convert(input, input.getTraitSet().plus(DrillRel.DRILL_LOGICAL));
    call.transformTo(new DrillFilterRel(filter.getCluster(), convertedInput.getTraitSet(), convertedInput, filter.getCondition()));
  }
}


text:
import sys

line = sys.stdin.readline()
while line:
    if len(line.strip()) == 1:
        print('15', flush=True)
    else:
        print('liar', flush=True)
    line = sys.stdin.readline()


text:
import xml.parsers.expat  # you may need to install this package

### The entries file parser in tools/client-side/change-svn-wc-format.py
### handles the WC format for Subversion 1.4 and 1.5, which is no
### longer in XML.

class svn_entry:
  "An object that represents an entry from an 'entries' file."

  def __init__(self, attributes):   # constructor
    self.atts = attributes

  def prettyprint(self):
    print(" Entryname: %s" % self.atts['name'])
    print("      Kind: %s" % self.atts['kind'])
    print("  Revision: %s" % self.atts['revision'])
    print("  Ancestor: %s" % self.atts['ancestor'])
    print("  all atts: %s" % self.atts)
    print("")

class svn_entryparser:
  "A class to parse an 'entries' file."

  def __init__(self):   # constructor
    self.entry_dict = {}
    self.parser = xml.parsers.expat.ParserCreate()
    self.parser.StartElementHandler = self.handle_start_tag

  def handle_start_tag(self, name, attrs):
    "Expat callback that receives a new open-tag."

    if 'name' in attrs:
      entry = svn_entry(attrs) # create new entry object

      # Derive missing values
      if 'kind' not in entry.atts:
        entry.atts['kind'] = 'file' # default kind if none mentioned
      if 'revision' not in entry.atts:
        if "" in self.entry_dict:
          parent = self.entry_dict[""]
          entry.atts['revision'] = parent.atts['revision']
      if 'ancestor' not in entry.atts:
        if "" in self.entry_dict:
          parent = self.entry_dict[""]
          entry.atts['ancestor'] = parent.atts['ancestor'] + '/' \
                                   + entry.atts['name']

      self.entry_dict[attrs['name']] = entry  # store the new entry

# The main exported routine
def get_entries(path):
  "Parse the entries file at PATH and return a list of svn_entry objects."

  entryparser = svn_entryparser() # make a parser instance
  fp = open(path, 'r')
  entryparser.parser.ParseFile(fp)
  fp.close()
  return entryparser.entry_dict

### End of file.


text:
from enum import Enum
from datetime import datetime
from json_serializable import JsonSerializable

class Category(Enum):
    technology = 1
    life = 2

class BlogPost(JsonSerializable):

    def __init__(self, title="", category=Category.technology, date=None, content=""):
        super().__init__()
        self.title = title
        self.category = category
        self.date = date
        self.content = content

    def __str__(self):
        return "{0}@{1} [{2}]: {3}".format(self.title, self.date, self.category, self.content)

if __name__ == "__main__":
    # serialize
    post = BlogPost("About Python", Category.technology, datetime.today(), "I learned about Python.")
    post_json = post.to_json()  # serialize the class object
    print("original:{0}".format(post))
    print("serialized:{0}".format(post_json))

    # deserialize
    another_post_json = '{"title": "About Todays Lunch", "category": 2, "date": "2014/1/1 12:00:00", "content":"I ate Sushi." }'
    another_post = BlogPost().load_json(another_post_json)
    print("deserialized:{0}".format(another_post))


text:
// @(#)SeismicProp.java   12/2003
// Copyright (c) 1998-2003, Distributed Real-time Computing Lab (DRCL)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
// 3. Neither the name of "DRCL" nor the names of its contributors may be used
//    to endorse or promote products derived from this software without specific
//    prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//

package drcl.inet.sensorsim;

import drcl.comp.Port;
import drcl.comp.Contract;

/** This class implements the seismic propagation model.
*
* @author Ahmed Sobeih
* @version 1.0, 12/19/2003
*/
public class SeismicProp extends SensorRadioPropagationModel
{
	double d0 ;
	/** Attenuation Factor  */
	double atnFactor ;

	public SeismicProp()
	{
		super();
		d0 = 0.1 ;
		atnFactor = 1.0 ;
	}

 	public SeismicProp(String id_)
	{
		super(id_);
		d0 = 0.1 ;
		atnFactor = 1.0 ;
	}

	/** Sets the minimum value of the distance between two nodes */
	public void setD0(double d0_)
	{
		d0 = d0_ ;
	}

	/** Sets the attenuation factor  */
	public void setAtnFactor(double atnFactor_)
	{
		atnFactor = atnFactor_ ;
	}

	/** Calculates the signal strength of a received signal based on the distance between the transmitter and the receiver and also based on the attenuation factor  */
    protected synchronized double calculateReceivedSignalStrength(Object data_) {
        SensorRadioPropagationQueryContract.Message msg = (SensorRadioPropagationQueryContract.Message) data_;

        double Pt; // power with which the packet was sent
		   // Pt is included in the request (i.e., query)
	double Xs, Ys, Zs; // location of sender
	double Xr, Yr, Zr; // location of receiver
        double Pr; // power with which the packet was received
		   // Pr is included in the reply

	double d;			// distance between sender and receiver

	Xs = msg.getXs();
        Ys = msg.getYs();
        Zs = msg.getZs();
        Xr = msg.getXr();
        Yr = msg.getYr();
        Zr = msg.getZr();
        Pt = msg.getPt();

	d = Math.sqrt((Xs - Xr) * (Xs - Xr)
	   + (Ys - Yr) * (Ys - Yr)
	   + (Zs - Zr) * (Zs - Zr));

	d = Math.max(d, d0);

	Pr = Pt/ (Math.pow(d, atnFactor));
	return Pr;
    }
       	public String info() {
        return "SeismicProp" + "\n";
    }
}


text:
'use strict';

const models = require('./index');

/**
 * Class representing a PivotSuggestions.
 */
class PivotSuggestions {
  /**
   * Create a PivotSuggestions.
   * @member {string} pivot
   * @member {array} suggestions
   */
  constructor() {
  }

  /**
   * Defines the metadata of PivotSuggestions
   *
   * @returns {object} metadata of PivotSuggestions
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'PivotSuggestions',
      type: {
        name: 'Composite',
        className: 'PivotSuggestions',
        modelProperties: {
          pivot: {
            required: true,
            serializedName: 'pivot',
            type: {
              name: 'String'
            }
          },
          suggestions: {
            required: true,
            serializedName: 'suggestions',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'QueryElementType',
                  type: {
                    name: 'Composite',
                    className: 'Query'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = PivotSuggestions;


text:
set -ex

rm -fr geniatagger-python-0.1 geniatagger-3.0.1

# First let's install GeniaTagger

wget http://www.nactem.ac.uk/tsujii/GENIA/tagger/geniatagger-3.0.1.tar.gz

tar xvf geniatagger-3.0.1.tar.gz

cd geniatagger-3.0.1

# Fix a missing header
echo "#include <cstdlib>" > morph2.cpp
cat morph.cpp >> morph2.cpp
mv morph2.cpp morph.cpp

make

cd -

rm geniatagger-3.0.1.tar.gz

# Then let's install a Python wrapper for it
wget https://pypi.python.org/packages/cf/19/f61aa1318ca440a834ce433c49832047919a9665c421a633fe32896455fb/geniatagger-python-0.1.tar.gz
tar xvf geniatagger-python-0.1.tar.gz
rm geniatagger-python-0.1.tar.gz
cd geniatagger-python-0.1
python setup.py install
cd ../


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-securitygroups.html

module Stratosphere.ResourceProperties.EC2SpotFleetGroupIdentifier where

import Stratosphere.ResourceImports

-- | Full data type definition for EC2SpotFleetGroupIdentifier. See
-- 'ec2SpotFleetGroupIdentifier' for a more convenient constructor.
data EC2SpotFleetGroupIdentifier =
  EC2SpotFleetGroupIdentifier
  { _eC2SpotFleetGroupIdentifierGroupId :: Val Text
  } deriving (Show, Eq)

instance ToJSON EC2SpotFleetGroupIdentifier where
  toJSON EC2SpotFleetGroupIdentifier{..} =
    object $
    catMaybes
    [ (Just . ("GroupId",) . toJSON) _eC2SpotFleetGroupIdentifierGroupId
    ]

-- | Constructor for 'EC2SpotFleetGroupIdentifier' containing required fields
-- as arguments.
ec2SpotFleetGroupIdentifier
  :: Val Text -- ^ 'ecsfgiGroupId'
  -> EC2SpotFleetGroupIdentifier
ec2SpotFleetGroupIdentifier groupIdarg =
  EC2SpotFleetGroupIdentifier
  { _eC2SpotFleetGroupIdentifierGroupId = groupIdarg
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-spotfleetrequestconfigdata-launchspecifications-securitygroups.html#cfn-ec2-spotfleet-groupidentifier-groupid
ecsfgiGroupId :: Lens' EC2SpotFleetGroupIdentifier (Val Text)
ecsfgiGroupId = lens _eC2SpotFleetGroupIdentifierGroupId (\s a -> s { _eC2SpotFleetGroupIdentifierGroupId = a })


text:
<?php

namespace Symfony\Component\Messenger\Tests\Transport\Receiver;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
use Symfony\Component\Messenger\Transport\Receiver\SingleMessageReceiver;

class SingleMessageReceiverTest extends TestCase
{
    public function testItReceivesOnlyOneMessage()
    {
        $innerReceiver = $this->createMock(ReceiverInterface::class);
        $envelope = new Envelope(new \stdClass());

        $receiver = new SingleMessageReceiver($innerReceiver, $envelope);
        $received = $receiver->get();
        $this->assertCount(1, $received);
        $this->assertSame($received[0], $envelope);

        $this->assertEmpty($receiver->get());
    }

    public function testCallsAreForwarded()
    {
        $envelope = new Envelope(new \stdClass());

        $innerReceiver = $this->createMock(ReceiverInterface::class);
        $innerReceiver->expects($this->once())->method('ack')->with($envelope);
        $innerReceiver->expects($this->once())->method('reject')->with($envelope);

        $receiver = new SingleMessageReceiver($innerReceiver, $envelope);
        $receiver->ack($envelope);
        $receiver->reject($envelope);
    }
}