text:
<!DOCTYPE html>

		<title>Log Timer</title>
		<meta charset="utf-8" />
		<meta name="robots" content="noindex" />

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

		{{template "nav.html" .}}

Logs

Values can't be changed once entered

		Nui
		<form action="/save/" method="POST">
			0:00

				[edit]

					<input type="text" name="nui" placeholder="Time in minutes" pattern="[0-9]{1,2}" title="Integer, 1-2 digits" />
					<input type="submit" value="Save">

		</form>

		Forest
		<form action="/save/" method="POST">
			0:00

				[edit]

					<input type="text" name="forest" placeholder="Time in minutes" pattern="[0-9]{1,2}" title="Integer, 1-2 digits" />
					<input type="submit" value="Save">

		</form>

		Above the Castle
		<form action="/save/" method="POST">
			0:00

				[edit]

					<input type="text" name="atc" placeholder="Time in minutes" pattern="[0-9]{1,2}" title="Integer, 1-2 digits" />
					<input type="submit" value="Save">

		</form>

		Below the Castle
		<form action="/save/" method="POST">
			0:00

				[edit]

					<input type="text" name="btc" placeholder="Time in minutes" pattern="[0-9]{1,2}" title="Integer, 1-2 digits" />
					<input type="submit" value="Save">

		</form>

Braziers

			Not lit!

			<form action="/brazierStart/" method="POST">
				<input id="bri" type="submit" value="Start Countdown">
			</form>

		{{template "footer.html" .}}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/sdl__progressPanel"
    style="@style/SDL.Group"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <ProgressBar
        android:id="@+id/sdl__progress"
        style="@style/SDL.Progress"
        android:layout_marginRight="@dimen/grid_1" />

    <include layout="@layout/dialog_part_message" />

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
import datetime
# import urllib2
# from urlparse import urlparse

from django import http
from django.shortcuts import render, redirect, get_object_or_404
from django.db import transaction
from django.conf import settings
# from django.core.files import File
from django.utils import timezone
# from django.core.files.temp import NamedTemporaryFile
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.utils.functional import wraps

from jsonview.decorators import json_view
from slugify import slugify
from funfactory.urlresolvers import reverse

# from airmozilla.base.mozillians import fetch_user
from airmozilla.main.models import (
    Channel,
    Event,
    VidlySubmission,
    Template
)
from airmozilla.manage import vidly
from . import forms

def must_be_your_event(f):

    @wraps(f)
    def inner(request, id, **kwargs):
        assert request.user.is_authenticated()
        event = get_object_or_404(Event, pk=id)
        if event.creator != request.user:
            return http.HttpResponseForbidden("Not your event")
        return f(request, event, **kwargs)

    return inner

@transaction.commit_on_success
@login_required
def start(request):
    context = {}
    if request.method == 'POST':
        form = forms.StartForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            # information = fetch_user(name, is_username='@' not in name)

            # print "INFORMATION"
            # from pprint import pprint
            # pprint( information)
            # assert information  # must have something
            # description = []
            # if information.get('bio'):
            #     description.append(information['bio'])
            # if information.get('city'):
            #     description.append('City: %s' % information['city'])
            # if information.get('ircname'):
            #     description.append('IRC nick: %s' % information['ircname'])
            # # lastly make it a string
            # description = '\n'.join(description)

            # additional_links = []
            # if information.get('url'):
            #     additional_links.append(information['url'])
            # for each in information.get('accounts', []):
            #     if '://' in each.get('identifier', ''):
            #         additional_links.append(each['identifier'])
            # # lastly make it a string
            # additional_links = '\n'.join(additional_links)

            now = timezone.now()
            slug = slug_start = slugify(name).lower()
            increment = 1
            while Event.objects.filter(slug=slug):
                slug = slug_start + '-' + timezone.now().strftime('%Y%m%d')
                if increment > 1:
                    slug += '-%s' % increment
                increment += 1

            title = name
            event = Event.objects.create(
                status=Event.STATUS_INITIATED,
                creator=request.user,
                mozillian=name,
                slug=slug,
                title=title,
                privacy=Event.PRIVACY_COMPANY,
                short_description='',
                # description=description,
                # additional_links=additional_links,
                start_time=now,
            )
            # if information.get('photo'):
            #     # download it locally and
        #     photo_name = urlparse(information['photo']).path.split('/')[-1]
            #     img_temp = NamedTemporaryFile(delete=True)
            #     img_temp.write(urllib2.urlopen(information['photo']).read())
            #     img_temp.flush()
            #     event.placeholder_img.save(
            #         photo_name,
            #         File(img_temp),
            #         save=True
            #     )
            # mozillians_channel, __ = Channel.objects.get_or_create(
            #     name=settings.MOZILLIANS_CHANNEL_NAME,
            #     slug=settings.MOZILLIANS_CHANNEL_SLUG,
            # )
            # event.channels.add(mozillians_channel)
            channel, __ = Channel.objects.get_or_create(
                name="MozShortz",
                slug="mozshortz",
            )
            event.channels.add(channel)
            # messages.info(
            #     request,
            #     "That's great!"
            # )
            return redirect('webrtc:details', event.id)
    else:
        form = forms.StartForm()
        qs = (
            Event.objects
            .filter(mozillian__isnull=False)
            .filter(creator=request.user)
        )
        for event in qs:
            context['event'] = event
    context['form'] = form
    return render(request, 'webrtc/start.html', context)

@login_required
@transaction.commit_on_success
@must_be_your_event
def details(request, event):
    if request.method == 'POST':
        form = forms.DetailsForm(request.POST, instance=event)
        if form.is_valid():
            form.save()
            return redirect('webrtc:placeholder', event.id)
    else:
        form = forms.DetailsForm(instance=event)
    context = {
        'form': form,
        'event': event,
    }
    return render(request, 'webrtc/details.html', context)

@login_required
@transaction.commit_on_success
@must_be_your_event
def placeholder(request, event):
    if request.method == 'POST':
        form = forms.PlaceholderForm(
            request.POST,
            request.FILES,
            instance=event
        )
        if form.is_valid():
            event = form.save()
            return redirect('webrtc:video', event.id)
    else:
        form = forms.PlaceholderForm()

    context = {'form': form, 'event': event}
    return render(request, 'webrtc/placeholder.html', context)

@login_required
@transaction.commit_on_success
@must_be_your_event
@json_view
def photobooth(request, event):
    if request.method == 'POST':
        form = forms.PlaceholderForm(
            request.POST,
            request.FILES,
            instance=event
        )
        if form.is_valid():
            event = form.save()
            return {'url': reverse('webrtc:video', args=(event.id,))}
    else:
        form = forms.PlaceholderForm()

    context = {'form': form, 'event': event}
    return render(request, 'webrtc/photobooth.html', context)

@login_required
@transaction.commit_on_success
@must_be_your_event
def video(request, event):
    context = {'event': event}
    request.session['active_event'] = event.id
    return render(request, 'webrtc/video.html', context)

@login_required
@transaction.commit_on_success
@must_be_your_event
def summary(request, event):
    if request.method == 'POST':
        # Start the archiving process.
        # This is basically the same code as
        # in manage.views.vidly_url_to_shortcode().
        token_protection = event.privacy != Event.PRIVACY_PUBLIC
        # email = request.user.email
        email = settings.EMAIL_FROM_ADDRESS
        url = event.upload.url
        shortcode, error = vidly.add_media(
            url,
            email=email,
            token_protection=token_protection,
            hd=True,
        )
        VidlySubmission.objects.create(
            event=event,
            url=url,
            email=email,
            token_protection=token_protection,
            hd=True,
            tag=shortcode,
            submission_error=error
        )
        event.archive_time = None
        event.status = Event.STATUS_PENDING
        template = Template.objects.get(default_archive_template=True)
        event.template = template
        event.template_environment = {'tag': shortcode}
        event.save()
        messages.info(
            request,
            "Excellent! Your video is being transcoded. "
            "Once it finishes, you'll receive an email."
        )
        return redirect('webrtc:summary', event.id)

    successful_vidly_submission = False
    # If the uploaded file has a successful VidlySubmission, there's nothing
    # the user needs to do at this point.
    if event.upload:
        submissions = VidlySubmission.objects.filter(
            event=event,
            url=event.upload.url,
            submission_error__isnull=True,
        )
        for submission in submissions.order_by('-submission_time'):
            successful_vidly_submission = True
            break

    context = {
        'event': event,
        'successful_vidly_submission': successful_vidly_submission,
    }
    return render(request, 'webrtc/summary.html', context)

@json_view
def save(request):
    for key in request.FILES:
        file = request.FILES[key]
        filename = datetime.datetime.now().strftime('file-%H%S.webm')
        with open('/Users/peterbe/Downloads/' + filename, 'wb') as f:
            f.write(file.read())

    return {'done': 'OK'}


text:
package org.hisp.dhis.api.mobile.model;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.List;

import javax.xml.bind.annotation.XmlElement;

public class Section
    extends Model
{
    private String clientVersion;

    private List<DataElement> dataElements;

    @XmlElement( name = "dataElement" )
    public List<DataElement> getDataElements()
    {
        return dataElements;
    }

    public void setDataElements( List<DataElement> des )
    {
        this.dataElements = des;
    }

    @Override
    public String getClientVersion()
    {
        return clientVersion;
    }

    @Override
    public void setClientVersion( String clientVersion )
    {
        this.clientVersion = clientVersion;
    }

    @Override
    public void serialize( DataOutputStream dout )
        throws IOException
    {
        if ( this.getClientVersion().equals( DataStreamSerializable.TWO_POINT_EIGHT ) )
        {
            this.serializeVersion2_8( dout );
        }
        else if ( this.getClientVersion().equals( DataStreamSerializable.TWO_POINT_NINE ) )
        {
            this.serializeVersion2_9( dout );
        }
        else if ( this.getClientVersion().equals( DataStreamSerializable.TWO_POINT_TEN ) )
        {
            this.serializeVersion2_10( dout );
        }
    }

    @Override
    public void serializeVersion2_8( DataOutputStream dout )
        throws IOException
    {
        dout.writeInt( this.getId() );
        dout.writeUTF( getName() );

        if ( dataElements == null )
        {
            dout.writeInt( 0 );
        }
        else
        {
            dout.writeInt( dataElements.size() );
            for ( DataElement de : dataElements )
            {
                de.setClientVersion( TWO_POINT_EIGHT );
                de.serialize( dout );
            }
        }
    }

    @Override
    public void serializeVersion2_9( DataOutputStream dout )
        throws IOException
    {
        dout.writeInt( this.getId() );
        dout.writeUTF( getName() );

        if ( dataElements == null )
        {
            dout.writeInt( 0 );
        }
        else
        {
            dout.writeInt( dataElements.size() );
            for ( DataElement de : dataElements )
            {
                de.setClientVersion( TWO_POINT_NINE );
                de.serialize( dout );
            }
        }
    }

    @Override
    public void serializeVersion2_10( DataOutputStream dout )
        throws IOException
    {
        dout.writeInt( this.getId() );
        dout.writeUTF( getName() );

        if ( dataElements == null )
        {
            dout.writeInt( 0 );
        }
        else
        {
            dout.writeInt( dataElements.size() );
            for ( DataElement de : dataElements )
            {
                de.setClientVersion( TWO_POINT_TEN );
                de.serialize( dout );
            }
        }
    }

}


text:
./configure --prefix=$PREFIX
make
make install

