text:
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404, HttpResponseForbidden
from django.shortcuts import redirect, render
from django.views.decorators.cache import cache_page, never_cache
from django.views.decorators.http import require_POST

import commonware.log
from funfactory.urlresolvers import reverse
from tower import ugettext as _

from mozillians.common.decorators import allow_public, allow_unvouched
from mozillians.common.middleware import LOGIN_MESSAGE, GET_VOUCHED_MESSAGE
from mozillians.groups.helpers import stringify_groups
from mozillians.groups.models import Group
from mozillians.users.models import (COUNTRIES, EMPLOYEES, MOZILLIANS,
                               PUBLIC, PRIVILEGED, UserProfile)
from mozillians.users.tasks import remove_from_basket_task

import forms
from models import Invite

log = commonware.log.getLogger('m.phonebook')
BAD_VOUCHER = 'Unknown Voucher'

@never_cache
@allow_public
def home(request):
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        my_groups = profile.groups.exclude(steward=None).order_by('name')
        curated_groups = Group.get_curated()
        data = dict(groups=my_groups, curated_groups=curated_groups)
        return render(request, 'phonebook/home.html', data)
    else:
        return render(request, 'phonebook/home.html')

@allow_public
@never_cache
def view_profile(request, username):
    """View a profile by username."""
    data = {}
    if (request.user.is_authenticated() and request.user.username == username):
        # own profile
        view_as = request.GET.get('view_as', 'myself')
        profile = request.user.userprofile
        if view_as == 'anonymous':
            profile = (UserProfile.objects
                       .privacy_level(PUBLIC).get(user__username=username))
        elif view_as == 'mozillian':
            profile = (UserProfile.objects
                       .privacy_level(MOZILLIANS).get(user__username=username))
        elif view_as == 'employee':
            profile = (UserProfile.objects
                       .privacy_level(EMPLOYEES).get(user__username=username))
        elif view_as == 'privileged':
            profile = (UserProfile.objects
                       .privacy_level(PRIVILEGED).get(user__username=username))
        data['privacy_mode'] = view_as
    else:
        userprofile_query = UserProfile.objects.filter(user__username=username)
        public_profile_exists = userprofile_query.public().exists()
        profile_exists = userprofile_query.exists()
        profile_complete = userprofile_query.exclude(full_name='').exists()

        if not public_profile_exists:
            if not request.user.is_authenticated():
                # you have to be authenticated to continue
                messages.warning(request, LOGIN_MESSAGE)
                return login_required(view_profile)(request, username)
            if not request.user.userprofile.is_vouched:
                # you have to be vouched to continue
                messages.error(request, GET_VOUCHED_MESSAGE)
                return redirect('home')

        if not profile_exists or not profile_complete:
            raise Http404

        profile = UserProfile.objects.get(user__username=username)
        profile.set_instance_privacy_level(profile.privacy_level)

        if (not profile.is_vouched
            and request.user.is_authenticated()
            and request.user.userprofile.is_vouched):
            data['vouch_form'] = (
                forms.VouchForm(initial={'vouchee': profile.pk}))

    data['shown_user'] = profile.user
    data['profile'] = profile
    return render(request, 'phonebook/profile.html', data)

@allow_unvouched
@never_cache
def edit_profile(request):
    """Edit user profile view."""
    # Don't user request.user
    user = User.objects.get(pk=request.user.id)
    profile = user.get_profile()
    user_groups = stringify_groups(profile.groups.all().order_by('name'))
    user_skills = stringify_groups(profile.skills.all().order_by('name'))
    user_languages = stringify_groups(profile.languages.all().order_by('name'))

    user_form = forms.UserForm(request.POST or None, instance=user)
    profile_form = forms.ProfileForm(
        request.POST or None, request.FILES or None, instance=profile,
        initial=dict(groups=user_groups, skills=user_skills,
                     languages=user_languages),
        locale=request.locale)

    if request.method == 'POST':
        if (user_form.is_valid() and profile_form.is_valid()):
            old_username = request.user.username
            user_form.save()
            profile_form.save()

            # Notify the user that their old profile URL won't work.
            if user.username != old_username:
                messages.info(request, _(u'You changed your username; please '
                                         'note your profile URL has also '
                                         'changed.'))
            return redirect(reverse('profile', args=[user.username]))

    d = dict(profile_form=profile_form,
             user_form=user_form,
             mode='edit',
             user_groups=user_groups,
             my_vouches=UserProfile.objects.filter(vouched_by=profile),
             profile=profile,
             apps=user.apiapp_set.filter(is_active=True))

    # If there are form errors, don't send a 200 OK.
    status = 400 if (profile_form.errors or user_form.errors) else 200
    return render(request, 'phonebook/edit_profile.html', d, status=status)

@allow_unvouched
@never_cache
def confirm_delete(request):
    """Display a confirmation page asking the user if they want to
    leave.

    """
    return render(request, 'phonebook/confirm_delete.html')

@allow_unvouched
@never_cache
@require_POST
def delete(request):
    user_profile = request.user.get_profile()
    remove_from_basket_task.delay(user_profile.id)
    user_profile.anonymize()
    log.info('Deleting %d' % user_profile.user.id)
    logout(request)
    return redirect(reverse('home'))

@allow_public
def search(request):
    num_pages = 0
    limit = None
    people = []
    show_pagination = False
    form = forms.SearchForm(request.GET)
    groups = None
    curated_groups = None

    if form.is_valid():
        query = form.cleaned_data.get('q', u'')
        limit = form.cleaned_data['limit']
        include_non_vouched = form.cleaned_data['include_non_vouched']
        page = request.GET.get('page', 1)
        curated_groups = Group.get_curated()
        public = not (request.user.is_authenticated()
                      and request.user.userprofile.is_vouched)

        profiles = UserProfile.search(query, public=public,
                                      include_non_vouched=include_non_vouched)
        groups = Group.search(query)

        paginator = Paginator(profiles, limit)

        try:
            people = paginator.page(page)
        except PageNotAnInteger:
            people = paginator.page(1)
        except EmptyPage:
            people = paginator.page(paginator.num_pages)

        if profiles.count() == 1 and not groups:
            return redirect(reverse('profile', args=[people[0].user.username]))

        if paginator.count > forms.PAGINATION_LIMIT:
            show_pagination = True
            num_pages = len(people.paginator.page_range)

    d = dict(people=people,
             form=form,
             limit=limit,
             show_pagination=show_pagination,
             num_pages=num_pages,
             groups=groups,
             curated_groups=curated_groups)

    if request.is_ajax():
        return render(request, 'search_ajax.html', d)

    return render(request, 'phonebook/search.html', d)

@allow_public
@cache_page(60 * 60 * 168)  # 1 week.
def search_plugin(request):
    """Render an OpenSearch Plugin."""
    return render(request, 'phonebook/search_opensearch.xml',
                  content_type='application/opensearchdescription+xml')

def invite(request):
    profile = request.user.userprofile
    invite_form = forms.InviteForm(request.POST or None,
                                   instance=Invite(inviter=profile))
    if request.method == 'POST' and invite_form.is_valid():
        invite = invite_form.save()
        invite.send(sender=profile)
        msg = _(u"%s has been invited to Mozillians. They'll receive an email "
                 "with instructions on how to join. You can "
                 "invite another Mozillian if you like." % invite.recipient)
        messages.success(request, msg)
        return redirect(reverse('profile', args=[request.user.username]))

    return render(request, 'phonebook/invite.html',
                  {'invite_form': invite_form})

@require_POST
def vouch(request):
    """Vouch a user."""
    form = forms.VouchForm(request.POST)

    if form.is_valid():
        p = UserProfile.objects.get(pk=form.cleaned_data.get('vouchee'))
        p.vouch(request.user.get_profile())

        # Notify the current user that they vouched successfully.
        msg = _(u'Thanks for vouching for a fellow Mozillian! '
                 'This user is now vouched!')
        messages.info(request, msg)
        return redirect(reverse('profile', args=[p.user.username]))

    return HttpResponseForbidden

def list_mozillians_in_location(request, country, region=None, city=None):
    country = country.lower()
    country_name = COUNTRIES.get(country, country)
    queryset = UserProfile.objects.vouched().filter(country=country)
    if city:
        queryset = queryset.filter(city__iexact=city)
    if region:
        queryset = queryset.filter(region__iexact=region)

    data = {'people': queryset,
            'country_name': country_name,
            'city_name': city,
            'region_name': region}
    return render(request, 'phonebook/location-list.html', data)


text:
<?php

namespace Drupal\Tests\content_translation\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Tests the content translation UI check skip.
 *
 * @group content_translation
 */
class ContentTranslationUISkipTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['content_translation_test', 'user', 'node'];

  /**
   * Tests the content_translation_ui_skip key functionality.
   */
  public function testUICheckSkip() {
    $admin_user = $this->drupalCreateUser([
      'translate any entity',
      'administer content translation',
      'administer languages'
    ]);
    $this->drupalLogin($admin_user);
    // Visit the content translation.
    $this->drupalGet('admin/config/regional/content-language');

    // Check the message regarding UI integration.
    $this->assertText('Test entity - Translatable skip UI check');
    $this->assertText('Test entity - Translatable check UI (Translation is not supported)');
  }

}

redpajama_set_name: RedPajamaGithub


text:
import axios from 'axios';
import uuid from 'uuid/v1';
import he from 'he';
import { parse } from 'fast-xml-parser/src/parser';

class ChatBot {
    constructor(botID) {
        this.botID = botID;
    }

    Think(thought) {
        return new Promise((resolve, reject) => {
            const data = '?input=' + encodeURIComponent(thought) + '&' +
                'botid=' + this.botID + '&' +
                'uuid=' + uuid();

            axios.get('https://www.pandorabots.com/pandora/talk-xml' + data).then(response => {
                resolve(he.decode(parse(response.data).result.that));
            }).catch(err => {
                reject(null);
            });
        });
    }
}

export default ChatBot;


text:
package com.rey.material.demo;

import android.annotation.TargetApi;
import android.os.Build;
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.Toast;

import com.rey.material.app.DialogFragment;
import com.rey.material.app.Recurring;
import com.rey.material.app.RecurringPickerDialog;
import com.rey.material.widget.Button;
import com.rey.material.widget.FloatingActionButton;

