text:
package com.google.cloud.memcache.v1beta2.samples;

// [START memcache_v1beta2_generated_CloudMemcache_ApplySoftwareUpdate_StringListstringBoolean_sync]
import com.google.cloud.memcache.v1beta2.CloudMemcacheClient;
import com.google.cloud.memcache.v1beta2.Instance;
import com.google.cloud.memcache.v1beta2.InstanceName;
import java.util.ArrayList;
import java.util.List;

public class SyncApplySoftwareUpdateStringListstringBoolean {

  public static void main(String[] args) throws Exception {
    syncApplySoftwareUpdateStringListstringBoolean();
  }

  public static void syncApplySoftwareUpdateStringListstringBoolean() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudMemcacheClient cloudMemcacheClient = CloudMemcacheClient.create()) {
      String instance = InstanceName.of("[PROJECT]", "[LOCATION]", "[INSTANCE]").toString();
      List<String> nodeIds = new ArrayList<>();
      boolean applyAll = true;
      Instance response =
          cloudMemcacheClient.applySoftwareUpdateAsync(instance, nodeIds, applyAll).get();
    }
  }
}
// [END memcache_v1beta2_generated_CloudMemcache_ApplySoftwareUpdate_StringListstringBoolean_sync]


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

		<item value="false" key="isRegEx"/>
		<item value="" key="selection"/>
		<item value="false" key="casesensitive"/>
		<item value="false" key="incremental"/>
		<item value="true" key="wrap"/>
		<item value="false" key="wholeword"/>
		<list key="findhistory">
			<item value="¹?0Ebo`b["/>
			<item value="varietal""/>
			<item value="varietal"/>
			<item value="origin""/>
			<item value="origin"/>
			<item value="primary"/>
			<item value="is_dead"/>
			<item value="},"/>
		</list>
		<list key="replacehistory">
		</list>

		<item value="257" key="DIALOG_WIDTH"/>
		<item value="1|Segoe UI|9.0|0|WINDOWS|1|-12|0|0|0|400|0|0|0|1|0|0|0|0|Segoe UI" key="DIALOG_FONT_NAME"/>
		<item value="381" key="DIALOG_HEIGHT"/>
		<item value="809" key="DIALOG_X_ORIGIN"/>
		<item value="120" key="DIALOG_Y_ORIGIN"/>

redpajama_set_name: RedPajamaGithub


text:
@class ELCell;

@interface ELSurfaceView : LMHoneycombView {
  NSMutableArray  *octaveColors;
  // NSColor         *tokenColor;
  NSEvent         *savedEvent;
}

@property (assign) NSColor *tokenColor;

- (void)setActivePlayheadColor:(NSColor *)color;
- (NSColor *)activePlayheadColor;
- (void)setTonicNoteColor:(NSColor *)color;
- (NSColor *)tonicNoteColor;
- (void)setScaleNoteColor:(NSColor *)color;
- (NSColor *)scaleNoteColor;
- (NSColor *)octaveColor:(int)octave;

- (ELCell *)cellUnderMouseLocation:(NSPoint)point;
- (ELCell *)selectedCell;

- (void)dragFromCell:(ELCell *)sourceCell to:(ELCell *)targetCell with:(NSDragOperation)modifiers;

- (void)cellWasUpdated:(NSNotification*)notification;

@end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.AI.TextAnalytics.Models
{
    [CodeGenModel("WarningCodeValue")]
    internal enum WarningCodeValue
    {
        /// <summary> LongWordsInDocument. </summary>
        LongWordsInDocument,
        /// <summary> DocumentTruncated. </summary>
        DocumentTruncated
    }
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateApiRequestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('api_requests', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->string('url');
            $table->string('method');
            $table->timestamps();
            $table->softDeletes();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('api_requests', function (Blueprint $table) {
            $table->dropForeign('api_requests_user_id_foreign');
            $table->drop();
        });
    }
}


text:
<?php

namespace blinkmobile;

class IsUaGzipCapable
{
    private static function testAcceptEncoding($acceptEncoding = null)
    {
        return is_string($acceptEncoding) && stripos($acceptEncoding, 'gzip') !== false;
    }

    private static function testUserAgentString($userAgent = null)
    {
        if (empty($userAgent) || !is_string($userAgent)) {
            return true;
        }
        if (stripos($userAgent, 'MSIE') !== false ||  stripos($userAgent, 'Trident') !== false) {
            if (stripos($userAgent, 'rv:11.0') !== false) {
                // https://connect.microsoft.com/IE/feedbackdetail/view/950689
                return false;
            }
            // http://httpd.apache.org/docs/2.0/en/mod/mod_deflate.html
            return true;
        }

        if (stripos($userAgent, 'Mozilla/4') === 0) {
            // http://httpd.apache.org/docs/2.0/en/mod/mod_deflate.html
            // technically we should still GZIP text/html, but this is easier
            return false;
        }
        return true;
    }

    public static function testRequest($_server = null)
    {
        if ($_server == null || !is_array($_server)) {
            if (!empty($_SERVER)) {
                $_server = $_SERVER;
            } else {
                $_server = array(
                    'HTTP_ACCEPT_ENCODING' => '',
                    'HTTP_USER_AGENT' => ''
                );
            }
        }
        if (!self::testAcceptEncoding($_server['HTTP_ACCEPT_ENCODING'])) {
            // never GZIP if the user agent doesn't accept it
            return false;
        }
        return self::testUserAgentString($_server['HTTP_USER_AGENT']);
    }
}


text:
#region Usings

using System;
using System.Threading;
using System.Threading.Tasks;
using ModInstallation.Annotations;
using ModInstallation.Interfaces.Mods;

#endregion

namespace ModInstallation.Interfaces
{
    public interface IPackageInstaller
    {
        [NotNull]
        string InstallationDirectory { get; set; }

        [NotNull]
        Task InstallPackageAsync([NotNull] IPackage package, [NotNull] IProgress<IInstallationProgress> progressReporter, CancellationToken token);

        /// <summary>
        ///     Uninstalles a package. This should delete the files associated with the specified package. If
        ///     <paramref name="uninstallMod" /> is <c>true</c> the mod associated with <paramref name="package" /> will be
        ///     uninstalled.
        /// </summary>
        /// <param name="package">The package to be uninstalled</param>
        /// <param name="uninstallMod"><c>true</c> if uninstallation should be forced</param>
        /// <param name="progressReporter">A progress reporter</param>
        /// <param name="token">Token to cancel the operation</param>
        /// <exception cref="InvalidOperationException">
        ///     Thrown if <paramref name="package" /> has insufficient file informations and
        ///     <paramref name="uninstallMod" /> is <c>false</c>.
        /// </exception>
        /// <returns>An async Task</returns>
        Task UninstallPackageAsync(IPackage package, bool uninstallMod, IProgress<IInstallationProgress> progressReporter, CancellationToken token);
    }

    public interface IInstallationProgress
    {
        [NotNull]
        string Message { get; }

        double OverallProgress { get; }

        double SubProgress { get; }
    }
}


text:
#ifndef SVGCircleElement_h
#define SVGCircleElement_h

#include "core/SVGNames.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/SVGGeometryElement.h"
#include "platform/heap/Handle.h"

namespace blink {

class SVGCircleElement final : public SVGGeometryElement {
    DEFINE_WRAPPERTYPEINFO();
public:
    DECLARE_NODE_FACTORY(SVGCircleElement);

    SVGAnimatedLength* cx() const { return m_cx.get(); }
    SVGAnimatedLength* cy() const { return m_cy.get(); }
    SVGAnimatedLength* r() const { return m_r.get(); }

    DECLARE_VIRTUAL_TRACE();

private:
    explicit SVGCircleElement(Document&);

    virtual void svgAttributeChanged(const QualifiedName&) override;

    virtual bool isPresentationAttribute(const QualifiedName&) const override;
    virtual bool isPresentationAttributeWithSVGDOM(const QualifiedName&) const override;
    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) override;

    virtual bool selfHasRelativeLengths() const override;

    virtual LayoutObject* createLayoutObject(const ComputedStyle&) override;

    RefPtrWillBeMember<SVGAnimatedLength> m_cx;
    RefPtrWillBeMember<SVGAnimatedLength> m_cy;
    RefPtrWillBeMember<SVGAnimatedLength> m_r;
};

} // namespace blink

#endif // SVGCircleElement_h


text:
package org.jon.ivmark.graphit.core.properties;

import java.util.*;

/**
 * A {@link Properties} implementation backed by a {@link EnumMap}.
 *
 * @author jon
 *
 */
public class EnumMapProperties<E extends Enum<E>> implements Properties {

    private final Class<E> enumClass;
    private final EnumMap<E, Object> properties;

    /**
     * Crates a new instance with.
     */
    public EnumMapProperties(Class<E> enumClass) {
        this.enumClass = enumClass;
        this.properties = new EnumMap<E, Object>(enumClass);
    }

    private E getKey(String keyName) {
        return Enum.valueOf(enumClass, keyName);
    }

    @Override
    public Object getProperty(String keyName) {
        return getProperty(getKey(keyName));
    }

    /**
     * Gets a property.
     */
    public Object getProperty(E key) {
        return properties.get(key);
    }

    @Override
    public void setProperty(String keyName, Object value) {
        setProperty(getKey(keyName), value);
    }

    /**
     * Sets a property.
     */
    public void setProperty(E key, Object value) {
        properties.put(key, value);
    }

    @Override
    public Object removeProperty(String keyName) {
        return removeProperty(getKey(keyName));
    }

    /**
     * Removes a property.
     */
    public Object removeProperty(E key) {
        return properties.remove(key);
    }

    @Override
    public boolean containsProperty(String keyName) {
        return containsProperty(getKey(keyName));
    }

    /**
     * Returns true if this instance contains the given key.
     */
    public boolean containsProperty(E key) {
        return properties.containsKey(key);
    }

    @Override
    public Set<String> getPropertyKeys() {
        Set<String> res = new HashSet<String>();
        for (Enum<E> key : properties.keySet()) {
            res.add(key.name());
        }
        return res;
    }

    @Override
    public Map<String, Object> asPropertyMap() {
        Map<String, Object> res = new HashMap<String, Object>();
        for (Map.Entry<E, Object> e : properties.entrySet()) {
            Object value = e.getValue();
            E key = e.getKey();
            res.put(key.name(), value);
        }
        return res;
    }

    @Override
    public String toString() {
        return "EnumMapProperties [enumClass=" + enumClass + ", properties=" + properties + "]";
    }

    @Override
    public int size() {
        return properties.size();
    }

    @Override
    public boolean isEmpty() {
        return properties.isEmpty();
    }
}


text:
class ReferenceNameChange32Mapper
  include XmlSchemaMapper
  schema File.expand_path('../../vendor/ezags-protocols/eZAGS/public/UploadService.xsd', File.dirname(__FILE__))
  type 'ReferenceNameChange32'

  # @return [RequisitesPaperReferenceMapper]
  # minOccurs: 1, maxOccurs: 1
  attr_accessor :requisites_paper_reference
  # @return [ActRecordToReferenceNameChange32Mapper]
  # minOccurs: 1, maxOccurs: 1
  attr_accessor :reference_name_change32

end


text:
//
//  DDPCacheManager.h
//  DanDanPlayForiOS
//
//  Created by JimHuang on 2017/4/19.
//  Copyright © 2017年 JimHuang. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "JHBaseDanmaku.h"
#import "DDPSMBInfo.h"

/**
 视频播放模式

 - DDPPlayerPlayModeSingle: 单集播放
 - DDPPlayerPlayModeSingleCircle: 单集循环
 - DDPPlayerPlayModeCircle: 列表循环
 - DDPPlayerPlayModeOrder: 顺序播放
 */
typedef NS_ENUM(NSUInteger, DDPPlayerPlayMode) {
    DDPPlayerPlayModeSingle,
    DDPPlayerPlayModeSingleCircle,
    DDPPlayerPlayModeCircle,
    DDPPlayerPlayModeOrder,
};

typedef NS_ENUM(NSUInteger, DDPCollectionCacheDidChangeType) {
    DDPCollectionCacheDidChangeTypeAdd,
    DDPCollectionCacheDidChangeTypeRemove,
};

/**
 屏蔽弹幕类型

 - DDPDanmakuShieldTypeScrollToLeft: 滚动到左边
 - DDPDanmakuShieldTypeScrollToRight: 滚动到右边
 - DDPDanmakuShieldTypeScrollToTop: 滚动到顶部
 - DDPDanmakuShieldTypeScrollToBottom: 滚动到底部
 - DDPDanmakuShieldTypeFloatAtTo: 浮动在顶部
 - DDPDanmakuShieldTypeFloatAtBottom: 浮动在底部
 - DDPDanmakuShieldTypeColor: 彩色弹幕
 - DDPDanmakuShieldTypeScroll: 所有滚动弹幕
 - DDPDanmakuShieldTypeFloat: 所以浮动弹幕
 */