# Run tests
./testit.sh


text:
require 'rails/generators/active_record'
require 'generators/aasm/orm_helpers'

module ActiveRecord
  module Generators
    class AASMGenerator < ActiveRecord::Generators::Base
      include AASM::Generators::OrmHelpers
      namespace "active_record:aasm"
      argument :column_name, type: :string, default: 'aasm_state'

      source_root File.expand_path("../templates", __FILE__)

      def copy_aasm_migration
        if column_exists?
          puts "Both model and column exists"
        elsif model_exists?
          migration_template "migration_existing.rb", "db/migrate/add_#{column_name}_to_#{table_name}.rb"
        else
          migration_template "migration.rb", "db/migrate/aasm_create_#{table_name}.rb"
        end
      end

      def generate_model
        invoke "active_record:model", [name], migration: false unless model_exists?
      end

      def inject_aasm_content
        content = model_contents

        class_path = if namespaced?
                       class_name.to_s.split("::")
                     else
                       [class_name]
                     end
        inject_into_class(model_path, class_path.last, content) if model_exists?
      end

    end
  end
end


text:
package org.mifos.dto.domain;

public class CustomerSearchDto {

	private final String searchTerm;
	private final Integer page;
	private final Integer pageSize;

	public CustomerSearchDto(String searchTerm, Integer page, Integer pageSize) {
		this.searchTerm = searchTerm;
		this.page = page;
		this.pageSize = pageSize;
	}

	public Integer getPage() {
		return this.page;
	}

	public Integer getPageSize() {
		return this.pageSize;
	}