import java.util.Calendar;

public class ButtonFragment extends Fragment{

	public static ButtonFragment newInstance(){
		ButtonFragment fragment = new ButtonFragment();

		return fragment;
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_button, container, false);

		Button bt_flat = (Button)v.findViewById(R.id.button_bt_flat);
		Button bt_flat_color = (Button)v.findViewById(R.id.button_bt_flat_color);
		Button bt_flat_wave = (Button)v.findViewById(R.id.button_bt_flat_wave);
		Button bt_flat_wave_color = (Button)v.findViewById(R.id.button_bt_flat_wave_color);
		Button bt_raise = (Button)v.findViewById(R.id.button_bt_raise);
		Button bt_raise_color = (Button)v.findViewById(R.id.button_bt_raise_color);
		Button bt_raise_wave = (Button)v.findViewById(R.id.button_bt_raise_wave);
		Button bt_raise_wave_color = (Button)v.findViewById(R.id.button_bt_raise_wave_color);
		FloatingActionButton bt_float = (FloatingActionButton)v.findViewById(R.id.button_bt_float);
        FloatingActionButton bt_float_color = (FloatingActionButton)v.findViewById(R.id.button_bt_float_color);
        FloatingActionButton bt_float_wave = (FloatingActionButton)v.findViewById(R.id.button_bt_float_wave);
        FloatingActionButton bt_float_wave_color = (FloatingActionButton)v.findViewById(R.id.button_bt_float_wave_color);

		View.OnClickListener listener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getActivity(), "Button Clicked!\nEvent's fired when in anim end.", Toast.LENGTH_SHORT).show();
                if(v instanceof  FloatingActionButton){
                    FloatingActionButton bt = (FloatingActionButton)v;
                    bt.setLineMorphingState((bt.getLineMorphingState() + 1) % 2, true);
                }
			}
		};

		View.OnClickListener listener_delay = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Toast.makeText(getActivity(), "Button Clicked!\nEvent's fired when out anim end.", Toast.LENGTH_SHORT).show();
                if(v instanceof  FloatingActionButton){
                    FloatingActionButton bt = (FloatingActionButton)v;
                    bt.setLineMorphingState((bt.getLineMorphingState() + 1) % 2, true);
                }
			}
		};

		bt_flat.setOnClickListener(listener);
		bt_flat_wave.setOnClickListener(listener);
		bt_raise.setOnClickListener(listener);
		bt_raise_wave.setOnClickListener(listener);
		bt_float.setOnClickListener(listener);
		bt_float_wave.setOnClickListener(listener);

		bt_flat_color.setOnClickListener(listener_delay);
		bt_flat_wave_color.setOnClickListener(listener_delay);
		bt_raise_color.setOnClickListener(listener_delay);
		bt_raise_wave_color.setOnClickListener(listener_delay);
		bt_float_color.setOnClickListener(listener_delay);
		bt_float_wave_color.setOnClickListener(listener_delay);

//        bt_flat.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View v) {
//                RecurringPickerDialog.Builder builder = new RecurringPickerDialog.Builder(R.style.Material_App_Dialog_Light){
//                    @Override
//                    public void onPositiveActionClicked(DialogFragment fragment) {
//                        RecurringPickerDialog dialog = (RecurringPickerDialog)fragment.getDialog();
//                        Toast.makeText(fragment.getActivity(), dialog.getRecurring().toString(), Toast.LENGTH_LONG).show();
//                        fragment.dismiss();
//                    }
//
//                    @Override
//                    public void onNegativeActionClicked(DialogFragment fragment) {
//                        Toast.makeText(fragment.getActivity(), "Cancelled", Toast.LENGTH_SHORT).show();
//                        fragment.dismiss();
//                    }
//                };
//                Recurring recurring = new Recurring();
//                recurring.setStartTime(System.currentTimeMillis());
//                recurring.setRepeatMode(Recurring.REPEAT_WEEKLY);
//                recurring.setEnabledWeekday(Calendar.SUNDAY, true);
//                recurring.setEnabledWeekday(Calendar.TUESDAY, true);
//                builder.recurring(recurring)
//                        .datePickerLayoutStyle(R.style.Material_App_Dialog_DatePicker_Light)
//                        .positiveAction("OK")
//                        .negativeAction("CANCEL");
//
//                DialogFragment fragment = DialogFragment.newInstance(builder);
//                fragment.show(getFragmentManager(), null);
//            }
//        });

		return v;
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
	}

}


text:
package org.apache.druid.query.aggregation.histogram;

import org.apache.druid.testing.InitializedNullHandlingTest;
import org.junit.Assert;
import org.junit.Test;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class MaxPostAggregatorTest extends InitializedNullHandlingTest
{
  @Test
  public void testComparator()
  {
    final String aggName = "doubleWithNulls";
    Map<String, Object> metricValues = new HashMap<>();

    MaxPostAggregator max = new MaxPostAggregator("max", aggName);
    Comparator comp = max.getComparator();
    ApproximateHistogram histo1 = new ApproximateHistogram();
    metricValues.put(aggName, histo1);

    Object before = max.compute(metricValues);

    ApproximateHistogram histo2 = new ApproximateHistogram();
    histo2.offer(1.0f);
    metricValues.put(aggName, histo2);
    Object after = max.compute(metricValues);

    Assert.assertEquals(-1, comp.compare(before, after));
    Assert.assertEquals(0, comp.compare(before, before));
    Assert.assertEquals(0, comp.compare(after, after));
    Assert.assertEquals(1, comp.compare(after, before));
  }
}


text:
using System;
using System.Collections.Generic;
using System.Drawing;

using Grasshopper.Kernel;
using Rhino.Geometry;