typedef NS_OPTIONS(NSUInteger, DDPDanmakuShieldType) {
    DDPDanmakuShieldTypeNone = kNilOptions,
    DDPDanmakuShieldTypeScrollToLeft = 1 << 0,
    DDPDanmakuShieldTypeScrollToRight = 1 << 1,
    DDPDanmakuShieldTypeScrollToTop = 1 << 2,
    DDPDanmakuShieldTypeScrollToBottom = 1 << 3,
    DDPDanmakuShieldTypeFloatAtTo = 1 << 4,
    DDPDanmakuShieldTypeFloatAtBottom = 1 << 5,
    DDPDanmakuShieldTypeColor = 1 << 6,

    DDPDanmakuShieldTypeScroll =
    DDPDanmakuShieldTypeScrollToLeft |
    DDPDanmakuShieldTypeScrollToRight |
    DDPDanmakuShieldTypeScrollToTop |
    DDPDanmakuShieldTypeScrollToBottom,

    DDPDanmakuShieldTypeFloat =
    DDPDanmakuShieldTypeFloatAtTo |
    DDPDanmakuShieldTypeFloatAtBottom,
};

typedef NS_ENUM(NSUInteger, DDPFileSortType) {
    DDPFileSortTypeAsc,
    DDPFileSortTypeDesc,
};

//缓存所有弹幕的标识
#define CACHE_ALL_DANMAKU_FLAG 9999

@class DDPUser, DDPFile, TOSMBSessionFile, TOSMBSessionDownloadTask, DDPMediaPlayer, DDPCollectionCache, DDPSMBFileHashCache;

@protocol DDPCacheManagerDelagate <NSObject>
@optional

- (void)lastPlayTimeWithVideoModel:(DDPVideoModel *)videoModel time:(NSInteger)time;
- (void)collectionDidHandleCache:(DDPCollectionCache *)cache operation:(DDPCollectionCacheDidChangeType)operation;
- (void)userLoginStatusDidChange:(DDPUser *)user;
- (void)linkInfoDidChange:(DDPLinkInfo *)linkInfo;
@end

@interface DDPCacheManager : NSObject

@property (weak, nonatomic) DDPMediaPlayer *mediaPlayer;

/**
 当前登录的用户
 */
@property (strong, nonatomic) DDPUser *currentUser;

/**
 当前连接信息
 */
@property (strong, nonatomic) DDPLinkInfo *linkInfo;

/**
 弹幕字体
 */
@property (strong, nonatomic) UIFont *danmakuFont;

/**
 弹幕边缘特效
 */
@property (assign, nonatomic) JHDanmakuEffectStyle danmakuEffectStyle;

/**
 字幕保护区域
 */
@property (assign, nonatomic) BOOL subtitleProtectArea;

/**
 弹幕缓存时间 默认7天
 */
@property (assign, nonatomic) NSUInteger danmakuCacheTime;

/**
 自动请求第三方弹幕
 */
@property (assign, nonatomic) BOOL autoRequestThirdPartyDanmaku;

/**
 是否打开快速匹配
 */
@property (assign, nonatomic) BOOL openFastMatch;

/**
 是否自动下载局域网设备字幕
 */
@property (assign, nonatomic) BOOL openAutoDownloadSubtitle;

/**
 使用touchId登录
 */
@property (assign, nonatomic) BOOL useTouchIdLogin;

/**
 显示下载状态视图
 */
@property (assign, nonatomic) BOOL showDownloadStatusView;

/**
 播放器播放模式
 */
@property (assign, nonatomic) DDPPlayerPlayMode playMode;

/**
 弹幕速度
 */
@property (assign, nonatomic) float danmakuSpeed;

/**
 弹幕不透明度
 */
@property (assign, nonatomic) float danmakuOpacity;

/**
 选择的弹幕颜色
 */
@property (strong, nonatomic) UIColor *sendDanmakuColor;

/**
 选择的弹幕类型
 */
@property (assign, nonatomic) DDPDanmakuMode sendDanmakuMode;

/**
 同屏弹幕数量 默认14
 */
@property (assign, nonatomic) NSUInteger danmakuLimitCount;

/**
 播放页默认旋屏位置
 */
@property (assign, nonatomic) UIInterfaceOrientation playInterfaceOrientation;

/**
 屏蔽弹幕类型
 */
@property (assign, nonatomic) DDPDanmakuShieldType danmakuShieldType;

/**
 用于请求的域名
 */
@property (copy, nonatomic) NSString *userDefineRequestDomain;

/** 用于搜索资源的域名 */
@property (copy, nonatomic) NSString *userDefineResRequestDomain;

/**
 文件排序类型
 */
@property (assign, nonatomic) DDPFileSortType fileSortType;

/**
 存储文件夹名称和文件hash
 */
@property (strong, nonatomic) NSMutableDictionary <NSString *, NSMutableArray <NSString *>*>*folderCache;

//当前分析的视频模型
@property (strong, nonatomic) DDPVideoModel *currentPlayVideoModel;

/**
 刷新中显示的文字
 */
@property (strong, nonatomic) NSMutableArray <NSString *>*refreshTexts;

/**
 弹幕偏移时间 不进行本地保存
 */
@property (assign, nonatomic) CGFloat danmakuOffsetTime;

/// 字幕偏移 单位秒
@property (nonatomic, assign) CGFloat subtitleDelay;

/// 视频比例
@property (assign, nonatomic) CGSize videoAspectRatio;

/// 播放速率
@property (assign, nonatomic) float playerSpeed;

/// 上次忽略的版本
@property (copy, nonatomic) NSString *ignoreVersion;

/// 引导视图是否显示过
@property (nonatomic, assign) BOOL guildViewIsShow;

/// 自动加载本地弹幕
@property (nonatomic, assign) BOOL loadLocalDanmaku;

+ (instancetype)shareCacheManager;
@end


text:
#region License and Copyright

#endregion

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Guifreaks.Common
{
   /// <summary>
   /// A Message Loop filter which detect mouse events whilst the popup form is shown
   /// and notifies the owning <see cref="PopupWindowHelper"/> class when a mouse
   /// click outside the popup occurs.
   /// </summary>
   public class PopupWindowHelperMessageFilter : IMessageFilter
   {
      /// <summary>
      /// Raised when the Popup Window is about to be cancelled.  The
      /// <see cref="PopupCancelEventArgs.Cancel"/> property can be
      /// set to <c>true</c> to prevent the form from being cancelled.
      /// </summary>
      public event PopupCancelEventHandler PopupCancel;

      /// <summary>
      /// The popup form
      /// </summary>
      private Form popup = null;
      /// <summary>
      /// The owning <see cref="PopupWindowHelper"/> object.
      /// </summary>
      private PopupWindowHelper owner = null;

      /// <summary>
      /// Constructs a new instance of this class and sets the owning
      /// object.
      /// </summary>
      /// <param name="owner">The <see cref="PopupWindowHelper"/> object
      /// which owns this class.</param>
      public PopupWindowHelperMessageFilter(PopupWindowHelper owner)
      {
         this.owner = owner;
      }

      /// <summary>
      /// Gets/sets the popup form which is being displayed.
      /// </summary>
      public Form Popup
      {
         get
         {
            return this.popup;
         }
         set
         {
            this.popup = value;
         }
      }

      /// <summary>
      /// Checks the message loop for mouse messages whilst the popup
      /// window is displayed.  If one is detected the position is
      /// checked to see if it is outside the form, and the owner
      /// is notified if so.
      /// </summary>
      /// <param name="m">Windows Message about to be processed by the
      /// message loop</param>
      /// <returns><c>true</c> to filter the message, <c>false</c> otherwise.
      /// This implementation always returns <c>false</c>.</returns>
      public bool PreFilterMessage(ref Message m)
      {
         if (this.popup != null)
         {
            switch (m.Msg)
            {
               case NativeMethods.WM_LBUTTONDOWN:
               case NativeMethods.WM_RBUTTONDOWN:
               case NativeMethods.WM_MBUTTONDOWN:
               case NativeMethods.WM_NCLBUTTONDOWN:
               case NativeMethods.WM_NCRBUTTONDOWN:
               case NativeMethods.WM_NCMBUTTONDOWN:
                  OnMouseDown();
                  break;
            }
         }
         return false;
      }

      /// <summary>
      /// Checks the mouse location and calls the OnCancelPopup method
      /// if the mouse is outside the popup form.
      /// </summary>
      private void OnMouseDown()
      {
         // Get the cursor location
         Point cursorPos = Cursor.Position;
         // Check if it is within the popup form
         if (!popup.Bounds.Contains(cursorPos))
         {
            // If not, then call to see if it should be closed
            OnCancelPopup(new PopupCancelEventArgs(popup, cursorPos));
         }
      }

      /// <summary>
      /// Raises the <see cref="PopupCancel"/> event.
      /// </summary>
      /// <param name="e">The <see cref="PopupCancelEventArgs"/> associated
      /// with the cancel event.</param>
      protected virtual void OnCancelPopup(PopupCancelEventArgs e)
      {
         if (this.PopupCancel != null)
         {
            this.PopupCancel(this, e);
         }
         if (!e.Cancel)
         {
            owner.ClosePopup();
            // Clear reference for GC
            popup = null;
         }
      }
   }
}


text:
/*
shellescape provides the Quote to escape arbitrary
strings for a safe use as command line arguments in the most common
POSIX shells.
The Python package which this work was inspired by can be found
at https://pypi.python.org/pypi/shellescape.
*/
package main

/*
The functionality provided by Quote could be helpful
in those cases where it is known that the output of a Go program will
be appended to/used in the context of shell programs' command line arguments.
*/

import (
	"regexp"
	"strings"
)

var pattern *regexp.Regexp

func init() {
	pattern = regexp.MustCompile(`[^\w@%+=:,./-]`)
}

// Quote returns a shell-escaped version of the string s. The returned value
// is a string that can safely be used as one token in a shell command line.
func Quote(s string) string {
	if len(s) == 0 {
		return "''"
	}

	if pattern.MatchString(s) {
		return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'"
	}

	return s
}

// QuoteCommand returns a shell-escaped version of the slice of strings.
// The returned value is a string that can safely be used as shell command arguments.
func QuoteCommand(args []string) string {
	l := make([]string, len(args))

	for i, s := range args {
		l[i] = Quote(s)
	}

	return strings.Join(l, " ")
}


text:
'use strict';

define(['app'], function (app) {
    app.controller('OrderCtrl', ['$scope', '$state', 'resourceService', 'Environment', 'collectionService',
        function ($scope, $state, resourceService, Environment, collectionService) {

            var itemService = new resourceService('order');

            $scope.collectionTitle = 'Orders';
            $scope.disableNew = true;
            $scope.pageLimit = 20;
            $scope.pageNumber = 1;
            $scope.columns = [
                {name: 'id', enableColumnMenu: false, width: '100'},
                {name: 'status', enableColumnMenu: false},
                {name: 'subtotal', enableColumnMenu: false},
                {name: 'grandtotal', enableColumnMenu: false},
                {name: 'currency', enableColumnMenu: false},
                {name: 'country', enableColumnMenu: false},
                {name: 'region', enableColumnMenu: false},
                {name: 'city', enableColumnMenu: false},
                {name: 'created_at', enableColumnMenu: false},
                {name: 'updated_at', enableColumnMenu: false},
                {
                    name: 'action',
                    enableSorting: false,
                    enableFiltering: false,
                    enableColumnMenu: false,
                    width: '100',
                    cellTemplate: collectionService.actionTemplate()
                }
            ];
            $scope.gridOptions = collectionService.gridOptions($scope);

            // === Item Action ===
            $scope.editDetails = function (id) {
                $state.transitionTo('orderEdit', {locale: Environment.currentLocale(), id: id});
            };

            // === Load collection from remote ===
            $scope.loadCollection = function (pageNumber) {
                collectionService.loadCollection($scope, itemService, pageNumber);
            };
            $scope.loadCollection();

        }]);
});