	public String getSearchTerm() {
		return this.searchTerm;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 69(12): 2700 (1992)

#### Original name
Amanita fibrillopes O.K. Mill.

### Remarks
null


text:
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED

#include <pthread.h>
#include <time.h>
#include "e_enum.h"

#define QUEUE_ALLOCATE_EXTRA    60 //extra allocate amount
#define QUEUE_ALLOCATE_TH       30 //50% of the _EXTRA (autoremove threshhold)

#define QUEUE_FLAG_ALLOWGROW    1   //allow to increase amount of slots
#define QUEUE_FLAG_IMID_DEALLOC 2   //imidiatly remove extra slots

#define FOREACH_QERROR(DV)\
    DV(QERROR_OK, 0, "no error")\
    DV(QERROR_OUT_OF_SPACE, 1, "queue has left out of free space")\
    DV(QERROR_NULL_ARG, 2, "queue function argument is null")\
    DV(QERROR_MALLOC, 3, "queue malloc failure")\
    DV(QERROR_EMPTY, 4, "queue list is empty")\
    DV(QERROR_NOTFOUND, 5, "queue item not found")\
    DV(QERROR_CRC32, 6, "crc32 mismatch")

enum qerror
{
    FOREACH_QERROR(GENERATE_ENUM_VAL_EX)
};

typedef int queue_data_destruct(void * qdata);
typedef int queue_compare(void * qdata);

#define BUILD_WITH_QITERATOR 0

#if BUILD_WITH_QITERATOR == 1

    #define QIT_FLAG_STATIC 1

    /*
     * struct queue_iterator
     * A structure with hidden fields, used for queue iterating.
     */
    struct queue_iterator;

#endif

/*
 * struct queue_record
 */
struct queue_record
{
    void * qdata;  //queued data
    uint32_t qdatalen;

    uint64_t uid;
    uint32_t crc32;
    struct timeval time_added;      //received to queue
    uint32_t retry_count;           //requeue amount
#if BUILD_WITH_QITERATOR == 1
    struct queue_iterator * lock;   //locked by iterator
#endif

    struct queue_record * next; //pointer to next record
};

/*
 * struct queue_container
 */
struct queue_container
{
    uint8_t flags;
    uint32_t qid;                               //queue id (uniqie)
    uint32_t cqlen;                             //current queue length
    uint32_t qlen;                              //length of queue
    uint32_t exqlen;                            //extra allocated
    uint32_t recqlen;                           //recycled
    pthread_mutex_t mux;                        //pointer to mutex
    pthread_mutex_t recmux;                     //pointer to mutex
    enum qerror e_qerror;                       //last error
    struct queue_record * queue_front;          //front of the queue
    struct queue_record * queue_tail;           //tail of the queue

    struct queue_record * queue_recycle_front;  //for recycling

    queue_data_destruct * f_qdd_callback;       //called by queue to clean the queued data corrctly
};

#if BUILD_WITH_QITERATOR == 1
/*
 * create_qiterator_stack initializes qiterator statically
 *      (does not require to be deallocated)
 * qc - pointer to the queue container
 * qit - a pointer to the created local queue_iterator instance
 * returns 0 on success, and 1 on fail
 */
int32_t create_qiterator_stack(struct queue_container * qc, struct queue_iterator * qit);

/*
 * Function create_qiterator creates a queue_iterator instance in heap.
 *      (does requre deallocation when no longer to be used)
 * qc - pointer to the queue container
 * returns pointer to the record and NULL on error
 */
struct queue_iterator * create_qiterator(struct queue_container * qc);

/*
 * Function reset_qiterator performs reset of the fields of the queue_iterator
 *      instance for the same queue instance, so it become reusable.
 *      After successfull reset, the qiterator will point to the start of the queue.
 * qit - a pointer to the qiterator record
 * returns 0 on error and 1 on success
 */
int32_t reset_qiterator(struct queue_iterator * qit);

/*
 * Procedure destruct_qiterator reset memeory block for queue_iterator
 *  and deallocates the qiterator instance if it was created with
 *  create_qiterator function.
 * qit - a pointer to the qiterator record
 * returns void
 */
void destruct_qiterator(struct queue_iterator * qit);

/*
 * ATTENTION! Please make sure that the iteration is performed
 *  when mutex allocated to the queue is locked as qiterator does
 *  not perform mutex locking when walking through the queue records.
 *  If the mutex will not be locked it can cause synchronization
 *  problems and lead to the crash of the program.
 *  i.e please use:
 *      MUTEX_BLOCK(mutex, MUTEX_UNLOCK)
 *      {
 *          while (queue_it_next(...)...) ...
 *      }
 */

/*
 * Function queue_it_next gets next record from the queue.
 * qit - a pointer to the qiterator record
 * qrec - a pointer to pointer of the fetched queue record declared locally pointer
 *      (the qrec will be set to the original location of the queue_record, which contains
 *       pointer to the next record, so please don't modify that (this will be fixed later))
 * returns 1 is hasnext == true and 0 when end was reached
 */
int32_t queue_it_next(struct queue_iterator * qit, struct queue_record ** qrec);

/*
 * Function queue_it_remove removes the current iterated instance
 * qit - a pointer to the qiterator record
 * returns 0 on success and 1 on error
 */

int32_t queue_it_remove(struct queue_iterator * qit);

#endif

//---------QITERATOR ENDS

/*
 * queue_container is a queue contructor.
 * qid - queue id
 * mutx - pointer to created mutex for thread safe operations
 * qlen - max queue slots
 *
 * return NULL is error happened, or pointer to struct queue_container.
 */
struct queue_container *
queue_create(uint32_t qid, uint32_t qlen, uint8_t flags, queue_data_destruct * f_qdd_callback);

/*
 * queue destructor
 * qc - pointer to the valid record struct queue_container
 */
void queue_destruct(struct queue_container * qc);

/*
 * free queue record not deallocating payload
 * qc - queue container
 * qr - pointer to pointer of queue record
 */
int32_t queue_free_record(struct queue_container * qc, struct queue_record ** qr);

/*
 * free queue record and payload
 * qc - queue container
 * qr - pointer to pointer of queue record
 */
int32_t queue_free_record_witpayload(struct queue_container * qc, struct queue_record ** qr);

/*
 * removes item fromt the queue
 * qc - queue container
 * rec - pointer to pointer of queue record
 * f_qc_callback - callback for looking in payload for a specific data
 * returns 1 on error and QERROR_NOTFOUND is set
 */
int32_t queue_remove_item(struct queue_container * qc, struct queue_record ** rec, queue_compare * f_qc_callback);

/*
 * runs though the queue and calculating CRC32
 * returns the mount of the errors, 0 is none
 */
int32_t queue_control_errors(struct queue_container * qc);

/*
 * push to queue
 * qc - pointer to queue container
 * req - pointer to request (can be NULL)
 * res - pointer to response (can be NULL)
 * return: 0 on success
 */
int32_t queue_push(struct queue_container * qc, void * dtoq, uint32_t dtoqlen);

/*
 * push to queue
 * qc - pointer to queue container
 * rec - return pointer to queue record on success
 * return: 0 on success
 */
int32_t queue_pop(struct queue_container * qc, struct queue_record ** rec);

/*
 * push queue_record to queue
 * qc - pointer to queue container
 * rec - pointer to valid queue_record
 * return: 0 on success
 */
int32_t queue_repush_record(struct queue_container * qc, struct queue_record * rec);

/*
 * This function is fetching a record from queue by transaction number (tid)
 * qc - pointer to queue container
 * rec - pointer to queue_record on success
 * tid - transaction id which is used to lookup and fetch
 * return: 0 on success
 */
int32_t
queue_fetch_record_by_content(struct queue_container * qc, struct queue_record ** rec, queue_compare * f_qc_callback);

/*
 * checks if queue is empty
 * qc - pointer to queue container
 * return: 1 if error, 0 is queue is NOT empty, -1 if empty
 */
int32_t queue_is_empty(struct queue_container * qc);

/*
 * This function was developed to check if the record with fid and tid is still in the queue.
 * qc - pointer to queue container
 * fid - device fid
 * tid - transaction id
 * return: 0 on success
 */
int32_t queue_is_still_there(struct queue_container * qc, queue_compare * f_qc_callback);

/*
 * queue_get_fslots_amount returns the amount of the available queue slots(places...)
 * qc - pointer to queue container
 * return: amount from 0 to N or if error -1
 */
int32_t queue_get_fslots_amount(struct queue_container * qc, uint32_t * o_amt);

/*
 * returns the amount of the records in queue
 */
int32_t queue_get_amount(struct queue_container * qc, uint32_t * o_amt);

/*
 * queue_get_error returns the error description
 * qc - pointer to queue container
 * returns string (pointer to the char sequence)
 */
const char * queue_get_error(struct queue_container * qc);

enum qerror queue_get_errorcode(struct queue_container * qc);

#endif // QUEUE_H_INCLUDED


text:
var fs = require('fs');
var path = require('path');
var assert = require('assert');

var summary = require('../').parse.summary;

var CONTENT = fs.readFileSync(path.join(__dirname, './fixtures/SUMMARY.md'), 'utf8');
var LEXED = summary(CONTENT);

describe('Summary parsing', function () {
    console.log(LEXED);

    it('should detect chapters', function() {
        assert.equal(LEXED.chapters.length, 5);
    });

    it('should support articles', function() {
        assert.equal(LEXED.chapters[0].articles.length, 2);
        assert.equal(LEXED.chapters[1].articles.length, 0);
        assert.equal(LEXED.chapters[2].articles.length, 0);
    });

    it('should detect paths and titles', function() {
        assert(LEXED.chapters[0].path);
        assert(LEXED.chapters[1].path);
        assert(LEXED.chapters[2].path);
        assert(LEXED.chapters[3].path);
        assert.equal(LEXED.chapters[4].path, null);

        assert(LEXED.chapters[0].title);
        assert(LEXED.chapters[1].title);
        assert(LEXED.chapters[2].title);
        assert(LEXED.chapters[3].title);
        assert(LEXED.chapters[4].title);
    });

    it('should normalize paths from .md to .html', function() {
        assert.equal(LEXED.chapters[0].path,'chapter-1/README.html');
        assert.equal(LEXED.chapters[0]._path,'chapter-1/README.md');
        assert.equal(LEXED.chapters[1].path,'chapter-2/README.html');
        assert.equal(LEXED.chapters[1]._path,'chapter-2/README.md');
        assert.equal(LEXED.chapters[2].path,'chapter-3/README.html');
        assert.equal(LEXED.chapters[2]._path,'chapter-3/README.md');
    });

    it('should detect levels correctly', function() {
        var c = LEXED.chapters;

        assert.equal(c[0].level, '1');
        assert.equal(c[1].level, '2');
        assert.equal(c[2].level, '3');

        assert.equal(c[0].articles[0].level, '1.1');
        assert.equal(c[0].articles[1].level, '1.2');
    });
});


text:
    Owned  by Sleeplessy

    Powered By Jekyll


text:
@interface XMLRPCEncoder : NSObject {
	NSString *_method, *_source;
	NSArray *_objects;
}

- (NSString *)encode;

#pragma mark -

- (void)setMethod: (NSString *)method withObjects: (NSArray *)objects;

#pragma mark -

- (NSString *)method;
- (NSArray *)objects;

#pragma mark -

- (NSString *)source;

@end


text:
.class Lcom/android/gallery3d/ui/SlotView$1;
.super Ljava/lang/Object;
.source "SlotView.java"

# interfaces
.implements Ljava/lang/Runnable;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/gallery3d/ui/SlotView;->render(Lcom/android/gallery3d/ui/GLCanvas;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/gallery3d/ui/SlotView;

.field final synthetic val$listener:Lcom/android/gallery3d/ui/UserInteractionListener;

# direct methods
.method constructor <init>(Lcom/android/gallery3d/ui/SlotView;Lcom/android/gallery3d/ui/UserInteractionListener;)V
    .locals 0
    .parameter
    .parameter

    .prologue
    .line 483
    iput-object p1, p0, Lcom/android/gallery3d/ui/SlotView$1;->this$0:Lcom/android/gallery3d/ui/SlotView;

    iput-object p2, p0, Lcom/android/gallery3d/ui/SlotView$1;->val$listener:Lcom/android/gallery3d/ui/UserInteractionListener;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 1

    .prologue
    .line 486
    iget-object v0, p0, Lcom/android/gallery3d/ui/SlotView$1;->val$listener:Lcom/android/gallery3d/ui/UserInteractionListener;

    invoke-interface {v0}, Lcom/android/gallery3d/ui/UserInteractionListener;->onUserInteractionEnd()V

    .line 487
    return-void
.end method


text:
<?php

/**
 * Spiral Framework.
 *
 * @license   MIT
 * @author    Anton Titov (Wolfy-J)
 */

declare(strict_types=1);

namespace Spiral\Auth;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

/**
 * Provides the ability to read and write token values using PSR-7 Request/Response.
 */
interface HttpTransportInterface
{
    /**
     * Fetch tokenID from incoming request.
     *
     * @param Request $request
     * @return string|null
     */
    public function fetchToken(Request $request): ?string;

    /**
     * Commit (write) token to the outgoing response.
     *
     * @param Request                 $request
     * @param Response                $response
     * @param string                  $tokenID
     * @param \DateTimeInterface|null $expiresAt
     * @return Response
     */
    public function commitToken(
        Request $request,
        Response $response,
        string $tokenID,
        \DateTimeInterface $expiresAt = null
    ): Response;

    /**
     * Remove token from the outgoing response.
     *
     * @param Request  $request
     * @param Response $response
     * @param string   $tokenID
     * @return Response
     */
    public function removeToken(Request $request, Response $response, string $tokenID): Response;
}


text:
package me.stupidme.cooker.presenter;

import android.text.TextUtils;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.stupidme.cooker.mock.MockCookerService;
import me.stupidme.cooker.model.UserBean;
import me.stupidme.cooker.model.http.CookerRetrofit;
import me.stupidme.cooker.model.http.HttpResult;
import me.stupidme.cooker.util.SharedPreferenceUtil;
import me.stupidme.cooker.view.login.LoginView;

/**
 * Created by StupidL on 2017/4/30.
 * <p>
 * A mock presenter to mock server response for test.
 */

public class UserLoginMockPresenterImpl implements UserLoginPresenter {

    //debug
    private static final String TAG = "UserLoginMockPresenter";

    /**
     * A callback interface to transfer response from server to UI fragment.
     */
    private LoginView mView;

    /**
     * A mock server.
     */
    private MockCookerService mMockService;

    public UserLoginMockPresenterImpl(LoginView view) {
        mView = view;
        mMockService = CookerRetrofit.getInstance().getMockService();
    }

    @Override
    public void login(String name, String password, boolean remember) {
        mView.showProgress(true);
        Long userId = SharedPreferenceUtil.getAccountUserId(0L);
        mMockService.login(userId, name, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResult<List<UserBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HttpResult<List<UserBean>> value) {
                        List<UserBean> userBeanList = value.getData();
                        if (userBeanList == null || userBeanList.size() <= 0 || value.getResultCode() != 200) {
                            mView.showProgress(false);
                            mView.showMessage(MESSAGE_WHAT_LOGIN_FAILED, null);
                            return;
                        }
                        if (remember) {
                            UserBean user = userBeanList.get(0);
                            mView.rememberUser(user);
                        }
                        mView.showMessage(MESSAGE_WHAT_LOGIN_SUCCESS, null);
                        mView.loginSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showProgress(false);
                        mView.showMessage(MESSAGE_WHAT_LOGIN_FAILED, e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void attemptAutoLogin() {
        Long userId = SharedPreferenceUtil.getAccountUserId(0L);
        String userName = SharedPreferenceUtil.getAccountUserName("");
        String userPassword = SharedPreferenceUtil.getAccountUserPassword("");
        if (userId == 0L || TextUtils.isEmpty(userName) || TextUtils.isEmpty(userPassword)) {
            mView.showMessage(MESSAGE_WHAT_LOGIN_AUTO_FAILED, null);
            mView.showProgress(false);
            return;
        }
        mMockService.login(userId, userName, userPassword)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HttpResult<List<UserBean>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(HttpResult<List<UserBean>> value) {
                        if (value == null || value.getData().size() <= 0 || value.getResultCode() != 200) {
                            mView.showProgress(false);
                            mView.showMessage(MESSAGE_WHAT_LOGIN_AUTO_FAILED, null);
                            return;
                        }
                        mView.showMessage(MESSAGE_WHAT_LOGIN_AUTO_SUCCESS, null);
                        mView.loginSuccess();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showProgress(false);
                        mView.showMessage(MESSAGE_WHAT_LOGIN_AUTO_FAILED, e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }
}


text:
"""
Sample app to asynchronously read out sensor values.

All sensors are polled on their own thread with individual polling frequencies.The program blocks until cancelled
by a keyboard interrupt.
"""

from sensirion_sensors import find_sensor_by_type, SensorReader

import sys

def main():

    sfm = find_sensor_by_type('sfm3000')
    sdp = find_sensor_by_type('sdp600')
    sht = find_sensor_by_type('sht3x')
    if not all((sfm, sdp, sht)):
        sys.stderr.writelines("couldn't find all sensors\n")
        return

    def print_sensor_values(sensor_name):
        def print_to_console(timestamp, values):
            print "{0}: {1}".format(sensor_name, values.values()[0])
            return True
        return print_to_console

    try:
        sfm_reader = SensorReader((sfm,), 100, print_sensor_values('sfm'))
        sdp_reader = SensorReader((sdp,), 10, print_sensor_values('sdp'))
        sht_reader = SensorReader((sht,), 1, print_sensor_values('sht'))
        sfm_reader.start()
        sdp_reader.start()
        sht_reader.run()
    finally:
        sfm_reader.join()
        sdp_reader.join()

if __name__ == '__main__':
    main()


text:
This is my personal blog, I use Ghost + ghost-s3 plugin

Here is the configuration you have to setup, to get your Ghost running.

```sh
$ herok config:add NODE_ENV=production

$ herok config:add MYSQL_DATABASE=<database-name>
$ herok config:add MYSQL_HOST=<database-host>
$ herok config:add MYSQL_PASSWORD=<database-password>
$ herok config:add MYSQL_USER=<database-username>

$ herok config:add AWS_ACCESS_KEY_ID=<your-aws-access-key>
$ herok config:add AWS_REGION=<your-aws-region>
$ herok config:add AWS_SECRET_ACCESS_KEY=<your-aws-secret-key>
$ herok config:add AWS_STORAGE_BUCKET_NAME=<your-bucket-name>
```


text:
from __future__ import absolute_import

from rest_framework import serializers

from sentry.utils.http import parse_uri_match

class OriginField(serializers.CharField):
    # Special case origins that don't fit the normal regex pattern, but are valid
    WHITELIST_ORIGINS = "*"

    def to_internal_value(self, data):
        rv = super(OriginField, self).to_internal_value(data)
        if not rv:
            return
        if not self.is_valid_origin(rv):
            raise serializers.ValidationError("%s is not an acceptable domain" % rv)
        return rv

    def is_valid_origin(self, value):
        if value in self.WHITELIST_ORIGINS:
            return True

        bits = parse_uri_match(value)
        # ports are not supported on matching expressions (yet)
        if ":" in bits.domain:
            return False

        return True


text:
set -ue

export USER="root"
export LANG=C.UTF-8 LANGUAGE=C.UTF-8

echo "--- bundle install"
bundle config --local path vendor/bundle
bundle install --jobs=7 --retry=3

echo "+++ bundle exec task"
bundle exec $@


text:
class PktVectorException{};

//this is a custon vector that I use to store the packets
// may not needed
class PktVector{
private:
        Packet *m_collection;
        u_int32_t m_capacity;
        u_int32_t m_size;
        void resize();
public:
        PktVector();
        PktVector(u_int32_t capacity);
        ~PktVector();

        void push_back(const u_char *packet, const char *timeRecv, u_int8_t ifType);

        void pop_back();

        const Packet& front();
        const Packet& back();

        const Packet& operator[](int i) const {
            if(i < 0 || i >= (int)m_size)
                throw new PktVectorException();
            return m_collection[i];
        }

        int size();

        void clear();

};

#endif // PACKETVECTOR_H


text:
/**
 * @module ol/format/filter/During
 */
import Comparison from './Comparison.js';

/**
 * @classdesc
 * Represents a `<During>` comparison operator.
 * @api
 */
class During extends Comparison {
  /**
   * @param {!string} propertyName Name of the context property to compare.
   * @param {!string} begin The begin date in ISO-8601 format.
   * @param {!string} end The end date in ISO-8601 format.
   */
  constructor(propertyName, begin, end) {
    super('During', propertyName);

    /**
     * @type {!string}
     */
    this.begin = begin;

    /**
     * @type {!string}
     */
    this.end = end;
  }
}

export default During;


text:
package com.datastax.driver.core.exceptions;

import com.datastax.driver.core.ConsistencyLevel;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * Exception thrown when the coordinator knows there is not enough replicas
 * alive to perform a query with the requested consistency level.
 */
public class UnavailableException extends QueryExecutionException implements CoordinatorException {

    private static final long serialVersionUID = 0;

    private final InetSocketAddress address;
    private final ConsistencyLevel consistency;
    private final int required;
    private final int alive;

    /**
     * This constructor should only be used internally by the driver
     * when decoding error responses.
     */
    public UnavailableException(ConsistencyLevel consistency, int required, int alive) {
        this(null, consistency, required, alive);
    }

    public UnavailableException(InetSocketAddress address, ConsistencyLevel consistency, int required, int alive) {
        super(String.format("Not enough replicas available for query at consistency %s (%d required but only %d alive)", consistency, required, alive));
        this.address = address;
        this.consistency = consistency;
        this.required = required;
        this.alive = alive;
    }

    private UnavailableException(InetSocketAddress address, String message, Throwable cause, ConsistencyLevel consistency, int required, int alive) {
        super(message, cause);
        this.address = address;
        this.consistency = consistency;
        this.required = required;
        this.alive = alive;
    }

    /**
     * The consistency level of the operation triggering this unavailable exception.
     *
     * @return the consistency level of the operation triggering this unavailable exception.
     */
    public ConsistencyLevel getConsistencyLevel() {
        return consistency;
    }

    /**
     * The number of replica acknowledgements/responses required to perform the
     * operation (with its required consistency level).
     *
     * @return the number of replica acknowledgements/responses required to perform the
     * operation.
     */
    public int getRequiredReplicas() {
        return required;
    }

    /**
     * The number of replicas that were known to be alive by the Cassandra
     * coordinator node when it tried to execute the operation.
     *
     * @return The number of replicas that were known to be alive by the Cassandra
     * coordinator node when it tried to execute the operation.
     */
    public int getAliveReplicas() {
        return alive;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public InetAddress getHost() {
        return address.getAddress();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public InetSocketAddress getAddress() {
        return address;
    }

    @Override
    public UnavailableException copy() {
        return new UnavailableException(getAddress(), getMessage(), this, consistency, required, alive);
    }

    /**
     * Create a copy of this exception with a nicer stack trace, and including the coordinator
     * address that caused this exception to be raised.
     *

     * This method is mainly intended for internal use by the driver and exists mainly because:
     *

     *
the original exception was decoded from a response frame
     * and at that time, the coordinator address was not available; and

     *
the newly-created exception will refer to the current thread in its stack trace,
     * which generally yields a more user-friendly stack trace that the original one.

     *

     *
     * @param address The full address of the host that caused this exception to be thrown.
     * @return a copy/clone of this exception, but with the given host address instead of the original one.
     */
    public UnavailableException copy(InetSocketAddress address) {
        return new UnavailableException(address, getMessage(), this, consistency, required, alive);
    }
}


text:
#include <srs_app_mpegts_udp.hpp>

#ifdef SRS_AUTO_STREAM_CASTER

#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

#include <srs_app_config.hpp>
#include <srs_kernel_error.hpp>
#include <srs_kernel_log.hpp>
#include <srs_app_config.hpp>
#include <srs_kernel_ts.hpp>
#include <srs_kernel_buffer.hpp>
#include <srs_kernel_ts.hpp>
#include <srs_kernel_stream.hpp>
#include <srs_kernel_file.hpp>
#include <srs_core_autofree.hpp>
#include <srs_kernel_utility.hpp>
#include <srs_rtmp_stack.hpp>
#include <srs_app_st.hpp>
#include <srs_protocol_utility.hpp>
#include <srs_app_utility.hpp>
#include <srs_protocol_amf0.hpp>
#include <srs_raw_avc.hpp>
#include <srs_app_pithy_print.hpp>
#include <srs_app_rtmp_conn.hpp>
#include <srs_protocol_utility.hpp>

SrsMpegtsQueue::SrsMpegtsQueue()
{
    nb_audios = nb_videos = 0;
}

SrsMpegtsQueue::~SrsMpegtsQueue()
{
    std::map<int64_t, SrsSharedPtrMessage*>::iterator it;
    for (it = msgs.begin(); it != msgs.end(); ++it) {
        SrsSharedPtrMessage* msg = it->second;
        srs_freep(msg);
    }
    msgs.clear();
}

int SrsMpegtsQueue::push(SrsSharedPtrMessage* msg)
{
    int ret = ERROR_SUCCESS;

    // TODO: FIXME: use right way.
    for (int i = 0; i < 10; i++) {
        if (msgs.find(msg->timestamp) == msgs.end()) {
            break;
        }

        // adjust the ts, add 1ms.
        msg->timestamp += 1;

        if (i >= 5) {
            srs_warn("mpegts: free the msg for dts exists, dts=%"PRId64, msg->timestamp);
            srs_freep(msg);
            return ret;
        }
    }

    if (msg->is_audio()) {
        nb_audios++;
    }

    if (msg->is_video()) {
        nb_videos++;
    }

    msgs[msg->timestamp] = msg;

    return ret;
}

SrsSharedPtrMessage* SrsMpegtsQueue::dequeue()
{
    // got 2+ videos and audios, ok to dequeue.
    bool av_ok = nb_videos >= 2 && nb_audios >= 2;
    // 100 videos about 30s, while 300 audios about 30s
    bool av_overflow = nb_videos > 100 || nb_audios > 300;

    if (av_ok || av_overflow) {
        std::map<int64_t, SrsSharedPtrMessage*>::iterator it = msgs.begin();
        SrsSharedPtrMessage* msg = it->second;
        msgs.erase(it);

        if (msg->is_audio()) {
            nb_audios--;
        }

        if (msg->is_video()) {
            nb_videos--;
        }

        return msg;
    }

    return NULL;
}

SrsMpegtsOverUdp::SrsMpegtsOverUdp(SrsConfDirective* c)
{
    stream = new SrsBuffer();
    context = new SrsTsContext();
    buffer = new SrsSimpleStream();
    output = _srs_config->get_stream_caster_output(c);

    sdk = NULL;

    avc = new SrsRawH264Stream();
    aac = new SrsRawAacStream();
    h264_sps_changed = false;
    h264_pps_changed = false;
    h264_sps_pps_sent = false;
    queue = new SrsMpegtsQueue();
    pprint = SrsPithyPrint::create_caster();
}

SrsMpegtsOverUdp::~SrsMpegtsOverUdp()
{
    close();

    srs_freep(buffer);
    srs_freep(stream);
    srs_freep(context);
    srs_freep(avc);
    srs_freep(aac);
    srs_freep(queue);
    srs_freep(pprint);
}

int SrsMpegtsOverUdp::on_udp_packet(sockaddr_in* from, char* buf, int nb_buf)
{
    std::string peer_ip = inet_ntoa(from->sin_addr);
    int peer_port = ntohs(from->sin_port);

    // append to buffer.
    buffer->append(buf, nb_buf);

    srs_info("udp: got %s:%d packet %d/%d bytes",
        peer_ip.c_str(), peer_port, nb_buf, buffer->length());

    return on_udp_bytes(peer_ip, peer_port, buf, nb_buf);
}

int SrsMpegtsOverUdp::on_udp_bytes(string host, int port, char* buf, int nb_buf)
{
    int ret = ERROR_SUCCESS;

    // collect nMB data to parse in a time.
    // TODO: FIXME: comment the following for release.
    //if (buffer->length() < 3 * 1024 * 1024) return ret;
    // TODO: FIXME: remove the debug to file.
#if 0
    SrsFileWriter fw;
    if ((ret = fw.open("latest.ts")) != ERROR_SUCCESS) {
        return ret;
    }
    if ((ret = fw.write(buffer->bytes(), buffer->length(), NULL)) != ERROR_SUCCESS) {
        return ret;
    }
    fw.close();
#endif
#if 0
    SrsFileReader fr;
    if ((ret = fr.open("latest.ts")) != ERROR_SUCCESS) {
        return ret;
    }
    buffer->erase(buffer->length());
    int nb_fbuf = fr.filesize();
    char* fbuf = new char[nb_fbuf];
    SrsAutoFreeA(char, fbuf);
    if ((ret = fr.read(fbuf, nb_fbuf, NULL)) != ERROR_SUCCESS) {
        return ret;
    }
    fr.close();
    buffer->append(fbuf, nb_fbuf);
#endif

    // find the sync byte of mpegts.
    char* p = buffer->bytes();
    for (int i = 0; i < buffer->length(); i++) {
        if (p[i] != 0x47) {
            continue;
        }

        if (i > 0) {
            buffer->erase(i);
        }
        break;
    }

    // drop ts packet when size not modulus by 188
    if (buffer->length() < SRS_TS_PACKET_SIZE) {
        srs_warn("udp: wait %s:%d packet %d/%d bytes", host.c_str(), port, nb_buf, buffer->length());
        return ret;
    }

    // use stream to parse ts packet.
    int nb_packet = buffer->length() / SRS_TS_PACKET_SIZE;
    for (int i = 0; i < nb_packet; i++) {
        char* p = buffer->bytes() + (i * SRS_TS_PACKET_SIZE);
        if ((ret = stream->initialize(p, SRS_TS_PACKET_SIZE)) != ERROR_SUCCESS) {
            return ret;
        }

        // process each ts packet
        if ((ret = context->decode(stream, this)) != ERROR_SUCCESS) {
            srs_warn("mpegts: ignore parse ts packet failed. ret=%d", ret);
            continue;
        }
        srs_info("mpegts: parse ts packet completed");
    }
    srs_info("mpegts: parse udp packet completed");

    // erase consumed bytes
    if (nb_packet > 0) {
        buffer->erase(nb_packet * SRS_TS_PACKET_SIZE);
    }

    return ret;
}

int SrsMpegtsOverUdp::on_ts_message(SrsTsMessage* msg)
{
    int ret = ERROR_SUCCESS;

    pprint->elapse();

    // about the bytes of msg, specified by elementary stream which indicates by PES_packet_data_byte and stream_id
    // for example, when SrsTsStream of SrsTsChannel indicates stream_type is SrsTsStreamVideoMpeg4 and SrsTsStreamAudioMpeg4,
    // the elementary stream can be mux in "2.11 Carriage of ISO/IEC 14496 data" in hls-mpeg-ts-iso13818-1.pdf, page 103
    // @remark, the most popular stream_id is 0xe0 for h.264 over mpegts, which indicates the stream_id is video and
    //      stream_number is 0, where I guess the elementary is specified in annexb format(ISO_IEC_14496-10-AVC-2003.pdf, page 211).
    //      because when audio stream_number is 0, the elementary is ADTS(ISO_IEC_14496-3-AAC-2001.pdf, page 75, 1.A.2.2 ADTS).

    // about the bytes of PES_packet_data_byte, defined in hls-mpeg-ts-iso13818-1.pdf, page 58
    // PES_packet_data_byte "C PES_packet_data_bytes shall be contiguous bytes of data from the elementary stream
    // indicated by the packets stream_id or PID. When the elementary stream data conforms to ITU-T
    // Rec. H.262 | ISO/IEC 13818-2 or ISO/IEC 13818-3, the PES_packet_data_bytes shall be byte aligned to the bytes of this
    // Recommendation | International Standard. The byte-order of the elementary stream shall be preserved. The number of
    // PES_packet_data_bytes, N, is specified by the PES_packet_length field. N shall be equal to the value indicated in the
    // PES_packet_length minus the number of bytes between the last byte of the PES_packet_length field and the first
    // PES_packet_data_byte.
    //
    // In the case of a private_stream_1, private_stream_2, ECM_stream, or EMM_stream, the contents of the
    // PES_packet_data_byte field are user definable and will not be specified by ITU-T | ISO/IEC in the future.

    // about the bytes of stream_id, define in  hls-mpeg-ts-iso13818-1.pdf, page 49
    // stream_id "C In Program Streams, the stream_id specifies the type and number of the elementary stream as defined by the
    // stream_id Table 2-18. In Transport Streams, the stream_id may be set to any valid value which correctly describes the
    // elementary stream type as defined in Table 2-18. In Transport Streams, the elementary stream type is specified in the
    // Program Specific Information as specified in 2.4.4.

    // about the stream_id table, define in Table 2-18 "C Stream_id assignments, hls-mpeg-ts-iso13818-1.pdf, page 52.
    //
    // 110x xxxx
    // ISO/IEC 13818-3 or ISO/IEC 11172-3 or ISO/IEC 13818-7 or ISO/IEC
    // 14496-3 audio stream number x xxxx
    // ((sid >> 5) & 0x07) == SrsTsPESStreamIdAudio
    //
    // 1110 xxxx
    // ITU-T Rec. H.262 | ISO/IEC 13818-2 or ISO/IEC 11172-2 or ISO/IEC
    // 14496-2 video stream number xxxx
    // ((stream_id >> 4) & 0x0f) == SrsTsPESStreamIdVideo

    if (pprint->can_print()) {
        srs_trace("<- "SRS_CONSTS_LOG_STREAM_CASTER" mpegts: got %s age=%d stream=%s, dts=%"PRId64", pts=%"PRId64", size=%d, us=%d, cc=%d, sid=%#x(%s-%d)",
            (msg->channel->apply == SrsTsPidApplyVideo)? "Video":"Audio", pprint->age(), srs_ts_stream2string(msg->channel->stream).c_str(),
            msg->dts, msg->pts, msg->payload->length(), msg->packet->payload_unit_start_indicator, msg->continuity_counter, msg->sid,
            msg->is_audio()? "A":msg->is_video()? "V":"N", msg->stream_number());
    }

    // When the audio SID is private stream 1, we use common audio.
    // @see https://github.com/ossrs/srs/issues/740
    if (msg->channel->apply == SrsTsPidApplyAudio && msg->sid == SrsTsPESStreamIdPrivateStream1) {
        msg->sid = SrsTsPESStreamIdAudioCommon;
    }

    // when not audio/video, or not adts/annexb format, donot support.
    if (msg->stream_number() != 0) {
        ret = ERROR_STREAM_CASTER_TS_ES;
        srs_error("mpegts: unsupported stream format, sid=%#x(%s-%d). ret=%d",
            msg->sid, msg->is_audio()? "A":msg->is_video()? "V":"N", msg->stream_number(), ret);
        return ret;
    }

    // check supported codec
    if (msg->channel->stream != SrsTsStreamVideoH264 && msg->channel->stream != SrsTsStreamAudioAAC) {
        ret = ERROR_STREAM_CASTER_TS_CODEC;
        srs_error("mpegts: unsupported stream codec=%d. ret=%d", msg->channel->stream, ret);
        return ret;
    }

    // parse the stream.
    SrsBuffer avs;
    if ((ret = avs.initialize(msg->payload->bytes(), msg->payload->length())) != ERROR_SUCCESS) {
        srs_error("mpegts: initialize av stream failed. ret=%d", ret);
        return ret;
    }

    // publish audio or video.
    if (msg->channel->stream == SrsTsStreamVideoH264) {
        return on_ts_video(msg, &avs);
    }
    if (msg->channel->stream == SrsTsStreamAudioAAC) {
        return on_ts_audio(msg, &avs);
    }

    // TODO: FIXME: implements it.
    return ret;
}

int SrsMpegtsOverUdp::on_ts_video(SrsTsMessage* msg, SrsBuffer* avs)
{
    int ret = ERROR_SUCCESS;

    // ensure rtmp connected.
    if ((ret = connect()) != ERROR_SUCCESS) {
        return ret;
    }

    // ts tbn to flv tbn.
    uint32_t dts = (uint32_t)(msg->dts / 90);
    uint32_t pts = (uint32_t)(msg->dts / 90);

    // send each frame.
    while (!avs->empty()) {
        char* frame = NULL;
        int frame_size = 0;
        if ((ret = avc->annexb_demux(avs, &frame, &frame_size)) != ERROR_SUCCESS) {
            return ret;
        }

        // 5bits, 7.3.1 NAL unit syntax,
        // ISO_IEC_14496-10-AVC-2003.pdf, page 44.
        //  7: SPS, 8: PPS, 5: I Frame, 1: P Frame
        SrsAvcNaluType nal_unit_type = (SrsAvcNaluType)(frame[0] & 0x1f);

        // ignore the nalu type sps(7), pps(8), aud(9)
        if (nal_unit_type == SrsAvcNaluTypeAccessUnitDelimiter) {
            continue;
        }

        // for sps
        if (avc->is_sps(frame, frame_size)) {
            std::string sps;
            if ((ret = avc->sps_demux(frame, frame_size, sps)) != ERROR_SUCCESS) {
                return ret;
            }

            if (h264_sps == sps) {
                continue;
            }
            h264_sps_changed = true;
            h264_sps = sps;

            if ((ret = write_h264_sps_pps(dts, pts)) != ERROR_SUCCESS) {
                return ret;
            }
            continue;
        }

        // for pps
        if (avc->is_pps(frame, frame_size)) {
            std::string pps;
            if ((ret = avc->pps_demux(frame, frame_size, pps)) != ERROR_SUCCESS) {
                return ret;
            }

            if (h264_pps == pps) {
                continue;
            }
            h264_pps_changed = true;
            h264_pps = pps;

            if ((ret = write_h264_sps_pps(dts, pts)) != ERROR_SUCCESS) {
                return ret;
            }
            continue;
        }

        // ibp frame.
        // TODO: FIXME: we should group all frames to a rtmp/flv message from one ts message.
        srs_info("mpegts: demux avc ibp frame size=%d, dts=%d", ibpframe_size, dts);
        if ((ret = write_h264_ipb_frame(frame, frame_size, dts, pts)) != ERROR_SUCCESS) {
            return ret;
        }
    }

    return ret;
}

int SrsMpegtsOverUdp::write_h264_sps_pps(uint32_t dts, uint32_t pts)
{
    int ret = ERROR_SUCCESS;

    // TODO: FIMXE: there exists bug, see following comments.
    // when sps or pps changed, update the sequence header,
    // for the pps maybe not changed while sps changed.
    // so, we must check when each video ts message frame parsed.
    if (!h264_sps_changed || !h264_pps_changed) {
        return ret;
    }

    // h264 raw to h264 packet.
    std::string sh;
    if ((ret = avc->mux_sequence_header(h264_sps, h264_pps, dts, pts, sh)) != ERROR_SUCCESS) {
        return ret;
    }

    // h264 packet to flv packet.
    int8_t frame_type = SrsCodecVideoAVCFrameKeyFrame;
    int8_t avc_packet_type = SrsCodecVideoAVCTypeSequenceHeader;
    char* flv = NULL;
    int nb_flv = 0;
    if ((ret = avc->mux_avc2flv(sh, frame_type, avc_packet_type, dts, pts, &flv, &nb_flv)) != ERROR_SUCCESS) {
        return ret;
    }

    // the timestamp in rtmp message header is dts.
    uint32_t timestamp = dts;
    if ((ret = rtmp_write_packet(SrsCodecFlvTagVideo, timestamp, flv, nb_flv)) != ERROR_SUCCESS) {
        return ret;
    }

    // reset sps and pps.
    h264_sps_changed = false;
    h264_pps_changed = false;
    h264_sps_pps_sent = true;

    return ret;
}

int SrsMpegtsOverUdp::write_h264_ipb_frame(char* frame, int frame_size, uint32_t dts, uint32_t pts)
{
    int ret = ERROR_SUCCESS;

    // when sps or pps not sent, ignore the packet.
    // @see https://github.com/ossrs/srs/issues/203
    if (!h264_sps_pps_sent) {
        return ERROR_H264_DROP_BEFORE_SPS_PPS;
    }

    // 5bits, 7.3.1 NAL unit syntax,
    // ISO_IEC_14496-10-AVC-2003.pdf, page 44.
    //  7: SPS, 8: PPS, 5: I Frame, 1: P Frame
    SrsAvcNaluType nal_unit_type = (SrsAvcNaluType)(frame[0] & 0x1f);

    // for IDR frame, the frame is keyframe.
    SrsCodecVideoAVCFrame frame_type = SrsCodecVideoAVCFrameInterFrame;
    if (nal_unit_type == SrsAvcNaluTypeIDR) {
        frame_type = SrsCodecVideoAVCFrameKeyFrame;
    }

    std::string ibp;
    if ((ret = avc->mux_ipb_frame(frame, frame_size, ibp)) != ERROR_SUCCESS) {
        return ret;
    }

    int8_t avc_packet_type = SrsCodecVideoAVCTypeNALU;
    char* flv = NULL;
    int nb_flv = 0;
    if ((ret = avc->mux_avc2flv(ibp, frame_type, avc_packet_type, dts, pts, &flv, &nb_flv)) != ERROR_SUCCESS) {
        return ret;
    }

    // the timestamp in rtmp message header is dts.
    uint32_t timestamp = dts;
    return rtmp_write_packet(SrsCodecFlvTagVideo, timestamp, flv, nb_flv);
}

int SrsMpegtsOverUdp::on_ts_audio(SrsTsMessage* msg, SrsBuffer* avs)
{
    int ret = ERROR_SUCCESS;

    // ensure rtmp connected.
    if ((ret = connect()) != ERROR_SUCCESS) {
        return ret;
    }

    // ts tbn to flv tbn.
    uint32_t dts = (uint32_t)(msg->dts / 90);

    // send each frame.
    while (!avs->empty()) {
        char* frame = NULL;
        int frame_size = 0;
        SrsRawAacStreamCodec codec;
        if ((ret = aac->adts_demux(avs, &frame, &frame_size, codec)) != ERROR_SUCCESS) {
            return ret;
        }

        // ignore invalid frame,
        //  * atleast 1bytes for aac to decode the data.
        if (frame_size <= 0) {
            continue;
        }
        srs_info("mpegts: demux aac frame size=%d, dts=%d", frame_size, dts);

        // generate sh.
        if (aac_specific_config.empty()) {
            std::string sh;
            if ((ret = aac->mux_sequence_header(&codec, sh)) != ERROR_SUCCESS) {
                return ret;
            }
            aac_specific_config = sh;

            codec.aac_packet_type = 0;

            if ((ret = write_audio_raw_frame((char*)sh.data(), (int)sh.length(), &codec, dts)) != ERROR_SUCCESS) {
                return ret;
            }
        }

        // audio raw data.
        codec.aac_packet_type = 1;
        if ((ret = write_audio_raw_frame(frame, frame_size, &codec, dts)) != ERROR_SUCCESS) {
            return ret;
        }
    }

    return ret;
}

int SrsMpegtsOverUdp::write_audio_raw_frame(char* frame, int frame_size, SrsRawAacStreamCodec* codec, uint32_t dts)
{
    int ret = ERROR_SUCCESS;

    char* data = NULL;
    int size = 0;
    if ((ret = aac->mux_aac2flv(frame, frame_size, codec, dts, &data, &size)) != ERROR_SUCCESS) {
        return ret;
    }

    return rtmp_write_packet(SrsCodecFlvTagAudio, dts, data, size);
}

int SrsMpegtsOverUdp::rtmp_write_packet(char type, uint32_t timestamp, char* data, int size)
{
    int ret = ERROR_SUCCESS;

    if ((ret = connect()) != ERROR_SUCCESS) {
        return ret;
    }

    SrsSharedPtrMessage* msg = NULL;

    if ((ret = srs_rtmp_create_msg(type, timestamp, data, size, sdk->sid(), &msg)) != ERROR_SUCCESS) {
        srs_error("mpegts: create shared ptr msg failed. ret=%d", ret);
        return ret;
    }
    srs_assert(msg);

    // push msg to queue.
    if ((ret = queue->push(msg)) != ERROR_SUCCESS) {
        srs_error("mpegts: push msg to queue failed. ret=%d", ret);
        return ret;
    }

    // for all ready msg, dequeue and send out.
    for (;;) {
        if ((msg = queue->dequeue()) == NULL) {
            break;
        }

        if (pprint->can_print()) {
            srs_trace("mpegts: send msg %s age=%d, dts=%"PRId64", size=%d",
                msg->is_audio()? "A":msg->is_video()? "V":"N", pprint->age(), msg->timestamp, msg->size);
        }

        // send out encoded msg.
        if ((ret = sdk->send_and_free_message(msg)) != ERROR_SUCCESS) {
            close();
            return ret;
        }
    }

    return ret;
}

int SrsMpegtsOverUdp::connect()
{
    int ret = ERROR_SUCCESS;

    // Ignore when connected.
    if (sdk) {
        return ret;
    }

    int64_t cto = SRS_CONSTS_RTMP_TMMS;
    int64_t sto = SRS_CONSTS_RTMP_PULSE_TMMS;
    sdk = new SrsSimpleRtmpClient(output, cto, sto);

    if ((ret = sdk->connect()) != ERROR_SUCCESS) {
        close();
        srs_error("mpegts: connect %s failed, cto=%"PRId64", sto=%"PRId64". ret=%d", output.c_str(), cto, sto, ret);
        return ret;
    }

    if ((ret = sdk->publish()) != ERROR_SUCCESS) {
        close();
        srs_error("mpegts: publish failed. ret=%d", ret);
        return ret;
    }

    return ret;
}

void SrsMpegtsOverUdp::close()
{
    srs_freep(sdk);
}

#endif


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.net;

import android.content.Context;
import android.net.http.HttpResponseCache;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.Executor;

import javax.net.ssl.HttpsURLConnection;
/**
 * An engine to process {@link UrlRequest}s, which uses the best HTTP stack
 * available on the current platform. An instance of this class can be created
 * using {@link Builder}.
 */
public abstract class CronetEngine {
    /**
     * A builder for {@link CronetEngine}s, which allows runtime configuration of
     * {@code CronetEngine}. Configuration options are set on the builder and
     * then {@link #build} is called to create the {@code CronetEngine}.
     */
    // NOTE(kapishnikov): In order to avoid breaking the existing API clients, all future methods
    // added to this class and other API classes must have default implementation.
    public static class Builder {
        /**
         * A class which provides a method for loading the cronet native library. Apps needing to
         * implement custom library loading logic can inherit from this class and pass an instance
         * to {@link CronetEngine.Builder#setLibraryLoader}. For example, this might be required
         * to work around {@code UnsatisfiedLinkError}s caused by flaky installation on certain
         * older devices.
         */
        public abstract static class LibraryLoader {
            /**
             * Loads the native library.
             * @param libName name of the library to load
             */
            public abstract void loadLibrary(String libName);
        }

        /**
         * Reference to the actual builder implementation.
         * {@hide exclude from JavaDoc}.
         */
        protected final ICronetEngineBuilder mBuilderDelegate;

        /**
         * Constructs a {@link Builder} object that facilitates creating a
         * {@link CronetEngine}. The default configuration enables HTTP/2 and
         * disables QUIC, SDCH and the HTTP cache.
         *
         * @param context Android {@link Context}, which is used by
         *                {@link Builder} to retrieve the application
         *                context. A reference to only the application
         *                context will be kept, so as to avoid extending
         *                the lifetime of {@code context} unnecessarily.
         */
        public Builder(Context context) {
            mBuilderDelegate = ImplLoader.load(context);
        }

        /**
         * Constructs a User-Agent string including application name and version,
         * system build version, model and id, and Cronet version.
         *
         * @return User-Agent string.
         */
        public String getDefaultUserAgent() {
            return mBuilderDelegate.getDefaultUserAgent();
        }

        /**
         * Overrides the User-Agent header for all requests. An explicitly
         * set User-Agent header (set using
         * {@link UrlRequest.Builder#addHeader}) will override a value set
         * using this function.
         *
         * @param userAgent the User-Agent string to use for all requests.
         * @return the builder to facilitate chaining.
         */
        public Builder setUserAgent(String userAgent) {
            mBuilderDelegate.setUserAgent(userAgent);
            return this;
        }

        /**
         * Sets directory for HTTP Cache and Cookie Storage. The directory must
         * exist.
         *

         * NOTE: Do not use the same storage directory with more than one
         * {@code CronetEngine} at a time. Access to the storage directory does
         * not support concurrent access by multiple {@code CronetEngine}s.
         *
         * @param value path to existing directory.
         * @return the builder to facilitate chaining.
         */
        public Builder setStoragePath(String value) {
            mBuilderDelegate.setStoragePath(value);
            return this;
        }

        /**
         * Sets a {@link LibraryLoader} to be used to load the native library.
         * If not set, the library will be loaded using {@link System#loadLibrary}.
         * @param loader {@code LibraryLoader} to be used to load the native library.
         * @return the builder to facilitate chaining.
         */
        public Builder setLibraryLoader(LibraryLoader loader) {
            mBuilderDelegate.setLibraryLoader(loader);
            return this;
        }

        /**
         * Sets whether QUIC protocol
         * is enabled. Defaults to disabled. If QUIC is enabled, then QUIC User Agent Id
         * containing application name and Cronet version is sent to the server.
         * @param value {@code true} to enable QUIC, {@code false} to disable.
         * @return the builder to facilitate chaining.
         */
        public Builder enableQuic(boolean value) {
            mBuilderDelegate.enableQuic(value);
            return this;
        }

        /**
         * Sets whether HTTP/2
         * protocol is enabled. Defaults to enabled.
         * @param value {@code true} to enable HTTP/2, {@code false} to disable.
         * @return the builder to facilitate chaining.
         */
        public Builder enableHttp2(boolean value) {
            mBuilderDelegate.enableHttp2(value);
            return this;
        }

        /**
         * Sets whether
         *
         * SDCH compression is enabled. Defaults to disabled.
         * @param value {@code true} to enable SDCH, {@code false} to disable.
         * @return the builder to facilitate chaining.
         */
        public Builder enableSdch(boolean value) {
            mBuilderDelegate.enableSdch(value);
            return this;
        }

        /**
         * Setting to disable HTTP cache. Some data may still be temporarily stored in memory.
         * Passed to {@link #enableHttpCache}.
         */
        public static final int HTTP_CACHE_DISABLED = 0;

        /**
         * Setting to enable in-memory HTTP cache, including HTTP data.
         * Passed to {@link #enableHttpCache}.
         */
        public static final int HTTP_CACHE_IN_MEMORY = 1;

        /**
         * Setting to enable on-disk cache, excluding HTTP data.
         * {@link #setStoragePath} must be called prior to passing this constant to
         * {@link #enableHttpCache}.
         */
        public static final int HTTP_CACHE_DISK_NO_HTTP = 2;

        /**
         * Setting to enable on-disk cache, including HTTP data.
         * {@link #setStoragePath} must be called prior to passing this constant to
         * {@link #enableHttpCache}.
         */
        public static final int HTTP_CACHE_DISK = 3;

        /**
         * Enables or disables caching of HTTP data and other information like QUIC
         * server information.
         * @param cacheMode control location and type of cached data. Must be one of
         *         {@link #HTTP_CACHE_DISABLED HTTP_CACHE_*}.
         * @param maxSize maximum size in bytes used to cache data (advisory and maybe
         * exceeded at times).
         * @return the builder to facilitate chaining.
         */
        public Builder enableHttpCache(int cacheMode, long maxSize) {
            mBuilderDelegate.enableHttpCache(cacheMode, maxSize);
            return this;
        }

        /**
         * Adds hint that {@code host} supports QUIC.
         * Note that {@link #enableHttpCache enableHttpCache}
         * ({@link #HTTP_CACHE_DISK}) is needed to take advantage of 0-RTT
         * connection establishment between sessions.
         *
         * @param host hostname of the server that supports QUIC.
         * @param port host of the server that supports QUIC.
         * @param alternatePort alternate port to use for QUIC.
         * @return the builder to facilitate chaining.
         */
        public Builder addQuicHint(String host, int port, int alternatePort) {
            mBuilderDelegate.addQuicHint(host, port, alternatePort);
            return this;
        }

        /**
         *

         * Pins a set of public keys for a given host. By pinning a set of public keys,
         * {@code pinsSha256}, communication with {@code hostName} is required to
         * authenticate with a certificate with a public key from the set of pinned ones.
         * An app can pin the public key of the root certificate, any of the intermediate
         * certificates or the end-entry certificate. Authentication will fail and secure
         * communication will not be established if none of the public keys is present in the
         * host's certificate chain, even if the host attempts to authenticate with a
         * certificate allowed by the device's trusted store of certificates.
         *

         *

         * Calling this method multiple times with the same host name overrides the previously
         * set pins for the host.
         *

         *

         * More information about the public key pinning can be found in
         * RFC 7469.
         *

         *
         * @param hostName name of the host to which the public keys should be pinned. A host that
         *                 consists only of digits and the dot character is treated as invalid.
         * @param pinsSha256 a set of pins. Each pin is the SHA-256 cryptographic
         *                   hash of the DER-encoded ASN.1 representation of the Subject Public
         *                   Key Info (SPKI) of the host's X.509 certificate. Use
         *                   {@link java.security.cert.Certificate#getPublicKey()
         *                   Certificate.getPublicKey()} and
         *                   {@link java.security.Key#getEncoded() Key.getEncoded()}
         *                   to obtain DER-encoded ASN.1 representation of the SPKI.
         *                   Although, the method does not mandate the presence of the backup pin
         *                   that can be used if the control of the primary private key has been
         *                   lost, it is highly recommended to supply one.
         * @param includeSubdomains indicates whether the pinning policy should be applied to
         *                          subdomains of {@code hostName}.
         * @param expirationDate specifies the expiration date for the pins.
         * @return the builder to facilitate chaining.
         * @throws NullPointerException if any of the input parameters are {@code null}.
         * @throws IllegalArgumentException if the given host name is invalid or {@code pinsSha256}
         *                                  contains a byte array that does not represent a valid
         *                                  SHA-256 hash.
         */
        public Builder addPublicKeyPins(String hostName, Set<byte[]> pinsSha256,
                boolean includeSubdomains, Date expirationDate) {
            mBuilderDelegate.addPublicKeyPins(
                    hostName, pinsSha256, includeSubdomains, expirationDate);
            return this;
        }

        /**
         * Enables or disables public key pinning bypass for local trust anchors. Disabling the
         * bypass for local trust anchors is highly discouraged since it may prohibit the app
         * from communicating with the pinned hosts. E.g., a user may want to send all traffic
         * through an SSL enabled proxy by changing the device proxy settings and adding the
         * proxy certificate to the list of local trust anchor. Disabling the bypass will most
         * likly prevent the app from sending any traffic to the pinned hosts. For more
         * information see 'How does key pinning interact with local proxies and filters?' at
         * https://www.chromium.org/Home/chromium-security/security-faq
         *
         * @param value {@code true} to enable the bypass, {@code false} to disable.
         * @return the builder to facilitate chaining.
         */
        public Builder enablePublicKeyPinningBypassForLocalTrustAnchors(boolean value) {
            mBuilderDelegate.enablePublicKeyPinningBypassForLocalTrustAnchors(value);
            return this;
        }

        /**
         * Sets experimental options to be used in Cronet.
         *
         * @param options JSON formatted experimental options.
         * @return the builder to facilitate chaining.
         */
        public Builder setExperimentalOptions(String options) {
            mBuilderDelegate.setExperimentalOptions(options);
            return this;
        }

        /**
         * Build a {@link CronetEngine} using this builder's configuration.
         * @return constructed {@link CronetEngine}.
         */
        public CronetEngine build() {
            return mBuilderDelegate.build();
        }
    }

    /**
     * @return a human-readable version string of the engine.
     */
    public abstract String getVersionString();

    /**
     * Shuts down the {@link CronetEngine} if there are no active requests,
     * otherwise throws an exception.
     *
     * Cannot be called on network thread - the thread Cronet calls into
     * Executor on (which is different from the thread the Executor invokes
     * callbacks on). May block until all the {@code CronetEngine}'s
     * resources have been cleaned up.
     */
    public abstract void shutdown();

    /**
     * Starts NetLog logging to a file. The NetLog will contain events emitted
     * by all live CronetEngines. The NetLog is useful for debugging.
     * The file can be viewed using a Chrome browser navigated to
     * chrome://net-internals/#import
     * @param fileName the complete file path. It must not be empty. If the file
     *            exists, it is truncated before starting. If actively logging,
     *            this method is ignored.
     * @param logAll {@code true} to include basic events, user cookies,
     *            credentials and all transferred bytes in the log. This option presents
     *            a privacy risk, since it exposes the user's credentials, and should
     *            only be used with the user's consent and in situations where the log
     *            won't be public.
     *            {@code false} to just include basic events.
     */
    public abstract void startNetLogToFile(String fileName, boolean logAll);

    /**
     * Stops NetLog logging and flushes file to disk. If a logging session is
     * not in progress, this call is ignored.
     */
    public abstract void stopNetLog();

    /**
     * Returns differences in metrics collected by Cronet since the last call to
     * this method.
     *

     * Cronet collects these metrics globally. This means deltas returned by
     * {@code getGlobalMetricsDeltas()} will include measurements of requests
     * processed by other {@link CronetEngine} instances. Since this function
     * returns differences in metrics collected since the last call, and these
     * metrics are collected globally, a call to any {@code CronetEngine}
     * instance's {@code getGlobalMetricsDeltas()} method will affect the deltas
     * returned by any other {@code CronetEngine} instance's
     * {@code getGlobalMetricsDeltas()}.
     *

     * Cronet starts collecting these metrics after the first call to
     * {@code getGlobalMetricsDeltras()}, so the first call returns no
     * useful data as no metrics have yet been collected.
     *
     * @return differences in metrics collected by Cronet, since the last call
     *         to {@code getGlobalMetricsDeltas()}, serialized as a
     *         protobuf
     *         .
     */
    public abstract byte[] getGlobalMetricsDeltas();

    /**
     * Establishes a new connection to the resource specified by the {@link URL} {@code url}.
     *

     * Note: Cronet's {@link java.net.HttpURLConnection} implementation is subject to certain
     * limitations, see {@link #createURLStreamHandlerFactory} for details.
     *
     * @param url URL of resource to connect to.
     * @return an {@link java.net.HttpURLConnection} instance implemented by this CronetEngine.
     * @throws IOException if an error occurs while opening the connection.
     */
    public abstract URLConnection openConnection(URL url) throws IOException;

    /**
     * Creates a {@link URLStreamHandlerFactory} to handle HTTP and HTTPS
     * traffic. An instance of this class can be installed via
     * {@link URL#setURLStreamHandlerFactory} thus using this CronetEngine by default for
     * all requests created via {@link URL#openConnection}.
     *

     * Cronet does not use certain HTTP features provided via the system:
     *

     *
the HTTP cache installed via
     *     {@link HttpResponseCache#install(java.io.File, long) HttpResponseCache.install()}

     *
the HTTP authentication method installed via
     *     {@link java.net.Authenticator#setDefault}

     *
the HTTP cookie storage installed via {@link java.net.CookieHandler#setDefault}

     *

     *

     * While Cronet supports and encourages requests using the HTTPS protocol,
     * Cronet does not provide support for the
     * {@link HttpsURLConnection} API. This lack of support also
     * includes not using certain HTTPS features provided via the system:
     *

     *
the HTTPS hostname verifier installed via {@link
     *   HttpsURLConnection#setDefaultHostnameVerifier(javax.net.ssl.HostnameVerifier)
     *     HttpsURLConnection.setDefaultHostnameVerifier()}

     *
the HTTPS socket factory installed via {@link
     *   HttpsURLConnection#setDefaultSSLSocketFactory(javax.net.ssl.SSLSocketFactory)
     *     HttpsURLConnection.setDefaultSSLSocketFactory()}

     *

     *
     * @return an {@link URLStreamHandlerFactory} instance implemented by this
     *         CronetEngine.
     */
    public abstract URLStreamHandlerFactory createURLStreamHandlerFactory();

    /**
     * Creates a builder for {@link UrlRequest}. All callbacks for
     * generated {@link UrlRequest} objects will be invoked on
     * {@code executor}'s threads. {@code executor} must not run tasks on the
     * thread calling {@link Executor#execute} to prevent blocking networking
     * operations and causing exceptions during shutdown.
     *
     * @param url URL for the generated requests.
     * @param callback callback object that gets invoked on different events.
     * @param executor {@link Executor} on which all callbacks will be invoked.
     */
    public abstract UrlRequest.Builder newUrlRequestBuilder(
            String url, UrlRequest.Callback callback, Executor executor);
}


text:
package org.ovirt.engine.core.bll;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.ovirt.engine.core.common.action.ImportRepoImageParameters;
import org.ovirt.engine.core.common.businessentities.StoragePoolStatus;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.errors.EngineMessage;

/** A test case for {@link org.ovirt.engine.core.bll.ImportRepoImageCommandTest} */
@RunWith(MockitoJUnitRunner.class)
public class ImportRepoImageCommandTest extends ImportExportRepoImageCommandTest {

    protected ImportRepoImageCommand<ImportRepoImageParameters> cmd;

    @Before
    public void setUp() {
        super.setUp();

        ImportRepoImageParameters importParameters = new ImportRepoImageParameters();

        importParameters.setSourceRepoImageId(getRepoImageId());
        importParameters.setSourceStorageDomainId(getRepoStorageDomainId());
        importParameters.setStoragePoolId(getStoragePoolId());
        importParameters.setStorageDomainId(getStorageDomainId());

        cmd = spy(new ImportRepoImageCommand<>(importParameters));

        doReturn(getStorageDomainDao()).when(cmd).getStorageDomainDao();
        doReturn(getStoragePoolDao()).when(cmd).getStoragePoolDao();
        doReturn(getProviderProxy()).when(cmd).getProviderProxy();
        doReturn(true).when(cmd).validateSpaceRequirements(any(DiskImage.class));
    }

    @Test
    public void testCanDoActionSuccess() {
        CanDoActionTestUtils.runAndAssertCanDoActionSuccess(cmd);
    }

    @Test
    public void testCanDoActionImageDoesNotExist() {
        when(getProviderProxy().getImageAsDiskImage(getRepoImageId())).thenReturn(null);
        CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd,
                EngineMessage.ACTION_TYPE_FAILED_DISK_NOT_EXIST);
    }

    @Test
    public void testCanDoActionPoolInMaintenance() {
        getStoragePool().setStatus(StoragePoolStatus.Maintenance);
        CanDoActionTestUtils.runAndAssertCanDoActionFailure(cmd,
                EngineMessage.ACTION_TYPE_FAILED_IMAGE_REPOSITORY_NOT_FOUND);
    }
}


text:
// <copyright file="IHealthReportingBuilder.cs" company="App Metrics Contributors">
// Copyright (c) App Metrics Contributors. All rights reserved.
// </copyright>

using System;

// ReSharper disable CheckNamespace
namespace App.Metrics.Health
    // ReSharper restore CheckNamespace
{
    public interface IHealthReportingBuilder
    {
        /// <summary>
        ///     Gets the <see cref="IHealthBuilder" /> where App Metrics Health is configured.
        /// </summary>
        IHealthBuilder Builder { get; }

        /// <summary>
        ///     Reports health status using the specified <see cref="IReportHealthStatus" />.
        /// </summary>
        /// <param name="reporter">An <see cref="IReportHealthStatus" /> instance used to report health status.</param>
        /// <returns>
        ///     An <see cref="IHealthBuilder" /> that can be used to further configure App Metrics Health.
        /// </returns>
        IHealthBuilder Using(IReportHealthStatus reporter);

        /// <summary>
        ///     Reports metrics using the specified <see cref="IReportHealthStatus" />.
        /// </summary>
        /// <typeparam name="TReportHealth">
        ///     An <see cref="IReportHealthStatus" /> type used to report health status.
        /// </typeparam>
        /// <returns>
        ///     An <see cref="IHealthBuilder" /> that can be used to further configure App Metrics Health.
        /// </returns>
        IHealthBuilder Using<TReportHealth>()
            where TReportHealth : IReportHealthStatus, new();

        /// <summary>
        ///     Reports metrics using the specified <see cref="IReportHealthStatus" />.
        /// </summary>
        /// <param name="reportInterval">The <see cref="TimeSpan" /> interval used to schedule health status reporting.</param>
        /// <typeparam name="TReportHealth">
        ///     An <see cref="IReportHealthStatus" /> type used to report health status.
        /// </typeparam>
        /// <returns>
        ///     An <see cref="IHealthBuilder" /> that can be used to further configure App Metrics Health.
        /// </returns>
        IHealthBuilder Using<TReportHealth>(TimeSpan reportInterval)
            where TReportHealth : IReportHealthStatus, new();
    }
}


text:
package highlighterfragmenter

import "strings"

// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/_global/search/_types/highlighting.ts#L67-L70
type HighlighterFragmenter struct {
	Name string
}

var (
	Simple = HighlighterFragmenter{"simple"}

	Span = HighlighterFragmenter{"span"}
)

func (h HighlighterFragmenter) MarshalText() (text []byte, err error) {
	return []byte(h.String()), nil
}

func (h *HighlighterFragmenter) UnmarshalText(text []byte) error {
	switch strings.ToLower(string(text)) {

	case "simple":
		*h = Simple
	case "span":
		*h = Span
	default:
		*h = HighlighterFragmenter{string(text)}
	}

	return nil
}

func (h HighlighterFragmenter) String() string {
	return h.Name
}


text:
module ApplicationHelper
  def avatar_url(user)
    gravatar_id = Digest::MD5::hexdigest(user.email_address.downcase)
    "https://www.gravatar.com/avatar/#{gravatar_id}"
  end

  def display_onboarding?
    current_user.repos.select { |repo| repo.builds.any? }.empty?
  end
end


text:
namespace ui {
class LocatedEvent;
}  // namespace ui

namespace ash {

class AppListControllerImpl;
class AppListPresenterImpl;
class AppListView;

// Listens for mouse clicks and taps outside the app list to close the UI when
// necessary. Used by the peeking/fullscreen launcher.
class ASH_EXPORT AppListPresenterEventFilter : public ui::EventHandler {
 public:
  AppListPresenterEventFilter(AppListControllerImpl* controller,
                              AppListPresenterImpl* presenter,
                              AppListView* view);
  AppListPresenterEventFilter(const AppListPresenterEventFilter&) = delete;
  AppListPresenterEventFilter& operator=(const AppListPresenterEventFilter&) =
      delete;
  ~AppListPresenterEventFilter() override;

  // ui::EventHandler overrides:
  void OnMouseEvent(ui::MouseEvent* event) override;
  void OnGestureEvent(ui::GestureEvent* event) override;
  void OnKeyEvent(ui::KeyEvent* event) override;

 private:
  void ProcessLocatedEvent(ui::LocatedEvent* event);

  AppListControllerImpl* const controller_;
  AppListPresenterImpl* const presenter_;
  AppListView* const view_;
};

}  // namespace ash

#endif  // ASH_APP_LIST_APP_LIST_PRESENTER_EVENT_FILTER_H_


text:
#include "ethernet.h"
#include "system/generic.h"
#include "stm32f4x7_eth.h"
#include "stm32f2x7_eth_bsp.h"

volatile uint EthInitStatus = 0;

static void ETH_GPIO_Config(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

#ifdef MII_MODE
#ifdef PHY_CLOCK_MCO
    RCC_MCO1Config(RCC_MCO1Source_HSE, RCC_MCO1Div_1);
#endif
    SYSCFG_ETH_MediaInterfaceConfig(SYSCFG_ETH_MediaInterface_MII);
#elif defined RMII_MODE
    RCC_MCO1Config(RCC_MCO1Source_PLLCLK, RCC_MCO1Div_2);
    SYSCFG_ETH_MediaInterfaceConfig(SYSCFG_ETH_MediaInterface_RMII);
#endif

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_7;
    GPIO_Init(GPIOA, &GPIO_InitStructure);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource1, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_ETH);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_5 | GPIO_Pin_8 | GPIO_Pin_10 | GPIO_Pin_11 | GPIO_Pin_13 | GPIO_Pin_12;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource0, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource1, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource5, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource8, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource12, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_ETH);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5;
    GPIO_Init(GPIOC, &GPIO_InitStructure);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource1, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource2, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource3, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource4, GPIO_AF_ETH);
    GPIO_PinAFConfig(GPIOC, GPIO_PinSource5, GPIO_AF_ETH);
}

static void ETH_NVIC_Config(void)
{
    NVIC_InitTypeDef   NVIC_InitStructure;

    /* 2 bit for pre-emption priority, 2 bits for subpriority */
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);

    /* Enable the Ethernet global Interrupt */
    NVIC_InitStructure.NVIC_IRQChannel = ETH_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 10;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
}

static void ETH_MACDMA_Config(void)
{
    ETH_InitTypeDef ETH_InitStructure;

    ETH_DeInit();
    ETH_SoftwareReset();

    while (ETH_GetSoftwareResetStatus() == SET);

    ETH_StructInit(&ETH_InitStructure);

    ETH_InitStructure.ETH_AutoNegotiation = ETH_AutoNegotiation_Disable;
    ETH_InitStructure.ETH_Speed = ETH_Speed_100M; // <<<< was 10M
    ETH_InitStructure.ETH_Mode = ETH_Mode_HalfDuplex;
    ETH_InitStructure.ETH_LoopbackMode = ETH_LoopbackMode_Disable;
    ETH_InitStructure.ETH_RetryTransmission = ETH_RetryTransmission_Enable; // <<<< was Disable
    ETH_InitStructure.ETH_AutomaticPadCRCStrip = ETH_AutomaticPadCRCStrip_Disable;
    ETH_InitStructure.ETH_ReceiveAll = ETH_ReceiveAll_Disable;
    ETH_InitStructure.ETH_BroadcastFramesReception = ETH_BroadcastFramesReception_Enable;
    ETH_InitStructure.ETH_PromiscuousMode = ETH_PromiscuousMode_Disable;
    ETH_InitStructure.ETH_MulticastFramesFilter = ETH_MulticastFramesFilter_Perfect;
    ETH_InitStructure.ETH_UnicastFramesFilter = ETH_UnicastFramesFilter_Perfect;
#ifdef CHECKSUM_BY_HARDWARE
    ETH_InitStructure.ETH_ChecksumOffload = ETH_ChecksumOffload_Enable;
#endif
    ETH_InitStructure.ETH_DropTCPIPChecksumErrorFrame = ETH_DropTCPIPChecksumErrorFrame_Enable;
    ETH_InitStructure.ETH_ReceiveStoreForward = ETH_ReceiveStoreForward_Enable;
    ETH_InitStructure.ETH_TransmitStoreForward = ETH_TransmitStoreForward_Enable;

    ETH_InitStructure.ETH_ForwardErrorFrames = ETH_ForwardErrorFrames_Disable;
    ETH_InitStructure.ETH_ForwardUndersizedGoodFrames = ETH_ForwardUndersizedGoodFrames_Disable;
    ETH_InitStructure.ETH_SecondFrameOperate = ETH_SecondFrameOperate_Enable;
    ETH_InitStructure.ETH_AddressAlignedBeats = ETH_AddressAlignedBeats_Enable;
    ETH_InitStructure.ETH_FixedBurst = ETH_FixedBurst_Enable;
    ETH_InitStructure.ETH_RxDMABurstLength = ETH_RxDMABurstLength_32Beat;
    ETH_InitStructure.ETH_TxDMABurstLength = ETH_TxDMABurstLength_32Beat;
    ETH_InitStructure.ETH_DMAArbitration = ETH_DMAArbitration_RoundRobin_RxTx_2_1;

    EthInitStatus = ETH_Init(&ETH_InitStructure, DP83848_PHY_ADDRESS);

    ETH_DMAITConfig(ETH_DMA_IT_NIS | ETH_DMA_IT_R, ENABLE);
}

void ethernet_initialize(void)
{
    ETH_GPIO_Config();
    ETH_NVIC_Config();
    ETH_MACDMA_Config();

    // TODO: Make it safe
    if (EthInitStatus == 0)
        while (1);
}


text:
package com.likya.tlossw.core.spc.helpers;

import java.util.ArrayList;

public class LimitedArrayList<E> extends ArrayList<E> {

	public LimitedArrayList() {
		super();
	}

	public LimitedArrayList(int maxLength) {
		super();
		setMaxLength(maxLength);
	}

	private static final long serialVersionUID = 238155686014345308L;

	private int maxLength = -1;

	@Override
	public boolean add(E e) {
		if (maxLength > 0 && this.size() == maxLength) {
			super.remove(0);
		}
		return super.add(e);
	}

	public int getMaxLength() {
		return maxLength;
	}

	public void setMaxLength(int maxLength) {
		if (maxLength < 1) {
			throw new IllegalArgumentException("Illegal Capacity: " + maxLength);
		}
		this.maxLength = maxLength;
	}

}


text:
<?php

namespace Scraip\StudyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Event
 */
class Event
{
    /**
     * @var integer
     */
    private $event_id;

    /**
     * @var string
     */
    private $event_title;

    /**
     * @var string
     */
    private $url;

    /**
     * @var string
     */
    private $event_detail;

    /**
     * @var string
     */
    private $event_address;

    /**
     * @var string
     */
    private $event_pref;

    /**
     * @var string
     */
    private $event_year;

    /**
     * @var string
     */
    private $event_month;

    /**
     * @var string
     */
    private $event_day;

    /**
     * @var \DateTime
     */
    private $last_update;

    /**
     * Set event_id
     *
     * @param integer $eventId
     * @return Event
     */
    public function setEventId($eventId)
    {
        $this->event_id = $eventId;

        return $this;
    }

    /**
     * Get event_id
     *
     * @return integer
     */
    public function getEventId()
    {
        return $this->event_id;
    }

    /**
     * Set event_title
     *
     * @param string $eventTitle
     * @return Event
     */
    public function setEventTitle($eventTitle)
    {
        $this->event_title = $eventTitle;

        return $this;
    }

    /**
     * Get event_title
     *
     * @return string
     */
    public function getEventTitle()
    {
        return $this->event_title;
    }

    /**
     * Set url
     *
     * @param string $url
     * @return Event
     */
    public function setUrl($url)
    {
        $this->url = $url;

        return $this;
    }

    /**
     * Get url
     *
     * @return string
     */
    public function getUrl()
    {
        return $this->url;
    }

    /**
     * Set event_detail
     *
     * @param string $eventDetail
     * @return Event
     */
    public function setEventDetail($eventDetail)
    {
        $this->event_detail = $eventDetail;

        return $this;
    }

    /**
     * Get event_detail
     *
     * @return string
     */
    public function getEventDetail()
    {
        return $this->event_detail;
    }

    /**
     * Set event_address
     *
     * @param string $eventAddress
     * @return Event
     */
    public function setEventAddress($eventAddress)
    {
        $this->event_address = $eventAddress;

        return $this;
    }

    /**
     * Get event_address
     *
     * @return string
     */
    public function getEventAddress()
    {
        return $this->event_address;
    }

    /**
     * Set event_pref
     *
     * @param string $eventPref
     * @return Event
     */
    public function setEventPref($eventPref)
    {
        $this->event_pref = $eventPref;

        return $this;
    }

    /**
     * Get event_pref
     *
     * @return string
     */
    public function getEventPref()
    {
        return $this->event_pref;
    }

    /**
     * Set event_year
     *
     * @param string $eventYear
     * @return Event
     */
    public function setEventYear($eventYear)
    {
        $this->event_year = $eventYear;

        return $this;
    }

    /**
     * Get event_year
     *
     * @return string
     */
    public function getEventYear()
    {
        return $this->event_year;
    }

    /**
     * Set event_month
     *
     * @param string $eventMonth
     * @return Event
     */
    public function setEventMonth($eventMonth)
    {
        $this->event_month = $eventMonth;

        return $this;
    }

    /**
     * Get event_month
     *
     * @return string
     */
    public function getEventMonth()
    {
        return $this->event_month;
    }

    /**
     * Set event_day
     *
     * @param string $eventDay
     * @return Event
     */
    public function setEventDay($eventDay)
    {
        $this->event_day = $eventDay;

        return $this;
    }

    /**
     * Get event_day
     *
     * @return string
     */
    public function getEventDay()
    {
        return $this->event_day;
    }

    /**
     * Set last_update
     *
     * @param \DateTime $lastUpdate
     * @return Event
     */
    public function setLastUpdate($lastUpdate)
    {
        $this->last_update = $lastUpdate;

        return $this;
    }

    /**
     * Get last_update
     *
     * @return \DateTime
     */
    public function getLastUpdate()
    {
        return $this->last_update;
    }
}