namespace Physarealm.Setting
{
    public abstract class AbstractSettingComponent : AbstractComponent
    {
        /// <summary>
        /// Initializes a new instance of the AbstractSettingComponent class.
        /// </summary>
        public AbstractSettingComponent(string name, string nickname, string description,
                                    Bitmap icon, string componentGuid)
            : base(name, nickname,
                description,
                "Physarealm", "Setting", icon, componentGuid)
        {
        }

    }
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CompositionExpressionToolkit.Ref")]
[assembly: AssemblyDescription("This project contains class definitions for CompositionExpressionToolkit. These classes define the surface area for the C# compiler and Visual Studio Intellisense ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CompositionExpressionToolkit.Ref")]
[assembly: AssemblyCopyright("Copyright ©  2016 Ratish Philip")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: ComVisible(false)]


text:
[RadTrack](https://github.com/radiasoft/radtrack) simplifies the use of
particle accelerator codes.

### To Run RadTrack

Inside container, you can start RadTrack with:

```bash
radia-run-radtrack
```

### Build Info

* [Vagrant repository](https://atlas.hashicorp.com/radiasoft/boxes/radtrack)
* [Docker repository](https://hub.docker.com/r/radiasoft/radtrack)
* [Base container config: radiasoft/beamsim](https://github.com/radiasoft/containers/tree/master/vagrant/radiasoft/beamsim)


text:
module TokyoMetro::Factory::Convert::Customize::Api::TrainTimetable::TrainRelationsOnMarunouchiBranchLine
end


text:
package com.ncode.android.apps.schedo.iowear.fragments;

import com.ncode.android.apps.schedo.iowear.OnQuestionAnsweredListener;

import android.app.Fragment;

/**
 * The base class for feedback fragments.
 */
public class FeedbackFragment extends Fragment {

    protected  OnQuestionAnsweredListener mListener;
    protected static final String KEY_PERSISTED_RESPONSE = "persistedResponse";
    protected static final String KEY_QUESTION = "question";

    public void setOnQuestionListener(OnQuestionAnsweredListener listener) {
        if (null != listener) {
            this.mListener = listener;
        }
    }

    public void removeOnQuestionListener() {
        this.mListener  = null;
    }

    public void reshowQuestion(){
       // do nothing, let the subclasses handle
    }

}


text:
<?php

namespace Esier\Models\Endpoints;

class UserInterface implements CanCallAPIInterface
{
    use ChecksScopes;
}


text:
package com.xeiam.xchange.independentreserve.service.polling;

import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.exceptions.ExchangeException;
import com.xeiam.xchange.independentreserve.IndependentReserveAuthenticated;
import com.xeiam.xchange.independentreserve.dto.account.IndependentReserveBalance;
import com.xeiam.xchange.independentreserve.dto.auth.AuthAggregate;
import com.xeiam.xchange.independentreserve.service.IndependentReserveDigest;
import com.xeiam.xchange.independentreserve.util.ExchangeEndpoint;
import si.mazi.rescu.RestProxyFactory;

import java.io.IOException;

/**
 * Author: Kamil Zbikowski
 * Date: 4/10/15
 */
public class IndependentReserveAccountServiceRaw extends IndependentReserveBasePollingService{

    private final IndependentReserveDigest signatureCreator;
    private final IndependentReserveAuthenticated independentReserveAuthenticated;

    /**
     * Constructor
     *
     * @param exchange
     */
    protected IndependentReserveAccountServiceRaw(Exchange exchange) {

        super(exchange);

        this.independentReserveAuthenticated = RestProxyFactory.createProxy(IndependentReserveAuthenticated.class, exchange.getExchangeSpecification().getSslUri());
        this.signatureCreator = IndependentReserveDigest.createInstance(exchange.getExchangeSpecification().getSecretKey(),
                exchange.getExchangeSpecification().getApiKey(), exchange.getExchangeSpecification().getSslUri());
    }

    public IndependentReserveBalance getIndependentReserveBalance() throws IOException {
        Long nonce = exchange.getNonceFactory().createValue();
        String apiKey = exchange.getExchangeSpecification().getApiKey();
        AuthAggregate authAggregate = new AuthAggregate(apiKey, nonce);

        authAggregate.setSignature(signatureCreator.digestParamsToString(ExchangeEndpoint.GET_ACCOUNTS,nonce, authAggregate.getParameters()));
        IndependentReserveBalance independentReserveBalance = independentReserveAuthenticated.getBalance(
                authAggregate);
        if (independentReserveBalance == null) {
            throw new ExchangeException("Error getting balance");
        }
        return independentReserveBalance;
    }

}


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid cite: port-multiple-letters</title>
<q cite="http://f:fifty-two/c"></q>


text:
var Form = {
	config: {
		validation: {
			'required-class': 'input-required',
			'error-class': 'has-error',
			'message': 'This field is required.',
		},
	},
	validation: function(target, type){
		var fConfig = Form.config.validation;

		// get all input list
		var $inputs = $(target + ' :input:not(:button)');

		// formatting
		var rules = { };
		if(type['format'] == true &&  type['format'] != undefined){
			for(let i = 0; i < $inputs.length; i++){
				$input = $inputs[i];
				let name = $input.name;
				let id = '#'+$input.id;
				let is_required = $(id).hasClass(fConfig['required-class']);
				if(is_required){
					rules[name] = { 'required': true }
				}
			}
		}

		$( target ).validate({
		  rules: rules,
		  highlight: function (element, errorClass) {
	      $(element).closest('.form-group').addClass(fConfig['error-class']);
	    },
		  messages: {
		  	'Subject[code]': {
		  		required: fConfig['message'],
		  	}
		  },
		});

	}
}


text:
import mock

from cinder import objects
from cinder.tests.unit import fake_volume
from cinder.tests.unit import objects as test_objects

class TestVolumeType(test_objects.BaseObjectsTestCase):

    @mock.patch('cinder.db.sqlalchemy.api._volume_type_get_full')
    def test_get_by_id(self, volume_type_get):
        db_volume_type = fake_volume.fake_db_volume_type()
        volume_type_get.return_value = db_volume_type
        volume_type = objects.VolumeType.get_by_id(self.context, '1')
        self._compare(self, db_volume_type, volume_type)

    @mock.patch('cinder.volume.volume_types.create')
    def test_create(self, volume_type_create):
        db_volume_type = fake_volume.fake_db_volume_type()
        volume_type_create.return_value = db_volume_type

        volume_type = objects.VolumeType(context=self.context)
        volume_type.name = db_volume_type['name']
        volume_type.extra_specs = db_volume_type['extra_specs']
        volume_type.is_public = db_volume_type['is_public']
        volume_type.projects = db_volume_type['projects']
        volume_type.description = db_volume_type['description']
        volume_type.create()

        volume_type_create.assert_called_once_with(
            self.context, db_volume_type['name'],
            db_volume_type['extra_specs'], db_volume_type['is_public'],
            db_volume_type['projects'], db_volume_type['description'])

    @mock.patch('cinder.volume.volume_types.update')
    def test_save(self, volume_type_update):
        db_volume_type = fake_volume.fake_db_volume_type()
        volume_type = objects.VolumeType._from_db_object(self.context,
                                                         objects.VolumeType(),
                                                         db_volume_type)
        volume_type.description = 'foobar'
        volume_type.save()
        volume_type_update.assert_called_once_with(self.context,
                                                   volume_type.id,
                                                   volume_type.name,
                                                   volume_type.description)

    @mock.patch('cinder.volume.volume_types.destroy')
    def test_destroy(self, volume_type_destroy):
        db_volume_type = fake_volume.fake_db_volume_type()
        volume_type = objects.VolumeType._from_db_object(self.context,
                                                         objects.VolumeType(),
                                                         db_volume_type)
        volume_type.destroy()
        self.assertTrue(volume_type_destroy.called)
        admin_context = volume_type_destroy.call_args[0][0]
        self.assertTrue(admin_context.is_admin)

class TestVolumeTypeList(test_objects.BaseObjectsTestCase):
    @mock.patch('cinder.volume.volume_types.get_all_types')
    def test_get_all(self, get_all_types):
        db_volume_type = fake_volume.fake_db_volume_type()
        get_all_types.return_value = {db_volume_type['name']: db_volume_type}

        volume_types = objects.VolumeTypeList.get_all(self.context)
        self.assertEqual(1, len(volume_types))
        TestVolumeType._compare(self, db_volume_type, volume_types[0])


text:
<?php

namespace backend\controllers;

use Yii;
use backend\models\EasyUpload;
use backend\models\EasyUploadSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * EasyUploadController implements the CRUD actions for EasyUpload model.
 */
class EasyUploadController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all EasyUpload models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new EasyUploadSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single EasyUpload model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new EasyUpload model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new EasyUpload();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->photo = $model->upload($model,'photo');
            $model->photos = $model->uploadMultiple($model,'photos');
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing EasyUpload model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->photo = $model->upload($model,'photo');
            $model->photos = $model->uploadMultiple($model,'photos');
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }  else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing EasyUpload model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the EasyUpload model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return EasyUpload the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = EasyUpload::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
using System;
using System.Linq;
using Orchard.DisplayManagement.Shapes;
using System.Reflection;
using System.Collections.Generic;

namespace Orchard.DisplayManagement.Zones
{
    /// <summary>
    /// Provides the behavior of shapes that have a Zones property.
    /// Examples include Layout and Item
    ///
    /// * Returns a fake parent object for zones
    /// Foo.Zones
    ///
    /// *
    /// Foo.Zones.Alpha :
    /// Foo.Zones["Alpha"]
    /// Foo.Alpha :same
    ///
    /// </summary>
    public class ZoneHolding : Shape
    {
        private readonly Func<dynamic> _zoneFactory;

        public ZoneHolding(Func<dynamic> zoneFactory)
        {
            _zoneFactory = zoneFactory;
        }

        private Zones _zones;
        public Zones Zones
        {
            get
            {
                if (_zones == null)
                {
                    return _zones = new Zones(_zoneFactory, this);
                }

                return _zones;
            }
        }

        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            var name = binder.Name;

            if (!base.TryGetMember(binder, out result) || (null == result))
            {
                // substitute nil results with a robot that turns adds a zone on
                // the parent when .Add is invoked
                result = new ZoneOnDemand(_zoneFactory, this, name);
                TrySetMemberImpl(name, result);
            }

            return true;
        }
    }

    /// <remarks>
    /// InterfaceProxyBehavior()
    /// ZonesBehavior(_zoneFactory, self, _layoutShape) => Create ZoneOnDemand if member access
    /// </remarks>
    public class Zones : Composite
    {
        private readonly Func<dynamic> _zoneFactory;
        private readonly object _parent;

        public Zones(Func<dynamic> zoneFactory, object parent)
        {
            _zoneFactory = zoneFactory;
            _parent = parent;
        }

        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            return TryGetMemberImpl(binder.Name, out result);
        }

        protected override bool TryGetMemberImpl(string name, out object result)
        {

            var parentMember = ((dynamic)_parent)[name];
            if (parentMember == null)
            {
                result = new ZoneOnDemand(_zoneFactory, _parent, name);
                return true;
            }

            result = parentMember;
            return true;
        }

        protected override bool TrySetMemberImpl(string name, object value)
        {
            ((dynamic)_parent)[name] = value;
            return true;
        }

        public override bool TryGetIndex(System.Dynamic.GetIndexBinder binder, object[] indexes, out object result)
        {

            if (indexes.Count() == 1)
            {
                var key = Convert.ToString(indexes.First());

                return TryGetMemberImpl(key, out result);
            }

            return base.TryGetIndex(binder, indexes, out result);
        }

        public override bool TrySetIndex(System.Dynamic.SetIndexBinder binder, object[] indexes, object value)
        {
            if (indexes.Count() == 1)
            {
                var key = Convert.ToString(indexes.First());

                return TrySetMemberImpl(key, value);
            }

            return base.TrySetIndex(binder, indexes, value);
        }
    }

    /// <remarks>
    /// InterfaceProxyBehavior()
    /// NilBehavior() => return Nil on GetMember and GetIndex in all cases
    /// ZoneOnDemandBehavior(_zoneFactory, _parent, name)  => when a zone (Shape) is
    /// created, replace itself with the zone so that Layout.ZoneName is no more equal to Nil
    /// </remarks>
    public class ZoneOnDemand : Shape
    {

        private readonly Func<dynamic> _zoneFactory;
        private readonly object _parent;
        private readonly string _potentialZoneName;

        public ZoneOnDemand(Func<dynamic> zoneFactory, object parent, string potentialZoneName)
        {
            _zoneFactory = zoneFactory;
            _parent = parent;
            _potentialZoneName = potentialZoneName;
        }

        public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
        {
            // NilBehavior
            result = Nil.Instance;
            return true;
        }

        public override bool TryGetIndex(System.Dynamic.GetIndexBinder binder, object[] indexes, out object result)
        {
            // NilBehavior
            result = Nil.Instance;
            return true;
        }

        public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object[] args, out object result)
        {
            var name = binder.Name;

            // NilBehavior
            if (!args.Any() && name != "ToString")
            {
                result = Nil.Instance;
                return true;
            }

            return base.TryInvokeMember(binder, args, out result);
        }

        public override string ToString()
        {
            return String.Empty;
        }

        public override bool TryConvert(System.Dynamic.ConvertBinder binder, out object result)
        {
            if (binder.ReturnType == typeof(string))
            {
                result = null;
            }
            else if (binder.ReturnType.GetTypeInfo().IsValueType)
            {
                result = Activator.CreateInstance(binder.ReturnType);
            }
            else
            {
                result = null;
            }

            return true;
        }

        public static bool operator ==(ZoneOnDemand a, object b)
        {
            // if ZoneOnDemand is compared to null it must return true
            return b == null || ReferenceEquals(b, Nil.Instance);
        }

        public static bool operator !=(ZoneOnDemand a, object b)
        {
            // if ZoneOnDemand is compared to null it must return true
            return !(a == b);
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj))
            {
                return true;
            }

            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            return false;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = (_parent != null ? _parent.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (_potentialZoneName != null ? _potentialZoneName.GetHashCode() : 0);
                return hashCode;
            }
        }

        public override Shape Add(object item, string position = null)
        {
            if (item == null)
            {
                return (Shape)_parent;
            }

            dynamic parent = _parent;

            dynamic zone = _zoneFactory();
            zone.Parent = _parent;
            zone.ZoneName = _potentialZoneName;
            parent[_potentialZoneName] = zone;

            if (position == null)
            {
                return zone.Add(item);
            }

            return zone.Add(item, position);
        }
    }
}


text:
const DrawCard = require('../../../drawcard.js');