text:
package org.sagebionetworks.download.worker;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.sagebionetworks.repo.model.annotation.v2.AnnotationsValueType.STRING;
import static org.sagebionetworks.repo.model.util.AccessControlListUtil.createResourceAccess;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.AsynchronousJobWorkerHelper;
import org.sagebionetworks.aws.SynapseS3Client;
import org.sagebionetworks.repo.manager.UserManager;
import org.sagebionetworks.repo.manager.file.FileHandleManager;
import org.sagebionetworks.repo.model.ACCESS_TYPE;
import org.sagebionetworks.repo.model.AccessControlListDAO;
import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;
import org.sagebionetworks.repo.model.EntityType;
import org.sagebionetworks.repo.model.Node;
import org.sagebionetworks.repo.model.NodeDAO;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.annotation.v2.Annotations;
import org.sagebionetworks.repo.model.annotation.v2.AnnotationsValue;
import org.sagebionetworks.repo.model.auth.NewUser;
import org.sagebionetworks.repo.model.dbo.file.download.v2.DownloadListDAO;
import org.sagebionetworks.repo.model.dbo.file.download.v2.ManifestKeys;
import org.sagebionetworks.repo.model.download.DownloadListItem;
import org.sagebionetworks.repo.model.download.DownloadListManifestRequest;
import org.sagebionetworks.repo.model.download.DownloadListManifestResponse;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.helper.AccessControlListObjectHelper;
import org.sagebionetworks.repo.model.helper.DaoObjectHelper;
import org.sagebionetworks.repo.model.helper.FileHandleObjectHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import com.amazonaws.services.s3.model.GetObjectRequest;

import au.com.bytecode.opencsv.CSVReader;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public class DownloadListManifestWorkerIntegrationTest {

	public static final long MAX_WAIT_MS = 1000_30;

	public static final int MAX_RETRIES = 25;

	@Autowired
	private UserManager userManager;
	@Autowired
	private DownloadListDAO downloadListDao;
	@Autowired
	private DaoObjectHelper<Node> nodeDaoHelper;
	@Autowired
	private NodeDAO nodeDao;
	@Autowired
	private AccessControlListObjectHelper aclHelper;
	@Autowired
	private AccessControlListDAO aclDao;
	@Autowired
	private FileHandleManager fileUploadManager;
	@Autowired
	private SynapseS3Client s3Client;
	@Autowired
	private FileHandleObjectHelper fileHandleObjectHelper;

	@Autowired
	AsynchronousJobWorkerHelper asynchronousJobWorkerHelper;

	UserInfo adminUser;
	UserInfo user;

	List<String> fileHandleIdsToDelete;

	@BeforeEach
	public void before() {
		aclDao.truncateAll();
		nodeDao.truncateAll();
		downloadListDao.truncateAllData();

		adminUser = userManager.getUserInfo(BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId());
		boolean acceptsTermsOfUse = true;
		String userName = UUID.randomUUID().toString();
		user = userManager.createOrGetTestUser(adminUser,
				new NewUser().setUserName(userName).setEmail(userName + "@foo.org"), acceptsTermsOfUse);
		fileHandleIdsToDelete = new ArrayList<>();
	}

	@AfterEach
	public void after() {
		aclDao.truncateAll();
		nodeDao.truncateAll();
		downloadListDao.truncateAllData();
		if (fileHandleIdsToDelete != null && user != null) {
			for (String fileHandleId : fileHandleIdsToDelete) {
				fileUploadManager.deleteFileHandle(user, fileHandleId);
			}
		}
		if (user != null) {
			userManager.deletePrincipal(adminUser, user.getId());
		}

	}

	@Test
	public void testManifest() throws Exception {
		Node project = nodeDaoHelper.create((n) -> {
			n.setNodeType(EntityType.project);
			n.setName("project");
		});
		aclHelper.create((a) -> {
			a.setId(project.getId());
			a.getResourceAccess().add(createResourceAccess(user.getId(), ACCESS_TYPE.DOWNLOAD));
			a.getResourceAccess().add(createResourceAccess(user.getId(), ACCESS_TYPE.READ));
		});

		// one
		S3FileHandle fh1 = fileHandleObjectHelper.createS3(f -> {
			f.setContentSize(101L);
			f.setFileName("a.txt");
		});
		Node file1 = nodeDaoHelper.create((n) -> {
			n.setParentId(project.getId());
			n.setNodeType(EntityType.file);
			n.setName("a.txt");
			n.setFileHandleId(fh1.getId());
		});
		Annotations annotations = new Annotations().setAnnotations(new LinkedHashMap<>());
		annotations.getAnnotations().put("a", new AnnotationsValue().setType(STRING).setValue(Arrays.asList("one")));
		annotations.getAnnotations().put("b", new AnnotationsValue().setType(STRING).setValue(Arrays.asList("two")));
		annotations.getAnnotations().put("c", new AnnotationsValue().setType(STRING).setValue(Arrays.asList("three")));
		nodeDao.updateUserAnnotations(file1.getId(), annotations);
		// two
		S3FileHandle fh2 = fileHandleObjectHelper.createS3(f -> {
			f.setContentSize(202L);
			f.setFileName("b.txt");
		});
		Node file2 = nodeDaoHelper.create((n) -> {
			n.setParentId(project.getId());
			n.setNodeType(EntityType.file);
			n.setName("b.txt");
			n.setFileHandleId(fh2.getId());
		});
		annotations = new Annotations().setAnnotations(new LinkedHashMap<>());
		annotations.getAnnotations().put("a", new AnnotationsValue().setType(STRING).setValue(Arrays.asList("one-one")));
		annotations.getAnnotations().put("b", new AnnotationsValue().setType(STRING).setValue(Arrays.asList("two-two")));
		annotations.getAnnotations().put("d", new AnnotationsValue().setType(STRING).setValue(Arrays.asList("three-threes")));
		nodeDao.updateUserAnnotations(file2.getId(), annotations);

		long addedCount = downloadListDao.addBatchOfFilesToDownloadList(user.getId(),
				Arrays.asList(new DownloadListItem().setFileEntityId(file1.getId()),
						new DownloadListItem().setFileEntityId(file2.getId())));
		assertEquals(2L, addedCount);

		DownloadListManifestRequest request = new DownloadListManifestRequest();
		// call under test
		DownloadListManifestResponse respone = asynchronousJobWorkerHelper
				.assertJobResponse(user, request, (DownloadListManifestResponse response) -> {
					assertNotNull(response.getResultFileHandleId());
					fileHandleIdsToDelete.add(response.getResultFileHandleId());
				}, MAX_WAIT_MS, MAX_RETRIES).getResponse();

		S3FileHandle csvHandle = (S3FileHandle) fileUploadManager.getRawFileHandle(user,
				respone.getResultFileHandleId());

		File temp = File.createTempFile("manifest", ".csv");
		List<String> expectedHeaders = Stream.of(ManifestKeys.values()).map(k->k.name()).collect(Collectors.toList());
		expectedHeaders.addAll(Arrays.asList("a","b","c","d"));
		int aIndex = expectedHeaders.size()-4;
		int bIndex = expectedHeaders.size()-3;
		int cIndex = expectedHeaders.size()-2;
		int dIndex = expectedHeaders.size()-1;
 		try {
			s3Client.getObject(new GetObjectRequest(csvHandle.getBucketName(), csvHandle.getKey()), temp);
			try (CSVReader csvReader = new CSVReader(new FileReader(temp));) {
				List<String[]> allData = csvReader.readAll();
				assertNotNull(allData);
				assertEquals(3, allData.size());
				// headers
				String[] row = allData.get(0);
				assertEquals(expectedHeaders, Arrays.asList(row));
				// one
				row = allData.get(1);
				assertEquals(file1.getId(), row[0]);
				assertEquals("a.txt", row[1]);
				assertEquals("one", row[aIndex]);
				assertEquals("two", row[bIndex]);
				assertEquals("three", row[cIndex]);
				assertEquals(null, row[dIndex]);
				// two
				row = allData.get(2);
				assertEquals(file2.getId(), row[0]);
				assertEquals("b.txt", row[1]);
				assertEquals("one-one", row[aIndex]);
				assertEquals("two-two", row[bIndex]);
				assertEquals(null, row[cIndex]);
				assertEquals("three-threes", row[dIndex]);
			}
		} finally {
			temp.delete();
		}
	}

}


text:
function mazeDemo() {
  var g = graph(15, 15);
  var stack = [];

  var lineLengthUnit = 20;
  var stepTime = 50;
  var offset = 5;
  var mazeCanvas = document.getElementById('maze');
  var ctx = mazeCanvas.getContext('2d');

  function drawerCallback(vedge) {
    ctx.lineTo(
      offset + vedge.x * lineLengthUnit,
      offset + vedge.y * lineLengthUnit
    );
    ctx.stroke();
  }

  ctx.beginPath();
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 5;
  ctx.moveTo(offset, offset);

  g.genMaze(
    g.vedges[0],
    stack,
    drawerCallback,
    stepTime
  )
}


text:
// Copyright (c) 2012 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.

#include "remoting/protocol/rtp_utils.h"

#include "base/logging.h"
#include "third_party/libjingle/source/talk/base/byteorder.h"

using talk_base::GetBE16;
using talk_base::GetBE32;
using talk_base::SetBE16;
using talk_base::SetBE32;

