text:
using Nucleus.Geometry;
using Nucleus.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nucleus.Model.Loading
{
    /// <summary>
    /// A point load applied to a linear element
    /// </summary>
    [Serializable]
    public class LinearElementPointLoad : ForceLoad<LinearElementSet, LinearElement>
    {
        #region Properties

        /// <summary>
        /// Private backing field for point load position.
        /// </summary>
        private double _Position = 0.5;

        /// <summary>
        /// The position of the point load along the element.
        /// By default (when Relative = true), this is a relative position
        /// along the element where
        /// 0 = the element start and 1 = the element end.
        /// Otherwise (when Relative = false) it is an absolute distance
        /// value from the element start.
        /// </summary>
        [AutoUI(650)]
        public double Position
        {
            get { return _Position; }
            set { ChangeProperty(ref _Position, value, "Position"); }
        }

        /// <summary>
        /// Private backing field for 'Relative' property
        /// </summary>
        private bool _Relative = true;

        /// <summary>
        /// Is the position of this point load defined relatively?
        /// If true (default) the Position property refers to a
        /// relative position along the element where
        /// 0 = the element start and 1 = the element end.
        /// Otherwise (when Relative = false) it is an absolute distance
        /// value from the element start.
        /// </summary>
        [AutoUI(655)]
        public bool Relative
        {
            get { return _Relative; }
            set { ChangeProperty(ref _Relative, value, "Relative"); }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Set the position of this point load to to represent the
        /// closest point on a curve to a point
        /// </summary>
        /// <param name="onCurve"></param>
        /// <param name="closestTo"></param>
        public bool SetPosition(Curve onCurve, Vector closestTo)
        {
            if (onCurve != null)
            {
                Position = onCurve.ClosestParameter(closestTo);
                Relative = true;
                return true;
            }
            else return false;
        }

        /// <summary>
        /// Set the position of this point load to represent the
        /// closest point on the specified linear element to
        /// a point
        /// </summary>
        /// <param name="element"></param>
        /// <param name="closestTo"></param>
        public bool SetPosition(LinearElement element, Vector closestTo)
        {
            return SetPosition(element.Geometry, closestTo);
        }

        /// <summary>
        /// Calculate the moment induced in a simply supported beam
        /// by this point load at a given position x along a member
        /// of length l
        /// </summary>
        /// <param name="x"></param>
        /// <param name="l"></param>
        /// <returns></returns>
        internal double SimpleBeamMoment(double x, double l)
        {
            //TODO: Consider direction of point load

            throw new NotImplementedException();
        }

        #endregion
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class News extends Admin_Controller{

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

        // Access control
        if(!$this->session->userdata('logged_in'))
        {
            redirect('admin/login');
        }
    }

    function index()
    {
        // Get list
        $data['news'] = $this->News_model->get_list();

        // Load view
        $this->template->load('admin', 'default', 'news/index', $data);
    }

    // Add new one news
    public function add()
    {
        // Validation rules
        $this->form_validation->set_rules('title','Заголовок','trim|required|min_length[3]');
        $this->form_validation->set_rules('body','Тело новости','required');
        $this->form_validation->set_rules('is_published','Опубликовано','required');
        $this->form_validation->set_rules('order','Порядок','integer');

        if($this->form_validation->run() == FALSE)
        {
            $this->template->load('admin', 'default', 'news/add');
        }else {

            $main_img = '';

            if ($_FILES)
            {
                $config['upload_path'] = './assets/images/news/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']	= 5000;
                $config['encrypt_name'] = TRUE; // переименование файла в уникальное название
                $config['remove_spaces'] = TRUE; // убирает пробелы из названия файлов
                $config['max_width']            = 4000;
                $config['max_height']           = 4000;

                $this->load->library('upload', $config);

                if ( ! $this->upload->do_upload('userfile'))
                {
                    $error = array('error' => $this->upload->display_errors());

                }
                else
                {
                    $data = array('upload_data' => $this->upload->data());
                    $main_img = $data['upload_data']['file_name'];

                }//end of else
            }

            // News Data
            $data = [
                'title' => $this->input->post('title'),
                'body' => $this->input->post('body'),
                'main_img' => $main_img,
                'is_published' => $this->input->post('is_published'),
                'user_id' => $this->session->userdata('user_id'),
                'list_order' => $this->input->post('order')
            ];

            // Insert News
            $this->News_model->add_news($data);

            // Activity Array
            $data = [
                'resource_id' => $this->db->insert_id(),
                'type' => 'news',
                'action' => 'added',
                'user_id' => $this->session->userdata('user_id'),
                'message' => 'Была добавлена новость ('.$data['title'].')'
            ];

            // Insert Activity
            $this->Activity_model->add($data);

            //Set Message
            $this->session->set_flashdata('success', 'Новость добавлена');

            redirect('admin/news');
        }

    }

    public function edit($id)
    {
        // Validation rules
        $this->form_validation->set_rules('title','Заголовок','trim|required|min_length[3]');
        $this->form_validation->set_rules('body','Тело новости','required');
        $this->form_validation->set_rules('is_published','Опубликовано','required');
        $this->form_validation->set_rules('order','Порядок','integer');

        if($this->form_validation->run() == FALSE)
        {
            $data['news'] = $this->News_model->get($id);

            $this->template->load('admin', 'default', 'news/edit', $data);
        }else {
            $main_img = $this->News_model->get($id)->main_img;

            if ($_FILES)
            {
                $config['upload_path'] = './assets/images/news/';
                $config['allowed_types'] = 'gif|jpg|png';
                $config['max_size']	= 5000;
                $config['encrypt_name'] = TRUE; // переименование файла в уникальное название
                $config['remove_spaces'] = TRUE; // убирает пробелы из названия файлов
                $config['max_width']            = 4000;
                $config['max_height']           = 4000;

                $this->load->library('upload', $config);

                if ( ! $this->upload->do_upload('userfile'))
                {
                    $error = array('error' => $this->upload->display_errors());

                }
                else
                {
                    $data = array('upload_data' => $this->upload->data());
                    $main_img = $data['upload_data']['file_name'];

                }//end of else
            }

            // News Data
            $data = [
                'title' => $this->input->post('title'),
                'body' => $this->input->post('body'),
                'main_img' => $main_img,
                'is_published' => $this->input->post('is_published'),
                'user_id' => $this->session->userdata('user_id'),
                'list_order' => $this->input->post('order')
            ];

            // Update News
            $this->News_model->update_news($id, $data);

            // Activity Array
            $data = [
                'resource_id' => $id,
                'type' => 'news',
                'action' => 'updated',
                'user_id' => $this->session->userdata('user_id'),
                'message' => 'Была отредактированна новость ('.$data['title'].')'
            ];

            // Insert Activity
            $this->Activity_model->add($data);

            //Set Message
            $this->session->set_flashdata('success', 'Новость обновлена');

            redirect('admin/news/edit/'.$id);
        }

    }

    public function delete($id)
    {
        $page_title = $this->News_model->get($id)->title;
        $this->News_model->delete_news($id);

        // Activity Array
        $data = [
            'resource_id' => $id,
            'type' => 'news',
            'action' => 'deleted',
            'user_id' => $this->session->userdata('user_id'),
            'message' => 'Новость ('.$page_title.') удалена'
        ];

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('deleted', 'Новость удалена');

        redirect('admin/news');
    }

}

redpajama_set_name: RedPajamaGithub


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

<TITLE>
OutputMetaData
</TITLE>

<META NAME="date" CONTENT="2012-05-24">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Package
    Class
      Tree
      Index

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

SimpleOpenNI

Class OutputMetaData

java.lang.Object
  SimpleOpenNI.OutputMetaData

Direct Known Subclasses:
MapMetaData

public class OutputMetaData
extends java.lang.Object

Constructor Summary

OutputMetaData(long cPtr,
               boolean cMemoryOwn)

OutputMetaData(SWIGTYPE_p_p_unsigned_char ppData)

Method Summary

 long
AllocateData(long nBytes)

 SWIGTYPE_p_p_unsigned_char
Data()

 long
DataSize()

 void
delete()

 long
FrameID()

 void
Free()

static long
getCPtr(OutputMetaData obj)

 SWIGTYPE_p_XnOutputMetaData
GetUnderlying()

 boolean
IsDataNew()

 long
MakeDataWritable()

 void
swigReleaseOwnership()

 void
swigTakeOwnership()

 SWIGTYPE_p_XnUInt64
Timestamp()

 SWIGTYPE_p_unsigned_char
WritableData()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

OutputMetaData

public OutputMetaData(long cPtr,
                      boolean cMemoryOwn)

OutputMetaData

public OutputMetaData(SWIGTYPE_p_p_unsigned_char ppData)

Method Detail

AllocateData

public long AllocateData(long nBytes)

Data

public SWIGTYPE_p_p_unsigned_char Data()

DataSize

public long DataSize()

delete

public void delete()

FrameID

public long FrameID()

Free

public void Free()

getCPtr

public static long getCPtr(OutputMetaData obj)

GetUnderlying

public SWIGTYPE_p_XnOutputMetaData GetUnderlying()

IsDataNew

public boolean IsDataNew()

MakeDataWritable

public long MakeDataWritable()

swigReleaseOwnership

public void swigReleaseOwnership()

swigTakeOwnership

public void swigTakeOwnership()

Timestamp

public SWIGTYPE_p_XnUInt64 Timestamp()

WritableData

public SWIGTYPE_p_unsigned_char WritableData()

      Package
    Class
      Tree
      Index

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
CMsgQueueManager::CMsgQueueManager()
: m_bInit(false)
{
    m_poMsgqCntl = new CMsgQueue;
    m_poMsgqBack = new CMsgQueue;

    assert(m_poMsgqCntl);
    assert(m_poMsgqBack);
}

CMsgQueueManager::~CMsgQueueManager()
{
    delete m_poMsgqCntl;
    delete m_poMsgqBack;

	for(m_l_it = m_mapGroupMsgqFront.begin()
		; m_l_it != m_mapGroupMsgqFront.end(); ++m_l_it)
	{
		FrontQueues_T& rFrontQueues = (*m_l_it).second;
		for(uint32_t i = 0; i < rFrontQueues.nKeyNum; ++i)
		{
			CMsgQueue* pMsgq = rFrontQueues.arrMsgQueues[i];
			assert(pMsgq);
			delete pMsgq;
		}
	}
}

int CMsgQueueManager::Initialize()
{
    int iCntlKey = CAPP->getCfgLoader().getLocalCfgItem().iMsgqCntlKey;
    if(m_poMsgqCntl->Initialize(iCntlKey, true) != 0)
    {
        m_sLastErrMsg = "Init MsgqCntl failed";
        return -1;
    }

    // Get MsgqFront/BackKeyId from ConfigLoader
    int iBackKey = CAPP->getCfgLoader().getLocalCfgItem().iMsgqBackKey;
    if(m_poMsgqBack->Initialize(iBackKey, true) != 0)
    {
        m_sLastErrMsg = "Init MsgqBack failed";
        return -1;
    }

    m_bInit = true;
    return 0;
}

CMsgQueue* CMsgQueueManager::addMsgQueue_i(uint32_t dwGroupId, uint32_t dwRouteKey)
{
    const GroupMsgqKeyFrontMap_T& rMsgqKeyMap = CAPP->getCfgLoader().getGroupMsgqKeyFront();
    GroupMsgqKeyFrontMap_T::const_iterator it = rMsgqKeyMap.find(dwGroupId);
    if(it == rMsgqKeyMap.end())
    {
        std::ostringstream oss;
        oss.str("");
        oss << "Cannot find MsgqKey from ConfigLoader for : 0x" << std::hex << dwGroupId << std::dec;
        m_sLastErrMsg = oss.str();
        return NULL;
    }

	const FrontKeys_T& rFrontKeys = (*it).second;

	FrontQueues_T stFrontQueue;
	stFrontQueue.nKeyNum = rFrontKeys.nKeyNum;
	assert(stFrontQueue.nKeyNum > 0);

	CMsgQueue* pMsgq = NULL;
	int iKey  = 0;
	for(uint32_t i = 0; i < stFrontQueue.nKeyNum; ++i)
	{
		pMsgq = new CMsgQueue;
		iKey = rFrontKeys.arrKeys[i];
		if(pMsgq->Initialize(iKey, true) != 0)
		{
			delete pMsgq;
			std::ostringstream oss;
			oss.str("");
			oss << "Init MsgqFront failed, Key = " << iKey << ", GroupId = 0x" << std::hex << dwGroupId << std::dec;
			m_sLastErrMsg = oss.str();
			return NULL;
		}
		stFrontQueue.arrMsgQueues[i] = pMsgq;
	}

	m_mapGroupMsgqFront[dwGroupId] = stFrontQueue;

    return stFrontQueue.arrMsgQueues[(dwRouteKey % stFrontQueue.nKeyNum)];
}

CMsgQueue* CMsgQueueManager::getMsgQueue(uint32_t dwGroupId, uint32_t dwRouteKey)
{
    assert(m_bInit);

    m_l_it = m_mapGroupMsgqFront.find(dwGroupId);
    if(m_l_it != m_mapGroupMsgqFront.end())
    {
		FrontQueues_T& rFrontQueues = (*m_l_it).second;
		assert(rFrontQueues.nKeyNum > 0);
		return rFrontQueues.arrMsgQueues[(dwRouteKey % rFrontQueues.nKeyNum)];
    }

    return addMsgQueue_i(dwGroupId, dwRouteKey);
}


text:
package org.apache.click.extras.control;

/**
 * Provides a Long Field control:   <input type='text'>.
 *
 *

 *

 * Long Field
 * <input type='text' value='93019382701' title='LongField Control'/>
 *

 *

 *
 * LongField will validate the number when the control is processed and invoke
 * the control listener if defined.
 *

 * The LongField uses a JavaScript onkeypress() integerFilter() method to prevent
 * users from entering invalid characters.  To enable number key filtering
 * reference the variables <tt class="blue">$jsElements</tt> and
 * <tt class="blue">$headElements</tt> in your page template. For example:
 *
 *

 * <html>
 * <head>
 * $headElements
 * </head>
 * <body>
 *
 * $form
 *
 * $jsElements
 * </body>
 * </html>

 *
 * The LongField has left justified horizontal text alignment,
 * {@link #setTextAlign(String)}.
 *

 *
 * See also W3C HTML reference
 * INPUT
 */
public class LongField extends NumberField {

    private static final long serialVersionUID = 1L;

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a LongField field with the given name.
     *
     * @param name the name of the field
     */
    public LongField(String name) {
        super(name);
        setAttribute("onkeypress", "javascript:return integerFilter(event);");
        setTextAlign("left");
    }

    /**
     * Construct a LongField field with the given name and required status.
     *
     * @param name the name of the field
     * @param required the field required status
     */
    public LongField(String name, boolean required) {
        super(name, required);
        setAttribute("onkeypress", "javascript:return integerFilter(event);");
        setTextAlign("left");
    }

    /**
     * Construct a LongField field with the given name and label.
     *
     * @param name the name of the field
     * @param label the label of the field
     */
    public LongField(String name, String label) {
        super(name, label);
        setAttribute("onkeypress", "javascript:return integerFilter(event);");
        setTextAlign("left");
    }

    /**
     * Construct a LongField field with the given name, label and required
     * status.
     *
     * @param name the name of the field
     * @param label the label of the field
     * @param required the field required status
     */
    public LongField(String name, String label, boolean required) {
        this(name, label);
        setRequired(required);
    }

    /**
     * Construct the LongField with the given name, label and size.
     *
     * @param name the name of the field
     * @param label the label of the field
     * @param size the size of the field
     */
    public LongField(String name, String label, int size) {
        this(name, label);
        setSize(size);
    }

    /**
     * Construct the LongField with the given name, label, size and
     * required status.
     *
     * @param name the name of the field
     * @param label the label of the field
     * @param size the size of the field
     * @param required the field required status
     */
    public LongField(String name, String label, int size, boolean required) {
        this(name, label, required);
        setSize(size);
    }

    /**
     * Create a LongField with no name defined.
     *

     * Please note the control's name must be defined before it is valid.
     */
    public LongField() {
        setAttribute("onkeypress", "javascript:return integerFilter(event);");
        setTextAlign("left");
    }

    // ------------------------------------------------------ Public Attributes

    /**
     * Return the field Long value, or null if value was empty or a parsing
     * error occurred.
     *
     * @return the field Long value
     */
    public Long getLong() {
        String value = getValue();
        if (value != null && value.length() > 0) {
            try {
                return Long.valueOf(value);

            } catch (NumberFormatException nfe) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * Return the field Integer value, or null if value was empty or a parsing
     * error occurred.
     *
     * @return the field Integer value
     */
    public Integer getInteger() {
        Long value = getLong();
        if (value != null) {
            return Integer.valueOf(value.intValue());
        } else {
            return null;
        }
    }

    /**
     * Return the field Long value, or null if value was empty or a parsing
     * error occurred.
     *
     * @see org.apache.click.control.Field#getValueObject()
     *
     * @return the Long object representation of the Field value
     */
    @Override
    public Object getValueObject() {
        return getLong();
    }

    /**
     * Set the long value of the field using the given object.
     *
     * @see org.apache.click.control.Field#setValueObject(Object)
     *
     * @param object the object value to set
     */
    @Override
    public void setValueObject(Object object) {
        if (object != null) {
            value = object.toString();
        }
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Validate the LongField request submission.
     *

     * A field error message is displayed if a validation error occurs.
     * These messages are defined in the resource bundle:
     *

     *

     *
/click-control.properties
     *

     *
field-required-error

     *
number-format-error

     *
number-maxvalue-error

     *
number-minvalue-error

     *

     *

     *

     *

     */
    @Override
    public void validate() {
        setError(null);

        String value = getValue();

        int length = value.length();
        if (length > 0) {
            try {
                long longValue = Long.parseLong(value);

                if (longValue > maxvalue) {
                    setErrorMessage("number-maxvalue-error", maxvalue);

                } else if (longValue < minvalue) {
                    setErrorMessage("number-minvalue-error", minvalue);
                }

            } catch (NumberFormatException nfe) {
                setError(getMessage("number-format-error", getErrorLabel()));
            }
        } else {
            if (isRequired()) {
                setErrorMessage("field-required-error");
            }
        }
    }
}


text:
Ext.BLANK_IMAGE_URL = 'images/s.gif';

tx = {data:{}, ui: {}};

// work around for broken cross frame Dates in Safari
function fixDate(d){
	return d ? new Date(d.getTime()) : d;
}

function fixDateMember(o, name){
	if(o[name]){
		o[name] = new Date(o[name].getTime());
	}
}


text:
Gets widgets.

```csharp
public Task<HttpResponseMessage?> TryHandleGetWidgetsAsync(HttpRequestMessage httpRequest,
    CancellationToken cancellationToken = default)
```

## See Also

* class [ConformanceApiHttpHandler](../ConformanceApiHttpHandler.md)
* namespace [Facility.ConformanceApi.Http](../../Facility.ConformanceApi.md)

<!-- DO NOT EDIT: generated by xmldocmd for Facility.ConformanceApi.dll -->


text:
package client

const (
	NodeDriverStatusType                             = "nodeDriverStatus"
	NodeDriverStatusFieldAppliedChecksum             = "appliedChecksum"
	NodeDriverStatusFieldAppliedDockerMachineVersion = "appliedDockerMachineVersion"
	NodeDriverStatusFieldAppliedURL                  = "appliedURL"
	NodeDriverStatusFieldConditions                  = "conditions"
)

type NodeDriverStatus struct {
	AppliedChecksum             string      `json:"appliedChecksum,omitempty" yaml:"appliedChecksum,omitempty"`
	AppliedDockerMachineVersion string      `json:"appliedDockerMachineVersion,omitempty" yaml:"appliedDockerMachineVersion,omitempty"`
	AppliedURL                  string      `json:"appliedURL,omitempty" yaml:"appliedURL,omitempty"`
	Conditions                  []Condition `json:"conditions,omitempty" yaml:"conditions,omitempty"`
}


text:
// Copyright (c) Qualcomm Atheros, Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted (subject to
// the limitations in the disclaimer below) provided that the following conditions are met:
//
// · Redistributions of source code must retain the above copyright notice, this list of conditions and the
//   following disclaimer.
// · Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
//   following disclaimer in the documentation and/or other materials provided with the distribution.
// · Neither the name of nor the names of its contributors may be used to endorse or promote products derived
//   from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. THIS SOFTWARE IS
// PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//==============================================================================
// Author(s): ="Atheros"
//==============================================================================

#ifndef __HTC_SERVICES_H__
#define __HTC_SERVICES_H__

/* Current service IDs */

typedef enum
{
    RSVD_SERVICE_GROUP = 0,
    WMI_SERVICE_GROUP = 1,

    HTC_TEST_GROUP = 254,
    HTC_SERVICE_GROUP_LAST = 255
} HTC_SERVICE_GROUP_IDS;

#define MAKE_SERVICE_ID(group, index) (int)(((int)group << 8) | (int)(index))

/* NOTE: service ID of 0x0000 is reserved and should never be used */
#define HTC_CTRL_RSVD_SVC MAKE_SERVICE_ID(RSVD_SERVICE_GROUP, 1)
#define WMI_CONTROL_SVC MAKE_SERVICE_ID(WMI_SERVICE_GROUP, 0)
#define WMI_DATA_BE_SVC MAKE_SERVICE_ID(WMI_SERVICE_GROUP, 1)
#define WMI_DATA_BK_SVC MAKE_SERVICE_ID(WMI_SERVICE_GROUP, 2)
#define WMI_DATA_VI_SVC MAKE_SERVICE_ID(WMI_SERVICE_GROUP, 3)
#define WMI_DATA_VO_SVC MAKE_SERVICE_ID(WMI_SERVICE_GROUP, 4)
#define WMI_MAX_SERVICES 5

/* raw stream service (i.e. flash, tcmd, calibration apps) */
#define HTC_RAW_STREAMS_SVC MAKE_SERVICE_ID(HTC_TEST_GROUP, 0)

#endif /*HTC_SERVICES_H_*/


text:
<?php

class Page
{
    private $id;
    private $parentId;
    private $name;
    private $type;

    function __construct($id, $parentId, $name, $type)
    {
        $this->id = $id;
        $this->parentId = $parentId;
        $this->name = $name;
        $this->type = $type;
    }

    public function getId()
    {
        return $this->id;
    }

    public function getParentId()
    {
        return $this->parentId;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getType()
    {
        return $this->type;
    }
}


text:
import threading
import time

DEVICESDIR = "/sys/bus/w1/devices/"

#class for holding temperature values
class Temperature():
    def __init__(self, rawData):
        self.rawData = rawData
    @property
    def C(self):
        return float(self.rawData) / 1000
    @property
    def F(self):
        return self.C * 9.0 / 5.0 + 23.0

#class for controlling the temperature sensor
class TempSensorController(threading.Thread):
    def __init__(self, sensorId, timeToSleep):
        threading.Thread.__init__(self)

        #persist the file location
        self.tempSensorFile = DEVICESDIR + sensorId + "/w1_slave"

        #persist properties
        self.sensorId = sensorId
        self.timeToSleep = timeToSleep

         #update the temperature
        self.updateTemp()

        #set to not running
        self.running = False

    def run(self):
        #loop until its set to stopped
        self.running = True
        while(self.running):
            #update temperature
            self.updateTemp()
            #sleep
            time.sleep(self.timeToSleep)
        self.running = False

    def stopController(self):
        self.running = False

    def readFile(self):
        sensorFile = open(self.tempSensorFile, "r")
        lines = sensorFile.readlines()
        sensorFile.close()
        return lines

    def updateTemp(self):
        data = self.readFile()
        #the output from the tempsensor looks like this
        #f6 01 4b 46 7f ff 0a 10 eb : crc=eb YES
        #f6 01 4b 46 7f ff 0a 10 eb t=31375
        #has a YES been returned?
        if data[0].strip()[-3:] == "YES":
            #can I find a temperature (t=)
            equals_pos = data[1].find("t=")
            if equals_pos != -1:
                tempData = data[1][equals_pos+2:]
                #update temperature
                self.temperature = Temperature(tempData)
                #update success status
                self.updateSuccess = True
            else:
                self.updateSuccess = False
        else:
            self.updateSuccess = False

if __name__ == "__main__":

    #create temp sensor controller, put your controller Id here
    # look in "/sys/bus/w1/devices/" after running
    #  sudo modprobe w1-gpio
    #  sudo modprobe w1-therm
    tempcontrol = TempSensorController("28-00000xxxxxxx", 1)

    try:
        print("Starting temp sensor controller")
        #start up temp sensor controller
        tempcontrol.start()
        #loop forever, wait for Ctrl C
        while(True):
            print tempcontrol.temperature.C
            print tempcontrol.temperature.F
            time.sleep(5)
    #Ctrl C
    except KeyboardInterrupt:
        print "Cancelled"

    #Error
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise

    #if it finishes or Ctrl C, shut it down
    finally:
        print "Stopping temp sensor controller"
        #stop the controller
        tempcontrol.stopController()
        #wait for the tread to finish if it hasn't already
        tempcontrol.join()

    print "Done"


text:
<resources>
    <string name="app_name">Show labels on layer</string>
    <string name="congressional_districts_url">https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_116th_Congressional_Districts/FeatureServer/0</string>
    <string name="error_message">Error loading feature layer: </string>
</resources>


text: gcc -o displayd displayd.c


text:
public class J1_5_AmbiguousName_LocalVsField_SameLine {
	public int a = 123;

	public J1_5_AmbiguousName_LocalVsField_SameLine() {}

	public int method() {
		int b = a; int a = 0;
		return b;
	}

	public static int test() {
		J1_5_AmbiguousName_LocalVsField_SameLine j = new J1_5_AmbiguousName_LocalVsField_SameLine();
		return j.a;
	}
}


text:
using System;

namespace NAudio.Wave.SampleProviders
{
    /// <summary>
    /// Converts an IWaveProvider containing 8 bit PCM to an
    /// ISampleProvider
    /// </summary>
    public class Pcm8BitToSampleProvider : SampleProviderConverterBase
    {
        /// <summary>
        /// Initialises a new instance of Pcm8BitToSampleProvider
        /// </summary>
        /// <param name="source">Source wave provider</param>
        public Pcm8BitToSampleProvider(IWaveProvider source) :
            base(source)
        {
        }

        /// <summary>
        /// Reads samples from this sample provider
        /// </summary>
        /// <param name="buffer">Sample buffer</param>
        /// <param name="offset">Offset into sample buffer</param>
        /// <param name="count">Number of samples to read</param>
        /// <returns>Number of samples read</returns>
        public override int Read(float[] buffer, int offset, int count)
        {
            int sourceBytesRequired = count;
            EnsureSourceBuffer(sourceBytesRequired);
            int bytesRead = source.Read(sourceBuffer, 0, sourceBytesRequired);
            int outIndex = offset;
            for (int n = 0; n < bytesRead; n++)
            {
                buffer[outIndex++] = sourceBuffer[n] / 128f - 1.0f;
            }
            return bytesRead;
        }
    }
}


text:
package corbaapp;

import java.io.*;

/**ClientHandler performs all functions for the client application.*/
public class ClientHandler {
  /**createStudent takes arguments from the command line and the remote server reference
  *createStudent creates a Student object and sets data according to command line arguments
  *createStudent passes the Student object to the remote server for storage
  */
  public void createStudent (String[] args, Registration regClient) {
    try {
      Student s = new Student();
      s.studentID = args[1];
      s.name = args[2];
      s.major = args[3];
      if (regClient.createStudent(s)) {
          System.out.println("new Student created\n");
      }
      else {
        System.out.println("Error trying to create new Student\n");
        System.exit(1);
      }
    }
    catch (Exception e) {
      System.out.print("Error: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    }
  }
  /**createCourse functions just as createStudent only with Course objects
  */
  public void createCourse (String[] args, Registration regClient) {
    try {
      Course c = new Course();
      c.courseID = args[1];
      c.description = args[2];
      c.instructor = args[3];
      c.meetingTime = args[4];
      c.location = args[5];
      if (regClient.createCourse(c)) {
        System.out.println("new Course created\n");
      }
      else {
        System.out.println("Error trying to create new Course\n");
        System.exit(1);
      }
    }
    catch (Exception e) {
      System.out.print("Error: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    }
  }
  /**register takes arguments from command line and remote server reference
  *register calls register method on remote server passing arguments
  */
  public void register (String[] args, Registration regClient) {
    try {
      if (regClient.register(args[1], args[2])) {
        System.out.println("Student registered successfully\n");
      }
      else {
        System.out.println("Error trying to create new Course\n");
        System.exit(1);
      }
    }
    catch (Exception e) {
      System.out.print("Error: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    }
  }
  /**printStudentReport prints a report of Student ID and courses, including course description, instructor, meeting time, and location
  */
  public void printStudentReport (String[] args, Registration regClient) {
    try {
      Course[] courseList = regClient.getCourses(args[1]);
      System.out.print("\nStudent Registration Report\n");
      System.out.print(args[1]);
      System.out.print("\nCourses for Spring 2000\n\n");
      System.out.print("Course ID  Description  Instructor  MeetingTime/Location\n");
      System.out.print("_________  ___________  __________  ____________________\n");
      String line = new String();
      for (int i = 0; i < (courseList.length + 1); i++) {
        line = courseList[i].courseID + "  " + courseList[i].description + "  " + courseList[i].instructor + "  " + courseList[i].meetingTime + "/" + courseList[i].location + "\n";
        System.out.print(line + "\n");
      }
    }
    catch (Exception e) {
      System.out.print("Error: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    }
  }
  /**printCourseReport prints a Course report for students registered including student ID, name, and major
  */
  public void printCourseReport (String[] args, Registration regClient) {
    try {
      Student[] studentList = regClient.getStudents(args[1]);
      System.out.print("\nCourse Registration Report\n");
      System.out.print(args[1]);
      System.out.print("\n\n");
      System.out.print("Student ID  Student Name  Major\n");
      System.out.print("__________  ____________  _____\n");
      String line = new String();
      for (int i = 0; i < (studentList.length + 1); i++) {
        line = studentList[i].studentID + "  " + studentList[i].name + "  " + studentList[i].major + "\n";
        System.out.print(line + "\n");
      }
    }
    catch (Exception e) {
      System.out.print("Error: " + e.getMessage());
      e.printStackTrace();
      System.exit(1);
    }
  }
}


text:
function dstm = distmatrix(varargin)

% DISTMATRIX constructor method
% --------------------------------------------------
% (1) dstm = distmatrix()
% (2) dstm = distmatrix(no_instances)
% (3) dstm = distmatrix(dstm0)
% (4) dstm = distmatrix(ssm)
% (5) dstm = distmatrix(vsm, dist_type, P1, P2, ...)
% --------------------------------------------------
% Description: constructs a DISTMATRIX instance.
% Input:       (1) An empty default DISTMATRIX is formed.
%              (2) {no_instances} integer. In this case {dstm} would be an
%                  empty DISTMATRIX vector of length {no_instances}.
%              (3) {dstm0} DISTMATRIX instance. In this case {dstm} would
%                  be an identical copy.
%              (4) {ssm} SSMATRIX instance.
%              (5) {vsm} VSMATRIX instance.
%                  <{dist_type}> Can be a reserved keyword string, or a
%                       handle to a distance function, see details in
%                       PDIST. The default is 'euclidean'.
%                  <{P1, P2}> parameters that are required to compute
%                       {dist_type}, see details in PDIST.
% Output:      {dstm} instance(s) of DISTMATRIX.

% © Liran Carmel
% Classification: Constructors
% Last revision date: 12-Jan-2005

% decide on which kind of constructor should be used
if nargin == 0      % case (1)
    ssm = ssmatrix;                 % parent class
    ssm = set(ssm,'type','distance');
    dstm.dist_type = '';
    dstm.no_variables = 0;
    dstm = class(dstm,'distmatrix',ssm);
else
    if isa(varargin{1},'double')    % case (2)
        error(nargchk(1,1,nargin));
        dstm = [];
        for ii = 1:varargin{1}
            dstm = [dstm distmatrix];
            dstm(ii).name = sprintf('Distance Matrix #%d',ii);
        end
    elseif isa(varargin{1},'distmatrix') % case (3)
        error(nargchk(1,1,nargin));
        dstm = varargin{1};
    elseif isa(varargin{1},'ssmatrix')  % case (4)
        error(nargchk(1,1,nargin));
        dstm = distmatrix;
        dstm.ssmatrix = varargin{1};
        dstm = set(dstm,'type','distance');
    elseif isa(varargin{1},'vsmatrix')   % case (5)
        % take complete data only
        vsm = varargin{1};
        error(chkvar(vsm,{},'scalar',{mfilename,inputname(1),1}));
        no_samples = nosamples(vsm);
        no_variables = novariables(vsm);
        samp_to_keep = 1:no_samples;
        for ii = 1:no_variables
            [data idx] = nanless(vsm.variables(ii));    %#ok
            samp_to_keep = intersect(samp_to_keep,idx);
        end
        if length(samp_to_keep) < 2
            error('Less than two samples have all their variables complete');
        end
        samp_to_remove = allbut(samp_to_keep,no_samples);
        if ~isempty(samp_to_remove)
            str = sprintf('some variables are not complete. Taking only');
            str = sprintf('%s %d out of the %d samples',str,...
                length(samp_to_keep),no_samples);
            warning(str)
        end
        data = vsm.variables(:,samp_to_keep)';
        % compute pairwise distances
        dst = pdist(data,varargin{2:end});
        % compute distance matrix
        dist_mat = nan(no_samples);
        dist_mat(samp_to_keep,samp_to_keep) = squareform(dst);
        % find {dist_type}
        dist_type = 'Euclidean';
        if nargin > 1
            if isa(varargin{2},'function_handle')
                dist_type = sprintf('@%s',func2str(varargin{2}));
            else
                dist_type = varargin{2};
            end
        end
        % substitute in DISTMATRIX object
        dstm = distmatrix;
        if ~isempty(vsm.description)
            dstm = set(dstm,'description',...
                sprintf('(data) %s',vsm.description));
        end
        dstm.dist_type = dist_type;
        type = sprintf('%s distance',dist_type);
        dstm = set(dstm,'name',vsm.name,'dist_type',dist_type,...
            'sampleset',vsm.sampleset,'matrix',dist_mat,...
            'no_variables',no_variables,'type',type);
    else
        error('Unrecognized input argument');
    end
end


text:
package com.datastax.killrweather

import java.net.InetSocketAddress

import scala.util.Try
import scala.concurrent.duration._
import org.reactivestreams.Publisher
import akka.http.Http.IncomingConnection
import akka.stream.FlowMaterializer
import akka.stream.scaladsl.{Source, Sink}
import akka.http.model._
import akka.http.model.HttpMethods._
import akka.io.IO
import akka.actor._
import akka.cluster.Cluster
import akka.util.Timeout
import akka.routing.BalancingPool
import kafka.producer.ProducerConfig
import kafka.serializer.StringEncoder
import com.typesafe.config.ConfigFactory
import com.datastax.spark.connector.embedded._
import com.datastax.killrweather.cluster.ClusterAwareNodeGuardian
import com.datastax.spark.connector.embedded.KafkaEvent.KafkaMessageEnvelope

/** Run with: sbt clients/run for automatic data file import to Kafka.
  *
  * To do manual curl import:
  * {{{
  *   curl -v -X POST --header "X-DATA-FEED: ./data/load/sf-2008.csv.gz" http://127.0.0.1:8080/weather/data
  * }}}
  *
  * NOTE does not support running on Windows
  */
object KafkaDataIngestionApp extends App {

  /** Creates the ActorSystem. */
  val system = ActorSystem("KillrWeather", ConfigFactory.parseString("akka.remote.netty.tcp.port = 2551"))

  /* The root supervisor and fault tolerance handler of the data ingestion nodes. */
  val guardian = system.actorOf(Props[HttpNodeGuardian], "node-guardian")

  system.registerOnTermination {
    guardian ! PoisonPill
  }
}

/**
 * Transforms raw weather data .gz files to line data and publishes to the Kafka topic.
 *
 * Simulates real time weather events individually sent to the KillrWeather App for demos.
 * @see [[HttpDataFeedActor]] for sending data files via curl instead.
 *
 * Because we run locally vs against a cluster as a demo app, we keep that file size data small.
 * Using rdd.toLocalIterator will consume as much memory as the largest partition in this RDD,
 * which in this use case is 360 or fewer (if current year before December 31) small Strings.
 *
 * The ingested data is sent to the kafka actor for processing in the stream.
 */
final class HttpNodeGuardian extends ClusterAwareNodeGuardian with ClientHelper {

  /** The [[KafkaPublisherActor]] as a load-balancing pool router
    * which sends messages to idle or less busy routees to handle work. */
  val router = context.actorOf(BalancingPool(5).props(
    Props(new KafkaPublisherActor(KafkaHosts, KafkaBatchSendSize))), "kafka-ingestion-router")

  /** Wait for this node's [[akka.cluster.MemberStatus]] to be
    * [[akka.cluster.ClusterEvent.MemberUp]] before starting work, which means
    * it's membership in the [[Cluster]] node ring has been gossipped, and we
    * can leverage the cluster's adaptive load balancing which will route data
    * to the `KillrWeatherApp` nodes based on most healthy, by their health metrics
    * - cpu, system load average and heap. */
  cluster registerOnMemberUp {

    /* As http data is received, publishes to Kafka. */
    context.actorOf(BalancingPool(10).props(
      Props(new HttpDataFeedActor(router))), "dynamic-data-feed")

    log.info("Starting data ingestion on {}.", cluster.selfAddress)

    /* Handles initial data ingestion in Kafka for running as a demo. */
    for (fs <- initialData; data <- fs.data) {
      log.info("Sending {} to Kafka", data)
      router ! KafkaMessageEnvelope[String, String](KafkaTopic, KafkaKey, data)
    }
  }

  def initialized: Actor.Receive = {
    case WeatherEvent.TaskCompleted => // ignore for now
  }
}

/** The KafkaPublisherActor receives initial data on startup (because this
  * is for a runnable demo) and also receives data in runtime.
  *
  * Publishes [[com.datastax.spark.connector.embedded.KafkaEvent.KafkaMessageEnvelope]]
  * to Kafka on a sender's behalf. Multiple instances are load-balanced in the [[HttpNodeGuardian]].
  */
class KafkaPublisherActor(val producerConfig: ProducerConfig) extends KafkaProducerActor[String,String] {

  def this(hosts: Set[String], batchSize: Int) = this(KafkaProducer.createConfig(
    hosts, batchSize, "async", classOf[StringEncoder].getName))

}

/** An Http server receiving requests containing header or entity based data which it sends to Kafka.
  * by delegating to the [[KafkaPublisherActor]]. */
class HttpDataFeedActor(kafka: ActorRef) extends Actor with ActorLogging with ClientHelper {
  import akka.http.Http
  import Sources._
  import context.dispatcher

  implicit val system = context.system
  implicit val materializer = FlowMaterializer()
  implicit val askTimeout: Timeout = 500.millis

  IO(Http) ! Http.Bind(HttpHost, HttpPort)

  val requestHandler: HttpRequest => HttpResponse = {
    case HttpRequest(POST, Uri.Path("/weather/data"), headers, entity, _) =>
      HttpSource.unapply(headers,entity).collect { case hs: HeaderSource =>
        hs.extract.foreach({ fs: FileSource =>
          log.info(s"Ingesting {} and publishing {} data points to Kafka topic {}.", fs.name, fs.data.size, KafkaTopic)
          kafka ! KafkaMessageEnvelope[String, String](KafkaTopic, KafkaKey, fs.data:_*)
        })
        HttpResponse(200, entity = HttpEntity(MediaTypes.`text/html`, s"POST [${hs.sources.mkString}] successful."))
      }.getOrElse(
        HttpResponse(404, entity = "Unsupported request") )
    case _: HttpRequest =>
        HttpResponse(400, entity = "Unsupported request")
  }

  def receive : Actor.Receive = {
    case Http.ServerBinding(local, stream) => bound(local, stream)
  }

  def bound(localAddress: InetSocketAddress, connection: Publisher[IncomingConnection]): Unit = {
    Source(connection).foreach({
      case Http.IncomingConnection(remoteAddress, requestProducer, responseConsumer) =>
        log.info("Connected to [{}] with [{}] from [{}]", localAddress, connection, remoteAddress)
        Source(requestProducer).map(requestHandler).to(Sink(responseConsumer)).run()
    })
  }
}


text:
package org.apache.phoenix.end2end;

import java.util.Map;

import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.ReadOnlyProps;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;

import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;

@Category(NeedsOwnMiniClusterTest.class)
public class OrderByWithSpillingIT extends BaseOrderByIT {
    @BeforeClass
    public static synchronized void doSetup() throws Exception {
        Map<String, String> props = Maps.newHashMapWithExpectedSize(1);
        // do lot's of spooling!
        props.put(QueryServices.SERVER_SPOOL_THRESHOLD_BYTES_ATTRIB, Integer.toString(1));
        props.put(QueryServices.CLIENT_SPOOL_THRESHOLD_BYTES_ATTRIB, Integer.toString(1));
        setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
    }
}


text:
using DragonSpark.Runtime.Activation;

namespace DragonSpark.Runtime.Execution;

public sealed class ContextDetails : IActivateUsing<string>
{
	public ContextDetails(string name) : this(new Details(name), new ThreadingDetails(), new TaskDetails()) {}

	public ContextDetails(Details details, ThreadingDetails threading, TaskDetails task)
	{
		Details   = details;
		Threading = threading;
		Task      = task;
	}

	public Details Details { get; }
	public ThreadingDetails Threading { get; }
	public TaskDetails Task { get; }
}


text:
Example:

```
 ./terraformer import github --owner=YOUR_ORGANIZATION --resources=repositories --token=YOUR_TOKEN // or GITHUB_TOKEN in env
 ./terraformer import github --owner=YOUR_ORGANIZATION --resources=repositories --filter=repository=id1:id2:id4 --token=YOUR_TOKEN // or GITHUB_TOKEN in env

  ./terraformer import github --owner=YOUR_ORGANIZATION --resources=repositories --base-url=https://your-enterprise-github-url
```

Supports only organizational resources. List of supported resources:

*   `members`
    * `github_membership`
*   `organization_blocks`
    * `github_organization_block`
*   `organization_projects`
    * `github_organization_project`
*   `organization_webhooks`
    * `github_organization_webhook`
*   `repositories`
    * `github_repository`
    * `github_repository_webhook`
    * `github_branch_protection`
    * `github_repository_collaborator`
    * `github_repository_deploy_key`
*   `teams`
    * `github_team`
    * `github_team_membership`
    * `github_team_repository`
*   `user_ssh_keys`
    * `github_user_ssh_key`

Notes:
* Terraformer can't get webhook secrets from the GitHub API. If you use a secret token in any of your webhooks, running `terraform plan` will result in a change being detected:
=> `configuration.#: "1" => "0"` in tfstate only.


text:
import { dispatch, dispatchAsync } from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, PeerTypes } from '../constants/ActorAppConstants';
import history from '../utils/history';
import ActorClient from '../utils/ActorClient';
import PeerUtils from '../utils/PeerUtils';

import ActionCreators from './ActionCreators';
import MessageActionCreators from './MessageActionCreators';
import TypingActionCreators from './TypingActionCreators';
import DialogInfoActionCreators from './DialogInfoActionCreators';
import OnlineActionCreators from './OnlineActionCreators';
import GroupProfileActionCreators from './GroupProfileActionCreators';
import DraftActionCreators from './DraftActionCreators';

import DialogStore from '../stores/DialogStore';
import MessageStore from '../stores/MessageStore';

class DialogActionCreators extends ActionCreators {
  setDialogs(dialogs) {
    dispatch(ActionTypes.DIALOGS_CHANGED, { dialogs });
  }

  selectDialogPeerUser(uid) {
    if (uid === ActorClient.getUid()) {
      console.warn('You can\'t chat with yourself');
    } else {
      history.push(`/im/${PeerUtils.peerToString(ActorClient.getUserPeer(uid))}`);
    }
  }

  selectDialogPeer(peer) {
    const currentPeer = DialogStore.getCurrentPeer();

    if (currentPeer) {
      DraftActionCreators.saveDraft(currentPeer);
      dispatch(ActionTypes.UNBIND_DIALOG_PEER, { peer: currentPeer });
      ActorClient.onConversationClosed(currentPeer);

      this.removeBindings('peer');
    }

    if (!peer) {
      return;
    }

    dispatch(ActionTypes.BIND_DIALOG_PEER, { peer });
    ActorClient.onConversationOpen(peer);
    DraftActionCreators.loadDraft(peer);

    const bindings = [
      ActorClient.bindMessages(peer, MessageActionCreators.setMessages),
      ActorClient.bindTyping(peer, TypingActionCreators.setTyping)
    ];

    switch (peer.type) {
      case PeerTypes.USER:
        bindings.push(
          ActorClient.bindUser(peer.id, DialogInfoActionCreators.setDialogInfo),
          ActorClient.bindUserOnline(peer.id, OnlineActionCreators.setUserOnline)
        );
        break;
      case PeerTypes.GROUP:
        bindings.push(
          ActorClient.bindGroup(peer.id, DialogInfoActionCreators.setDialogInfo),
          ActorClient.bindGroupOnline(peer.id, OnlineActionCreators.setGroupOnline)
        );
        GroupProfileActionCreators.getIntegrationToken(peer.id);
        break;
    }

    this.setBindings('peer', bindings);
  }

  onDialogsEnd() {
    ActorClient.onDialogsEnd();
  }

  onChatEnd(peer) {
    ActorClient.onChatEnd(peer);
  }

  leaveGroup(gid) {
    dispatchAsync(ActorClient.leaveGroup(gid), {
      request: ActionTypes.GROUP_LEAVE,
      success: ActionTypes.GROUP_LEAVE_SUCCESS,
      failure: ActionTypes.GROUP_LEAVE_ERROR
    }, { gid });
  }

  deleteChat(peer) {
    const gid = peer.id;
    const leaveGroup = () => dispatchAsync(ActorClient.leaveGroup(gid), {
      request: ActionTypes.GROUP_LEAVE,
      success: ActionTypes.GROUP_LEAVE_SUCCESS,
      failure: ActionTypes.GROUP_LEAVE_ERROR
    }, { gid });
    const deleteChat = () => dispatchAsync(ActorClient.deleteChat(peer), {
      request: ActionTypes.GROUP_DELETE,
      success: ActionTypes.GROUP_DELETE_SUCCESS,
      failure: ActionTypes.GROUP_DELETE_ERROR
    }, { peer });

    switch (peer.type) {
      case PeerTypes.USER:
        deleteChat();
        break;
      case PeerTypes.GROUP:
        leaveGroup()
          .then(deleteChat);
        break;
      default:
    }
  }

  clearChat(peer) {
    dispatchAsync(ActorClient.clearChat(peer), {
      request: ActionTypes.GROUP_CLEAR,
      success: ActionTypes.GROUP_CLEAR_SUCCESS,
      failure: ActionTypes.GROUP_CLEAR_ERROR
    }, { peer });
  }

  hideChat(peer) {
    dispatchAsync(ActorClient.hideChat(peer), {
      request: ActionTypes.GROUP_HIDE,
      success: ActionTypes.GROUP_HIDE_SUCCESS,
      failure: ActionTypes.GROUP_HIDE_ERROR
    }, { peer });
  }

  blockUser(id) {
    console.debug('Block user %s', id);
  }

  loadMoreMessages(peer) {
    if (MessageStore.isAllRendered()) {
      this.onChatEnd(peer);
    } else {
      dispatch(ActionTypes.MESSAGES_LOAD_MORE);
    }
  }
}

export default new DialogActionCreators();


text:
namespace Incoding.UnitTest.MvcContribGroup
{
    #region << Using >>

    using System.Collections.Generic;
    using Incoding.Extensions;
    using Incoding.MSpecContrib;
    using Incoding.MvcContrib;
    using Machine.Specifications;
    using Newtonsoft.Json.Linq;

    #endregion

    [Subject(typeof(ExecutableBase))]
    public class When_executable_base_conditionals
    {
        #region Establish value

        static ExecutableBase executable;

        static ConditionalEval conditional1FromGroup1;

        static ConditionalEval conditional2FromGroup1;

        static ConditionalEval conditional1FromGroup2;

        static ConditionalEval conditional2FromGroup2;

        static ConditionalEval conditional3FromGroup2;

        static ConditionalEval conditional1FromGroup3;

        static void Compare(object left, object right)
        {
            left.TryGetValue("code").ShouldEqual(right.TryGetValue("code"));
        }

        #endregion

        Establish establish = () =>
                              {
                                  executable = new ExecutableBreak();
                                  conditional1FromGroup1 = new ConditionalEval(Pleasure.Generator.String(), true);
                                  conditional2FromGroup1 = new ConditionalEval(Pleasure.Generator.String(), true);

                                  conditional1FromGroup2 = new ConditionalEval(Pleasure.Generator.String(), false);
                                  conditional2FromGroup2 = new ConditionalEval(Pleasure.Generator.String(), true);
                                  conditional3FromGroup2 = new ConditionalEval(Pleasure.Generator.String(), true);

                                  conditional1FromGroup3 = new ConditionalEval(Pleasure.Generator.String(), false);
                              };

        Because of = () => executable.SetValue("conditionals", new List<ConditionalBase>
                                                               {
                                                                       conditional1FromGroup1,
                                                                       conditional2FromGroup1,
                                                                       conditional1FromGroup2,
                                                                       conditional2FromGroup2,
                                                                       conditional3FromGroup2,
                                                                       conditional1FromGroup3,
                                                               });

        It should_be_group_1 = () => executable
                                             .AsObject()
                                             .Should(dictionary =>
                                                     {
                                                         var dynamicData = (ExecutableBreak)dictionary.data;
                                                         var ands = (List<List<object>>)dynamicData["ands"];

                                                         ands.Count.ShouldEqual(3);

                                                         var group1 = ands[0];
                                                         Compare(group1[0], conditional1FromGroup1.GetData());
                                                         Compare(group1[1], conditional2FromGroup1.GetData());

                                                         var group2 = ands[1];
                                                         Compare(group2[0], conditional1FromGroup2.GetData());
                                                         Compare(group2[1], conditional2FromGroup2.GetData());
                                                         Compare(group2[2], conditional3FromGroup2.GetData());

                                                         var group3 = ands[2];
                                                         Compare(group3[0], conditional1FromGroup3.GetData());
                                                     });
    }
}


text:
function(test)

  timer_start(t1)
  foreach(i RANGE 0 10)
    process_start_info_new(COMMAND echo ads)
    ans(pi)
    process_handle_new(${pi})
  endforeach()
  timer_print_elapsed(t1)

endfunction()


text:
namespace(:member) do |member|

  member.with_options(:controller => 'messages') do |messages|
    messages.resources :messages,
      :collection => { :move => :post,
                       :copy => :post,
                       :mark_as_read => :post,
                       :mark_as_unread => :post,
                       :search => :get
                     },
      :member => { :reply => :get }
    messages.new_message_to 'messages/new/:user_id', :action => "new"
  end

end


text:
package conversion

import (
	"fmt"
	"reflect"
	"strings"
)

// Equalities is a map from type to a function comparing two values of
// that type.
type Equalities map[reflect.Type]reflect.Value

// For convenience, panics on errrors
func EqualitiesOrDie(funcs ...interface{}) Equalities {
	e := Equalities{}
	if err := e.AddFuncs(funcs...); err != nil {
		panic(err)
	}
	return e
}

// AddFuncs is a shortcut for multiple calls to AddFunc.
func (e Equalities) AddFuncs(funcs ...interface{}) error {
	for _, f := range funcs {
		if err := e.AddFunc(f); err != nil {
			return err
		}
	}
	return nil
}

// AddFunc uses func as an equality function: it must take
// two parameters of the same type, and return a boolean.
func (e Equalities) AddFunc(eqFunc interface{}) error {
	fv := reflect.ValueOf(eqFunc)
	ft := fv.Type()
	if ft.Kind() != reflect.Func {
		return fmt.Errorf("expected func, got: %v", ft)
	}
	if ft.NumIn() != 2 {
		return fmt.Errorf("expected three 'in' params, got: %v", ft)
	}
	if ft.NumOut() != 1 {
		return fmt.Errorf("expected one 'out' param, got: %v", ft)
	}
	if ft.In(0) != ft.In(1) {
		return fmt.Errorf("expected arg 1 and 2 to have same type, but got %v", ft)
	}
	var forReturnType bool
	boolType := reflect.TypeOf(forReturnType)
	if ft.Out(0) != boolType {
		return fmt.Errorf("expected bool return, got: %v", ft)
	}
	e[ft.In(0)] = fv
	return nil
}

// Equal return true if a matching equality function thinks a == b;
// if there is no matching equality function, it calls the standard
// go == operator.
func (e Equalities) Equal(a, b interface{}) bool {
	av, bv := reflect.ValueOf(a), reflect.ValueOf(a)
	if !av.IsValid() || !av.IsValid() {
		return av.IsValid() == av.IsValid()
	}
	if av.Type() != av.Type() {
		return false
	}
	if fv, ok := e[av.Type()]; ok {
		return fv.Call([]reflect.Value{av, bv})[0].Bool()
	}
	return av.Interface() == bv.Interface()
}

// Below here is forked from go's reflect/deepequal.go

// During deepValueEqual, must keep track of checks that are
// in progress.  The comparison algorithm assumes that all
// checks in progress are true when it reencounters them.
// Visited comparisons are stored in a map indexed by visit.
type visit struct {
	a1  uintptr
	a2  uintptr
	typ reflect.Type
}

// unexportedTypePanic is thrown when you use this DeepEqual on something that has an
// unexported type. It indicates a programmer error, so should not occur at runtime,
// which is why it's not public and thus impossible to catch.
type unexportedTypePanic []reflect.Type

func (u unexportedTypePanic) Error() string { return u.String() }
func (u unexportedTypePanic) String() string {
	strs := make([]string, len(u))
	for i, t := range u {
		strs[i] = fmt.Sprintf("%v", t)
	}
	return "an unexported field was encountered, nested like this: " + strings.Join(strs, " -> ")
}

func makeUsefulPanic(v reflect.Value) {
	if x := recover(); x != nil {
		if u, ok := x.(unexportedTypePanic); ok {
			u = append(unexportedTypePanic{v.Type()}, u...)
			x = u
		}
		panic(x)
	}
}

// Tests for deep equality using reflected types. The map argument tracks
// comparisons that have already been seen, which allows short circuiting on
// recursive types.
func (e Equalities) deepValueEqual(v1, v2 reflect.Value, visited map[visit]bool, depth int) bool {
	defer makeUsefulPanic(v1)

	if !v1.IsValid() || !v2.IsValid() {
		return v1.IsValid() == v2.IsValid()
	}
	if v1.Type() != v2.Type() {
		return false
	}
	if fv, ok := e[v1.Type()]; ok {
		return fv.Call([]reflect.Value{v1, v2})[0].Bool()
	}

	hard := func(k reflect.Kind) bool {
		switch k {
		case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
			return true
		}
		return false
	}

	if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) {
		addr1 := v1.UnsafeAddr()
		addr2 := v2.UnsafeAddr()
		if addr1 > addr2 {
			// Canonicalize order to reduce number of entries in visited.
			addr1, addr2 = addr2, addr1
		}

		// Short circuit if references are identical ...
		if addr1 == addr2 {
			return true
		}

		// ... or already seen
		typ := v1.Type()
		v := visit{addr1, addr2, typ}
		if visited[v] {
			return true
		}

		// Remember for later.
		visited[v] = true
	}

	switch v1.Kind() {
	case reflect.Array:
		// We don't need to check length here because length is part of
		// an array's type, which has already been filtered for.
		for i := 0; i < v1.Len(); i++ {
			if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Slice:
		if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) {
			return false
		}
		if v1.IsNil() || v1.Len() == 0 {
			return true
		}
		if v1.Len() != v2.Len() {
			return false
		}
		if v1.Pointer() == v2.Pointer() {
			return true
		}
		for i := 0; i < v1.Len(); i++ {
			if !e.deepValueEqual(v1.Index(i), v2.Index(i), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Interface:
		if v1.IsNil() || v2.IsNil() {
			return v1.IsNil() == v2.IsNil()
		}
		return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)
	case reflect.Ptr:
		return e.deepValueEqual(v1.Elem(), v2.Elem(), visited, depth+1)
	case reflect.Struct:
		for i, n := 0, v1.NumField(); i < n; i++ {
			if !e.deepValueEqual(v1.Field(i), v2.Field(i), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Map:
		if (v1.IsNil() || v1.Len() == 0) != (v2.IsNil() || v2.Len() == 0) {
			return false
		}
		if v1.IsNil() || v1.Len() == 0 {
			return true
		}
		if v1.Len() != v2.Len() {
			return false
		}
		if v1.Pointer() == v2.Pointer() {
			return true
		}
		for _, k := range v1.MapKeys() {
			if !e.deepValueEqual(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Func:
		if v1.IsNil() && v2.IsNil() {
			return true
		}
		// Can't do better than this:
		return false
	default:
		// Normal equality suffices
		if !v1.CanInterface() || !v2.CanInterface() {
			panic(unexportedTypePanic{})
		}
		return v1.Interface() == v2.Interface()
	}
}

// DeepEqual is like reflect.DeepEqual, but focused on semantic equality
// instead of memory equality.
//
// It will use e's equality functions if it finds types that match.
//
// An empty slice *is* equal to a nil slice for our purposes; same for maps.
//
// Unexported field members cannot be compared and will cause an imformative panic; you must add an Equality
// function for these types.
func (e Equalities) DeepEqual(a1, a2 interface{}) bool {
	if a1 == nil || a2 == nil {
		return a1 == a2
	}
	v1 := reflect.ValueOf(a1)
	v2 := reflect.ValueOf(a2)
	if v1.Type() != v2.Type() {
		return false
	}
	return e.deepValueEqual(v1, v2, make(map[visit]bool), 0)
}

func (e Equalities) deepValueDerive(v1, v2 reflect.Value, visited map[visit]bool, depth int) bool {
	defer makeUsefulPanic(v1)

	if !v1.IsValid() || !v2.IsValid() {
		return v1.IsValid() == v2.IsValid()
	}
	if v1.Type() != v2.Type() {
		return false
	}
	if fv, ok := e[v1.Type()]; ok {
		return fv.Call([]reflect.Value{v1, v2})[0].Bool()
	}

	hard := func(k reflect.Kind) bool {
		switch k {
		case reflect.Array, reflect.Map, reflect.Slice, reflect.Struct:
			return true
		}
		return false
	}

	if v1.CanAddr() && v2.CanAddr() && hard(v1.Kind()) {
		addr1 := v1.UnsafeAddr()
		addr2 := v2.UnsafeAddr()
		if addr1 > addr2 {
			// Canonicalize order to reduce number of entries in visited.
			addr1, addr2 = addr2, addr1
		}

		// Short circuit if references are identical ...
		if addr1 == addr2 {
			return true
		}

		// ... or already seen
		typ := v1.Type()
		v := visit{addr1, addr2, typ}
		if visited[v] {
			return true
		}

		// Remember for later.
		visited[v] = true
	}

	switch v1.Kind() {
	case reflect.Array:
		// We don't need to check length here because length is part of
		// an array's type, which has already been filtered for.
		for i := 0; i < v1.Len(); i++ {
			if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Slice:
		if v1.IsNil() || v1.Len() == 0 {
			return true
		}
		if v1.Len() > v2.Len() {
			return false
		}
		if v1.Pointer() == v2.Pointer() {
			return true
		}
		for i := 0; i < v1.Len(); i++ {
			if !e.deepValueDerive(v1.Index(i), v2.Index(i), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.String:
		if v1.Len() == 0 {
			return true
		}
		if v1.Len() > v2.Len() {
			return false
		}
		return v1.String() == v2.String()
	case reflect.Interface:
		if v1.IsNil() {
			return true
		}
		return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1)
	case reflect.Ptr:
		if v1.IsNil() {
			return true
		}
		return e.deepValueDerive(v1.Elem(), v2.Elem(), visited, depth+1)
	case reflect.Struct:
		for i, n := 0, v1.NumField(); i < n; i++ {
			if !e.deepValueDerive(v1.Field(i), v2.Field(i), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Map:
		if v1.IsNil() || v1.Len() == 0 {
			return true
		}
		if v1.Len() > v2.Len() {
			return false
		}
		if v1.Pointer() == v2.Pointer() {
			return true
		}
		for _, k := range v1.MapKeys() {
			if !e.deepValueDerive(v1.MapIndex(k), v2.MapIndex(k), visited, depth+1) {
				return false
			}
		}
		return true
	case reflect.Func:
		if v1.IsNil() && v2.IsNil() {
			return true
		}
		// Can't do better than this:
		return false
	default:
		// Normal equality suffices
		if !v1.CanInterface() || !v2.CanInterface() {
			panic(unexportedTypePanic{})
		}
		return v1.Interface() == v2.Interface()
	}
}

// DeepDerivative is similar to DeepEqual except that unset fields in a1 are
// ignored (not compared). This allows us to focus on the fields that matter to
// the semantic comparison.
//
// The unset fields include a nil pointer and an empty string.
func (e Equalities) DeepDerivative(a1, a2 interface{}) bool {
	if a1 == nil {
		return true
	}
	v1 := reflect.ValueOf(a1)
	v2 := reflect.ValueOf(a2)
	if v1.Type() != v2.Type() {
		return false
	}
	return e.deepValueDerive(v1, v2, make(map[visit]bool), 0)
}


text:
using Umbraco.Cms.Core.Models;

namespace Umbraco.Cms.Core.Deploy;

/// <summary>
///     Defines methods that can convert a grid cell value to / from an environment-agnostic string.
/// </summary>
/// <remarks>
///     Grid cell values may contain values such as content identifiers, that would be local
///     to one environment, and need to be converted in order to be deployed.
/// </remarks>
public interface IGridCellValueConnector
{
    /// <summary>
    ///     Gets a value indicating whether the connector supports a specified grid editor view.
    /// </summary>
    /// <param name="view">
    ///     The grid editor view. It needs to be the view instead of the alias as the view is really what
    ///     identifies what kind of connector should be used. Alias can be anything and you can have multiple different aliases
    ///     using the same kind of view.
    /// </param>
    /// <remarks>A value indicating whether the connector supports the grid editor view.</remarks>
    /// <remarks>Note that <paramref name="view" /> can be string.Empty to indicate the "default" connector.</remarks>
    bool IsConnector(string view);

    /// <summary>
    ///     Gets the value to be deployed from the control value as a string.
    /// </summary>
    /// <param name="gridControl">The control containing the value.</param>
    /// <param name="dependencies">The dependencies of the property.</param>
    /// <returns>The grid cell value to be deployed.</returns>
    /// <remarks>Note that </remarks>
    string? GetValue(GridValue.GridControl gridControl, ICollection<ArtifactDependency> dependencies);

    /// <summary>
    ///     Allows you to modify the value of a control being deployed.
    /// </summary>
    /// <param name="gridControl">The control being deployed.</param>
    /// <remarks>
    ///     Follows the pattern of the property value connectors (<see cref="IValueConnector" />). The SetValue method is
    ///     used to modify the value of the <paramref name="gridControl" />.
    /// </remarks>
    void SetValue(GridValue.GridControl gridControl);
}


text:
This gem provides a library for retrieving Canonical's Ubuntu AMI
release list for Amazon EC2.

It also includes a knife plugin to easily retrieve AMIs for launching
instances with Chef.

# Usage

Find an AMI based on criteria:

    ami = Ubuntu.release("lucid").amis.find do |ami|
      ami.arch == "amd64" and
      ami.root_store == "instance-store" and
      ami.region == "us-east-1"
    end

Return certain information about the AMIs:

    Ubuntu.release("lucid").amis.each do |ami|
      puts "#{ami.region} #{ami.name} (#{ami.arch}, #{ami.root_store})"
    end

Use the knife plugin with Knife, from Chef. Pass just a distro name
for the list of available AMIs by type:

    knife ec2 amis ubuntu lucid

The first column will be the available types, and the second is the
associated AMI. Specify the type to return just the AMI.

    knife ec2 amis ubuntu lucid us_east_small

The type is made up of the region, the architecture size (small for 32
bit, large for 64 bit). If the AMI is an EBS root store, that will be indicated.

# License and Authors

Author:: Joshua Timberman (<joshua@housepub.org>)
Author:: Michael Hale (<mike@hales.ws>)

Copyright:: 2011, Joshua Timberman

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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


text:
package main

import (
	. "github.com/vlorc/gioc"
	. "github.com/vlorc/gioc/module"
	. "github.com/vlorc/gioc/module/operation"
)

// config.go
var ConfigModule = NewModuleFactory(
	Export(
		Mapping(map[string]interface{}{
			"id":   1,
			"name": "ioc",
		}),
	),
)

// main.go
func main() {
	NewRootModule(
		Import(ConfigModule),
		Bootstrap(func(param struct {
			id   int
			name string
		}) {
			println("id: ", param.id, " name: ", param.name)
		}),
	)
}


text:
package net.imagej;

import net.imglib2.Dimensions;
import net.imglib2.exception.IncompatibleTypeException;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.util.Util;

/**
 * Base class for {@link ImgFactory} objects of {@link Dataset} implementations.
 *
 * @author Curtis Rueden
 */
public class DatasetImgFactory<T> extends ImgFactory<T> {

	private Dataset dataset;
	private ImgCreator creator;

	public DatasetImgFactory(final T type, final Dataset dataset,
		final ImgCreator creator)
	{
		super(type);
		this.dataset = dataset;
		this.creator = creator;
	}

	@Override
	public Img<T> create(final long... dimensions) {
		return creator.create(dataset, dimensions, type());
	}

	@Override
	public Img<T> create(final Dimensions dimensions) {
		final long[] size = new long[dimensions.numDimensions()];
		dimensions.dimensions(size);
		return create(size);
	}

	@Override
	public Img<T> create(final int[] dimensions) {
		return create(Util.int2long(dimensions));
	}

	@Override
	public <S> DatasetImgFactory<S> imgFactory(final S type)
		throws IncompatibleTypeException
	{
		return new DatasetImgFactory<>(type, dataset, creator);
	}

	@Deprecated
	@Override
	public Img<T> create(final long[] dim, final T type) {
		return creator.create(dataset, dim, type);
	}

	interface ImgCreator {
		<T> Img<T> create(Dataset dataset, long[] dims, T type);
	}
}


text:
interface Observer {

    onChange(type: string, data: any): void;
}

class EventEmitter {

    private _list: Observer[] = [];
    constructor() {
    }
    add(o: Observer) {
        this._list.push(o);
    }
    remove(o: Observer) {
        var index = this._list.indexOf(o);
        this._list.splice(index);
    }

    notify(type: string, data: any) {
        for (var i = 0; i < this._list.length; i++) {
            var observer = this._list[i];
            observer.onChange(type, data);
        }
    }
}

class TaskService extends EventEmitter {

    private _tasks: Task[];

    constructor() {
        super();

    }

    public addTask(task:Task){
        this._tasks.push(task);
    }

    public finishTask(task:Task) {
       // task.finish();
        this.notify("finish", task);
    }

}

class TaskPanel implements Observer {

    onChange(type: string, task: Task): void {
        alert(type+task.name);
    }
}

class Task {

    id: number;
    name: String;
}

function run() {
    var task = new Task();
    var taskservice = new TaskService();
    task.id = 1;
    task.name = "welcome";
    taskservice.addTask(task);
    var panel = new TaskPanel();
    taskservice.add(panel);
  //  alert('Strat');

    egret.setTimeout(() => {

        taskservice.finishTask(task);
    }, this, 3000);

}


text:
import mock

from nirikshak.tests.unit import base
from nirikshak.workers.systemd import active

class SystemdActiveWorkerTest(base.BaseTestCase):

    @staticmethod
    def _get_fake_systemd_active_jaanch():
        jaanch = {
            'type': 'systemd_active',
            'input': {
                'args': {
                    'service': 'ssh.service'
                }
            }
        }

        return jaanch

    @staticmethod
    def _get_fake_systemd_unit():
        units = [['ssh.service', 'test', 'test1', 'active'],
                 ['test.service', 'test', 'test2', 'inactive']]
        return units

    @mock.patch('dbus.Interface')
    @mock.patch('dbus.SystemBus')
    def test_system_active(self, mock_system_bus, mock_interface):
        sys = mock.Mock()
        sys.get_object = mock.Mock(return_value=mock.Mock())
        mock_system_bus.return_value = sys
        mock_interface.return_value = mock.Mock()
        mock_interface.return_value.ListUnits = mock.Mock()
        return_value = self._get_fake_systemd_unit()
        mock_interface.return_value.ListUnits.return_value = return_value
        jaanch = self._get_fake_systemd_active_jaanch()
        result = active.SystemdActiveWorker().work(**jaanch)
        self.assertEqual('active', result['input']['result'])

    @mock.patch('dbus.Interface')
    @mock.patch('dbus.SystemBus')
    def test_system_invalid_active(self, mock_system_bus, mock_interface):
        sys = mock.Mock()
        sys.get_object = mock.Mock(return_value=mock.Mock())
        mock_system_bus.return_value = sys
        mock_interface.return_value = mock.Mock()
        ret_value = self._get_fake_systemd_unit()
        ret_value[0][0] = 'test_service'
        mock_interface.return_value.ListUnits = mock.Mock()
        mock_interface.return_value.ListUnits.return_value = ret_value
        jaanch = self._get_fake_systemd_active_jaanch()
        result = active.SystemdActiveWorker().work(**jaanch)
        self.assertEqual('', result['input']['result'])


text:
#region using

using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using BlogEngine.Core.Web.Extensions;

#endregion

/// <summary>
/// Converts ASCII smilies into real smilies in the comments.
/// </summary>
/// <remarks>
/// Based on the extension by John Knipper - http://www.happytocode.com
/// </remarks>
[Extension("Converts ASCII smilies into real smilies in the comments", "1.3", "BlogEngine.NET")]
public class Smilies
{
    #region Constants and Fields

    /// <summary>
    /// The link string.
    /// </summary>
    private const string Link =
        "<img src=\"{0}admin/editors/tinymce/plugins/emoticons/img/smiley-{1}.gif\" class=\"flag\" alt=\"{2}\" />";

    #endregion

    #region Constructors and Destructors

    /// <summary>
    /// Initializes static members of the <see cref="Smilies"/> class.
    /// </summary>
    static Smilies()
    {
        Comment.Serving += PostCommentServing;
    }

    #endregion

    #region Methods

    /// <summary>
    /// Formats the anchor and inserts the right smiley image.
    /// </summary>
    /// <param name="name">The name of the link.</param>
    /// <param name="alt">The alternate string.</param>
    /// <returns>The link image.</returns>
    private static string Convert(string name, string alt)
    {
        return string.Format(Link, Utils.RelativeWebRoot, name, alt);
    }

    /// <summary>
    /// Handles the CommentServing event of the Post control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="BlogEngine.Core.ServingEventArgs"/> instance containing the event data.</param>
    private static void PostCommentServing(object sender, ServingEventArgs e)
    {
        if (!ExtensionManager.ExtensionEnabled("Smilies"))
            return;

        if (string.IsNullOrEmpty(e.Body))
            return;

        e.Body = e.Body.Replace("(H)", Convert("cool", "Cool"));
        e.Body = e.Body.Replace(":'(", Convert("cry", "Cry"));
        e.Body = e.Body.Replace(":$", Convert("embarassed", "Embarassed"));
        e.Body = e.Body.Replace(":|", Convert("foot-in-mouth", "Foot"));
        e.Body = e.Body.Replace(":(", Convert("frown", "Frown"));
        e.Body = e.Body.Replace("(A)", Convert("innocent", "Innocent"));
        e.Body = e.Body.Replace("(K)", Convert("kiss", "Kiss"));
        e.Body = e.Body.Replace(":D", Convert("laughing", "Laughing"));
        e.Body = e.Body.Replace("($)", Convert("money-mouth", "Money"));
        e.Body = e.Body.Replace(":-#", Convert("sealed", "Sealed"));
        e.Body = e.Body.Replace(":)", Convert("smile", "Smile"));
        e.Body = e.Body.Replace(":-)", Convert("smile", "Smile"));
        e.Body = e.Body.Replace(":-O", Convert("surprised", "Surprised"));
        e.Body = e.Body.Replace(":P", Convert("tongue-out", "Tong"));
        e.Body = e.Body.Replace("*-)", Convert("undecided", "Undecided"));
        e.Body = e.Body.Replace(";-)", Convert("wink", "Wink"));
        e.Body = e.Body.Replace("8o|", Convert("yell", "Yell"));
    }

    #endregion
}


text:
if (typeof define !== 'function') {
  var define = require('amdefine')(module);
}

define(function(require) {
  var Base = require('./base');

  var exports = Base.extend({
    url: '/users/:login',
    idAttribute: 'login'
  });
  exports.id = 'User';

  return exports;
});


text:
@interface SubContextController () <NSXMLParserDelegate>

@property (nonatomic, copy) NSMutableString *mString;
@property (nonatomic, strong) SubContext *subContext;
@property (nonatomic, strong) Mysub *mysub;
@property (nonatomic, strong) NSMutableArray *mArray;

@end

@implementation SubContextController

#pragma mark - 懒加载
-(NSMutableArray *)mArray
{
    if (_mArray == nil) {
        _mArray = [NSMutableArray array];
    }
    return _mArray;
}

-(NSMutableString *)mString
{
    if (_mString == nil) {
        _mString = [NSMutableString string];
    }
    return _mString;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];

    // 取消分隔线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 发送请求
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"id"] = self.task.subid;

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
    //设定返回类型为text/xml
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/xml"];
    //发送请求
    [manager GET:@"http://91dict.com/rr/subcontext_word.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSXMLParser *responseObject) {

        // 设置的代理并开始解析
        responseObject.delegate = self;
        [responseObject parse];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];

}

#pragma mark - xml解析代理
// 开始解析文档
-(void)parserDidStartDocument:(NSXMLParser *)parser
{

}

// 开始解析标签
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
{
    if ([elementName isEqualToString:@"subcontext"]) {
        // 创建整体模型
        self.subContext = [[SubContext alloc] init];
    }else if ([elementName isEqualToString:@"sub"]){
        // 创建内部数组模型并保存
        self.mysub = [[Mysub alloc] init];
        [self.mArray addObject:self.mysub];
    }
}

// 找到字符串
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [self.mString appendString:string];
    //NSLog(@"%@",string);
}

// 找到CDATA块
-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
    NSString *string = [[NSString alloc] initWithData:CDATABlock encoding:NSUTF8StringEncoding];

    [self.mString appendString:string];
}

// 标签结束
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{

    NSString *resultString = [self.mString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

    if ([elementName isEqualToString:@"mysid"]) {
        self.subContext.mysid = resultString.intValue;
    }else if ([elementName isEqualToString:@"subimg"]){
        self.mysub.subimg = resultString;
    }else if ([elementName isEqualToString:@"subaudio"]){
        self.mysub.subaudio = resultString;
    }else if ([elementName isEqualToString:@"suben"]){
        self.mysub.suben = resultString;
    }else if ([elementName isEqualToString:@"subcn"]){
        self.mysub.subcn = resultString;
    }else if ([elementName isEqualToString:@"sudid"]){
        self.mysub.sudid = resultString.intValue;
    }else if ([elementName isEqualToString:@"sid"]){
        self.mysub.sid = resultString.intValue;
    }

    // 清空字符串
    [self.mString setString:@""];
}

// 文档解析完毕
-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    self.subContext.mysub = self.mArray.copy;
    [self.tableView reloadData];
    //Mysub *sub = self.subContext.mysub[0];
    //NSLog(@"%@", sub.subimg);
}

#pragma mark - 数据源和代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"subContextCell";

    // 取得模型
    Mysub *model = self.subContext.mysub[indexPath.row];

    // 创建cell
    SubContextCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[SubContextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.mysid = self.subContext.mysid;
    cell.model = model;

    return cell;
}

// 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}

@end


text:
#include <aws/appflow/model/MarketoConnectorProfileCredentials.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace Appflow
{
namespace Model
{

MarketoConnectorProfileCredentials::MarketoConnectorProfileCredentials() :
    m_clientIdHasBeenSet(false),
    m_clientSecretHasBeenSet(false),
    m_accessTokenHasBeenSet(false),
    m_oAuthRequestHasBeenSet(false)
{
}

MarketoConnectorProfileCredentials::MarketoConnectorProfileCredentials(JsonView jsonValue) :
    m_clientIdHasBeenSet(false),
    m_clientSecretHasBeenSet(false),
    m_accessTokenHasBeenSet(false),
    m_oAuthRequestHasBeenSet(false)
{
  *this = jsonValue;
}

MarketoConnectorProfileCredentials& MarketoConnectorProfileCredentials::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("clientId"))
  {
    m_clientId = jsonValue.GetString("clientId");

    m_clientIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("clientSecret"))
  {
    m_clientSecret = jsonValue.GetString("clientSecret");

    m_clientSecretHasBeenSet = true;
  }

  if(jsonValue.ValueExists("accessToken"))
  {
    m_accessToken = jsonValue.GetString("accessToken");

    m_accessTokenHasBeenSet = true;
  }

  if(jsonValue.ValueExists("oAuthRequest"))
  {
    m_oAuthRequest = jsonValue.GetObject("oAuthRequest");

    m_oAuthRequestHasBeenSet = true;
  }

  return *this;
}

JsonValue MarketoConnectorProfileCredentials::Jsonize() const
{
  JsonValue payload;

  if(m_clientIdHasBeenSet)
  {
   payload.WithString("clientId", m_clientId);

  }

  if(m_clientSecretHasBeenSet)
  {
   payload.WithString("clientSecret", m_clientSecret);

  }

  if(m_accessTokenHasBeenSet)
  {
   payload.WithString("accessToken", m_accessToken);

  }

  if(m_oAuthRequestHasBeenSet)
  {
   payload.WithObject("oAuthRequest", m_oAuthRequest.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace Appflow
} // namespace Aws


text:
'use strict';

const electron = require('electron');
const path = require('path');
const fs = require('fs');
const dlutil = require('dlutil');
const request = require('request');
const unzip = require('unzip');
const co = require('co');

const {app, BrowserWindow, ipcMain, dialog} = electron;

let win;
let initializrUrl = "https://start.spring.io/";

function createWindow() {
    win = new BrowserWindow({ width: 1024, height: 600 });
    win.on('closed', () => { win = null; });
    win.loadURL(`file://${__dirname}/index.html#${initializrUrl}`);
}

function checkExistence(p, attr) {
    return new Promise((fulfill, reject) => {
        fs.access(p, attr, err => fulfill(err));
    });
}

co(function* () {
    if (process.argv.length >= 2) {
        const appDirExistence = yield checkExistence(process.argv[1], fs.constants.F_OK);
        if (appDirExistence === null) {
            // invoked with "electron . <args>"
            if (process.argv.length >= 3) {
                initializrUrl = process.argv[2];
            }
        } else {
            // invoked from application package
            initializrUrl = process.argv[1];
        }
    }

    ipcMain.on('submit', (ev, url, name) => {
        const dir = dialog.showOpenDialog(
            {
                properties: [ "openDirectory", "createDirectory", "promptToCreate" ]
            }
        )[0];
        const target = path.join(dir, name);

        co(function* () {
            const dirExistence = yield checkExistence(dir, fs.constants.W_OK);
            if (dirExistence !== null) {
                yield new Promise((fulfill, reject) => {
                    fs.mkdir(dir, err => {
                        err === null ? fulfill() : reject(err);
                    });
                });
            }

            const targetExistence = yield checkExistence(target, fs.constants.W_OK);
            if (targetExistence === null) {
                const res = yield new Promise((fulfill, reject) => {
                    dialog.showMessageBox(
                        {
                            type: 'question',
                            buttons: [ 'Yes', 'No' ],
                            title: 'Message',
                            message: `'${name}' already exists. Overwrite it?`
                        },
                        (response) => fulfill(response)
                    );
                });

                if (res === 0) {
                    dlutil.rmtree(target);
                } else {
                    ev.sender.send('enable-button');
                    return;
                }
            }

            yield new Promise((fulfill, reject) => {
                request(url)
                    .pipe(unzip.Extract({ path: dir }))
                    .on('close', () => fulfill());
            });

            yield new Promise((fulfill, reject) => {
                dialog.showMessageBox(
                    {
                        type: 'info',
                        buttons: [ 'OK' ],
                        title: 'Message',
                        message: 'Project successfully created at ' + target
                    },
                    () => fulfill()
                );
            });

            win.close();
        });
    });

    app.on('window-all-closed', () => {
        if (process.platform !== 'darwin') {
            app.quit();
        }
    });

    app.on('ready', createWindow);

    app.on('activate', () => {
        if (win === null) {
            createWindow();
        }
    });
});


text:
package org.apache.lucene.benchmark.byTask.utils;

import java.text.NumberFormat;

/**
 * Formatting utilities (for reports).
 */
public class Format {

  private static NumberFormat numFormat [] = {
    NumberFormat.getInstance(),
    NumberFormat.getInstance(),
    NumberFormat.getInstance(),
  };
  private static final String padd = "                                                 ";

  static {
    numFormat[0].setMaximumFractionDigits(0);
    numFormat[0].setMinimumFractionDigits(0);
    numFormat[1].setMaximumFractionDigits(1);
    numFormat[1].setMinimumFractionDigits(1);
    numFormat[2].setMaximumFractionDigits(2);
    numFormat[2].setMinimumFractionDigits(2);
  }

  /**
   * Padd a number from left.
   * @param numFracDigits number of digits in fraction part - must be 0 or 1 or 2.
   * @param f number to be formatted.
   * @param col column name (used for deciding on length).
   * @return formatted string.
   */
  public static String format(int numFracDigits, float f, String col) {
    String res = padd + numFormat[numFracDigits].format(f);
    return res.substring(res.length() - col.length());
  }

  public static String format(int numFracDigits, double f, String col) {
    String res = padd + numFormat[numFracDigits].format(f);
    return res.substring(res.length() - col.length());
  }

  /**
   * Pad a number from right.
   * @param numFracDigits number of digits in fraction part - must be 0 or 1 or 2.
   * @param f number to be formatted.
   * @param col column name (used for deciding on length).
   * @return formatted string.
   */
  public static String formatPaddRight(int numFracDigits, float f, String col) {
    String res = numFormat[numFracDigits].format(f) + padd;
    return res.substring(0, col.length());
  }

  public static String formatPaddRight(int numFracDigits, double f, String col) {
    String res = numFormat[numFracDigits].format(f) + padd;
    return res.substring(0, col.length());
  }

  /**
   * Pad a number from left.
   * @param n number to be formatted.
   * @param col column name (used for deciding on length).
   * @return formatted string.
   */
  public static String format(int n, String col) {
    String res = padd + n;
    return res.substring(res.length() - col.length());
  }

  /**
   * Pad a string from right.
   * @param s string to be formatted.
   * @param col column name (used for deciding on length).
   * @return formatted string.
   */
  public static String format(String s, String col) {
    String s1 = (s + padd);
    return s1.substring(0, Math.min(col.length(), s1.length()));
  }

  /**
   * Pad a string from left.
   * @param s string to be formatted.
   * @param col column name (used for deciding on length).
   * @return formatted string.
   */
  public static String formatPaddLeft(String s, String col) {
    String res = padd + s;
    return res.substring(res.length() - col.length());
  }

  /**
   * Extract simple class name
   * @param cls class whose simple name is required
   * @return simple class name
   */
  public static String simpleName (Class cls) {
    String c = cls.getName();
    String p = cls.getPackage().getName();
    int k = c.lastIndexOf(p+".");
    if (k<0) {
      return c;
    }
    return c.substring(k+1+p.length());
  }

}


text:
/) {}

	BOOL BuildOrigItems (UINT uiMenuResID);

	int GetGutterWidth ();
	BOOL HasGutterLogo() const
	{
		return m_bGutterLogo;
	}

	virtual BOOL IsDrawGutter() const
	{
		return !m_bDisableSideBarInXPMode;
	}

public:
// Overrides
	virtual void SetButtonStyle(int nIndex, UINT nStyle);

	virtual HRESULT get_accRole(VARIANT varChild, VARIANT *pvarRole);
	virtual HRESULT get_accState(VARIANT varChild, VARIANT *pvarState);
	virtual HRESULT get_accParent(IDispatch **ppdispParent);
	virtual HRESULT get_accName(VARIANT varChild, BSTR *pszName);

protected:
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CBCGPPopupMenuBar)
	//}}AFX_VIRTUAL

	virtual BOOL OnSendCommand (const CBCGPToolbarButton* pButton);
	virtual void AdjustLocations ();
	virtual void DrawSeparator (CDC* pDC, const CRect& rect, BOOL bHorz);
	virtual CSize CalcSize (BOOL bVertDock);
	virtual BOOL AllowSelectDisabled () const	{	return CBCGPMenuBar::IsHighlightDisabledItems ();	}
	virtual BOOL AllowShowOnList () const		{	return FALSE;	}
	virtual int FindDropIndex (const CPoint p, CRect& rectDrag) const;
	virtual void DrawDragMarker (CDC* pDC);
	virtual CBCGPToolbarButton* CreateDroppedButton (COleDataObject* pDataObject);
	virtual void OnChangeHot (int iHot);
	virtual BOOL OnKey (UINT nChar);
	virtual BOOL OnSetDefaultButtonText (CBCGPToolbarButton* pButton);
	virtual BOOL EnableContextMenuItems (CBCGPToolbarButton* pButton, CMenu* pPopup);
	virtual void OnFillBackground (CDC* pDC);
	virtual void ShowCommandMessageString (UINT uiCmdId);

	virtual DROPEFFECT OnDragOver(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point);
	virtual INT_PTR OnToolHitTest(CPoint point, TOOLINFO* pTI) const;

	virtual BOOL OnUserToolTip (CBCGPToolbarButton* /*pButton*/, CString& /*strTTText*/) const
	{
		return FALSE;
	}

	virtual CWnd* GetCommandTarget () const;
	void InvokeMenuCommand (UINT uiCmdId, const CBCGPToolbarButton* pMenuItem);

	void SetInCommand (BOOL bInCommand = TRUE);

	virtual BOOL TranslateChar (UINT /*nChar*/)
	{
		return FALSE;
	}

	virtual BOOL IsButtonExtraSizeAvailable () const
	{
		return FALSE;
	}

	virtual void AdjustLayout ();

	virtual void OnCalcSeparatorRect (CBCGPToolbarButton* pButton,
										CRect& rectSeparator,
										BOOL bHorz);
	virtual BOOL AllowAltCustomization () const	{	return FALSE;	}
	virtual void OnAfterButtonDelete ();

	virtual BOOL AllowShowOnControlMenu () const			{	return FALSE;	}
	virtual BOOL AlwaysSaveSelection () const				{	return FALSE;	}

	virtual CSize GetEmptyMenuSize() const;

// Implementation
protected:

	// Generated message map functions
	//{{AFX_MSG(CBCGPPopupMenuBar)
	afx_msg void OnNcPaint();
	afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS FAR* lpncsp);
	afx_msg void OnDestroy();
	afx_msg void OnTimer(UINT_PTR nIDEvent);
	afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
	afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);
	afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
	afx_msg LRESULT OnIdleUpdateCmdUI(WPARAM wParam, LPARAM lParam);
	afx_msg void OnToolbarImageAndText();
	afx_msg void OnToolbarText();
	afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_BCGPPOPUPMENUBAR_H__A6E1AD76_D511_11D1_A64D_00A0C93A70EC__INCLUDED_)