class Dracarys extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Reduce character STR by 4',
            condition: () => this.game.currentChallenge,
            cost: ability.costs.kneel(card => card.name === 'Daenerys Targaryen' || card.hasTrait('Dragon')),
            target: {
                activePromptTitle: 'Select a character',
                cardCondition: card => card.location === 'play area' && this.game.currentChallenge.isParticipating(card)
            },
            handler: context => {
                this.game.addMessage('{0} uses {1} to kneel {2} and give {3} -4 STR until the end of the phase', context.player, this, context.kneelingCostCard, context.target);
                this.untilEndOfPhase(ability => ({
                    match: context.target,
                    effect: [
                        ability.effects.modifyStrength(-4),
                        ability.effects.killByStrength
                    ]
                }));
            }
        });
    }
}

Dracarys.code = '01176';

module.exports = Dracarys;


text:
#include "sq.h"
#include "MIDIPlugin.h"
#include <Cocoa/Cocoa.h>
#include <QuickTime/QuickTimeMusic.h>

extern struct VirtualMachine *interpreterProxy;

/* Quicktime MIDI note allocator and channels */
#define FIRST_DRUM_KIT 16385

void* portNamesFn;
void* portIsOpenFn;
void* portSetControlFn;
void* serialPortOpenFn;
void* serialPortCloseFn;
void* serialPortCountFn;
void* serialPortReadIntoFn;
void* serialPortWriteFromFn;

NoteAllocator na = nil;
NoteChannel channel[16] = {
	nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil};

/* Initial instruments: drums on channel 10, piano on all other channels */
int channelInstrument[16] = {
	1, 1, 1, 1, 1, 1, 1, 1, 1, FIRST_DRUM_KIT, 1, 1, 1, 1, 1, 1};

/* Quicktime MIDI parser state */
enum {idle, want1of2, want2of2, want1of1, sysExclusive};
int state = idle;
int argByte1 = 0;
int argByte2 = 0;
int lastCmdByte = nil;

/* number of argument bytes for each MIDI command */
char argumentBytes[128] = {
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
	2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
	3, 1, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};

/*** Private Functions ***/
int setMidiClockRate(int portNum, int interfaceClockRate);
int sqMIDIGetSerialPortCount(void);

/*** Quicktime MIDI Support Functions ***/
void closeQuicktimeMIDIPort(void);
void openQuicktimeMIDIPort(void);
void performMIDICmd(int cmdByte, int arg1, int arg2);
void processMIDIByte(int aByte);
void startMIDICommand(int cmdByte);

/* initialize/shutdown */
int midiInit() {

	portIsOpenFn = interpreterProxy->ioLoadFunctionFrom("serialPortIsOpen", "SerialPlugin");
    if (portIsOpenFn == 0) {
    	portIsOpenFn = interpreterProxy->ioLoadFunctionFrom("serialPortIsOpen", "");
		   if (portIsOpenFn == 0)
		    return interpreterProxy->success(false);
	}

	portSetControlFn = interpreterProxy->ioLoadFunctionFrom("serialPortSetControl", "SerialPlugin");
    if (portSetControlFn == 0) {
    	portSetControlFn = interpreterProxy->ioLoadFunctionFrom("serialPortSetControl", "");
		if (portSetControlFn == 0)
		    return interpreterProxy->success(false);
	}

	serialPortCloseFn = interpreterProxy->ioLoadFunctionFrom("serialPortClose", "SerialPlugin");
    if (serialPortCloseFn == 0) {
    	serialPortCloseFn = interpreterProxy->ioLoadFunctionFrom("serialPortClose", "");
		if (serialPortCloseFn == 0)
		    return interpreterProxy->success(false);
	}

	serialPortCountFn = interpreterProxy->ioLoadFunctionFrom("serialPortCount", "SerialPlugin");
    if (serialPortCountFn == 0) {
	    serialPortCountFn = interpreterProxy->ioLoadFunctionFrom("serialPortCount", "");
	    if (serialPortCountFn == 0)
	    	return interpreterProxy->success(false);
	}

	portNamesFn = interpreterProxy->ioLoadFunctionFrom("serialPortNames", "SerialPlugin");
    if (portNamesFn == 0) {
    	portNamesFn = interpreterProxy->ioLoadFunctionFrom("serialPortNames", "");
        if (portNamesFn == 0)
		    return interpreterProxy->success(false);
	}

	serialPortOpenFn = interpreterProxy->ioLoadFunctionFrom("serialPortOpen", "SerialPlugin");
    if (serialPortOpenFn == 0) {
	    serialPortOpenFn = interpreterProxy->ioLoadFunctionFrom("serialPortOpen", "");
        if (serialPortOpenFn == 0)
 		    return interpreterProxy->success(false);
	}

	serialPortReadIntoFn = interpreterProxy->ioLoadFunctionFrom("serialPortReadInto", "SerialPlugin");
    if (serialPortReadIntoFn == 0) {
    	serialPortReadIntoFn = interpreterProxy->ioLoadFunctionFrom("serialPortReadInto", "");
        if (serialPortReadIntoFn == 0)
            return interpreterProxy->success(false);
	}

	serialPortWriteFromFn = interpreterProxy->ioLoadFunctionFrom("serialPortWriteFrom", "SerialPlugin");
    if (serialPortWriteFromFn == 0) {
    	serialPortWriteFromFn = interpreterProxy->ioLoadFunctionFrom("serialPortWriteFrom", "");
        if (serialPortWriteFromFn == 0)
            return interpreterProxy->success(false);
	}

    return true;
}

int midiShutdown() {
	return 1;
}

/* helper function for MIDI module */
int sqMIDIParameter(int whichParameter, int modify, int newValue);

int sqMIDIParameterSet(int whichParameter, int newValue) {
	sqMIDIParameter(whichParameter, true, newValue);
	return 0;
}

int sqMIDIParameterGet(int whichParameter) {
	sqMIDIParameter(whichParameter, false, 0);
	return 0;
}

int setMidiClockRate(int portNum, int interfaceClockRate) {
#pragma unused(portNum, interfaceClockRate)
/* Put the given port into MIDI mode, which uses a clock supplied
   by an external MIDI interface adaptor to determine the baud rate.
   Possible external clock rates: 31.25 KHz, 0.5 MHz, 1 MHz, or 2 MHz. */
    return false;
}/*** MIDI Parameters (used with sqMIDIParameter function) ***/

#define sqMIDIInstalled				1
/* Read-only. Return 1 if a MIDI driver is installed, 0 if not.
   On OMS-based MIDI drivers, this returns 1 only if the OMS
   system is properly installed and configured. */

#define sqMIDIVersion				2
/* Read-only. Return the integer version number of this MIDI driver.
   The version numbering sequence is relative to a particular driver.
   That is, version 3 of the Macintosh MIDI driver is not necessarily
   related to version 3 of the Win95 MIDI driver. */

#define sqMIDIHasBuffer				3
/* Read-only. Return 1 if this MIDI driver has a time-stamped output
   buffer, 0 otherwise. Such a buffer allows the client to schedule
   MIDI output packets to be sent later. This can allow more precise
   timing, since the driver uses timer interrupts to send the data
   at the right time even if the processor is in the midst of a
   long-running Squeak primitive or is running some other application
   or system task. */

#define sqMIDIHasDurs				4
/* Read-only. Return 1 if this MIDI driver supports an extended
   primitive for note-playing that includes the note duration and
   schedules both the note-on and the note-off messages in the
   driver. Otherwise, return 0. */

#define sqMIDICanSetClock			5
/* Read-only. Return 1 if this MIDI driverÕs clock can be set
   via an extended primitive, 0 if not. */

#define sqMIDICanUseSemaphore		6
/* Read-only. Return 1 if this MIDI driver can signal a semaphore
   when MIDI input arrives. Otherwise, return 0. If this driver
   supports controller caching and it is enabled, then incoming
   controller messages will not signal the semaphore. */

#define sqMIDIEchoOn				7
/* Read-write. If this flag is set to a non-zero value, and if
   the driver supports echoing, then incoming MIDI events will
   be echoed immediately. If this driver does not support echoing,
   then queries of this parameter will always return 0 and
   attempts to change its value will do nothing. */

#define sqMIDIUseControllerCache	8
/* Read-write. If this flag is set to a non-zero value, and if
   the driver supports a controller cache, then the driver will
   maintain a cache of the latest value seen for each MIDI controller,
   and control update messages will be filtered out of the incoming
   MIDI stream. An extended MIDI primitive allows the client to
   poll the driver for the current value of each controller. If
   this driver does not support a controller cache, then queries
   of this parameter will always return 0 and attempts to change
   its value will do nothing. */

#define sqMIDIEventsAvailable		9
/* Read-only. Return the number of MIDI packets in the input queue. */

#define sqMIDIFlushDriver			10
/* Write-only. Setting this parameter to any value forces the driver
   to flush its I/0 buffer, discarding all unprocessed data. Reading
   this parameter returns 0. Setting this parameter will do nothing
   if the driver does not support buffer flushing. */

#define sqMIDIClockTicksPerSec		11
/* Read-only. Return the MIDI clock rate in ticks per second. */

#define sqMIDIHasInputClock			12
/* Read-only. Return 1 if this MIDI driver timestamps incoming
   MIDI data with the current value of the MIDI clock, 0 otherwise.
   If the driver does not support such timestamping, then the
   client must read input data frequently and provide its own
   timestamping. */

/*** MIDI Functions ***/

int sqMIDIClosePort(int portNum) {
/* Close the given MIDI port. Do nothing if the port is not open.
   Fail if there is no port of the given number.*/

	int serialPorts;

	serialPorts = sqMIDIGetSerialPortCount();
	if (portNum == serialPorts) {
		closeQuicktimeMIDIPort();
		return 0;
	} else {

    	if (serialPortCloseFn == 0) {
			return interpreterProxy->success(false);
		}

		return ((int (*) (int)) serialPortCloseFn)(portNum);
	}
}

int sqMIDIGetClock(void) {
/* Return the current value of the clock used to schedule MIDI events.
   The MIDI clock is assumed to wrap at or before half the maximum
   positive SmallInteger value. This allows events to be scheduled
   into the future without overflowing into LargePositiveIntegers.
   This implementation does not support event scheduling, so it
   just returns the value of the Squeak millisecond clock. */

	return interpreterProxy->ioMicroMSecs();
}