namespace remoting {
namespace protocol {

namespace {
const int kRtpBaseHeaderSize = 12;
const uint8 kRtpVersionNumber = 2;
const int kRtpMaxSources = 16;
const int kBytesPerCSRC = 4;
const int kRtcpBaseHeaderSize = 4;
const int kRtcpReceiverReportSize = 28;
const int kRtcpReceiverReportTotalSize =
    kRtcpBaseHeaderSize + kRtcpReceiverReportSize;
const int kRtcpReceiverReportPacketType = 201;
}  // namespace

RtpHeader::RtpHeader()
    : padding(false),
      extension(false),
      sources(0),
      marker(false),
      payload_type(0),
      sequence_number(0),
      timestamp(0),
      sync_source_id(0) {
  memset(source_id, 0, sizeof(source_id));
}

RtcpReceiverReport::RtcpReceiverReport()
    : receiver_ssrc(0),
      sender_ssrc(0),
      loss_fraction(0),
      total_lost_packets(0),
      last_sequence_number(0),
      jitter(0),
      last_sender_report_timestamp(0),
      last_sender_report_delay(0) {
}

static inline uint8 ExtractBits(uint8 byte, int bits_count, int shift) {
  return (byte >> shift) & ((1 << bits_count) - 1);
}

// RTP Header format:
//
//  0                   1                   2                   3
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |V=2|P|X|  CC   |M|     PT      |       sequence number         |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |                           timestamp                           |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |           synchronization source (SSRC) identifier            |
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
// |            contributing source (CSRC) identifiers             |
// |                             ....                              |
// +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// On the diagram above order of bytes and order of bits within each
// byte are big-endian. So bits 0 and 7 are the most and the least
// significant bits in the first byte, bit 8 is the most significant
// bit in the second byte, etc.

int GetRtpHeaderSize(const RtpHeader& header) {
  DCHECK_GE(header.sources, 0);
  DCHECK_LT(header.sources, kRtpMaxSources);
  return kRtpBaseHeaderSize + header.sources * kBytesPerCSRC;
}

void PackRtpHeader(const RtpHeader& header, uint8* buffer, int buffer_size) {
  DCHECK_LT(header.sources, kRtpMaxSources);
  DCHECK_LT(header.payload_type, 1 << 7);
  CHECK_GE(buffer_size, GetRtpHeaderSize(header));

  buffer[0] = (kRtpVersionNumber << 6) |
      ((uint8)header.padding << 5) |
      ((uint8)header.extension << 4) |
      header.sources;
  buffer[1] = ((uint8)header.marker << 7) |
      header.payload_type;
  SetBE16(buffer + 2, header.sequence_number);
  SetBE32(buffer + 4, header.timestamp);
  SetBE32(buffer + 8, header.sync_source_id);

  for (int i = 0; i < header.sources; i++) {
    SetBE32(buffer + i * 4 + 12, header.source_id[i]);
  }
}

int UnpackRtpHeader(const uint8* buffer, int buffer_size, RtpHeader* header) {
  if (buffer_size < kRtpBaseHeaderSize) {
    return -1;
  }

  int version = ExtractBits(buffer[0], 2, 6);
  if (version != kRtpVersionNumber) {
    return -1;
  }

  header->padding = ExtractBits(buffer[0], 1, 5) != 0;
  header->extension = ExtractBits(buffer[0], 1, 4) != 0;
  header->sources = ExtractBits(buffer[0], 4, 0);

  header->marker = ExtractBits(buffer[1], 1, 7) != 0;
  header->payload_type = ExtractBits(buffer[1], 7, 0);

  header->sequence_number = GetBE16(buffer + 2);
  header->timestamp = GetBE32(buffer + 4);
  header->sync_source_id = GetBE32(buffer + 8);

  DCHECK_LT(header->sources, 16);

  if (buffer_size < GetRtpHeaderSize(*header)) {
    return -1;
  }
  for (int i = 0; i < header->sources; i++) {
    header->source_id[i] = GetBE32(buffer + i * 4 + 12);
  }

  return GetRtpHeaderSize(*header);
}

// RTCP receiver report:
//
// 0                   1                   2                   3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |V=2|P|   RC=1  |     PT=201    |             length            |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |                         SSRC of sender                        |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |                      SSRC of the reportee                     |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | fraction lost |       cumulative number of packets lost       |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |           extended highest sequence number received           |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |                      interarrival jitter                      |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |                         last SR (LSR)                         |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |                   delay since last SR (DLSR)                  |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

int GetRtcpReceiverReportSize(const RtcpReceiverReport& report) {
  return kRtcpReceiverReportTotalSize;
}

void PackRtcpReceiverReport(const RtcpReceiverReport& report,
                            uint8* buffer, int buffer_size) {
  CHECK_GE(buffer_size, GetRtcpReceiverReportSize(report));

  buffer[0] = (kRtpVersionNumber << 6) |
      1 /* RC=1 */;
  buffer[1] = kRtcpReceiverReportPacketType;
  SetBE16(buffer + 2, kRtcpReceiverReportSize);

  SetBE32(buffer + 4, report.receiver_ssrc);
  SetBE32(buffer + 8, report.sender_ssrc);
  SetBE32(buffer + 12, report.total_lost_packets & 0xFFFFFF);
  buffer[12] = report.loss_fraction;
  SetBE32(buffer + 16, report.last_sequence_number);
  SetBE32(buffer + 20, report.jitter);
  SetBE32(buffer + 24, report.last_sender_report_timestamp);
  SetBE32(buffer + 28, report.last_sender_report_delay);
}

int UnpackRtcpReceiverReport(const uint8* buffer, int buffer_size,
                             RtcpReceiverReport* report) {
  if (buffer_size < kRtcpReceiverReportTotalSize) {
    return -1;
  }

  int version = ExtractBits(buffer[0], 2, 6);
  if (version != kRtpVersionNumber) {
    return -1;
  }

  int report_count = ExtractBits(buffer[0], 5, 0);
  if (report_count != 1) {
    // Received RTCP packet with more than one report.  This isn't
    // supported in the current implementation.
    return -1;
  }

  int packet_type = buffer[1];
  if (packet_type != kRtcpReceiverReportPacketType) {
    // The packet isn't receiver report.
    return -1;
  }

  int report_size = GetBE16(buffer + 2);
  if (report_size != kRtcpReceiverReportSize) {
    // Invalid size of the report.
    return -1;
  }

  report->receiver_ssrc = GetBE32(buffer + 4);
  report->sender_ssrc = GetBE32(buffer + 8);
  report->loss_fraction = buffer[12];
  report->total_lost_packets = GetBE32(buffer + 12) & 0xFFFFFF;
  report->last_sequence_number = GetBE32(buffer + 16);
  report->jitter = GetBE32(buffer + 20);
  report->last_sender_report_timestamp = GetBE32(buffer + 24);
  report->last_sender_report_delay = GetBE32(buffer + 28);

  return kRtcpReceiverReportTotalSize;
}

// VP8 Payload Descriptor format:
//
//  0                   1                   2                   3
//  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | RSV |I|N|FI |B|         PictureID (integer #bytes)            |
// +-+-+-+-+-+-+-+-+                                               |
// :                                                               :
// |               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// |               : (VP8 data or VP8 payload header; byte aligned)|
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//
// On the diagram above order of bytes and order of bits within each
// byte are big-endian. So bits 0 and 7 are the most and the least
// significant bits in the first byte, bit 8 is the most significant
// bit in the second byte, etc.
//
// RSV: 3 bits
// Bits reserved for future use. MUST be equal to zero and MUST be
// ignored by the receiver.
//
// I: 1 bit
// PictureID present. When set to one, a PictureID is provided after
// the first byte of the payload descriptor. When set to zero, the
// PictureID is omitted, and the one-byte payload descriptor is
// immediately followed by the VP8 payload.
//
// N: 1 bit
// Non-reference frame. When set to one, the frame can be discarded
// without affecting any other future or past frames.
//
// FI: 2 bits
// Fragmentation information field. This field contains information
// about the fragmentation of VP8 payloads carried in the RTP
// packet. The four different values are listed below.
//
// FI   Fragmentation status
//   00 The RTP packet contains no fragmented VP8 partitions. The
//      payload is one or several complete partitions.
//   01 The RTP packet contains the first part of a fragmented
//      partition. The fragment must be placed in its own RTP packet.
//   10 The RTP packet contains a fragment that is neither the first nor
//      the last part of a fragmented partition. The fragment must be
//      placed in its own RTP packet.
//   11 The RTP packet contains the last part of a fragmented
//      partition. The fragment must be placed in its own RTP packet.
//
// B: 1 bit
// Beginning VP8 frame. When set to 1 this signals that a new VP8
// frame starts in this RTP packet.
//
// PictureID: Multiple of 8 bits
// This is a running index of the frames. The field is present only if
// the I bit is equal to one. The most significant bit of each byte is
// an extension flag. The 7 following bits carry (parts of) the
// PictureID. If the extension flag is one, the PictureID continues in
// the next byte. If the extension flag is zero, the 7 remaining bits
// are the last (and least significant) bits in the PictureID. The
// sender may choose any number of bytes for the PictureID. The
// PictureID SHALL start on a random number, and SHALL wrap after
// reaching the maximum ID as chosen by the application

int GetVp8DescriptorSize(const Vp8Descriptor& descriptor) {
  if (descriptor.picture_id == kuint32max)
    return 1;
  int result = 2;
  // We need 1 byte per each 7 bits in picture_id.
  uint32 picture_id = descriptor.picture_id >> 7;
  while (picture_id > 0) {
    picture_id >>= 7;
    ++result;
  }
  return result;
}

void PackVp8Descriptor(const Vp8Descriptor& descriptor, uint8* buffer,
                       int buffer_size) {
  CHECK_GT(buffer_size, 0);

  buffer[0] =
      ((uint8)(descriptor.picture_id != kuint32max) << 4) |
      ((uint8)descriptor.non_reference_frame << 3) |
      (descriptor.fragmentation_info << 1) |
      ((uint8)descriptor.frame_beginning);

  uint32 picture_id = descriptor.picture_id;
  if (picture_id == kuint32max)
    return;

  int pos = 1;
  while (picture_id > 0) {
    CHECK_LT(pos, buffer_size);
    buffer[pos] = picture_id & 0x7F;
    picture_id >>= 7;

    // Set the extension bit if neccessary.
    if (picture_id > 0)
      buffer[pos] |= 0x80;
    ++pos;
  }
}

int UnpackVp8Descriptor(const uint8* buffer, int buffer_size,
                        Vp8Descriptor* descriptor) {
  if (buffer_size <= 0)
    return -1;

  bool picture_id_present = ExtractBits(buffer[0], 1, 4) != 0;
  descriptor->non_reference_frame = ExtractBits(buffer[0], 1, 3) != 0;
  descriptor->fragmentation_info = ExtractBits(buffer[0], 2, 1);
  descriptor->frame_beginning = ExtractBits(buffer[0], 1, 0) != 0;

  // Return here if we don't need to decode PictureID.
  if (!picture_id_present) {
    descriptor->picture_id = kuint32max;
    return 1;
  }

  // Decode PictureID.
  bool extension = true;
  int pos = 1;
  descriptor->picture_id = 0;
  while (extension) {
    if (pos >= buffer_size)
      return -1;

    descriptor->picture_id |= buffer[pos] & 0x7F;
    extension = (buffer[pos] & 0x80) != 0;
    pos += 1;
  }
  return pos;
}

}  // namespace protocol
}  // namespace remoting


text:
package metrics

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestDefaultStabilityLevel(t *testing.T) {
	var tests = []struct {
		name        string
		inputValue  StabilityLevel
		expectValue StabilityLevel
		expectPanic bool
	}{
		{
			name:        "empty should take ALPHA by default",
			inputValue:  "",
			expectValue: ALPHA,
			expectPanic: false,
		},
		{
			name:        "ALPHA remain unchanged",
			inputValue:  ALPHA,
			expectValue: ALPHA,
			expectPanic: false,
		},
		{
			name:        "STABLE remain unchanged",
			inputValue:  STABLE,
			expectValue: STABLE,
			expectPanic: false,
		},
	}

	for _, tc := range tests {
		tc := tc
		t.Run(tc.name, func(t *testing.T) {
			var stability = tc.inputValue

			stability.setDefaults()
			assert.Equalf(t, tc.expectValue, stability, "Got %s, expected: %v ", stability, tc.expectValue)
		})
	}
}


text:
package ninja.mpnguyen.bisque.views.posts;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import ninja.mpnguyen.bisque.R;
import ninja.mpnguyen.bisque.things.PostMetadataWrapper;
import ninja.mpnguyen.bisque.views.errors.ErrorPresenter;
import ninja.mpnguyen.bisque.views.errors.ErrorViewHolder;
import ninja.mpnguyen.bisque.views.progress.ProgressPresenter;
import ninja.mpnguyen.bisque.views.progress.ProgressViewHolder;

public class PostsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    public interface PostClickListener {
        void onPostClicked(PostMetadataWrapper post);
    }

    public interface PostHideListener {
        void onPostHidden(PostMetadataWrapper post);
    }

    private final int TYPE_POST = 0, TYPE_ERROR = 1, TYPE_EMPTY = 2, TYPE_LOADING = 3;
    private final PostMetadataWrapper[] posts;
    private final boolean loading;
    private final PostClickListener clickListener;
    private final PostHideListener hideListener;

    public PostsAdapter(@Nullable PostMetadataWrapper[] posts, boolean loading, PostClickListener clickListener, PostHideListener hideListener) {
        this.posts = posts;
        this.loading = loading;
        this.clickListener = clickListener;
        this.hideListener = hideListener;
        setHasStableIds(true);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        if (viewType == TYPE_POST) return PostsPresenter.inflateListItem(inflater, viewGroup);
        else if (viewType == TYPE_LOADING) return ProgressPresenter.inflateListItem(inflater, viewGroup);
        else return ErrorPresenter.inflateListItem(inflater, viewGroup);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        int type = getItemViewType(position);
        if (getItemViewType(position) == TYPE_POST && posts != null) {
            PostItemViewHolder postItemViewHolder = (PostItemViewHolder) viewHolder;
            PostMetadataWrapper postWrapper = posts[position];
            View.OnClickListener listener = new PostItemClickListener(postWrapper, this.clickListener);
            postItemViewHolder.vh.cardView.setOnClickListener(listener);
            postItemViewHolder.vh.action_delete.setOnClickListener(new PostHideClickListener(hideListener, postWrapper));
            PostsPresenter.bindListItem(postItemViewHolder, new PostMetadataWrapper(postWrapper));
        } else if (type == TYPE_LOADING) {
            ProgressViewHolder progressViewHolder = (ProgressViewHolder) viewHolder;
            Context context = progressViewHolder.loadingText.getContext();
            String posts = context.getString(R.string.posts);
            ProgressPresenter.bindListItem(progressViewHolder, posts);
        } else {
            ErrorViewHolder errorViewHolder = (ErrorViewHolder) viewHolder;
            Context context = errorViewHolder.errorView.getContext();
            String pattern = posts == null ? context.getString(R.string.could_not_load_x) : context.getString(R.string.no_x_found);
            String value = context.getString(R.string.posts);
            String message = String.format(pattern, value);
            ErrorPresenter.bindListItem(errorViewHolder, message);
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (loading) return TYPE_LOADING;
        else if (posts == null) return TYPE_ERROR;
        else if (posts.length == 0) return TYPE_EMPTY;
        else return TYPE_POST;
    }

    @Override
    public long getItemId(int position) {
        if (loading) return -1;
        else if (posts == null) return -2;
        else if (posts.length == 0) return -3;
        else return posts[position].metadata.id;
    }

    @Override
    public int getItemCount() {
        // If there's a problem, make space for an error message
        if (loading || posts == null || posts.length == 0) return 1;
        else return posts.length;
    }

    private static class PostHideClickListener implements View.OnClickListener {
        private final PostHideListener listener;
        private final PostMetadataWrapper post;

        private PostHideClickListener(PostHideListener listener, PostMetadataWrapper post) {
            this.listener = listener;
            this.post = post;
        }

        @Override
        public void onClick(View v) {
            if (listener != null) listener.onPostHidden(post);
        }
    }

    private static class PostItemClickListener implements View.OnClickListener {
        private final PostMetadataWrapper post;
        private final PostClickListener listener;

        private PostItemClickListener(PostMetadataWrapper post, PostClickListener listener) {
            this.post = post;
            this.listener = listener;
        }

        @Override
        public void onClick(View v) {
            if (listener != null) listener.onPostClicked(post);
        }
    }
}


text:
class MakesBarcodeItemPolymorphic < ActiveRecord::Migration[5.1]
  def up
  	change_table :barcode_items do |t|
  		t.column :barcodeable_type, :string, default: "Item"
  		t.rename :item_id, :barcodeable_id
  	end
  	add_index :barcode_items, [:barcodeable_type, :barcodeable_id]
  end

  def down
  	remove_index :barcode_items, column: [:barcodeable_type, :barcodeable_id]
  	change_table :barcode_items do |t|
  		t.remove :barcodeable_type
  		t.rename :barcodeable_id, :item_id
  	end

  end
end


text:
@interface NSObject (FileProviderUIEnums)
@end


text:
package org.bouncycastle.cms;

import java.io.InputStream;
import java.io.OutputStream;

import org.bouncycastle.operator.InputAEADDecryptor;
import org.bouncycastle.operator.InputDecryptor;
import org.bouncycastle.operator.MacCalculator;
import org.bouncycastle.util.io.TeeInputStream;

public class RecipientOperator
{
    private final Object operator;

    public RecipientOperator(InputDecryptor decryptor)
    {
        this.operator = decryptor;
    }

    public RecipientOperator(MacCalculator macCalculator)
    {
        this.operator = macCalculator;
    }

    public InputStream getInputStream(InputStream dataIn)
    {
        if (operator instanceof InputDecryptor)
        {
            return ((InputDecryptor)operator).getInputStream(dataIn);
        }
        else
        {
            return new TeeInputStream(dataIn, ((MacCalculator)operator).getOutputStream());
        }
    }

    public boolean isAEADBased()
    {
        return operator instanceof InputAEADDecryptor;
    }

    public OutputStream getAADStream()
    {
        return ((InputAEADDecryptor)operator).getAADStream();
    }

    public boolean isMacBased()
    {
        return operator instanceof MacCalculator;
    }

    public byte[] getMac()
    {
        return ((MacCalculator)operator).getMac();
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using OpenSim.Region.Framework.Scenes;
using ProtoBuf;
using OpenSim.Region.Framework.Scenes.Serialization;

namespace InWorldz.Region.Data.Thoosa.Serialization
{
    /// <summary>
    /// A snapshot in time of the current state of a SceneObjectGroup that is
    /// also protobuf serializable
    /// </summary>
    [ProtoContract]
    public class SceneObjectGroupSnapshot
    {
        [ProtoMember(1)]
        public SceneObjectPartSnapshot RootPart;

        [ProtoMember(2)]
        public SceneObjectPartSnapshot[] ChildParts;

        /// <summary>
        /// Whether or not this attachment needs to be stored. Serialized so that we
        /// can send it around between regions. That way we remember to save the
        /// attachment when the user finally logs out from a region they didnt make
        /// the edits from
        /// </summary>
        [ProtoMember(3)]
        public bool TaintedAttachment;

        /// <summary>
        /// Whether or not this is a temporary attachment that should not be saved
        /// back to inventory
        /// </summary>
        [ProtoMember(4)]
        public bool TempAttachment;

        static SceneObjectGroupSnapshot()
        {
            ProtoBuf.Serializer.PrepareSerializer<SceneObjectGroupSnapshot>();
        }

        /// <summary>
        /// Creates a new snapshot from the given group
        /// </summary>
        /// <param name="sog"></param>
        /// <returns></returns>
        public static SceneObjectGroupSnapshot FromSceneObjectGroup(SceneObjectGroup sog, SerializationFlags flags)
        {
            SceneObjectGroupSnapshot snapshot = new SceneObjectGroupSnapshot
            {
                RootPart = SceneObjectPartSnapshot.FromSceneObjectPart(sog.RootPart, flags)
            };

            var parts = sog.GetParts();
            SceneObjectPartSnapshot[] partsSnap;

            //do we have more than just the root?
            if (parts.Count > 1)
            {
                List<SceneObjectPartSnapshot> partsCollect = new List<SceneObjectPartSnapshot>();

                foreach (SceneObjectPart part in parts)
                {
                    if (!part.IsRootPart())
                    {
                        partsCollect.Add(SceneObjectPartSnapshot.FromSceneObjectPart(part, flags));
                    }
                }

                partsSnap = partsCollect.ToArray();
            }
            else
            {
                //nope, just the root
                partsSnap = new SceneObjectPartSnapshot[0];
            }

            snapshot.ChildParts = partsSnap;

            if (sog.IsAttachment && sog.HasGroupChanged)
            {
                snapshot.TaintedAttachment = true;
            }
            else
            {
                snapshot.TaintedAttachment = false;
            }

            if (sog.IsAttachment && sog.IsTempAttachment)
            {
                snapshot.TempAttachment = true;
            }
            else
            {
                snapshot.TempAttachment = false;
            }

            return snapshot;
        }

        internal static SceneObjectGroupSnapshot FromBytes(byte[] bytes, int start)
        {
            using (MemoryStream ms = new MemoryStream(bytes, start, bytes.Length - start))
            {
                return ProtoBuf.Serializer.Deserialize<SceneObjectGroupSnapshot>(ms);
            }
        }

        internal SceneObjectGroup ToSceneObjectGroup()
        {
            SceneObjectGroup sog = new SceneObjectGroup();

            SceneObjectPart rootPart = RootPart.ToSceneObjectPart();

            sog.SetRootPart(rootPart);

            if (ChildParts != null)
            {
                foreach (var partSnap in ChildParts)
                {
                    SceneObjectPart childPart = partSnap.ToSceneObjectPart();

                    int originalLinkNum = childPart.LinkNum;
                    sog.AddPart(childPart);

                    // SceneObjectGroup.AddPart() tries to be smart and automatically set the LinkNum.
                    // We override that here
                    if (originalLinkNum != 0)
                        childPart.LinkNum = originalLinkNum;

                    childPart.StoreUndoState();
                }
            }

            sog.TaintedAttachment = this.TaintedAttachment;
            sog.IsTempAttachment = this.TempAttachment;

            return sog;
        }

        internal void SerializeToStream(Stream s)
        {
            ProtoBuf.Serializer.Serialize<SceneObjectGroupSnapshot>(s, this);
        }
    }
}


text:
/*
 * WARNING: because java doesn't support multi-inheritance some code is
 * duplicated. If you're changing this file you probably want to change
 * DeferredElementNSImpl.java at the same time.
 */

package mf.org.apache.xerces.dom;

import mf.org.w3c.dom.NamedNodeMap;

/**
 * Elements represent most of the "markup" and structure of the
 * document.  They contain both the data for the element itself
 * (element name and attributes), and any contained nodes, including
 * document text (as children).
 *

 * Elements may have Attributes associated with them; the API for this is
 * defined in Node, but the function is implemented here. In general, XML
 * applications should retrive Attributes as Nodes, since they may contain
 * entity references and hence be a fairly complex sub-tree. HTML users will
 * be dealing with simple string values, and convenience methods are provided
 * to work in terms of Strings.
 *

 * DeferredElementImpl inherits from ElementImpl which does not support
 * Namespaces. DeferredElementNSImpl, which inherits from ElementNSImpl, does.
 * @see DeferredElementNSImpl
 *
 * @xerces.internal
 *
 * @version $Id: DeferredElementImpl.java 447266 2006-09-18 05:57:49Z mrglavas $
 * @since  PR-DOM-Level-1-19980818.
 */
public class DeferredElementImpl
    extends ElementImpl
    implements DeferredNode {

    //
    // Constants
    //

    /** Serialization version. */
    static final long serialVersionUID = -7670981133940934842L;

    //
    // Data
    //

    /** Node index. */
    protected transient int fNodeIndex;

    //
    // Constructors
    //

    /**
     * This is the deferred constructor. Only the fNodeIndex is given here. All
     * other data, can be requested from the ownerDocument via the index.
     */
    DeferredElementImpl(DeferredDocumentImpl ownerDoc, int nodeIndex) {
        super(ownerDoc, null);

        fNodeIndex = nodeIndex;
        needsSyncChildren(true);

    } // <init>(DocumentImpl,int)

    //
    // DeferredNode methods
    //

    /** Returns the node index. */
    public final int getNodeIndex() {
        return fNodeIndex;
    }

    //
    // Protected methods
    //

    /** Synchronizes the data (name and value) for fast nodes. */
    protected final void synchronizeData() {

        // no need to sync in the future
        needsSyncData(false);

        // fluff data
        DeferredDocumentImpl ownerDocument =
            (DeferredDocumentImpl)this.ownerDocument;

        // we don't want to generate any event for this so turn them off
        boolean orig = ownerDocument.mutationEvents;
        ownerDocument.mutationEvents = false;

        name = ownerDocument.getNodeName(fNodeIndex);

        // attributes
        setupDefaultAttributes();
        int index = ownerDocument.getNodeExtra(fNodeIndex);
        if (index != -1) {
            NamedNodeMap attrs = getAttributes();
            do {
                NodeImpl attr = (NodeImpl)ownerDocument.getNodeObject(index);
                attrs.setNamedItem(attr);
                index = ownerDocument.getPrevSibling(index);
            } while (index != -1);
        }

        // set mutation events flag back to its original value
        ownerDocument.mutationEvents = orig;

    } // synchronizeData()

    protected final void synchronizeChildren() {
        DeferredDocumentImpl ownerDocument =
            (DeferredDocumentImpl) ownerDocument();
        ownerDocument.synchronizeChildren(this, fNodeIndex);
    } // synchronizeChildren()

} // class DeferredElementImpl


text:
<?php

namespace PhpBench\Benchmark\Metadata\Exception;

use InvalidArgumentException;

class CouldNotLoadMetadataException extends InvalidArgumentException
{
}


text:
require("ts-node").register();
const siteMeta = require("./src/content/metadata").default;
const collections = require("./src/content/collections").default;
const theme = require("./src/styles/theme-aux").default;

module.exports = {
  siteMetadata: siteMeta,
  plugins: [
    // configuration & SEO
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: siteMeta.siteUrl,
        short_name: siteMeta.title,
        start_url: "/",
        background_color: theme.colors.background,
        theme_color: theme.colors.background,
        display: "minimal-ui",
        icon: "src/images/pie/pie-svgrepo-com (4).svg", // This path is relative to the root of the site.
      },
    },
    "gatsby-plugin-sitemap",
    "gatsby-plugin-react-helmet",
    "gatsby-plugin-netlify",
    {
      resolve: "gatsby-plugin-extract-schema",
      options: {
        dest: `${__dirname}/.cache/schema.json`,
      },
    },

    // sources
    {
      resolve: "gatsby-plugin-mdx",
      options: {
        extensions: [".mdx", ".md"],
        defaultLayouts: {
          default: require.resolve("./src/templates/page"),
        },
        remarkPlugins: [
          require("remark-attr"),
          require("remark-emoji"),
          // require("remark-normalize-headings"),
        ],
        rehypePlugins: [require("rehype-highlight")],
        gatsbyRemarkPlugins: [
          {
            resolve: "gatsby-remark-smartypants",
            options: {
              dashes: "oldschool",
            },
          },
        ],
      },
    },

    // register content folders
    {
      resolve: "gatsby-source-filesystem",
      options: { name: "images", path: "./src/images" },
    },
    {
      resolve: "gatsby-source-filesystem",
      options: { name: "pages", path: "./src/pages" },
    },
    ...collections.map(({ name, path }) => ({
      resolve: "gatsby-source-filesystem",
      options: { name, path },
    })),

    // transforms
    "gatsby-transformer-sharp",
    "gatsby-plugin-sharp",
    "gatsby-plugin-typescript",
    "gatsby-plugin-catch-links",
    "gatsby-plugin-emotion",

    // other
    "gatsby-plugin-no-sourcemaps",
  ],
};