int sqMIDIGetSerialPortCount(void) {
/* Return the number of available
   hardware ports and software entities that act like ports. Ports
   are numbered from 0 to N-1, where N is the number returned by this
   primitive. */

    int serialPorts;

    if (serialPortCountFn == 0) {
		return 0;
	}

	serialPorts = ((int (*) (void)) serialPortCountFn)();
	return serialPorts;  /* serial ports */
}

int sqMIDIGetPortCount(void) {
/* Return the number of available MIDI interfaces, including both
   hardware ports and software entities that act like ports. Ports
   are numbered from 0 to N-1, where N is the number returned by this
   primitive. */

	return sqMIDIGetSerialPortCount() + 1;  /* serial ports + QuickTime Synth */
}

int sqMIDIGetPortDirectionality(int portNum) {
/* Return an integer indicating the directionality of the given
   port where: 1 = input, 2 = output, 3 = bidirectional. Fail if
   there is no port of the given number. */

	int serialPorts;

	serialPorts = sqMIDIGetSerialPortCount();
	if (portNum > serialPorts) return interpreterProxy->success(false);
	if (portNum == serialPorts) {
		return 2;
	} else {
		return 3;
	}
}

int sqMIDIGetPortName(int portNum, int namePtr, int length) {
/* Copy the name of the given MIDI port into the string at the given
   address. Copy at most length characters, and return the number of
   characters copied. Fail if there is no port of the given number.*/

	char userName[256], inName[256], outName[256];
	int serialPorts, count;

	serialPorts = sqMIDIGetSerialPortCount();
	if (portNum > serialPorts) return interpreterProxy->success(false);

	if (portNum == serialPorts) {
		strcpy(userName, "QuickTime MIDI");
	} else {

    	if (portNamesFn == 0) {
			return 0;
		}

		((int (*) (int , char *, char *, char *)) portNamesFn)(portNum, userName, inName, outName);
	}

	count = strlen(userName);
	if (count > length) count = length;
	memcpy((void *) namePtr, userName, count);
	return count;
}

int sqMIDIOpenPort(int portNum, int readSemaIndex, int interfaceClockRate) {
/* Open the given port, if possible. If non-zero, readSemaphoreIndex
   specifies the index in the external objects array of a semaphore
   to be signalled when incoming MIDI data is available. Note that
   not all implementations support read semaphores (this one does
   not); see sqMIDICanUseSemaphore. The interfaceClockRate parameter
   specifies the clock speed for an external MIDI interface
   adaptor on platforms that use such adaptors (e.g., Macintosh).
   Fail if there is no port of the given number.*/

#pragma unused(readSemaIndex)
	int serialPorts;
	int err;

	serialPorts = sqMIDIGetSerialPortCount();
	if (portNum > serialPorts) return interpreterProxy->success(false);

	if (portNum == serialPorts) {
		openQuicktimeMIDIPort();
		return 0;
	}

    if (serialPortOpenFn == 0) {
		return interpreterProxy->success(false);
	}

	err = ((int (*) (int , int , int , int , int , int , int , int , int ))serialPortOpenFn)(portNum, 9600, 1, 0, 8, 0, 0, 0, 0);
	if (!err) {
		err = setMidiClockRate(portNum, interfaceClockRate);
		if (err) {
			sqMIDIClosePort(portNum);
		}
	}
	return 0;
}

int sqMIDIParameter(int whichParameter, int modify, int newValue) {
/* Read or write the given MIDI driver parameter. If modify is 0,
   then newValue is ignored and the current value of the specified
   parameter is returned. If modify is non-zero, then the specified
   parameter is set to newValue. Note that many MIDI driver parameters
   are read-only; attempting to set one of these parameters fails.
   For boolean parameters, true = 1, false = 0. */
#pragma unused(newValue)

	if (modify == 0) {
		switch(whichParameter) {
		case sqMIDIInstalled:
			return 1;
			break;
		case sqMIDIVersion:
			return 100;
			break;
		case sqMIDIHasBuffer:
		case sqMIDIHasDurs:
		case sqMIDICanSetClock:
		case sqMIDICanUseSemaphore:
		case sqMIDIEchoOn:
		case sqMIDIUseControllerCache:
			return 0;
			break;
		case sqMIDIEventsAvailable:
			return 1;  /* pretend that events are always available */
			break;
		case sqMIDIFlushDriver:
			return 0;
			break;
		case sqMIDIClockTicksPerSec:
			return 1000;
			break;
		case sqMIDIHasInputClock:
			return 0;
			break;
		default:
			return interpreterProxy->success(false);
		}
	} else {
		switch(whichParameter) {
		case sqMIDIInstalled:
		case sqMIDIVersion:
		case sqMIDIHasBuffer:
		case sqMIDIHasDurs:
		case sqMIDICanSetClock:
		case sqMIDICanUseSemaphore:
			return interpreterProxy->success(false);
			break;
		case sqMIDIEchoOn:
			/* noop; echoing not supported */
			break;
		case sqMIDIUseControllerCache:
			/* noop; controller cache not supported */
			break;
		case sqMIDIEventsAvailable:
			return interpreterProxy->success(false);
			break;
		case sqMIDIFlushDriver:
			/* noop; buffer flushing not supported */
			break;
		case sqMIDIClockTicksPerSec:
			return interpreterProxy->success(false);
			break;
		default:
			return interpreterProxy->success(false);
		}
	}
	return 0;
}

int sqMIDIPortReadInto(int portNum, int count, int bufferPtr) {
/* bufferPtr is the address of the first byte of a Smalltalk
   ByteArray of the given length. Copy up to (length - 4) bytes
   of incoming MIDI data into that buffer, preceded by a 4-byte
   timestamp in the units of the MIDI clock, most significant byte
   first. Implementations that do not support timestamping of
   incoming data as it arrives (see sqMIDIHasInputClock) simply
   set the timestamp to the value of the MIDI clock when this
   function is called. Return the total number of bytes read,
   including the timestamp bytes. Return zero if no data is
   available. Fail if the buffer is shorter than five bytes,
   since there must be enough room for the timestamp plus at
   least one data byte. */

	int bytesRead;

	if (count < 5) return interpreterProxy->success(false);

    if (serialPortReadIntoFn == 0) {
		return interpreterProxy->success(false);
	}

	bytesRead = ((int (*) (int , int , int )) serialPortReadIntoFn)(portNum, count - 4, bufferPtr + 4);

	if (bytesRead == 0) return 0;
	*((int *) bufferPtr) = sqMIDIGetClock();  /* set timestamp */
	return bytesRead + 4;
}

int sqMIDIPortWriteFromAt(int portNum, int count, int bufferPtr, int time) {
/* bufferPtr is the address of the first byte of a Smalltalk
   ByteArray of the given length. Send its contents to the given
   port when the MIDI clock reaches the given time. If time equals
   zero, then send the data immediately. Implementations that do
   not support a timestamped output queue, such as this one, always
   send the data immediately; see sqMIDIHasBuffer. */
#pragma unused(time)
	int serialPorts, i;
	unsigned char *bytePtr;

	serialPorts = sqMIDIGetSerialPortCount();
	if (portNum > serialPorts) return interpreterProxy->success(false);

	if (portNum == serialPorts) {
		if (!na) return interpreterProxy->success(false);  /* QuickTime port not open */
		bytePtr = (unsigned char *) bufferPtr;
		for (i = 0; i < count; i++) {
			processMIDIByte(*bytePtr++);
		}
		return count;
	}

    if (serialPortWriteFromFn == 0) {
		return interpreterProxy->success(false);
	}

	return ((int (*) (int , int , int )) serialPortWriteFromFn)(portNum, count - 4, bufferPtr + 4);
}

/*** Quicktime MIDI Support Functions ***/

void closeQuicktimeMIDIPort(void) {
	int i;

	if (!na) return;
	for (i = 0; i < 16; i++) {
		/* dispose of note channels */
		if (channel[i]) NADisposeNoteChannel(na, channel[i]);
		channel[i] = nil;
	}
	CloseComponent(na);  /* close note allocator */
}

void openQuicktimeMIDIPort(void) {
	ComponentResult err;
	NoteRequest nr;
	NoteChannel nc;
	int i;
	short shortpoly;
	Fixed fixedtypical;

	closeQuicktimeMIDIPort();
	na = OpenDefaultComponent('nota', 0);
	if (!na) return;

	for (i = 0; i < 16; i++) {
		shortpoly = CFSwapInt16HostToBig(11);
		memcpy(&nr.info.polyphony,&shortpoly,2);			/* max simultaneous tones */
		fixedtypical = CFSwapInt32HostToBig(0x00010000);
		memcpy(&nr.info.typicalPolyphony,&fixedtypical,4);

		NAStuffToneDescription(na, 1, &nr.tone);
		err = NANewNoteChannel(na, &nr, &nc);
		if (err || !nc) {
			closeQuicktimeMIDIPort();
			return;
		}
		NAResetNoteChannel(na, nc);
		NASetInstrumentNumber(na, nc, channelInstrument[i]);
		channel[i] = nc;
	}
	state = idle;
	argByte1 = 0;
	argByte2 = 0;
	lastCmdByte = nil;
	return;
}

void performMIDICmd(int cmdByte, int arg1, int arg2) {
	/* Perform the given MIDI command with the given arguments. */

	int ch, cmd, val, instrument, bend;

	ch = cmdByte & 0x0F;
	cmd = cmdByte & 0xF0;
	if (cmd == 128) {  /* note off */
		NAPlayNote(na, channel[ch], arg1, 0);
	}
	if (cmd == 144) {  /* note on */
		NAPlayNote(na, channel[ch], arg1, arg2);
	}
	if (cmd == 176) {  /* control change */
		if ((arg1 >= 32) && (arg1 <= 63)) {
			val = arg2 << 1;  /* LSB of controllers 0-31 */
		} else {
			val = arg2 << 8;  /* scale MSB to QT controller range */
		}
		NASetController(na, channel[ch], arg1, val);
	}
	if (cmd == 192) {  /* program change */
		if (ch == 9) {
			instrument = FIRST_DRUM_KIT + arg1;  /* if channel 10, select a drum set */
		} else {
			instrument = arg1 + 1;
		}
		NASetInstrumentNumber(na, channel[ch], instrument);
		channelInstrument[ch] = instrument;
	}
	if (cmd == 224) {  /* pitch bend */
		bend = ((arg2 << 7) + arg1) - (64 << 7);
		bend = bend / 32;  /* default sensitivity = +/- 2 semitones */
		NASetController(na, channel[ch], kControllerPitchBend, bend);
	}
}