text:
/**
 * SECTION:gstminiobject
 * @title: GstMiniObject
 * @short_description: Lightweight base class for the GStreamer object hierarchy
 *
 * #GstMiniObject is a simple structure that can be used to implement refcounted
 * types.
 *
 * Subclasses will include #GstMiniObject as the first member in their structure
 * and then call gst_mini_object_init() to initialize the #GstMiniObject fields.
 *
 * gst_mini_object_ref() and gst_mini_object_unref() increment and decrement the
 * refcount respectively. When the refcount of a mini-object reaches 0, the
 * dispose function is called first and when this returns %TRUE, the free
 * function of the miniobject is called.
 *
 * A copy can be made with gst_mini_object_copy().
 *
 * gst_mini_object_is_writable() will return %TRUE when the refcount of the
 * object is exactly 1 and there is no parent or a single parent exists and is
 * writable itself, meaning the current caller has the only reference to the
 * object. gst_mini_object_make_writable() will return a writable version of
 * the object, which might be a new copy when the refcount was not 1.
 *
 * Opaque data can be associated with a #GstMiniObject with
 * gst_mini_object_set_qdata() and gst_mini_object_get_qdata(). The data is
 * meant to be specific to the particular object and is not automatically copied
 * with gst_mini_object_copy() or similar methods.
 *
 * A weak reference can be added and remove with gst_mini_object_weak_ref()
 * and gst_mini_object_weak_unref() respectively.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gst/gst_private.h"
#include "gst/gstminiobject.h"
#include "gst/gstinfo.h"
#include <gobject/gvaluecollector.h>

/* Mutex used for weak referencing */
G_LOCK_DEFINE_STATIC (qdata_mutex);
static GQuark weak_ref_quark;

#define SHARE_ONE (1 << 16)
#define SHARE_TWO (2 << 16)
#define SHARE_MASK (~(SHARE_ONE - 1))
#define IS_SHARED(state) (state >= SHARE_TWO)
#define LOCK_ONE (GST_LOCK_FLAG_LAST)
#define FLAG_MASK (GST_LOCK_FLAG_LAST - 1)
#define LOCK_MASK ((SHARE_ONE - 1) - FLAG_MASK)
#define LOCK_FLAG_MASK (SHARE_ONE - 1)

/* For backwards compatibility reasons we use the
 * guint and gpointer in the GstMiniObject struct in
 * a rather complicated way to store the parent(s) and qdata.
 * Originally the were just the number of qdatas and the qdata.
 *
 * The guint is used as an atomic state integer with the following
 * states:
 * - Locked: 0, basically a spinlock
 * - No parent, no qdata: 1 (pointer is NULL)
 * - One parent: 2 (pointer contains the parent)
 * - Multiple parents or qdata: 3 (pointer contains a PrivData struct)
 *
 * Unless we're in state 3, we always have to move to Locking state
 * atomically and release that again later to the target state whenever
 * accessing the pointer. When we're in state 3, we will never move to lower
 * states again
 *
 * FIXME 2.0: We should store this directly inside the struct, possibly
 * keeping space directly allocated for a couple of parents
 */

enum
{
  PRIV_DATA_STATE_LOCKED = 0,
  PRIV_DATA_STATE_NO_PARENT = 1,
  PRIV_DATA_STATE_ONE_PARENT = 2,
  PRIV_DATA_STATE_PARENTS_OR_QDATA = 3,
};

typedef struct
{
  GQuark quark;
  GstMiniObjectNotify notify;
  gpointer data;
  GDestroyNotify destroy;
} GstQData;

typedef struct
{
  /* Atomic spinlock: 1 if locked, 0 otherwise */
  gint parent_lock;
  guint n_parents, n_parents_len;
  GstMiniObject **parents;

  guint n_qdata, n_qdata_len;
  GstQData *qdata;
} PrivData;

#define QDATA(q,i)          (q->qdata)[(i)]
#define QDATA_QUARK(o,i)    (QDATA(o,i).quark)
#define QDATA_NOTIFY(o,i)   (QDATA(o,i).notify)
#define QDATA_DATA(o,i)     (QDATA(o,i).data)
#define QDATA_DESTROY(o,i)  (QDATA(o,i).destroy)

void
_priv_gst_mini_object_initialize (void)
{
  weak_ref_quark = g_quark_from_static_string ("GstMiniObjectWeakRefQuark");
}

/**
 * gst_mini_object_init: (skip)
 * @mini_object: a #GstMiniObject
 * @flags: initial #GstMiniObjectFlags
 * @type: the #GType of the mini-object to create
 * @copy_func: (allow-none): the copy function, or %NULL
 * @dispose_func: (allow-none): the dispose function, or %NULL
 * @free_func: (allow-none): the free function or %NULL
 *
 * Initializes a mini-object with the desired type and copy/dispose/free
 * functions.
 */
void
gst_mini_object_init (GstMiniObject * mini_object, guint flags, GType type,
    GstMiniObjectCopyFunction copy_func,
    GstMiniObjectDisposeFunction dispose_func,
    GstMiniObjectFreeFunction free_func)
{
  mini_object->type = type;
  mini_object->refcount = 1;
  mini_object->lockstate = 0;
  mini_object->flags = flags;

  mini_object->copy = copy_func;
  mini_object->dispose = dispose_func;
  mini_object->free = free_func;

  g_atomic_int_set ((gint *) & mini_object->priv_uint,
      PRIV_DATA_STATE_NO_PARENT);
  mini_object->priv_pointer = NULL;

  GST_TRACER_MINI_OBJECT_CREATED (mini_object);
}

/**
 * gst_mini_object_copy: (skip)
 * @mini_object: the mini-object to copy
 *
 * Creates a copy of the mini-object.
 *
 * MT safe
 *
 * Returns: (transfer full) (nullable): the new mini-object if copying is
 * possible, %NULL otherwise.
 */
GstMiniObject *
gst_mini_object_copy (const GstMiniObject * mini_object)
{
  GstMiniObject *copy;

  g_return_val_if_fail (mini_object != NULL, NULL);

  if (mini_object->copy)
    copy = mini_object->copy (mini_object);
  else
    copy = NULL;

  return copy;
}

/**
 * gst_mini_object_lock:
 * @object: the mini-object to lock
 * @flags: #GstLockFlags
 *
 * Lock the mini-object with the specified access mode in @flags.
 *
 * Returns: %TRUE if @object could be locked.
 */
gboolean
gst_mini_object_lock (GstMiniObject * object, GstLockFlags flags)
{
  gint access_mode, state, newstate;

  g_return_val_if_fail (object != NULL, FALSE);
  g_return_val_if_fail (GST_MINI_OBJECT_IS_LOCKABLE (object), FALSE);

  if (G_UNLIKELY (object->flags & GST_MINI_OBJECT_FLAG_LOCK_READONLY &&
          flags & GST_LOCK_FLAG_WRITE))
    return FALSE;

  do {
    access_mode = flags & FLAG_MASK;
    newstate = state = g_atomic_int_get (&object->lockstate);

    GST_CAT_TRACE (GST_CAT_LOCKING, "lock %p: state %08x, access_mode %d",
        object, state, access_mode);

    if (access_mode & GST_LOCK_FLAG_EXCLUSIVE) {
      /* shared ref */
      newstate += SHARE_ONE;
      access_mode &= ~GST_LOCK_FLAG_EXCLUSIVE;
    }

    /* shared counter > 1 and write access is not allowed */
    if (((state & GST_LOCK_FLAG_WRITE) != 0
            || (access_mode & GST_LOCK_FLAG_WRITE) != 0)
        && IS_SHARED (newstate))
      goto lock_failed;

    if (access_mode) {
      if ((state & LOCK_FLAG_MASK) == 0) {
        /* nothing mapped, set access_mode */
        newstate |= access_mode;
      } else {
        /* access_mode must match */
        if ((state & access_mode) != access_mode)
          goto lock_failed;
      }
      /* increase refcount */
      newstate += LOCK_ONE;
    }
  } while (!g_atomic_int_compare_and_exchange (&object->lockstate, state,
          newstate));

  return TRUE;

lock_failed:
  {
    GST_CAT_DEBUG (GST_CAT_LOCKING,
        "lock failed %p: state %08x, access_mode %d", object, state,
        access_mode);
    return FALSE;
  }
}

/**
 * gst_mini_object_unlock:
 * @object: the mini-object to unlock
 * @flags: #GstLockFlags
 *
 * Unlock the mini-object with the specified access mode in @flags.
 */
void
gst_mini_object_unlock (GstMiniObject * object, GstLockFlags flags)
{
  gint access_mode, state, newstate;

  g_return_if_fail (object != NULL);
  g_return_if_fail (GST_MINI_OBJECT_IS_LOCKABLE (object));

  do {
    access_mode = flags & FLAG_MASK;
    newstate = state = g_atomic_int_get (&object->lockstate);

    GST_CAT_TRACE (GST_CAT_LOCKING, "unlock %p: state %08x, access_mode %d",
        object, state, access_mode);

    if (access_mode & GST_LOCK_FLAG_EXCLUSIVE) {
      /* shared counter */
      g_return_if_fail (state >= SHARE_ONE);
      newstate -= SHARE_ONE;
      access_mode &= ~GST_LOCK_FLAG_EXCLUSIVE;
    }

    if (access_mode) {
      g_return_if_fail ((state & access_mode) == access_mode);
      /* decrease the refcount */
      newstate -= LOCK_ONE;
      /* last refcount, unset access_mode */
      if ((newstate & LOCK_FLAG_MASK) == access_mode)
        newstate &= ~LOCK_FLAG_MASK;
    }
  } while (!g_atomic_int_compare_and_exchange (&object->lockstate, state,
          newstate));
}

/* Locks the priv pointer and sets the priv uint to PRIV_DATA_STATE_LOCKED,
 * unless the full struct was already stored in the priv pointer.
 *
 * Returns the previous state of the priv uint
 */
static guint
lock_priv_pointer (GstMiniObject * object)
{
  gint priv_state = g_atomic_int_get ((gint *) & object->priv_uint);

  if (priv_state != PRIV_DATA_STATE_PARENTS_OR_QDATA) {
    /* As long as the struct was not allocated yet and either someone else
     * locked it or our priv_state is out of date, try to lock it */
    while (priv_state != PRIV_DATA_STATE_PARENTS_OR_QDATA &&
        (priv_state == PRIV_DATA_STATE_LOCKED ||
            !g_atomic_int_compare_and_exchange ((gint *) & object->priv_uint,
                priv_state, PRIV_DATA_STATE_LOCKED)))
      priv_state = g_atomic_int_get ((gint *) & object->priv_uint);

    /* Note that if we got the full struct, we did not store
     * PRIV_DATA_STATE_LOCKED and did not actually lock the priv pointer */
  }

  return priv_state;
}

/**
 * gst_mini_object_is_writable:
 * @mini_object: the mini-object to check
 *
 * If @mini_object has the LOCKABLE flag set, check if the current EXCLUSIVE
 * lock on @object is the only one, this means that changes to the object will
 * not be visible to any other object.
 *
 * If the LOCKABLE flag is not set, check if the refcount of @mini_object is
 * exactly 1, meaning that no other reference exists to the object and that the
 * object is therefore writable.
 *
 * Modification of a mini-object should only be done after verifying that it
 * is writable.
 *
 * Returns: %TRUE if the object is writable.
 */
gboolean
gst_mini_object_is_writable (const GstMiniObject * mini_object)
{
  gboolean result;
  gint priv_state;

  g_return_val_if_fail (mini_object != NULL, FALSE);

  /* Let's first check our own writability. If this already fails there's
   * no point in checking anything else */
  if (GST_MINI_OBJECT_IS_LOCKABLE (mini_object)) {
    result = !IS_SHARED (g_atomic_int_get (&mini_object->lockstate));
  } else {
    result = (GST_MINI_OBJECT_REFCOUNT_VALUE (mini_object) == 1);
  }
  if (!result)
    return result;

  /* We are writable ourselves, but are there parents and are they all
   * writable too? */
  priv_state = lock_priv_pointer (GST_MINI_OBJECT_CAST (mini_object));

  /* Now we either have to check the full struct and all the
   * parents in there, or if there is exactly one parent we
   * can check that one */
  if (priv_state == PRIV_DATA_STATE_PARENTS_OR_QDATA) {
    PrivData *priv_data = mini_object->priv_pointer;

    /* Lock parents */
    while (!g_atomic_int_compare_and_exchange (&priv_data->parent_lock, 0, 1));

    /* If we have one parent, we're only writable if that parent is writable.
     * Otherwise if we have multiple parents we are not writable, and if
     * we have no parent, we are writable */
    if (priv_data->n_parents == 1)
      result = gst_mini_object_is_writable (priv_data->parents[0]);
    else if (priv_data->n_parents == 0)
      result = TRUE;
    else
      result = FALSE;

    /* Unlock again */
    g_atomic_int_set (&priv_data->parent_lock, 0);
  } else {
    if (priv_state == PRIV_DATA_STATE_ONE_PARENT) {
      result = gst_mini_object_is_writable (mini_object->priv_pointer);
    } else {
      g_assert (priv_state == PRIV_DATA_STATE_NO_PARENT);
      result = TRUE;
    }

    /* Unlock again */
    g_atomic_int_set ((gint *) & mini_object->priv_uint, priv_state);
  }

  return result;
}