void processMIDIByte(int aByte) {
	/* Process the given incoming MIDI byte and perform any completed commands. */

	if (aByte > 247) return;  /* skip all real-time messages */

	switch (state) {
	case idle:
		if (aByte >= 128) {
			/* start a new command using the action table */
			startMIDICommand(aByte);
		} else {
			/* data byte arrived in idle state: use running status if possible */
			if (lastCmdByte == nil) {
				return;  /* last command byte is not defined; just skip this byte */
			} else {
				/* process this data as if it had the last command byte in front of it */
				startMIDICommand(lastCmdByte);
				/* the previous line put us into a new state; we now do a recursive
			   	   call to process the data byte in this new state. */
				processMIDIByte(aByte);
				return;
			}
		}
		break;
	case want1of2:
		argByte1 = aByte;
		state = want2of2;
		break;
	case want2of2:
		argByte2 = aByte;
		performMIDICmd(lastCmdByte, argByte1, argByte2);
		state = idle;
		break;
	case want1of1:
		argByte1 = aByte;
		performMIDICmd(lastCmdByte, argByte1, 0);
		state = idle;
		break;
	case sysExclusive:
		if (aByte < 128) {
			/* skip a system exclusive data byte */
		} else {
			if (aByte < 248) {
				/* a system exclusive message can be terminated by any non-real-time command byte */
				state = idle;
				if (aByte != 247) {
					processMIDIByte(aByte);	/* if not endSysExclusive, byte is the start the next command */
				}
			}
		}
		break;
	}
}

void startMIDICommand(int cmdByte) {
	/* Start processing a MIDI message beginning with the given command byte. */

	int argCount;

	argCount = argumentBytes[cmdByte - 128];
	switch (argCount) {
	case 0:						/* start a zero argument command (e.g., a real-time message) */
		/* Stay in the current state and don't change active status.
		   Real-time messages may arrive between data bytes without disruption. */
		performMIDICmd(cmdByte, 0, 0);
		break;
	case 1:						/* start a one argument command */
		lastCmdByte = cmdByte;
		state = want1of1;
		break;
	case 2:						/* start a two argument command */
		lastCmdByte = cmdByte;
		state = want1of2;
		break;
	case 3:						/* start a variable length 'system exclusive' command */
		/* a system exclusive command clears running status */
		lastCmdByte = nil;
		state = sysExclusive;
		break;
	}
}


text:
package com.forgerock.elasticsearch.changes;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.shard.IndexingOperationListener;
import org.elasticsearch.index.shard.ShardId;
import org.joda.time.DateTime;

/**
 * Date: 04/05/2017
 * Time: 16:54
 */
public class WebSocketIndexListener implements IndexingOperationListener {

    private final Logger log = Loggers.getLogger(WebSocketIndexListener.class);

    private final Set<Source> sources;
    private final List<String> filter;
    private final WebSocketRegister register;

    WebSocketIndexListener(Set<Source> sources, List<String> filter, WebSocketRegister register) {
        this.sources = sources;
        this.filter = filter;
        this.register = register;
    }

    @Override
    public void postIndex(ShardId shardId, Engine.Index index, Engine.IndexResult result) {

        ChangeEvent change=new ChangeEvent(
                shardId.getIndex().getName(),
                index.type(),
                index.id(),
                new DateTime(),
                result.isCreated() ? ChangeEvent.Operation.CREATE : ChangeEvent.Operation.INDEX,
                result.getVersion(),
                index.source()
        );

        addChange(change);
    }

    @Override
    public void postDelete(ShardId shardId, Engine.Delete delete, Engine.DeleteResult result) {

        ChangeEvent change=new ChangeEvent(
                shardId.getIndex().getName(),
                delete.type(),
                delete.id(),
                new DateTime(),
                ChangeEvent.Operation.DELETE,
                result.getVersion(),
                null
        );

        addChange(change);
    }

    private static boolean filter(String index, String type, String id, Source source) {

        if (source.getIndices() != null && !source.getIndices().contains(index) ) {

        	boolean result = false;
        	for (String s : source.getIndices() ) {
        		if ( s != null && s.length() > 0 && s.endsWith("*") && index.startsWith(s.substring(0, s.length()-1))) {
                    result = true;
                    break;
        		}
        	}

        	if (result == false ) {
            return false;
        	}
        }

        if (source.getTypes() != null && !source.getTypes().contains(type)) {
            return false;
        }

        if (source.getIds() != null && !source.getIds().contains(id)) {
            return false;
        }

        return true;
    }

    static boolean filter(ChangeEvent change, Set<Source> sources) {
        for (Source source : sources) {
            if (filter(change.getIndex(), change.getType(), change.getId(), source)) {
                return true;
            }
        }

        return false;
    }

    private void addChange(ChangeEvent change) {

        if (!filter(change, sources)) {
            return;
        }
        String message;

        Set<String> filters = new HashSet<>(filter);

        try {
            XContentBuilder builder = new XContentBuilder(JsonXContent.jsonXContent, new BytesStreamOutput(), filters);
            builder.startObject()
                    .field("_index", change.getIndex())
                    .field("_type", change.getType())
                    .field("_id", change.getId())
                    .field("_timestamp", change.getTimestamp())
                    .field("_version", change.getVersion())
                    .field("_operation", change.getOperation().toString());
            if (change.getSource() != null) {
                builder.rawField("_source", change.getSource().streamInput(), XContentType.JSON);
            }
            builder.endObject();
            message = Strings.toString(builder);
        } catch (IOException e) {
            log.error("Failed to write JSON", e);
            return;
        }

        for (WebSocketEndpoint listener : register.getListeners()) {
            try {
                listener.sendMessage(message);
            } catch (Exception e) {
                log.error("Failed to send message", e);
            }

        }

    }
}


text:
FROM debian:jessie

# MAINTAINER Henry

RUN apt-get update && apt-get install -y \
    elvis-tiny \
    lcov

CMD ["/bin/bash"]


text:
using Microsoft.AspNetCore.Builder;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Extension methods for the cookie policy middleware.
/// </summary>
public static class CookiePolicyServiceCollectionExtensions
{
    /// <summary>
    /// Adds services and options for the cookie policy middleware.
    /// </summary>
    /// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
    /// <param name="configureOptions">A delegate to configure the <see cref="CookiePolicyOptions"/>.</param>
    /// <returns></returns>
    public static IServiceCollection AddCookiePolicy(this IServiceCollection services, Action<CookiePolicyOptions> configureOptions)
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }
        if (configureOptions == null)
        {
            throw new ArgumentNullException(nameof(configureOptions));
        }

        return services.Configure(configureOptions);
    }

    /// <summary>
    /// Adds services and options for the cookie policy middleware.
    /// </summary>
    /// <param name="services">The <see cref="IServiceCollection"/> for adding services.</param>
    /// <param name="configureOptions">A delegate to configure the <see cref="CookiePolicyOptions"/>.</param>
    /// <returns></returns>
    public static IServiceCollection AddCookiePolicy<TService>(this IServiceCollection services, Action<CookiePolicyOptions, TService> configureOptions) where TService : class
    {
        if (services == null)
        {
            throw new ArgumentNullException(nameof(services));
        }
        if (configureOptions == null)
        {
            throw new ArgumentNullException(nameof(configureOptions));
        }

        services.AddOptions<CookiePolicyOptions>().Configure(configureOptions);
        return services;
    }
}


text:
Editing Comment

<?php echo render('comments/_form'); ?>

	<?php echo Html::anchor('comments/view/'.$comment->id, 'View'); ?> |
	<?php echo Html::anchor('comments', 'Back'); ?>


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Exploit - Mediashare.Blog</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="https://Mediashare.github.io/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//Mediashare.github.io/themes/ichi/assets/css/normalize.css?v=1480624447461" />
    <link rel="stylesheet" type="text/css" href="//Mediashare.github.io/themes/ichi/assets/css/foundation.min.css?v=1480624447461" />

    <link rel="stylesheet" type="text/css" href="//Mediashare.github.io/themes/ichi/assets/fonts/foundation-icons/foundation-icons.css?v=1480624447461" />
    <link rel="stylesheet" type="text/css" href="//Mediashare.github.io/themes/ichi/assets/css/styles.css?v=1480624447461" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans:300,700,400|Source+Sans+Pro:300,400,600,700,900,300italic,400italic,600italic,700italic,900italic" />

    <link rel="canonical" href="https://Mediashare.github.io/https://Mediashare.github.io/tag/Exploit/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="Mediashare.Blog" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Exploit - Mediashare.Blog" />
    <meta property="og:url" content="https://Mediashare.github.io/https://Mediashare.github.io/tag/Exploit/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Exploit - Mediashare.Blog" />
    <meta name="twitter:url" content="https://Mediashare.github.io/https://Mediashare.github.io/tag/Exploit/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="Mediashare.Blog" href="https://Mediashare.github.io/rss/" />

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

    <button type="button" class="overlay-close">Close</button>

Home

Mediashare.Blog

Le cahier de bord d'un développeur souhaitant partager ses connaissance en Développement, Technologie, Actualité & ses Projets.

Exploit

            <time datetime="2016-12-01">01 Dec 2016</time>

Exploit sur Tor

Attention, si vous utilisez Tor avec le navigateur Firefox (Le fameux Tor Browser). Un admin du service de mail Sigaint a publié sur la mailing list de Tor, un exploit utilisé activement en ce moment, qui permet d’exécuter du code malicieux sur un Windows. L’exploit composé d’un fichier HTML et d’un fichier CSS permet d’obtenir un accès direct à kernel32.dll grâce à…

        Read more
        Posted on Exploit,  Tor,  Firefox Mozilla,  Javascript

    Page 1 of 1


text:
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32l0xx_hal.h"
#include "iwdg.h"
#include "gpio.h"

/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/