/**
 * gst_mini_object_make_writable: (skip)
 * @mini_object: (transfer full): the mini-object to make writable
 *
 * Checks if a mini-object is writable.  If not, a writable copy is made and
 * returned.  This gives away the reference to the original mini object,
 * and returns a reference to the new object.
 *
 * MT safe
 *
 * Returns: (transfer full): a mini-object (possibly the same pointer) that
 *     is writable.
 */
GstMiniObject *
gst_mini_object_make_writable (GstMiniObject * mini_object)
{
  GstMiniObject *ret;

  g_return_val_if_fail (mini_object != NULL, NULL);

  if (gst_mini_object_is_writable (mini_object)) {
    ret = mini_object;
  } else {
    ret = gst_mini_object_copy (mini_object);
    GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy %s miniobject %p -> %p",
        g_type_name (GST_MINI_OBJECT_TYPE (mini_object)), mini_object, ret);
    gst_mini_object_unref (mini_object);
  }

  return ret;
}

/**
 * gst_mini_object_ref: (skip)
 * @mini_object: the mini-object
 *
 * Increase the reference count of the mini-object.
 *
 * Note that the refcount affects the writability
 * of @mini-object, see gst_mini_object_is_writable(). It is
 * important to note that keeping additional references to
 * GstMiniObject instances can potentially increase the number
 * of memcpy operations in a pipeline, especially if the miniobject
 * is a #GstBuffer.
 *
 * Returns: (transfer full): the mini-object.
 */
GstMiniObject *
gst_mini_object_ref (GstMiniObject * mini_object)
{
  gint old_refcount, new_refcount;

  g_return_val_if_fail (mini_object != NULL, NULL);
  /* we can't assert that the refcount > 0 since the _free functions
   * increments the refcount from 0 to 1 again to allow resurrecting
   * the object
   g_return_val_if_fail (mini_object->refcount > 0, NULL);
   */

  old_refcount = g_atomic_int_add (&mini_object->refcount, 1);
  new_refcount = old_refcount + 1;

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "%p ref %d->%d", mini_object,
      old_refcount, new_refcount);

  GST_TRACER_MINI_OBJECT_REFFED (mini_object, new_refcount);

  return mini_object;
}

/* Called with global qdata lock */
static gint
find_notify (GstMiniObject * object, GQuark quark, gboolean match_notify,
    GstMiniObjectNotify notify, gpointer data)
{
  guint i;
  gint priv_state = g_atomic_int_get ((gint *) & object->priv_uint);
  PrivData *priv_data;

  if (priv_state != PRIV_DATA_STATE_PARENTS_OR_QDATA)
    return -1;

  priv_data = object->priv_pointer;

  for (i = 0; i < priv_data->n_qdata; i++) {
    if (QDATA_QUARK (priv_data, i) == quark) {
      /* check if we need to match the callback too */
      if (!match_notify || (QDATA_NOTIFY (priv_data, i) == notify &&
              QDATA_DATA (priv_data, i) == data))
        return i;
    }
  }
  return -1;
}

static void
remove_notify (GstMiniObject * object, gint index)
{
  gint priv_state = g_atomic_int_get ((gint *) & object->priv_uint);
  PrivData *priv_data;

  g_assert (priv_state == PRIV_DATA_STATE_PARENTS_OR_QDATA);
  priv_data = object->priv_pointer;

  /* remove item */
  priv_data->n_qdata--;
  if (priv_data->n_qdata == 0) {
    /* we don't shrink but free when everything is gone */
    g_free (priv_data->qdata);
    priv_data->qdata = NULL;
    priv_data->n_qdata_len = 0;
  } else if (index != priv_data->n_qdata) {
    QDATA (priv_data, index) = QDATA (priv_data, priv_data->n_qdata);
  }
}

/* Make sure we allocate the PrivData of this object if not happened yet */
static void
ensure_priv_data (GstMiniObject * object)
{
  gint priv_state;
  PrivData *priv_data;
  GstMiniObject *parent = NULL;

  GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
      "allocating private data %s miniobject %p",
      g_type_name (GST_MINI_OBJECT_TYPE (object)), object);

  priv_state = lock_priv_pointer (object);
  if (priv_state == PRIV_DATA_STATE_PARENTS_OR_QDATA)
    return;

  /* Now we're either locked, or someone has already allocated the struct
   * before us and we can just go ahead
   *
   * Note: if someone else allocated it in the meantime, we don't have to
   * unlock as we didn't lock! */
  if (priv_state != PRIV_DATA_STATE_PARENTS_OR_QDATA) {
    if (priv_state == PRIV_DATA_STATE_ONE_PARENT)
      parent = object->priv_pointer;

    object->priv_pointer = priv_data = g_new0 (PrivData, 1);

    if (parent) {
      priv_data->parents = g_new (GstMiniObject *, 16);
      priv_data->n_parents_len = 16;
      priv_data->n_parents = 1;
      priv_data->parents[0] = parent;
    }

    /* Unlock */
    g_atomic_int_set ((gint *) & object->priv_uint,
        PRIV_DATA_STATE_PARENTS_OR_QDATA);
  }
}

static void
set_notify (GstMiniObject * object, gint index, GQuark quark,
    GstMiniObjectNotify notify, gpointer data, GDestroyNotify destroy)
{
  PrivData *priv_data;

  ensure_priv_data (object);
  priv_data = object->priv_pointer;

  if (index == -1) {
    /* add item */
    index = priv_data->n_qdata++;
    if (index >= priv_data->n_qdata_len) {
      priv_data->n_qdata_len *= 2;
      if (priv_data->n_qdata_len == 0)
        priv_data->n_qdata_len = 16;

      priv_data->qdata =
          g_realloc (priv_data->qdata,
          sizeof (GstQData) * priv_data->n_qdata_len);
    }
  }

  QDATA_QUARK (priv_data, index) = quark;
  QDATA_NOTIFY (priv_data, index) = notify;
  QDATA_DATA (priv_data, index) = data;
  QDATA_DESTROY (priv_data, index) = destroy;
}

static void
free_priv_data (GstMiniObject * obj)
{
  guint i;
  gint priv_state = g_atomic_int_get ((gint *) & obj->priv_uint);
  PrivData *priv_data;

  if (priv_state != PRIV_DATA_STATE_PARENTS_OR_QDATA) {
    if (priv_state == PRIV_DATA_STATE_LOCKED) {
      g_warning
          ("%s: object finalizing but has locked private data (object:%p)",
          G_STRFUNC, obj);
    } else if (priv_state == PRIV_DATA_STATE_ONE_PARENT) {
      g_warning
          ("%s: object finalizing but still has parent (object:%p, parent:%p)",
          G_STRFUNC, obj, obj->priv_pointer);
    }

    return;
  }

  priv_data = obj->priv_pointer;

  for (i = 0; i < priv_data->n_qdata; i++) {
    if (QDATA_QUARK (priv_data, i) == weak_ref_quark)
      QDATA_NOTIFY (priv_data, i) (QDATA_DATA (priv_data, i), obj);
    if (QDATA_DESTROY (priv_data, i))
      QDATA_DESTROY (priv_data, i) (QDATA_DATA (priv_data, i));
  }
  g_free (priv_data->qdata);

  if (priv_data->n_parents)
    g_warning ("%s: object finalizing but still has %d parents (object:%p)",
        G_STRFUNC, priv_data->n_parents, obj);
  g_free (priv_data->parents);

  g_free (priv_data);
}

/**
 * gst_mini_object_unref: (skip)
 * @mini_object: the mini-object
 *
 * Decreases the reference count of the mini-object, possibly freeing
 * the mini-object.
 */
void
gst_mini_object_unref (GstMiniObject * mini_object)
{
  gint old_refcount, new_refcount;

  g_return_if_fail (mini_object != NULL);
  g_return_if_fail (GST_MINI_OBJECT_REFCOUNT_VALUE (mini_object) > 0);

  old_refcount = g_atomic_int_add (&mini_object->refcount, -1);
  new_refcount = old_refcount - 1;

  g_return_if_fail (old_refcount > 0);

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "%p unref %d->%d",
      mini_object, old_refcount, new_refcount);

  GST_TRACER_MINI_OBJECT_UNREFFED (mini_object, new_refcount);

  if (new_refcount == 0) {
    gboolean do_free;

    if (mini_object->dispose)
      do_free = mini_object->dispose (mini_object);
    else
      do_free = TRUE;

    /* if the subclass recycled the object (and returned FALSE) we don't
     * want to free the instance anymore */
    if (G_LIKELY (do_free)) {
      /* there should be no outstanding locks */
      g_return_if_fail ((g_atomic_int_get (&mini_object->lockstate) & LOCK_MASK)
          < 4);

      free_priv_data (mini_object);

      GST_TRACER_MINI_OBJECT_DESTROYED (mini_object);
      if (mini_object->free)
        mini_object->free (mini_object);
    }
  }
}

/**
 * gst_clear_mini_object: (skip)
 * @object_ptr: a pointer to a #GstMiniObject reference
 *
 * Clears a reference to a #GstMiniObject.
 *
 * @object_ptr must not be %NULL.
 *
 * If the reference is %NULL then this function does nothing.
 * Otherwise, the reference count of the object is decreased using
 * gst_mini_object_unref() and the pointer is set to %NULL.
 *
 * A macro is also included that allows this function to be used without
 * pointer casts.
 *
 * Since: 1.16
 **/
#undef gst_clear_mini_object
void
gst_clear_mini_object (GstMiniObject ** object_ptr)
{
  g_clear_pointer (object_ptr, gst_mini_object_unref);
}

/**
 * gst_mini_object_replace:
 * @olddata: (inout) (transfer full) (nullable): pointer to a pointer to a
 *     mini-object to be replaced
 * @newdata: (allow-none): pointer to new mini-object
 *
 * Atomically modifies a pointer to point to a new mini-object.
 * The reference count of @olddata is decreased and the reference count of
 * @newdata is increased.
 *
 * Either @newdata and the value pointed to by @olddata may be %NULL.
 *
 * Returns: %TRUE if @newdata was different from @olddata
 */
gboolean
gst_mini_object_replace (GstMiniObject ** olddata, GstMiniObject * newdata)
{
  GstMiniObject *olddata_val;

  g_return_val_if_fail (olddata != NULL, FALSE);

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "replace %p (%d) with %p (%d)",
      *olddata, *olddata ? (*olddata)->refcount : 0,
      newdata, newdata ? newdata->refcount : 0);

  olddata_val = g_atomic_pointer_get ((gpointer *) olddata);

  if (G_UNLIKELY (olddata_val == newdata))
    return FALSE;

  if (newdata)
    gst_mini_object_ref (newdata);

  while (G_UNLIKELY (!g_atomic_pointer_compare_and_exchange ((gpointer *)
              olddata, olddata_val, newdata))) {
    olddata_val = g_atomic_pointer_get ((gpointer *) olddata);
    if (G_UNLIKELY (olddata_val == newdata))
      break;
  }

  if (olddata_val)
    gst_mini_object_unref (olddata_val);

  return olddata_val != newdata;
}

/**
 * gst_mini_object_steal: (skip)
 * @olddata: (inout) (transfer full): pointer to a pointer to a mini-object to
 *     be stolen
 *
 * Replace the current #GstMiniObject pointer to by @olddata with %NULL and
 * return the old value.
 *
 * Returns: (nullable): the #GstMiniObject at @oldata
 */
GstMiniObject *
gst_mini_object_steal (GstMiniObject ** olddata)
{
  GstMiniObject *olddata_val;

  g_return_val_if_fail (olddata != NULL, NULL);

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "steal %p (%d)",
      *olddata, *olddata ? (*olddata)->refcount : 0);

  do {
    olddata_val = g_atomic_pointer_get ((gpointer *) olddata);
    if (olddata_val == NULL)
      break;
  } while (G_UNLIKELY (!g_atomic_pointer_compare_and_exchange ((gpointer *)
              olddata, olddata_val, NULL)));

  return olddata_val;
}

/**
 * gst_mini_object_take:
 * @olddata: (inout) (transfer full): pointer to a pointer to a mini-object to
 *     be replaced
 * @newdata: pointer to new mini-object
 *
 * Modifies a pointer to point to a new mini-object. The modification
 * is done atomically. This version is similar to gst_mini_object_replace()
 * except that it does not increase the refcount of @newdata and thus
 * takes ownership of @newdata.
 *
 * Either @newdata and the value pointed to by @olddata may be %NULL.
 *
 * Returns: %TRUE if @newdata was different from @olddata
 */