/* USER CODE END PFP */

/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration----------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_IWDG_Init();

  /* USER CODE BEGIN 2 */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

      HAL_Delay(500);
      HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_RESET);

      // Watchdog will reset once its timer runs out
      // unless it is refreshed with the following line uncommented:
      //HAL_IWDG_Refresh(&hiwdg);

  }
  /* USER CODE END 3 */

}

/** System Clock Configuration
*/
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;

    /**Configure the main internal regulator output voltage
    */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

    /**Initializes the CPU, AHB and APB busses clocks
    */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = 0;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_5;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

    /**Initializes the CPU, AHB and APB busses clocks
    */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }

  HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_LSI, RCC_MCODIV_1);

    /**Configure the Systick interrupt time
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void _Error_Handler(char * file, int line)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  while(1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT

/**
   * @brief Reports the name of the source file and the source line number
   * where the assert_param error has occurred.
   * @param file: pointer to the source file name
   * @param line: assert_param error line source number
   * @retval None
   */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */

}

#endif

/**
  * @}
  */

/**
  * @}
*/

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
/*
 * NaCl Service Runtime API.
 */

#ifndef NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_INCLUDE_SYS_FCNTL_H_
#define NATIVE_CLIENT_SRC_TRUSTED_SERVICE_RUNTIME_INCLUDE_SYS_FCNTL_H_

#ifdef __native_client__
#include <sys/types.h>
#endif

/* from bits/fcntl.h */
#define NACL_ABI_O_ACCMODE     0003
#define NACL_ABI_O_RDONLY        00
#define NACL_ABI_O_WRONLY        01
#define NACL_ABI_O_RDWR          02

#define NACL_ABI_O_CREAT       0100 /* not fcntl */
#define NACL_ABI_O_TRUNC      01000 /* not fcntl */
#define NACL_ABI_O_APPEND     02000
#define NACL_ABI_O_CLOEXEC 02000000

/*
 * Features not implemented by NaCl, but required by the newlib build.
 */
#define NACL_ABI_O_EXCL        0200
#define NACL_ABI_O_NONBLOCK   04000
#define NACL_ABI_O_NDELAY      NACL_ABI_O_NONBLOCK
#define NACL_ABI_O_SYNC      010000
#define NACL_ABI_O_FSYNC       NACL_ABI_O_SYNC
#define NACL_ABI_O_ASYNC     020000

/* XXX close on exec request; must match UF_EXCLOSE in user.h */
#define FD_CLOEXEC  1 /* posix */

/* fcntl(2) requests */
#define NACL_ABI_F_DUPFD   0 /* Duplicate fildes */
#define NACL_ABI_F_GETFD   1 /* Get fildes flags (close on exec) */
#define NACL_ABI_F_SETFD   2 /* Set fildes flags (close on exec) */
#define NACL_ABI_F_GETFL   3 /* Get file flags */
#define NACL_ABI_F_SETFL   4 /* Set file flags */
#ifndef _POSIX_SOURCE
#define NACL_ABI_F_GETOWN  5 /* Get owner - for ASYNC */
#define NACL_ABI_F_SETOWN  6 /* Set owner - for ASYNC */
#endif  /* !_POSIX_SOURCE */
#define NACL_ABI_F_GETLK   7 /* Get record-locking information */
#define NACL_ABI_F_SETLK   8 /* Set or Clear a record-lock (Non-Blocking) */
#define NACL_ABI_F_SETLKW  9 /* Set or Clear a record-lock (Blocking) */
#ifndef _POSIX_SOURCE
#define NACL_ABI_F_RGETLK  10  /* Test a remote lock to see if it is blocked */
#define NACL_ABI_F_RSETLK  11  /* Set or unlock a remote lock */
#define NACL_ABI_F_CNVT    12  /* Convert a fhandle to an open fd */
#define NACL_ABI_F_RSETLKW   13  /* Set or Clear remote record-lock(Blocking) */
#endif  /* !_POSIX_SOURCE */

/* fcntl(2) flags (l_type field of flock structure) */
#define NACL_ABI_F_RDLCK   1 /* read lock */
#define NACL_ABI_F_WRLCK   2 /* write lock */
#define NACL_ABI_F_UNLCK   3 /* remove lock(s) */
#ifndef _POSIX_SOURCE
#define NACL_ABI_F_UNLKSYS 4 /* remove remote locks for a given system */
#endif  /* !_POSIX_SOURCE */

#ifdef __native_client__
#ifdef __cplusplus
extern "C" {
#endif  /* __cplusplus */

extern int open(const char *file, int oflag, ...);
extern int fcntl(int, int, ...);

#ifdef __cplusplus
}  /* extern "C" */
#endif  /* __cplusplus */
#endif  /* __native_client__ */

#endif


text:
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <?php
        if (!class_exists('lessc')) {
            include ( './libs/lessc.inc.php');
        }
        $less = new lessc;
        $less->compileFile('less/type-324.less', 'css/type-324.css');
        ?>
        <link href="css/type-324.css" rel="stylesheet" type="text/css" />
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <script src="js/jquery-1.11.2.min.js" type="text/javascript"></script>
        <script src="js/bootstrap.min.js" type="text/javascript"></script>
        <link href="css/font-awesome.min.css" rel="stylesheet" type="text/css"/>

        <title>type-324</title>
    </head>

    <body>

<?php
include 'type-324.php';
?>

        <script>
            function toggleIcon(e) {
                $(e.target)
                        .prev('.panel-heading')
                        .find(".more-less")
                        .toggleClass('glyphicon-plus glyphicon-minus');
            }
            $('.panel-group').on('hidden.bs.collapse', toggleIcon);
            $('.panel-group').on('shown.bs.collapse', toggleIcon);

        </script>

    </body>

</html>


text:
#region Using

using System.Numerics;
using Emotion.Common;
using Emotion.Graphics;
using Emotion.Plugins.ImGuiNet;
using Emotion.Plugins.ImGuiNet.Windowing;
using Emotion.Primitives;
using Emotion.Scenography;
using Emotion.Tools.Windows;
using ImGuiNET;

#endregion

namespace Emotion.Tools
{
    internal class Program : IScene
    {
        #region UI Logic

        private static WindowManager _manager = new WindowManager();

        #endregion

        private static void Main()
        {
            var config = new Configurator
            {
                DebugMode = true,
                HostSize = new Vector2(1280, 720)
            };
            config.AddPlugin(new ImGuiNetPlugin());

            Engine.Setup(config);
            Engine.SceneManager.SetScene(new Program());
            Engine.Run();
        }

        public void Update()
        {
            _manager.Update();
        }

        public void Load()
        {

        }

        public void Unload()
        {

        }

        public void Draw(RenderComposer composer)
        {
            composer.SetUseViewMatrix(false);
            composer.RenderSprite(new Vector3(0, 0, 0), Engine.Renderer.CurrentTarget.Size, Color.CornflowerBlue);

            ImGui.NewFrame();
            composer.RenderToolsMenu(_manager);
            _manager.Render(composer);
            ImGuiNetPlugin.RenderUI(composer);
        }
    }
}


text:
var root = document.createElement('div'),
    div = document.createElement('div'),
    //cardsSource = 'cardTheme2.png';
    cardsSource = 'http://belote.vbet.com/newBlot/cards/cardTheme2.png';

root.id = 'root';

div.style.position = 'absolute';
div.style.left = (document.body.clientWidth - 210) / 2 + 'px';
div.style.top = (document.body.clientHeight - 300) / 2 + 'px';
div.style.backgroundImage = 'url(' + cardsSource + ')';
div.style.backgroundPosition = (getRandomNumber(0, 8) | 0) * 210 + 'px '
    + (getRandomNumber(0, 4) | 0) * 300 + 'px';
div.style.width = '210px';
div.style.height = '300px';

root.appendChild(div);
document.body.insertBefore(root, document.body.firstChild);


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W29094_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Kodiak on & Gas (USA) Inc.

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">The above cement volumes are approximate and were calculated under the assumption that a gauge hole will be achieved with a 10% excess factor. Actual cement volumes may vary due to variations in the actual hole gauge and will be determined by running a caliper log on the drilled hole.
All waiting on cement (WOC) times will be adequate to achieve a minimum of 500 psi compressive strength at the casing shoe prior to drilling out.
5. MUD PROGRAM -

    <p class="styleSans52.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Fluid Loss
15cc's
1 True Vertical Depth. 2 Measured Depth.

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Sufficient mud material(s) to maintain mud properties, control lost circulation and contain a blowout will be available at the well site during drilling operations.

    <p class="styleSans12.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">6. EVALUATION PROGRAM
Logs 2 The logging program will be run by Schlumberger and will consist of their Platform Express plus BHC Sonic from 11845' to 2425'. The Gamma Ray and resistivity log will be pulled back to surface.

DST's : DST's will be run as warranted by logs and/or shows - none are scheduled at this time. Cores : None anticipated at this time.

The evaluation program may change at the discretion of the well site geologist, with prior approval from the Authorized Oficer, North Dakota Field Office, Bureau of Land Management.
Stimulation : No stimulation or frac treatment has been formulated for this test at this time. The drill site, as approved, will be of sufficient size to accommodate all completion activities.

    <p class="styleSans11.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">COMPLETION
The planned top of the 4.5" 11.6" production liner will be 50-100 ft above the kick off point. This liner will be cemented throughout the lateral and a wet shoe sub will be set at the toe of the liner. The frac string will be 12.75# P-l 10 with TSHP threads and stung into a PBR run

    <p class="styleSans4.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">P Vance 154-97-14-9-21-15HA


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

namespace Kassandra.Connector.Sql.Extensions
{
    public static class EnumerableExtensions
    {
        public static DataTable ToIdTable(this IEnumerable<int> ids, string datatableColumnIdName)
        {
            DataTable tableIds = new DataTable();
            tableIds.Columns.Add(new DataColumn(datatableColumnIdName, typeof (int)));

            foreach (int id in ids.Distinct())
            {
                DataRow row = tableIds.NewRow();
                row[datatableColumnIdName] = id;
                tableIds.Rows.Add(row);
            }

            return tableIds;
        }

        public static DataTable ToUidTable(this IEnumerable<Guid> uids, string datatableColumnUidName)
        {
            DataTable tableIds = new DataTable();
            tableIds.Columns.Add(new DataColumn(datatableColumnUidName, typeof (int)));

            foreach (Guid id in uids.Distinct())
            {
                DataRow row = tableIds.NewRow();
                row[datatableColumnUidName] = id;
                tableIds.Rows.Add(row);
            }

            return tableIds;
        }
    }
}


text:
package iso20022

// Specifies the reason why the corporate action reversal occurs.
type CorporateActionReversalReason4 struct {

	// Specifies the reason for the reversal.
	Reason *CorporateActionReversalReason4Choice `xml:"Rsn"`

	// Provides additional information about the processed instruction.
	AdditionalReasonInformation *RestrictedFINXMax256Text `xml:"AddtlRsnInf,omitempty"`
}

func (c *CorporateActionReversalReason4) AddReason() *CorporateActionReversalReason4Choice {
	c.Reason = new(CorporateActionReversalReason4Choice)
	return c.Reason
}

func (c *CorporateActionReversalReason4) SetAdditionalReasonInformation(value string) {
	c.AdditionalReasonInformation = (*RestrictedFINXMax256Text)(&value)
}


text:
// MIT License
//
// Copyright (c) 2016 Caring Labs, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#ifndef __SCENE__
#define __SCENE__

// System
#include <list>
#include <memory>
#include <set>
#include <map>

// Local
#include "Time.hpp"
#include "SceneNodeSim.hpp"

namespace mf
{

class SceneNode;
class ProducerNode;
class DisplayList;
class FrameRenderSet;
struct StateCache;

typedef std::shared_ptr<SceneNode> SceneNodePtr;

/**
 *  Scene class contains the scene node graph data structure for rendering a MF presentation.
 *
 *  Scene contains a list of SceneNode instances which describe transformation and animations
 *  of images. These images are created by ProducerNode instances and include static
 *  images, video and lines of text.
 *
 *  The Scene class owns the SceneNode and ProducerNode instances it has been given and
 *  will call "delete" on them in its destructor.
 *
 *  A Scene is rendered by calling GatherStateAtTime() to generate a DisplayList.
 *  Then call GetTexturesForAssets() on the DisplayList to get the OpenGL textures
 *  from the Image Assets and then render the DisplayList using a ListRenderer.
 *
 *  When playback starts, call PlayAllAssets().
 */
class Scene {

public:
    /** Default constructor */
    Scene();

    /**
     *  Destructor calls delete on all SceneNode and ProducerNode instances
     *  in its list.
     */
    ~Scene();

    /**
     * Add new scene node to root, ownership passes to Scene.
     *
     * @param node Pointer to SceneNode to add to scene, allocated by
     *      caller on heap using "new".
     */
    void addSceneNode(SceneNodePtr node);

    /** Access to nodes list */
    std::list<SceneNodePtr>& getNodes() { return _nodes; }

    /**
     *  Add new image asset (texture producer) to scene,
     *  ownership passes to Scene.
     *
     *  SceneNode instances also point to ProducerNodes, but only weakly.
     *  This function call is for passing ownership to the Scene for
     *  for the ProducerNode instances that will be used by SceneNode
     *  instances in the scene graph.
     *
     *  The Scene also uses this list of ProducerNodes for gathering
     *  lists of assets for the Preloader.
     *
     * @param asset Pointer to ProducerNode, allocated by
     *      caller on heap using "new".
     */
    void addProducerNode(ProducerNode* asset);

    /** Gathers visible nodes into oDisplayList with animations
     *  evaluated and state cached for given time value.
     *
     * @param[in] time Time to use when evaluating animations.
     * @param[out] oRenderSet Filled with state cached at time for each visible node.
     */
    void gatherStateAtTime(Time time, FrameRenderSet &oRenderSet);

    /** Variation where caller can set the root state structure to affect all objects. */
    void gatherStateAtTime(Time time, const StateCache& rootState, FrameRenderSet &oRenderSet);

    /** Gather state only for subscene rooted at node.
     *  Used for debugging the contribution of single
     *  nodes in authoring tools. */
    void gatherStateAtTimeForNode(SceneNodePtr node,
                                  Time time,
                                  const StateCache& rootState,
                                  FrameRenderSet &oRenderSet);

    /** Insert all used special effect renderer ids into set. */
    void gatherRendererIds(std::set<int>& oIds);

    /** Returns all assets in the scene.
     *
     * @param[out] oAssets Filled with all ProducerNode in scene.
    */
    void gatherAllAssets(std::list<ProducerNode*> &oAssets);

    /** Return all assets that will be visible during the given time range. */
    void gatherAssetsForRange(std::list<ProducerNode*> &oAssets, const Time& beginTime, const Time &endTime);

    /** Start all streaming assets in scene. This should be called
     *  when playback starts or when the player starts playing
     *  again after being paused.
     */
    void playAllAssets(const Time& time);

    /** Pause all streaming assets in scene. This should be called
     *  when playback is paused or when scrubbing starts.
     */
    void pauseAllAssets();

    /** Should the scene be redrawn when paused? (this would be set true if
     *  there is a physics simulation that runs outside of the timeline animation. */
    bool redrawWhenPaused() const;
    void setRedrawWhenPaused(bool redraw);

private:
    void gatherNodeStateAtTime(SceneNode* node,
                               const Time& time,
                               const StateCache& parentState,
                               int zorder,
                               FrameRenderSet& oRenderSet);

    std::list<SceneNodePtr> _nodes;
    std::list<ProducerNode*> _assets;
#ifdef USE_SIMULATOR
    SceneNodeSimulator _sim;
#endif
    bool _redrawWhenPaused;
};

} // namespace

#endif //__SCENE_GATHER__

// MIT License
//
// Copyright (c) 2016 Caring Labs, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.


text:
package org.sec.dataline.classfile.model.constantPool;

/**
 * @author zhou_wei
 * @since v0.1
 */
public class NameAndTypeInfo extends ConstantPoolInfo {

    private short nameIndex;
    private short descriptorIndex;

    public NameAndTypeInfo() {
        super(ConstantPoolTag.CONSTANT_NameAndType.getValue());
    }

    public short getNameIndex() {
        return nameIndex;
    }

    public void setNameIndex(short nameIndex) {
        this.nameIndex = nameIndex;
    }

    public short getDescriptorIndex() {
        return descriptorIndex;
    }

    public void setDescriptorIndex(short descriptorIndex) {
        this.descriptorIndex = descriptorIndex;
    }
}


text:
namespace PluginHelpers {

  export interface PluginModule {
    pluginName:string;
    log:Logging.Logger;
    _module: ng.IModule;
    controller?: (name:string, inlineAnnotatedConstructor:any[]) => any;
  }

  // creates a nice little shortcut function that plugins can use to easily
  // prefix controllers with the plugin name, helps avoid redundancy and typos
  export function createControllerFunction(_module:ng.IModule, pluginName:string) {
    return (name:string, inlineAnnotatedConstructor:any[]) => {
      return _module.controller(pluginName + '.' + name, inlineAnnotatedConstructor);
    }
  }

  // shorthand function to create a configuration for a route, saves a bit
  // of typing
  export function createRoutingFunction(templateUrl:string) {
    return (templateName:string, reloadOnSearch:boolean = true) => {
      return {
        templateUrl: UrlHelpers.join(templateUrl, templateName),
        reloadOnSearch: reloadOnSearch
      };
    }
  }

}


text:
require 'sensu-plugin/metric/cli'
require 'net/https'
require 'uri'
require 'socket'

class NginxMetrics < Sensu::Plugin::Metric::CLI::Graphite
  option :url,
         short: '-u URL',
         long: '--url URL',
         description: 'Full URL to nginx status page, example: https://yoursite.com/nginx_status This ignores ALL other options EXCEPT --scheme'

  option :hostname,
         short: '-h HOSTNAME',
         long: '--host HOSTNAME',
         description: 'Nginx hostname'

  option :port,
         short: '-P PORT',
         long: '--port PORT',
         description: 'Nginx  port',
         default: '80'

  option :path,
         short: '-q STATUSPATH',
         long: '--statspath STATUSPATH',
         description: 'Path to your stub status module',
         default: 'nginx_status'

  option :scheme,
         description: 'Metric naming scheme, text to prepend to metric',
         short: '-s SCHEME',
         long: '--scheme SCHEME',
         default: "#{Socket.gethostname}.nginx"

  def run
    found = false
    attempts = 0
    until found || attempts >= 10
      attempts += 1
      if config[:url]
        uri = URI.parse(config[:url])
        http = Net::HTTP.new(uri.host, uri.port)
        if uri.scheme == 'https'
          http.use_ssl = true
          http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
        request = Net::HTTP::Get.new(uri.request_uri)
        response = http.request(request)
        if response.code == '200'
          found = true
        elsif !response.header['location'].nil?
          config[:url] = response.header['location']
        end
      else
        response = Net::HTTP.start(config[:hostname], config[:port]) do |connection|
          request = Net::HTTP::Get.new("/#{config[:path]}")
          connection.request(request)
        end
        if response.code == '200'
          found = true
        end
      end
    end # until

    # #YELLOW
    response.body.split(/\r?\n/).each do |line|  # rubocop:disable Style/Next
      if line.match(/^Active connections:\s+(\d+)/)
        connections = line.match(/^Active connections:\s+(\d+)/).to_a
        output "#{config[:scheme]}.active_connections", connections[1]
      end
      if line.match(/^\s+(\d+)\s+(\d+)\s+(\d+)/)
        requests = line.match(/^\s+(\d+)\s+(\d+)\s+(\d+)/).to_a
        output "#{config[:scheme]}.accepts", requests[1]
        output "#{config[:scheme]}.handled", requests[2]
        output "#{config[:scheme]}.requests", requests[3]
      end
      if line.match(/^Reading:\s+(\d+).*Writing:\s+(\d+).*Waiting:\s+(\d+)/)
        queue = line.match(/^Reading:\s+(\d+).*Writing:\s+(\d+).*Waiting:\s+(\d+)/).to_a
        output "#{config[:scheme]}.reading", queue[1]
        output "#{config[:scheme]}.writing", queue[2]
        output "#{config[:scheme]}.waiting", queue[3]
      end
    end
    ok
  end
end