gboolean
gst_mini_object_take (GstMiniObject ** olddata, GstMiniObject * newdata)
{
  GstMiniObject *olddata_val;

  g_return_val_if_fail (olddata != NULL, FALSE);

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "take %p (%d) with %p (%d)",
      *olddata, *olddata ? (*olddata)->refcount : 0,
      newdata, newdata ? newdata->refcount : 0);

  do {
    olddata_val = g_atomic_pointer_get ((gpointer *) olddata);
    if (G_UNLIKELY (olddata_val == newdata))
      break;
  } while (G_UNLIKELY (!g_atomic_pointer_compare_and_exchange ((gpointer *)
              olddata, olddata_val, newdata)));

  if (olddata_val)
    gst_mini_object_unref (olddata_val);

  return olddata_val != newdata;
}

/**
 * gst_mini_object_weak_ref: (skip)
 * @object: #GstMiniObject to reference weakly
 * @notify: callback to invoke before the mini object is freed
 * @data: extra data to pass to notify
 *
 * Adds a weak reference callback to a mini object. Weak references are
 * used for notification when a mini object is finalized. They are called
 * "weak references" because they allow you to safely hold a pointer
 * to the mini object without calling gst_mini_object_ref()
 * (gst_mini_object_ref() adds a strong reference, that is, forces the object
 * to stay alive).
 */
void
gst_mini_object_weak_ref (GstMiniObject * object,
    GstMiniObjectNotify notify, gpointer data)
{
  g_return_if_fail (object != NULL);
  g_return_if_fail (notify != NULL);
  g_return_if_fail (GST_MINI_OBJECT_REFCOUNT_VALUE (object) >= 1);

  G_LOCK (qdata_mutex);
  set_notify (object, -1, weak_ref_quark, notify, data, NULL);
  G_UNLOCK (qdata_mutex);
}

/**
 * gst_mini_object_weak_unref: (skip)
 * @object: #GstMiniObject to remove a weak reference from
 * @notify: callback to search for
 * @data: data to search for
 *
 * Removes a weak reference callback from a mini object.
 */
void
gst_mini_object_weak_unref (GstMiniObject * object,
    GstMiniObjectNotify notify, gpointer data)
{
  gint i;

  g_return_if_fail (object != NULL);
  g_return_if_fail (notify != NULL);

  G_LOCK (qdata_mutex);
  if ((i = find_notify (object, weak_ref_quark, TRUE, notify, data)) != -1) {
    remove_notify (object, i);
  } else {
    g_warning ("%s: couldn't find weak ref %p (object:%p data:%p)", G_STRFUNC,
        notify, object, data);
  }
  G_UNLOCK (qdata_mutex);
}

/**
 * gst_mini_object_set_qdata:
 * @object: a #GstMiniObject
 * @quark: A #GQuark, naming the user data pointer
 * @data: An opaque user data pointer
 * @destroy: Function to invoke with @data as argument, when @data
 *           needs to be freed
 *
 * This sets an opaque, named pointer on a miniobject.
 * The name is specified through a #GQuark (retrieved e.g. via
 * g_quark_from_static_string()), and the pointer
 * can be gotten back from the @object with gst_mini_object_get_qdata()
 * until the @object is disposed.
 * Setting a previously set user data pointer, overrides (frees)
 * the old pointer set, using %NULL as pointer essentially
 * removes the data stored.
 *
 * @destroy may be specified which is called with @data as argument
 * when the @object is disposed, or the data is being overwritten by
 * a call to gst_mini_object_set_qdata() with the same @quark.
 */
void
gst_mini_object_set_qdata (GstMiniObject * object, GQuark quark,
    gpointer data, GDestroyNotify destroy)
{
  gint i;
  gpointer old_data = NULL;
  GDestroyNotify old_notify = NULL;

  g_return_if_fail (object != NULL);
  g_return_if_fail (quark > 0);

  G_LOCK (qdata_mutex);
  if ((i = find_notify (object, quark, FALSE, NULL, NULL)) != -1) {
    PrivData *priv_data = object->priv_pointer;

    old_data = QDATA_DATA (priv_data, i);
    old_notify = QDATA_DESTROY (priv_data, i);

    if (data == NULL)
      remove_notify (object, i);
  }
  if (data != NULL)
    set_notify (object, i, quark, NULL, data, destroy);
  G_UNLOCK (qdata_mutex);

  if (old_notify)
    old_notify (old_data);
}

/**
 * gst_mini_object_get_qdata:
 * @object: The GstMiniObject to get a stored user data pointer from
 * @quark: A #GQuark, naming the user data pointer
 *
 * This function gets back user data pointers stored via
 * gst_mini_object_set_qdata().
 *
 * Returns: (transfer none) (nullable): The user data pointer set, or
 * %NULL
 */
gpointer
gst_mini_object_get_qdata (GstMiniObject * object, GQuark quark)
{
  guint i;
  gpointer result;

  g_return_val_if_fail (object != NULL, NULL);
  g_return_val_if_fail (quark > 0, NULL);

  G_LOCK (qdata_mutex);
  if ((i = find_notify (object, quark, FALSE, NULL, NULL)) != -1) {
    PrivData *priv_data = object->priv_pointer;
    result = QDATA_DATA (priv_data, i);
  } else {
    result = NULL;
  }
  G_UNLOCK (qdata_mutex);

  return result;
}

/**
 * gst_mini_object_steal_qdata:
 * @object: The GstMiniObject to get a stored user data pointer from
 * @quark: A #GQuark, naming the user data pointer
 *
 * This function gets back user data pointers stored via gst_mini_object_set_qdata()
 * and removes the data from @object without invoking its destroy() function (if
 * any was set).
 *
 * Returns: (transfer full) (nullable): The user data pointer set, or
 * %NULL
 */
gpointer
gst_mini_object_steal_qdata (GstMiniObject * object, GQuark quark)
{
  guint i;
  gpointer result;

  g_return_val_if_fail (object != NULL, NULL);
  g_return_val_if_fail (quark > 0, NULL);

  G_LOCK (qdata_mutex);
  if ((i = find_notify (object, quark, FALSE, NULL, NULL)) != -1) {
    PrivData *priv_data = object->priv_pointer;
    result = QDATA_DATA (priv_data, i);
    remove_notify (object, i);
  } else {
    result = NULL;
  }
  G_UNLOCK (qdata_mutex);

  return result;
}

/**
 * gst_mini_object_add_parent:
 * @object: a #GstMiniObject
 * @parent: a parent #GstMiniObject
 *
 * This adds @parent as a parent for @object. Having one ore more parents affects the
 * writability of @object: if a @parent is not writable, @object is also not
 * writable, regardless of its refcount. @object is only writable if all
 * the parents are writable and its own refcount is exactly 1.
 *
 * Note: This function does not take ownership of @parent and also does not
 * take an additional reference. It is the responsibility of the caller to
 * remove the parent again at a later time.
 *
 * Since: 1.16
 */
void
gst_mini_object_add_parent (GstMiniObject * object, GstMiniObject * parent)
{
  gint priv_state;

  g_return_if_fail (object != NULL);

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "adding parent %p to object %p", parent,
      object);

  priv_state = lock_priv_pointer (object);
  /* If we already had one parent, we need to allocate the full struct now */
  if (priv_state == PRIV_DATA_STATE_ONE_PARENT) {
    /* Unlock again */
    g_atomic_int_set ((gint *) & object->priv_uint, priv_state);

    ensure_priv_data (object);
    priv_state = PRIV_DATA_STATE_PARENTS_OR_QDATA;
  }

  /* Now we either have to add the new parent to the full struct, or add
   * our one and only parent to the pointer field */
  if (priv_state == PRIV_DATA_STATE_PARENTS_OR_QDATA) {
    PrivData *priv_data = object->priv_pointer;

    /* Lock parents */
    while (!g_atomic_int_compare_and_exchange (&priv_data->parent_lock, 0, 1));

    if (priv_data->n_parents >= priv_data->n_parents_len) {
      priv_data->n_parents_len *= 2;
      if (priv_data->n_parents_len == 0)
        priv_data->n_parents_len = 16;

      priv_data->parents =
          g_realloc (priv_data->parents,
          priv_data->n_parents_len * sizeof (GstMiniObject *));
    }
    priv_data->parents[priv_data->n_parents] = parent;
    priv_data->n_parents++;

    /* Unlock again */
    g_atomic_int_set (&priv_data->parent_lock, 0);
  } else if (priv_state == PRIV_DATA_STATE_NO_PARENT) {
    object->priv_pointer = parent;

    /* Unlock again */
    g_atomic_int_set ((gint *) & object->priv_uint, PRIV_DATA_STATE_ONE_PARENT);
  } else {
    g_assert_not_reached ();
  }
}

/**
 * gst_mini_object_remove_parent:
 * @object: a #GstMiniObject
 * @parent: a parent #GstMiniObject
 *
 * This removes @parent as a parent for @object. See
 * gst_mini_object_add_parent().
 *
 * Since: 1.16
 */
void
gst_mini_object_remove_parent (GstMiniObject * object, GstMiniObject * parent)
{
  gint priv_state;

  g_return_if_fail (object != NULL);

  GST_CAT_TRACE (GST_CAT_REFCOUNTING, "removing parent %p from object %p",
      parent, object);

  priv_state = lock_priv_pointer (object);

  /* Now we either have to add the new parent to the full struct, or add
   * our one and only parent to the pointer field */
  if (priv_state == PRIV_DATA_STATE_PARENTS_OR_QDATA) {
    PrivData *priv_data = object->priv_pointer;
    guint i;

    /* Lock parents */
    while (!g_atomic_int_compare_and_exchange (&priv_data->parent_lock, 0, 1));

    for (i = 0; i < priv_data->n_parents; i++)
      if (parent == priv_data->parents[i])
        break;

    if (i != priv_data->n_parents) {
      priv_data->n_parents--;
      if (priv_data->n_parents != i)
        priv_data->parents[i] = priv_data->parents[priv_data->n_parents];
    } else {
      g_warning ("%s: couldn't find parent %p (object:%p)", G_STRFUNC,
          object, parent);
    }

    /* Unlock again */
    g_atomic_int_set (&priv_data->parent_lock, 0);
  } else if (priv_state == PRIV_DATA_STATE_ONE_PARENT) {
    if (object->priv_pointer != parent) {
      g_warning ("%s: couldn't find parent %p (object:%p)", G_STRFUNC,
          object, parent);
      /* Unlock again */
      g_atomic_int_set ((gint *) & object->priv_uint, priv_state);
    } else {
      object->priv_pointer = NULL;
      /* Unlock again */
      g_atomic_int_set ((gint *) & object->priv_uint,
          PRIV_DATA_STATE_NO_PARENT);
    }
  } else {
    /* Unlock again */
    g_atomic_int_set ((gint *) & object->priv_uint, PRIV_DATA_STATE_NO_PARENT);
  }
}


text:
package proxy

import (
	"io"
	"net"
)

type closeNotifyConn struct {
	net.Conn

	r io.Reader

	cnc chan bool
}

// CloseNotifyConn returns a net.Conn that implements http.CloseNotifier.
// Used to detect connections closed early on the client side.
func CloseNotifyConn(conn net.Conn) net.Conn {
	pr, pw := io.Pipe()

	c := &closeNotifyConn{
		Conn: conn,
		r:    pr,
		cnc:  make(chan bool),
	}

	go func() {
		_, err := io.Copy(pw, conn)
		if err == nil {
			err = io.EOF
		}
		pw.CloseWithError(err)
		close(c.cnc)
	}()

	return c
}

// CloseNotify returns a channel that receives a single value when the client
// connection has gone away.
func (c *closeNotifyConn) CloseNotify() <-chan bool {
	return c.cnc
}

func (c *closeNotifyConn) Read(p []byte) (n int, err error) {
	return c.r.Read(p)
}


text:
Any project with a "Release" should be safe for general use, if it is not, make an "Issue" and it will be fixed immediately!

Any use of these programs outside of re-writing/adding code via this repository needs to be cleared by ShadowDeath (Creator of Visionary Technologies)

Terms of use:
  1. Do not re-upload and claim as your own.
  2. If you would like to re-upload to another site/file hosting please aquire premissions.
  3. Programs **cannot** be sold.
  4. Any bugs must be reported (as they could be a major issue to anyone i.e. **Security issues** (it has happened to me!)).

# TO BE FINISHED