text:
const grammar = require('./grammar/grammar')
const nearley = require('nearley')

module.exports = {
  parse: code => {
    const p = new nearley.Parser(grammar.ParserRules, grammar.ParserStart)

    p.feed(code)

    let already = []
    const results = p.results.filter(tree => {
      // Remove duplicates.
      // I probably shouldn't do this, but does it matter..?

      if (tree === null) return false

      const treeJSON = JSON.stringify(tree)
      if (already.includes(treeJSON)) return false
      else {
        already.push(treeJSON)
        return true
      }
    })

    if (results.length > 1) {
      for (let tree of results) {
        console.error(JSON.stringify(tree)/*require('util').inspect(tree, { colors: true, depth: null })*/, '\n\n_________\n\n')
      }

      console.error(`WARN: ambiguous grammar (${results.length}) ^\n\n`)
    }
    if (results.length === 0) throw new SyntaxError('Empty')

    return results[0]
  }
}


text:
package vn.com.enclaveit.phatbeo.quickaction;

import android.graphics.drawable.Drawable;
import android.graphics.Bitmap;

/**
 * We firstly must create an entity which will represent a particular item of out quick action.
 * It will mainly contain an icon and a title (what is visible for the user). Besides this, the item
 * will have an id (in order to recognize it when we want to listen on click events on it), and
 * two states � sticky or not (i.e. after taping on the item the quick action will disappear or not).
 * It�s basically an object that holds the information for a particular item from the quick action.
 *
 * @author Phat (Phillip) H. VU <vuhongphat@hotmail.com>
 *
 */
public class ActionItem {
	private Drawable icon;
	private Bitmap thumb;
	private String title;
	private boolean selected;
	private Object data;
	private String iconUrl;

	public ActionItem() {
	}

	public ActionItem(Drawable icon) {
		this.icon = icon;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return this.title;
	}

	public void setIcon(Drawable icon) {
		this.icon = icon;
	}

	public Drawable getIcon() {
		return this.icon;
	}

	public void setSelected(boolean selected) {
		this.selected = selected;
	}

	public boolean isSelected() {
		return this.selected;
	}

	public void setThumb(Bitmap thumb) {
		this.thumb = thumb;
	}

	public Bitmap getThumb() {
		return this.thumb;
	}

	public void setData(Object data){
		this.data = data;
	}
	public Object getData(){
		return data;
	}
	public void setIconUrl(String url){
		this.iconUrl = url;
	}
	public String getIconUrl(){
		return iconUrl;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package me.lynnchurch.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.trello.rxlifecycle.components.support.RxFragment;

import javax.inject.Inject;

import me.lynnchurch.base.mvp.BasePresenter;

public abstract class BaseFragment<P extends BasePresenter> extends RxFragment {
    protected BaseActivity mActivity;
    protected View mRootView;
    @Inject
    protected P mPresenter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRootView = initView();
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = (BaseActivity) getActivity();
        ComponentInject();
        initData();
    }

    /**
     * 依赖注入的入口
     */
    protected abstract void ComponentInject();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) mPresenter.onDestroy();//释放资源
        this.mPresenter = null;
        this.mActivity = null;
        this.mRootView = null;
    }

    protected abstract View initView();

    protected abstract void initData();

}


text:
id: bd7158d8c442eddfaeb5bd13
title: Costruisci una Macchina per le citazioni casuali
challengeType: 3
forumTopicId: 301374
dashedName: build-a-random-quote-machine
---

# --description--

**Obiettivo:** Costruisci un'app [CodePen.io](https://codepen.io) funzionalmente simile a questa: <https://codepen.io/freeCodeCamp/full/qRZeGZ>.

Soddisfa le seguenti [user story](https://en.wikipedia.org/wiki/User_story) e fai passare tutti i test. Usa il tuo stile personale.

Puoi utilizzare qualsiasi mix di HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux e jQuery per completare questo progetto. Dovresti usare un framework frontend (come React per esempio) perché questa sezione riguarda l'apprendimento dei framework per il frontend. Ulteriori tecnologie non elencate sopra non sono raccomandate e usarle è a tuo rischio. Stiamo cercando di supportare altri framework per il frontend come Angular e Vue, ma attualmente non sono supportati. Accetteremo e cercheremo di risolvere tutte le segnalazioni di problemi che utilizzano lo stack tecnologico suggerito per questo progetto. Happy coding!

**User Story #1:** Posso vedere un elemento wrapper con un corrispondente `id="quote-box"`.

**User Story #2:** Dentro a `#quote-box` posso vedere un elemento con un corrispondente `id="text"`.

**User Story #3:** Dentro a `#quote-box` posso vedere un elemento con un corrispondente `id="author"`.

**User Story #4:** Dentro a `#quote-box`, posso vedere un elemento cliccabile con un corrispondente `id="new-quote"`.

**User Story #5:** Dentro a `#quote-box`, posso vedere un elemento cliccabile `a` con un corrispondente `id="tweet-quote"`.

**User Story #6:** Al caricamento iniziale, la mia macchina per le citazioni visualizza una citazione casuale nell'elemento con `id="text"`.

**User Story #7:** Al caricamento iniziale, la mia macchina per le citazioni visualizza l'autore della citazione casuale nell'elemento con `id="author"`.

**User Story #8:** Quando si clicca sul pulsante `#new-quote`, la mia macchina per le citazioni dovrebbe andare a prendere una nuova citazione e visualizzarla nell'elemento `#text`.

**User Story #9:** La mia macchina per le citazioni dovrebbe andare a prendere l'autore della nuova citazione quando viene cliccato il pulsante `#new-quote` e visualizzarlo nell'elemento `#author`.

**User Story #10:** Posso twittare la citazione corrente cliccando sull'elemento `a` `#tweet-quote`. Questo elemento `a` dovrebbe includere il percorso `"twitter.com/intent/tweet"` nel suo attributo `href` per twittare la citazione corrente.

**User Story #11:** L'elemento contenitore `#quote-box` dovrebbe essere centrato orizzontalmente. Ti preghiamo di eseguire i test con un livello di zoom del browser al 100% e la pagina massimizzata.

Puoi costruire il tuo progetto usando questo modello CodePen e facendo clic su `Save` per creare il tuo pen. Oppure puoi usare questo link CDN per eseguire i test in qualsiasi ambiente tu voglia: `https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`

Una volta fatto, invia l'URL del tuo progetto di lavoro con tutti i suoi test superati.

**Nota:** Twitter non consente di caricare i link in un iframe. Prova a usare l'attributo `target="_blank"` o `target="_top"` nell'elemento `#tweet-quote` se il tuo tweet non viene caricato. `target="_top"` sostituirà la scheda corrente quindi assicurati che il tuo lavoro sia stato salvato.

# --solutions--

```js
// solution required
```


text:
using System;
using System.Diagnostics;
using System.Linq;
using DediLib.Collections;
using Xunit;

namespace Test.DediLib.Collections
{
    public class TestTimeSeriesLookupList
    {
        [Fact]
        public void Constructor_NullCollection_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => new TimeSeriesLookupList<DateTime>(null, t => t));
        }

        [Fact]
        public void Constructor_NullTimestampFunc_Throws()
        {
            Assert.Throws<ArgumentNullException>(() => new TimeSeriesLookupList<DateTime>(new DateTime[0], null));
        }

        [Fact]
        public void Count()
        {
            var list = new DateTime[1];
            var sut = new TimeSeriesLookupList<DateTime>(list, t => t);
            Assert.Equal(1, sut.Count);
        }

        [Fact]
        public void Indexer_Ordered()
        {
            var value1 = DateTime.UtcNow;
            var value2 = DateTime.UtcNow.AddSeconds(-1);

            var sut = new TimeSeriesLookupList<DateTime>(new[] { value1, value2 }, t => t);
            Assert.Equal(value2, sut[0]);
            Assert.Equal(value1, sut[1]);
        }

        [Fact]
        public void GetEnumerator_Ordered()
        {
            var value1 = DateTime.UtcNow;
            var value2 = DateTime.UtcNow.AddSeconds(-1);

            var sut = new TimeSeriesLookupList<DateTime>(new[] { value1, value2 }, t => t);
            Assert.Equal(new[] { value2, value1 }, sut);
        }

        [Fact]
        public void GetBetween_RangeOutsideLeft_Empty()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 2500).Select(x => timestamp.AddSeconds(x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var result = sut.GetBetween(timestamp.AddSeconds(-2), timestamp.AddSeconds(-1));
            Assert.Empty(result);
        }

        [Fact]
        public void GetBetween_RangeOutsideRight_Empty()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 2500).Select(x => timestamp.AddSeconds(-x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var result = sut.GetBetween(timestamp.AddSeconds(1), timestamp.AddSeconds(2));
            Assert.Empty(result);
        }

        [Fact]
        public void GetBetween_RangeFromInclusive_Included()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 2500).Select(x => timestamp.AddSeconds(-x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var result = sut.GetBetween(timestamp, timestamp.AddMinutes(1));
            Assert.Equal(new[] { timestamp }, result.ToArray());
        }

        [Fact]
        public void GetBetween_RangeToExclusive_Excluded()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 2500).Select(x => timestamp.AddSeconds(x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var result = sut.GetBetween(timestamp.AddMinutes(-1), timestamp);
            Assert.Empty(result);
        }

        [Fact]
        public void GetBetween_RangeInside_Range()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 2500).Select(x => timestamp.AddSeconds(x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var result = sut.GetBetween(timestamp.AddMinutes(1), timestamp.AddMinutes(2));
            Assert.Equal(60, result.Count);
        }

        [Fact]
        public void GetBetween_RangeInsideWithDuplicates_IncludeDuplicates()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 20).Select(x => timestamp.AddMinutes(x)).ToList();
            values.AddRange(Enumerable.Range(0, 20).Select(x => timestamp.AddMinutes(x)));

            var sut = new TimeSeriesLookupList<DateTime>(values.ToList(), t => t);

            var result = sut.GetBetween(timestamp, timestamp.AddSeconds(1));
            Assert.Equal(new[] { timestamp, timestamp }, result.ToArray());
        }

        [Fact]
        public void GetBetween_Dates_Empty()
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, 200).Select(x => timestamp.AddDays(x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var result = sut.GetBetween(timestamp.AddDays(1), timestamp.AddDays(2));
            Assert.Equal(1, result.Count);
        }

        [Trait("Category", "Benchmark")]
        [Theory]
        [InlineData(1000000, 10, Skip = "benchmark")]
        [InlineData(100000, 100, Skip = "benchmark")]
        [InlineData(10000, 1000, Skip = "benchmark")]
        public void Benchmark(int count, int samplesPerWindow)
        {
            var timestamp = DateTime.UtcNow;
            var values = Enumerable.Range(0, count).Select(x => timestamp.AddSeconds(x));

            var sut = new TimeSeriesLookupList<DateTime>(values, t => t);

            var sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var result = sut.GetBetween(timestamp, timestamp.AddSeconds(samplesPerWindow)).Count;
            }
            sw.Stop();

            var opsPerSec = count / (sw.ElapsedMilliseconds + 0.001m) * 1000m;
            Console.WriteLine($"{count} iterations with {samplesPerWindow} samples per window, {sw.Elapsed} ({opsPerSec:N0} ops/sec)");
        }
    }
}


text:
module ActiveMapper
	module Resource
		module PersistentStates
			class NotPersisted < PersistenceState

				def delete
					Deleted.new(resource)
				end

				def commit(options={ })
					response = repository.create(resource, options).dup rescue nil
					set_attributes(response)
					if resource.key.get(resource).nil?
						self
					else
						set_child_keys
						set_repository
						Persisted.new(resource)
					end
				end

				private

				def set_attributes(response)
					(response || { }).each do |key, value|
						resource.properties[key.to_sym].set(resource, value)
					end
				end

				def track(subject)
					original_attributes[subject] = nil
				end

				def original_attributes
					@original_attributes ||= { }
				end

			end
		end
	end
end


text:
Puppet::Type.newtype(:rbenv_gem) do
  @doc = ""

  ensurable do
    newvalue :present do
      provider.create
    end

    newvalue :absent do
      provider.destroy
    end

    defaultto :present
  end

  newparam(:name) do
    isnamevar
  end

  newparam(:gem) do
  end

  newparam(:rbenv_version) do
  end

  newparam(:version) do
    defaultto '>= 0'
  end

  newparam(:rbenv_root) do
  end

  autorequire(:exec) do
    "ruby-install-#{self[:rbenv_version]}"
  end
end


text:
 #include <Aeon/Serialization/World.pb.h>
 #include "AeonEditorWorld.h"

#include "AeonWorldEditorWidget.h"

#include <Aeon/AeonTypes.h>

// -------------------------------------------------------------------------
AeonEditorWorld::AeonEditorWorld():
	worldEditor(nullptr)
{

}

// -------------------------------------------------------------------------
void AeonEditorWorld::OnUpdate(float /*delta*/)
{

}

// -------------------------------------------------------------------------
void AeonEditorWorld::OnSerializeEntities(Aeon::Serialize::World* target)
{
	auto it = entities.begin();
	for(; it != entities.end(); ++it)
	{
		it->second->OnSerialize(target->add_entity_table());
	}
}

// -------------------------------------------------------------------------
void AeonEditorWorld::OnLoadEntity(const Aeon::Serialize::EntityInstance& data)
{
	using namespace Aeon;

	if(!worldEditor) return;

	// We want to examine each entity instance we're going to instance
	Aeon::Entity* ent = Aeon::EntityDatabase::Instance().GetFactory()->CreateEntity(data);

	OnValidateEntity(ent);

	worldEditor->AddEntityToTree(ent);
	entities[ent->GetUniqueID()] = ent;
}

// -------------------------------------------------------------------------
void AeonEditorWorld::SetWorldEditor(AeonWorldEditorWidget* widget)
{
	worldEditor = widget;
}

// -------------------------------------------------------------------------
void AeonEditorWorld::SetParsedVEngineObjects(const QStringList& list)
{
	parsedVEngineObjects = list;
}

// -------------------------------------------------------------------------
void AeonEditorWorld::AddEntity(Aeon::Entity* entity)
{
	entities[entity->GetUniqueID()] = entity;
}

// -------------------------------------------------------------------------
void AeonEditorWorld::RemoveEntity(const Aeon::UUID& uuid)
{
	auto it = entities.find(uuid);

	if(it != entities.end())
	{
		Aeon::Entity* ptr = it->second;
		entities.erase(it);
		Aeon::EntityDatabase::Instance().GetFactory()->DestroyEntity(ptr);
	}
}

// -------------------------------------------------------------------------
Aeon::Entity* AeonEditorWorld::GetEntity(const Aeon::UUID& uuid)
{
	auto it = entities.find(uuid);

	if(it != entities.end())
	{
		return it->second;
	}

	return 0;
}

// -------------------------------------------------------------------------
void AeonEditorWorld::OnValidateEntity(Aeon::Entity* ent)
{
	// TODO: Proper validation code
	/*
	// Check whether the entity is missing any components
	if(ent->GetDescriptor())
	{
		const Aeon::Vector<Aeon::ComponentDescriptor*> components& = ent->GetDescriptor()->GetComponents();
		for(auto it = components.begin(); it != components.end(); ++it)
		{
			if(!ent->HasComponent((*it)->GetUUID()))
			{
				ent->AttachComponentInstance(Aeon::EntityDatabase::Instance().GetComponentRegistry()->CreateComponent((*it)->GetUUID(),ent));
				// Attach attributes
			}
		}
	}
	// Check whether any components were removed

	// Perform checks with attributes

	*/

	// If any VEngine object have been removed, remove them.
	if(ent->CheckAttribute(ATTR("VEngineObjectBehaviour.VEngineObject")) == Aeon::IAttribute::STRING)
	{
		Aeon::String str = ent->GetAttribute<Aeon::String>(ATTR("VEngineObjectBehaviour.VEngineObject"));
		if(!parsedVEngineObjects.contains(QString::fromStdString(str)))
		{
			ent->SetAttribute<Aeon::String>(ATTR("VEngineObjectBehaviour.VEngineObject"), "");
		}
	}
}
// -------------------------------------------------------------------------
void AeonEditorWorld::RefreshCallback()
{
	auto it = entities.begin();

	for(; it != entities.end(); ++it)
	{
		worldEditor->AddEntityToTree(it->second);
	}
}

// -------------------------------------------------------------------------
void AeonEditorWorld::ValidateEntities()
{
	for(auto it = entities.begin(); it != entities.end(); ++it)
	{
		OnValidateEntity(it->second);
	}
}

// -------------------------------------------------------------------------
void AeonEditorWorld::ClearAll()
{
	this->parsedVEngineObjects.clear();

	auto it = entities.begin();
	while(it != entities.end())
	{
		Aeon::Entity* ptr = it->second;
		Aeon::EntityDatabase::Instance().GetFactory()->DestroyEntity(ptr);
		it = entities.erase(it);
	}
}


text:
"""
Tests.
"""
import unittest

from bruges.rockphysics import moduli as m

vp = 2350.
vs = 1125.
rho = 2500
lam = 7478125000.
mu = 3164062500.
youngs = 8551470048.4510355
pr = 0.3513434150638673
pmod = 13806250000.
bulk = 9587500000.

class ModuliTest(unittest.TestCase):
    """
    Tests moduli calculation against spreadsheet
    https://dl.dropboxusercontent.com/u/14965965/Elastic_moduli_formula_checking.xlsx
    """

    def test_vpvs(self):
        self.assertAlmostEqual(m.youngs(vp=vp, vs=vs, rho=rho),
                               youngs, places=-2)
        self.assertAlmostEqual(m.mu(vp=vp, vs=vs, rho=rho), mu, places=-2)
        self.assertAlmostEqual(m.pr(vp=vp, vs=vs, rho=rho), pr)
        self.assertAlmostEqual(m.lam(vp=vp, vs=vs, rho=rho), lam, places=-2)
        self.assertAlmostEqual(m.bulk(vp=vp, vs=vs, rho=rho), bulk, places=-2)
        self.assertAlmostEqual(m.pmod(vp=vp, vs=vs, rho=rho), pmod, places=-2)

    def test_lammu(self):
        self.assertAlmostEqual(m.vp(lam=lam, mu=mu, rho=rho), vp, places=2)
        self.assertAlmostEqual(m.youngs(lam=lam, mu=mu), youngs, places=-2)
        self.assertAlmostEqual(m.pr(lam=lam, mu=mu), pr)
        self.assertAlmostEqual(m.bulk(lam=lam, mu=mu), bulk, places=-2)
        self.assertAlmostEqual(m.pmod(lam=lam, mu=mu), pmod, places=-2)

    def test_youngspr(self):
        self.assertAlmostEqual(m.vp(youngs=youngs, pr=pr, rho=rho),
                               vp, places=2)
        self.assertAlmostEqual(m.mu(youngs=youngs, pr=pr), mu, places=-2)
        self.assertAlmostEqual(m.lam(youngs=youngs, pr=pr), lam, places=-2)
        self.assertAlmostEqual(m.bulk(youngs=youngs, pr=pr), bulk, places=-2)
        self.assertAlmostEqual(m.pmod(youngs=youngs, pr=pr), pmod, places=-2)

    def test_youngslam(self):
        self.assertAlmostEqual(m.mu(youngs=youngs, lam=lam), mu, places=-2)
        self.assertAlmostEqual(m.pr(youngs=youngs, lam=lam), pr, places=-2)
        self.assertAlmostEqual(m.bulk(youngs=youngs, lam=lam), bulk, places=-2)
        self.assertAlmostEqual(m.pmod(youngs=youngs, lam=lam), pmod, places=-2)

    def test_moduli(self):
        mod = {'imp': vp * rho}
        mod['mu'] = mu
        mod['pr'] = pr
        mod['lam'] = lam
        mod['bulk'] = bulk
        mod['pmod'] = pmod
        mod['youngs'] = youngs

        self.assertDictEqual(m.moduli_dict(vp=vp, vs=vs, rho=rho), mod)

if __name__ == '__main__':
    suite = unittest.TestLoader().loadTestsFromTestCase(ModuliTest)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
from msrest.serialization import Model

class VirtualMachineScaleSetVMInstanceView(Model):
    """The instance view of a virtual machine scale set VM.

    Variables are only populated by the server, and will be ignored when
    sending a request.

    :param platform_update_domain: The Update Domain count.
    :type platform_update_domain: int
    :param platform_fault_domain: The Fault Domain count.
    :type platform_fault_domain: int
    :param rdp_thumb_print: The Remote desktop certificate thumbprint.
    :type rdp_thumb_print: str
    :param vm_agent: The VM Agent running on the virtual machine.
    :type vm_agent:
     ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineAgentInstanceView
    :param maintenance_redeploy_status: The Maintenance Operation status on
     the virtual machine.
    :type maintenance_redeploy_status:
     ~azure.mgmt.compute.v2017_12_01.models.MaintenanceRedeployStatus
    :param disks: The disks information.
    :type disks: list[~azure.mgmt.compute.v2017_12_01.models.DiskInstanceView]
    :param extensions: The extensions information.
    :type extensions:
     list[~azure.mgmt.compute.v2017_12_01.models.VirtualMachineExtensionInstanceView]
    :ivar vm_health: The health status for the VM.
    :vartype vm_health:
     ~azure.mgmt.compute.v2017_12_01.models.VirtualMachineHealthStatus
    :param boot_diagnostics: Boot Diagnostics is a debugging feature which
     allows you to view Console Output and Screenshot to diagnose VM status.

 For Linux Virtual Machines, you can easily view the output of
     your console log.

 For both Windows and Linux virtual machines,
     Azure also enables you to see a screenshot of the VM from the hypervisor.
    :type boot_diagnostics:
     ~azure.mgmt.compute.v2017_12_01.models.BootDiagnosticsInstanceView
    :param statuses: The resource status information.
    :type statuses:
     list[~azure.mgmt.compute.v2017_12_01.models.InstanceViewStatus]
    :param placement_group_id: The placement group in which the VM is running.
     If the VM is deallocated it will not have a placementGroupId.
    :type placement_group_id: str
    """

    _validation = {
        'vm_health': {'readonly': True},
    }

    _attribute_map = {
        'platform_update_domain': {'key': 'platformUpdateDomain', 'type': 'int'},
        'platform_fault_domain': {'key': 'platformFaultDomain', 'type': 'int'},
        'rdp_thumb_print': {'key': 'rdpThumbPrint', 'type': 'str'},
        'vm_agent': {'key': 'vmAgent', 'type': 'VirtualMachineAgentInstanceView'},
        'maintenance_redeploy_status': {'key': 'maintenanceRedeployStatus', 'type': 'MaintenanceRedeployStatus'},
        'disks': {'key': 'disks', 'type': '[DiskInstanceView]'},
        'extensions': {'key': 'extensions', 'type': '[VirtualMachineExtensionInstanceView]'},
        'vm_health': {'key': 'vmHealth', 'type': 'VirtualMachineHealthStatus'},
        'boot_diagnostics': {'key': 'bootDiagnostics', 'type': 'BootDiagnosticsInstanceView'},
        'statuses': {'key': 'statuses', 'type': '[InstanceViewStatus]'},
        'placement_group_id': {'key': 'placementGroupId', 'type': 'str'},
    }

    def __init__(self, **kwargs):
        super(VirtualMachineScaleSetVMInstanceView, self).__init__(**kwargs)
        self.platform_update_domain = kwargs.get('platform_update_domain', None)
        self.platform_fault_domain = kwargs.get('platform_fault_domain', None)
        self.rdp_thumb_print = kwargs.get('rdp_thumb_print', None)
        self.vm_agent = kwargs.get('vm_agent', None)
        self.maintenance_redeploy_status = kwargs.get('maintenance_redeploy_status', None)
        self.disks = kwargs.get('disks', None)
        self.extensions = kwargs.get('extensions', None)
        self.vm_health = None
        self.boot_diagnostics = kwargs.get('boot_diagnostics', None)
        self.statuses = kwargs.get('statuses', None)
        self.placement_group_id = kwargs.get('placement_group_id', None)


text:
package org.broadinstitute.sting.gatk.walkers;

import org.broadinstitute.sting.gatk.DownsampleType;

import java.lang.annotation.*;

/**
 * Specifies a method for downsampling the reads passed to a given
 * walker based on the input from that walker.
 *
 * @author hanna
 * @version 0.1
 */
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Downsample {
    DownsampleType by();
    int toCoverage() default -1;
    double toFraction() default -1.0F;
}


text:
import React = require('react');
import { BannerProps } from '../helper-types';

/**
 * Display a DFP Publisher banner
 */
declare class Banner extends React.Component<BannerProps> {}

declare namespace Banner {
    const simulatorId: string;
}

export = Banner;


text:
package org.redhelix.core.computer.system.id;

import org.redhelix.core.util.RedHxAbstractStringProperty;

/**
 *
 *
 *
 * @since RedHelix Version 0.1
 * @author Hank Bruning
 *
 */
public final class RedHxComputerModelNumberImpl extends RedHxAbstractStringProperty
    implements RedHxComputerModelNumber {

  /**
   * @param propName
   */
  public RedHxComputerModelNumberImpl(String propName) {
    super(MAX_CHAR_COUNT_RED_HELIX_DEFINED, propName);
  }
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "SGraphPin.h"
#include "SGraphPinComboBox.h"

class SGraphPinLiveEditVar : public SGraphPin
{
public:
	SLATE_BEGIN_ARGS(SGraphPinLiveEditVar) {}
	SLATE_END_ARGS()

	void Construct(const FArguments& InArgs, UEdGraphPin* InGraphPinObj, UClass *LiveEditObjectClass);

protected:

	/**
	 *	Function to create class specific widget.
	 *
	 *	@return Reference to the newly created widget object
	 */
	virtual TSharedRef<SWidget>	GetDefaultValueWidget() override;

private:

	/**
	 *	Function to get current string associated with the combo box selection
	 *
	 *	@return currently selected string
	 */
	FString OnGetText() const;

	/**
	 *	Function to generate the list of indexes from the enum object
	 *
	 *	@param OutComboBoxIndexes - Int array reference to store the list of indexes
	 */
	void GenerateComboBoxIndexes( TArray< TSharedPtr<int32> >& OutComboBoxIndexes );
	void GenerateComboBoxIndexesRecurse( UStruct *InStruct, FString PropertyPrefix, TArray< TSharedPtr<int32> >& OutComboBoxIndexes );

	/**
	 *	Function to set the newly selected index
	 *
	 * @param NewSelection The newly selected item in the combo box
	 * @param SelectInfo Provides context on how the selection changed
	 */
	void ComboBoxSelectionChanged( TSharedPtr<int32> NewSelection, ESelectInfo::Type SelectInfo );

	/**
	 * Returns the friendly name of the enum at index EnumIndex
	 *
	 * @param EnumIndex	- The index of the enum to return the friendly name for
	 */
	FText OnGetFriendlyName(int32 EnumIndex) const;

	/**
	 * Executes a series of checks to determine if this is a variable that the LiveEditor should really have access to
	 **/
	bool IsPropertyPermitedForLiveEditor( UProperty &Property );

private:
	TSharedPtr<class SPinComboBox>	ComboBox;
	TWeakObjectPtr<class UObject> NodeClass;
	TArray<FString> VariableNameList;
	FString CurrentValue;
};


text:
title: "Administration"
date: 2019-03-13T18:28:09-07:00
draft: false
weight: 4
---

This sections details the "ops" part of Hue, e.g. how to monitor the servers, get a big picture of the architecture, manage users and permissions.


text:
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.

package jodd.db;

import jodd.util.CharUtil;
import jodd.util.StringUtil;
import jodd.util.collection.IntArrayList;

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

/**
 * SQL parameters parser that recognizes named and ordinal parameters.
 */
class DbQueryParser {

	public static final String SQL_SEPARATORS = " \n\r\f\t,()=<>&|+-=/*'^![]#~\\";

	boolean prepared;
	String sql;

	// ---------------------------------------------------------------- ctors

	DbQueryParser() {
	}

	DbQueryParser(String sql) {
		parseSql(sql);
	}

	// ---------------------------------------------------------------- parameters

	private Map<String, IntArrayList> namedParameterLocationMap;

	private void storeNamedParameter(String name, int position) {
		IntArrayList locations = namedParameterLocationMap.get(name);
		if (locations == null) {
			locations = new IntArrayList();
			namedParameterLocationMap.put(name, locations);
		}
		locations.add(position);
	}

	IntArrayList lookupNamedParameterIndices(String name) {
		return namedParameterLocationMap.get(name);
	}

	IntArrayList getNamedParameterIndices(String name) {
		IntArrayList positions = namedParameterLocationMap.get(name);
		if (positions == null) {
			throw new DbSqlException("Named parameter not found: " + name + "\nQuery: " + sql);
		}
		return positions;
	}

	Iterator<String> iterateNamedParameters() {
		return namedParameterLocationMap.keySet().iterator();
	}

	// ---------------------------------------------------------------- batch

	private Map<String, Integer> batchParams;

	private void saveBatchParameter(String name, int size) {
		if (batchParams == null) {
			batchParams = new HashMap<String, Integer>();
		}
		batchParams.put(name, Integer.valueOf(size));
	}

	/**
	 * Returns the size of batch parameter. Returns 0
	 * if parameter does not exist.
	 */
	protected int getBatchParameterSize(String name) {
		if (batchParams == null) {
			return 0;
		}
		Integer size = batchParams.get(name);
		if (size == null) {
			return 0;
		}
		return size.intValue();
	}

	// ---------------------------------------------------------------- parser

	void parseSql(String sqlString) {
		namedParameterLocationMap = new HashMap<String, IntArrayList>();
		int stringLength = sqlString.length();
		StringBuilder pureSql = new StringBuilder(stringLength);
		boolean inQuote = false;
		int index = 0;
		int paramCount = 0;
		while (index < stringLength) {
			char c = sqlString.charAt(index);
			if (inQuote == true) {
				if (c == '\'') {
					inQuote = false;
				}
			} else if (c == '\'') {
				inQuote = true;
			} else if (c == ':') {
				int right = StringUtil.indexOfChars(sqlString, SQL_SEPARATORS, index + 1);
				boolean batch = false;

				if (right < 0) {
					right = stringLength;
				} else {
					if (sqlString.charAt(right) == '!') {
						batch = true;
					}
				}

				String param = sqlString.substring(index + 1, right);

				if (!batch) {
					paramCount++;
					storeNamedParameter(param, paramCount);
					pureSql.append('?');
				}
				else {
					// read batch size
					right++;
					int numStart = right;

					while (right < stringLength) {
						if (!CharUtil.isDigit(sqlString.charAt(right))) {
							break;
						}
						right++;
					}

					String numberValue = sqlString.substring(numStart, right);
					int batchSize;
					try {
						batchSize = Integer.parseInt(numberValue);
					} catch (NumberFormatException nfex) {
						throw new DbSqlException("Batch size is not an integer: " + numberValue, nfex);
					}

					saveBatchParameter(param, batchSize);

					// create batch parameters
					for (int i = 1; i <= batchSize; i++) {
						if (i != 1) {
							pureSql.append(',');
						}
						paramCount++;
						storeNamedParameter(param + '.' + i, paramCount);
						pureSql.append('?');
					}
				}

				index = right;
				continue;
			} else if (c == '?') {		// either an ordinal or positional parameter
				if ((index < stringLength - 1) && (Character.isDigit(sqlString.charAt(index + 1)))) {   // positional parameter
					int right = StringUtil.indexOfChars(sqlString, SQL_SEPARATORS, index + 1);
					if (right < 0) {
						right = stringLength;
					}
					String param = sqlString.substring(index + 1, right);
					try {
						Integer.parseInt(param);
					} catch (NumberFormatException nfex) {
						throw new DbSqlException("Positional parameter is not an integer: " + param, nfex);
					}
					paramCount++;
					storeNamedParameter(param, paramCount);
					pureSql.append('?');
					index = right;
					continue;
				}
				paramCount++;		// ordinal param
			}
			pureSql.append(c);
			index++;
		}
		this.prepared = (paramCount != 0);
		this.sql = pureSql.toString();
	}
}


text:
{{ template "header.html" . }}

Guild: {{ .guild.guildname }}

{{ nl2br .guild.motd }}

{{ if .validationError }}

    Error! {{ .validationError }}

{{ end }}
{{ if .success }}

    Success! {{ .success }}

{{ end }}

            Guild information

            Guild name
            {{ .guild.guildname }}

            Creation
            {{ .guild.created.Result }}

            Owner

                {{ .guild.name }}

        Guild statistics

        Member count
        {{ .guild.members }} ({{ .guild.onl }} Online)

        Highest level
        {{ .guild.top }}

        Lowest level
        {{ .guild.low }}

{{ if .wars.Active }}

            Current wars

        {{ range $index, $war := .wars.Active }}

            {{ $war.name1 }}
            {{ $war.guild1_kills }} - {{ $war.guild2_kills }}
            {{ $war.name2 }}
            {{unixToDate $war.started }}
            View

        {{ end }}

{{ end }}

Members

Invitations

        {{ if .owner }}

Motd

Ranks

Invite

Wars

Leadership

Logo

        {{ end }}
        {{ if not .owner }}
            {{ if .myGuildCharacters }}

Leave guild

            {{ end }}
        {{ end }}

        {{ if not .owner }}
            {{ if .myGuildCharacters }}

                    You are about to leave {{ .guild.guildname }} by clicking on the leave button. After you leave a guild you will need to be invited again by the guild leader.

                <form method="post" action="{{ url "subtopic" "community" "guilds" "leave" }}">

                            <select class="form-control" name="character-name">
                                {{ range $index, $element := .myGuildCharacters }}
                                <option>{{ $element.name }}</option>
                                {{ end }}
                            </select>

                                <button type="submit" name="leave" class="btn btn-danger">Leave guild</button>

                    <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
                    <input type="hidden" name="_csrf" value="{{ .csrfToken }}">
                </form>

            {{ end }}
        {{ end }}

                        Name
                        Level
                        Rank
                        {{ if $.owner }}
                        Promote
                        {{ end }}

                {{ if .memberlist }}
                    {{ range $index, $element := .memberlist }}

                                {{ $element.name }}

                            {{ $element.level }}
                            {{ $element.rank }}
                            {{ if $.owner }}

                                {{ if eqNumber $element.ranklevel 1 }}
                                <form method="post" action="{{ url "subtopic" "community" "guilds" "promote" }}">
                                    <input type="hidden" name="guild-name" value="{{ $.guild.guildname }}">
                                    <input type="hidden" name="_csrf" value="{{ $.csrfToken }}">
                                    <input type="hidden" name="character-name" value="{{ $element.name }}">
                                    <button type="submit" class="btn btn-xs btn-success">Promote</button>
                                </form>
                                {{ end }}
                                {{ if eqNumber $element.ranklevel 2 }}
                                <form method="post" action="{{ url "subtopic" "community" "guilds" "demote" }}">
                                <input type="hidden" name="guild-name" value="{{ $.guild.guildname }}">
                                <input type="hidden" name="_csrf" value="{{ $.csrfToken }}">
                                <input type="hidden" name="character-name" value="{{ $element.name }}">
                                <button type="submit" class="btn btn-xs btn-danger">Demote</button>
                                </form>
                                {{ end }}

                            {{ end }}

                    {{ end }}
                {{ else }}

                        There are no members

                {{ end }}

                        Name

                {{ if .invitations }}
                    {{ range $index, $element := .invitations }}

                        {{ $element.name }}
                        {{ if $element.m }}

                            <form action="{{ url "subtopic" "community" "guilds" "invite" "accept" }}" method="POST">
                                <input type="hidden" name="guild-name" value="{{ $.guild.guildname }}">
                                <input type="hidden" name="_csrf" value="{{ $.csrfToken }}">
                                <input type="hidden" name="character-name" value="{{ $element.name }}">
                                <button class="btn btn-success btn-xs">Accept</button>
                            </form>

                            <form action="{{ url "subtopic" "community" "guilds" "invite" "decline" }}" method="POST">
                                <input type="hidden" name="guild-name" value="{{ $.guild.guildname }}">
                                <input type="hidden" name="_csrf" value="{{ $.csrfToken }}">
                                <input type="hidden" name="character-name" value="{{ $element.name }}">
                                <button class="btn btn-danger btn-xs">Decline</button>
                            </form>

                        {{ else }}

                        {{ end }}

                    {{ end }}
                {{ else }}

                    No invitations made

                {{ end }}

        {{ if .owner }}

            <form enctype="multipart/form-data" action="{{ url "subtopic" "community" "guilds" "logo" }}" method="POST">
                <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
                <input type="hidden" name="_csrf" value="{{ .csrfToken }}">

                    Guild logo
                    <input type="file" id="guild-logo" name="guild-logo" class="form-control">

                        The guild logo needs to be a png image. Images are resized to 64x64

                    <button type="submit" class="btn btn-primary">Update logo</button>

            </form>

            <form action="{{ url "subtopic" "community" "guilds" "motd" }}" method="POST">
            <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
            <input type="hidden" name="_csrf" value="{{ .csrfToken }}">

                Guild motd
                <textarea class="form-control" name="guild-motd" id="guild-motd">{{ .guild.motd }}</textarea>

                    The guild message of the day. Can only contain between 0 - 250 characters.

                <button type="submit" class="btn btn-primary">Update</button>

            </form>

            <form action="{{ url "subtopic" "community" "guilds" "rank" }}" method="POST">
                <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
                <input type="hidden" name="_csrf" value="{{ .csrfToken }}">
                {{ range $index, $element := .ranks }}

                        Rank level {{ $element.level }}
                        <input name="rank-{{ $element.level }}" class="form-control" placeholder="Rank level {{ $element.level }}" type="text" value="{{ $element.name }}">

                {{ end }}

                    <button type="submit" class="btn btn-primary">Update</button>

            </form>

            <form action="{{ url "subtopic" "community" "guilds" "invite" }}" method="POST">
                <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
                <input type="hidden" name="_csrf" value="{{ .csrfToken }}">

                    Character name
                    <input name="invite-name" class="form-control" id="invite-name" placeholder="Character name">

                    <button type="submit" class="btn btn-primary">Invite</button>

            </form>

            <form action="{{ url "subtopic" "community" "guilds" "wars" "invite" }}" method="POST">
                <input type="hidden" name="guild1" value="{{ .guild.id }}">
                <input type="hidden" name="_csrf" value="{{ .csrfToken }}">

                        <input type="text" name="invite-guild" class="form-control" placeholder="Guild to invite">

                            <button type="submit" name="invite" value="0" class="btn btn-primary">Send invitation</button>

                {{ if .wars.Pending }}
                {{ $gid := .guild.id }}

                            Pending war invitations

                        {{ range $index, $war := .wars.Pending }}

                                {{ if eqNumber $war.guild1 $gid }}
                                {{ $war.name2 }}
                                {{ else }}
                                {{ $war.name1 }}
                                {{ end }}

                                {{ if eqNumber $war.guild1 $gid }}
                                <button type="submit" name="cancel" value="{{ $war.id }}" class="btn btn-xs btn-danger">Cancel</button>
                                {{ else }}
                                <button type="submit" name="accept" value="{{ $war.id }}" class="btn btn-xs btn-primary">Accept</button>
                                <button type="submit" name="reject" value="{{ $war.id }}" class="btn btn-xs btn-danger">Reject</button>
                                {{ end }}

                        {{ end }}

                {{ else }}

There are no pending war invitations.

                {{ end }}
            </form>
            {{ if .wars.Ended }}

                        Ended wars

                    {{ range $index, $war := .wars.Ended }}

                        {{ $war.name1 }}
                        {{ $war.guild1_kills }} - {{ $war.guild2_kills }}
                        {{ $war.name2 }}
                        {{unixToDate $war.started }}
                        View

                    {{ end }}

            {{ end }}
            {{ if .wars.Canceled }}

                        Canceled wars

                    {{ range $index, $war := .wars.Canceled }}

                        {{ $war.name1 }}
                        {{ $war.guild1_kills }} - {{ $war.guild2_kills }}
                        {{ $war.name2 }}
                        {{unixToDate $war.started }}
                        View

                    {{ end }}

            {{ end }}
            {{ if .wars.Rejected }}

                        Rejected wars

                    {{ range $index, $war := .wars.Rejected }}

                        {{ $war.name1 }}
                        {{ $war.guild1_kills }} - {{ $war.guild2_kills }}
                        {{ $war.name2 }}
                        {{unixToDate $war.started }}
                        View

                    {{ end }}

            {{ end }}

            <form action="{{ url "subtopic" "community" "guilds" "leadership" }}" method="POST">
                <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
                <input type="hidden" name="_csrf" value="{{ .csrfToken }}">

                        You can pass the guild leadership to any other member. Please select who you want to take the lead

                    <select name="leader-name" class="form-control" id="leader-name" placeholder="New guild leader">
                        {{ range $index, $element := .memberlist }}
                            {{ $r := eq $.ownerdata.name $element.name }}
                            {{ if not $r }}
                                <option>{{ $element.name }}</option>
                            {{ end }}
                        {{ end }}
                    </select>

                    <button type="submit" class="btn btn-primary">Pass leadership</button>

            </form>

            <form action="{{ url "subtopic" "community" "guilds" "disband" }}" method="POST">
                <input type="hidden" name="guild-name" value="{{ .guild.guildname }}">
                <input type="hidden" name="_csrf" value="{{ .csrfToken }}">

                        If your guild has no members you can disband it, otherwise if you need to leave the guild pass the leadership and then leave

                    <button type="submit" class="btn btn-danger">Disband guild</button>

            </form>

        {{ end }}

{{ template "footer.html" . }}


text:
using System;
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member

namespace Gibraltar.Server.Client
{
    /// <summary>
    /// Information about the capabilities and status of a server repository
    /// </summary>
    public class HubRepository
    {
        internal HubRepository(DateTimeOffset? expirationDt, Guid? serverRepositoryId, Version protocolVersion, string publicKey,
            NetworkConnectionOptions agentOptions, NetworkConnectionOptions clientOptions)
        {
            ExpirationDt = expirationDt;
            ServerRepositoryId = serverRepositoryId;
            ProtocolVersion = protocolVersion;
            PublicKey = publicKey;
            AgentLiveStreamOptions = agentOptions;
            ClientLiveStreamOptions = clientOptions;
        }

        public DateTimeOffset? ExpirationDt { get; private set; }

        public Guid? ServerRepositoryId { get; private set; }

        public Version ProtocolVersion { get; private set; }

        public string PublicKey { get; private set; }

        public NetworkConnectionOptions AgentLiveStreamOptions { get; private set; }

        public NetworkConnectionOptions ClientLiveStreamOptions { get; private set; }

        /// <summary>
        /// Indicates if the server supports file fragments or just a single stream per session
        /// </summary>
        public bool SupportsFileFragments
        {
            get
            {
                if (ProtocolVersion >= HubConnection.Hub30ProtocolVersion) //we introduced file fragments in 1.2
                    return true;
                return false;
            }
        }

        /// <summary>
        /// Indicates if the server supports the API for log events, etc.
        /// </summary>
        public bool SupportsServerApi
        {
            get
            {
                if (ProtocolVersion >= HubConnection.Hub38ProtocolVersion) //we introduced file fragments in 1.3
                    return true;
                return false;
            }
        }
    }
}


text:
#ifndef GRAPHLAB_MUTEX_HPP
#define GRAPHLAB_MUTEX_HPP

#include <pthread.h>
#include <graphlab/logger/assertions.hpp>

namespace graphlab {

  /**
   * \ingroup util
   *
   * Simple wrapper around pthread's mutex.
   * Before you use, see \ref parallel_object_intricacies.
   */
  class mutex {
  public:
    // mutable not actually needed
    mutable pthread_mutex_t m_mut;
    /// constructs a mutex
    mutex() {
      int error = pthread_mutex_init(&m_mut, NULL);
      ASSERT_TRUE(!error);
    }
    /** Copy constructor which does not copy. Do not use!
        Required for compatibility with some STL implementations (LLVM).
        which use the copy constructor for vector resize,
        rather than the standard constructor.    */
    mutex(const mutex&) {
      int error = pthread_mutex_init(&m_mut, NULL);
      ASSERT_TRUE(!error);
    }

    ~mutex(){
      int error = pthread_mutex_destroy( &m_mut );
      ASSERT_TRUE(!error);
    }

    // not copyable
    void operator=(const mutex& m) { }

    /// Acquires a lock on the mutex
    inline void lock() const {
      int error = pthread_mutex_lock( &m_mut  );
      // if (error) std::cout << "mutex.lock() error: " << error << std::endl;
      ASSERT_TRUE(!error);
    }
    /// Releases a lock on the mutex
    inline void unlock() const {
      int error = pthread_mutex_unlock( &m_mut );
      ASSERT_TRUE(!error);
    }
    /// Non-blocking attempt to acquire a lock on the mutex
    inline bool try_lock() const {
      return pthread_mutex_trylock( &m_mut ) == 0;
    }
    friend class conditional;
  }; // End of Mutex

  /**
   * \ingroup util
   *
   * Simple wrapper around pthread's recursive mutex.
   * Before you use, see \ref parallel_object_intricacies.
   */
  class recursive_mutex {
  public:
    // mutable not actually needed
    mutable pthread_mutex_t m_mut;
    /// constructs a mutex
    recursive_mutex() {
      pthread_mutexattr_t attr;
      int error = pthread_mutexattr_init(&attr);
      ASSERT_TRUE(!error);
      error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
      ASSERT_TRUE(!error);
      error = pthread_mutex_init(&m_mut, &attr);
      ASSERT_TRUE(!error);
      pthread_mutexattr_destroy(&attr);
    }
    /** Copy constructor which does not copy. Do not use!
        Required for compatibility with some STL implementations (LLVM).
        which use the copy constructor for vector resize,
        rather than the standard constructor.    */
    recursive_mutex(const recursive_mutex&) {
      pthread_mutexattr_t attr;
      int error = pthread_mutexattr_init(&attr);
      ASSERT_TRUE(!error);
      error = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
      ASSERT_TRUE(!error);
      error = pthread_mutex_init(&m_mut, &attr);
      ASSERT_TRUE(!error);
      pthread_mutexattr_destroy(&attr);
    }

    ~recursive_mutex(){
      int error = pthread_mutex_destroy( &m_mut );
      ASSERT_TRUE(!error);
    }

    // not copyable
    void operator=(const recursive_mutex& m) { }

    /// Acquires a lock on the mutex
    inline void lock() const {
      int error = pthread_mutex_lock( &m_mut  );
      // if (error) std::cout << "mutex.lock() error: " << error << std::endl;
      ASSERT_TRUE(!error);
    }
    /// Releases a lock on the mutex
    inline void unlock() const {
      int error = pthread_mutex_unlock( &m_mut );
      ASSERT_TRUE(!error);
    }
    /// Non-blocking attempt to acquire a lock on the mutex
    inline bool try_lock() const {
      return pthread_mutex_trylock( &m_mut ) == 0;
    }
    friend class conditional;
  }; // End of Mutex

} // end of graphlab namespace

#endif


text:
<!DOCTYPE html>

The word "PASS" should be seen below, on a straight line, with a somewhat large letter spacing.

P

A

S

S


text:
layout: page
title: About
permalink: /about/
---

This web site is built with [Jekyll](https://jekyllrb.com/),
a static web page build system.

The source code of Jekyll is available
at [github.com / jekyll / jekyll](https://github.com/jekyll/jekyll)

The theme of this web site is Minima,
and the color mode (_skin_) is Dark,
which is available in the latest branch of Jekyll version 3,
not in the Jekyll default version 2.
The source code of Minima is available
at [github.com / jekyll / minima](https://github.com/jekyll/minima)

The URL of this web site is [https://iphys.github.io/](https://iphys.github.io/).

The source of this site is hosted in [github](https://github.com/iphys/iphys.github.io/).
Thus, in the [`_config.yml`](https://github.com/iphys/iphys.github.io/blob/main/docs/_config.yml)
file in the source repository, the `baseurl` directive should be an empty string `""`.

Useful information about GitHub pages and Jekyll

- [Creating a GitHub Pages site with Jekyll](https://docs.github.com/en/pages/setting-up-a-github-pages-site-with-jekyll/creating-a-github-pages-site-with-jekyll)

- [Adding a theme to your GitHub Pages site using Jekyll](https://docs.github.com/en/pages/setting-up-a-github-pages-site-with-jekyll/adding-a-theme-to-your-github-pages-site-using-jekyll)

- [Adding content to your GitHub Pages site using Jekyll](https://docs.github.com/en/pages/setting-up-a-github-pages-site-with-jekyll/adding-content-to-your-github-pages-site-using-jekyll)

- [Step by Step Tutorial](https://jekyllrb.com/docs/step-by-step/01-setup/) at jekyllrb.com.

_Updated: 2022_


text:
'''

Test about monitor trigger on vm disk writing bandwidth in one minute

@author: Songtao,Haochen

'''

import os
import test_stub
import random
import time
import threading
import zstacklib.utils.ssh as ssh
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.operations.monitor_operations as mon_ops

def test():
    global vm
    global trigger
    global media
    global trigger_action

    vm = test_stub.create_vm()
    vm.check()
    vm_ip = vm.get_vm().vmNics[0].ip
    vm_uuid = vm.get_vm().uuid
    vm_username = os.environ.get('Vm_Username')
    vm_password = os.environ.get('Vm_Password')
    vm_port = os.environ.get('Vm_Sshport')

    test_item = "vm.disk.io"
    resource_type = "VmInstanceVO"
    vm_monitor_item = test_stub.get_monitor_item(resource_type)
    if test_item not in vm_monitor_item:
        test_util.test_fail('%s is not available for monitor' % test_item)

    #duration = 60
    duration = 20
    #expression = "vm.disk.io{type=\"bandwidth\", direction=\"write\"} > 300.0"
    expression = "vm.disk.io{type=\"bandwidth\", direction=\"write\"} > 10.0"
    monitor_trigger = mon_ops.create_monitor_trigger(vm_uuid, duration, expression)
    send_email = test_stub.create_email_media()
    media = send_email.uuid
    trigger_action_name = "trigger"+ ''.join(map(lambda xx:(hex(ord(xx))[2:]),os.urandom(8)))
    trigger = monitor_trigger.uuid
    receive_email = os.environ.get('receive_email')
    monitor_trigger_action = mon_ops.create_email_monitor_trigger_action(trigger_action_name, send_email.uuid, trigger.split(), receive_email)
    trigger_action = monitor_trigger_action.uuid

    ssh_cmd = test_stub.ssh_cmd_line(vm_ip, vm_username, vm_password, vm_port)
    rw = 'write'
    t = threading.Thread(target=test_stub.run_disk_load1,args=(ssh_cmd, rw,))
    t.start()
    time.sleep(90)
    test_stub.kill(ssh_cmd)

    status_problem, status_ok = test_stub.query_trigger_in_loop(trigger,50)
    test_util.action_logger('Trigger old status: %s triggered. Trigger new status: %s recovered' % (status_problem, status_ok ))
    if status_problem != 1 or status_ok != 1:
        test_util.test_fail('%s Monitor Test failed, expected Problem or OK status not triggered' % test_item)

    mail_list = test_stub.receive_email()
    keywords = "fired"
    mail_flag = test_stub.check_email(mail_list, keywords, trigger, vm_uuid)
    if mail_flag == 0:
        test_util.test_fail('Failed to Get Target: %s for: %s Trigger Mail' % (vm_uuid, test_item))

    mon_ops.delete_monitor_trigger_action(trigger_action)
    mon_ops.delete_monitor_trigger(trigger)
    mon_ops.delete_email_media(media)
    vm.destroy()

def error_cleanup():
    global trigger
    global media
    global trigger_action
    global vm
    mon_ops.delete_monitor_trigger_action(trigger_action)
    mon_ops.delete_monitor_trigger(trigger)
    mon_ops.delete_email_media(media)
    vm.destroy()


text:
require 'spec_helper'

RSpec.describe Admin::IntegrationsController do
  let(:admin) { create(:admin) }

  before do
    sign_in(admin)
  end

  describe '#edit' do
    Service.available_services_names.each do |integration_name|
      context "#{integration_name}" do
        it 'successfully displays the template' do
          get :edit, params: { id: integration_name }

          expect(response).to have_gitlab_http_status(:ok)
          expect(response).to render_template(:edit)
        end
      end
    end
  end

  describe '#update' do
    let(:integration) { create(:jira_service, :instance) }

    before do
      allow(PropagateIntegrationWorker).to receive(:perform_async)

      put :update, params: { id: integration.class.to_param, overwrite: true, service: { url: url } }
    end

    context 'valid params' do
      let(:url) { 'https://jira.gitlab-example.com' }

      it 'updates the integration' do
        expect(response).to have_gitlab_http_status(:found)
        expect(integration.reload.url).to eq(url)
      end

      it 'calls to PropagateIntegrationWorker' do
        expect(PropagateIntegrationWorker).to have_received(:perform_async).with(integration.id, true)
      end
    end

    context 'invalid params' do
      let(:url) { 'invalid' }

      it 'does not update the integration' do
        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to render_template(:edit)
        expect(integration.reload.url).not_to eq(url)
      end

      it 'does not call to PropagateIntegrationWorker' do
        expect(PropagateIntegrationWorker).not_to have_received(:perform_async)
      end
    end
  end
end


text:
package org.jkiss.dbeaver.debug.core.model;

import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.model.IValue;
import org.eclipse.debug.core.model.IVariable;
import org.jkiss.dbeaver.debug.DBGVariable;

public class DatabaseVariable extends DatabaseDebugElement implements IVariable {

    private final DBGVariable<?> dbgVariable;

    public DatabaseVariable(IDatabaseDebugTarget target, DBGVariable<?> variable) {
        super(target);
        this.dbgVariable = variable;
    }

    @Override
    public void setValue(String expression) throws DebugException {
        // TODO Auto-generated method stub

    }

    @Override
    public void setValue(IValue value) throws DebugException {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean supportsValueModification() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean verifyValue(String expression) throws DebugException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean verifyValue(IValue value) throws DebugException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public IValue getValue() throws DebugException {
        return new DatabaseValue(getDatabaseDebugTarget(), dbgVariable);
    }

    @Override
    public String getName() throws DebugException {
        return dbgVariable.getName();
    }

    @Override
    public String getReferenceTypeName() throws DebugException {
        return dbgVariable.getType().toString();
    }

    @Override
    public boolean hasValueChanged() throws DebugException {
        // TODO Auto-generated method stub
        return false;
    }

}


text:
"""
print_headers.py

Print the lines in a header object to a file or stdout.

Created by Måns Magnusson on 2015-01-22.
Copyright (c) 2015 __MoonsoInc__. All rights reserved.
"""

from __future__ import print_function

def print_headers(head, outfile=None, silent=False):
    """
    Print the vcf headers.

    If a result file is provided headers will be printed here, otherwise
    they are printed to stdout.

    Args:
        head (HeaderParser): A vcf header object
        outfile (FileHandle): A file handle
        silent (Bool): If nothing should be printed.

    """
    for header_line in head.print_header():

        if outfile:
            outfile.write(header_line+'\n')
        else:
            if not silent:
                print(header_line)
    return


text:
package jbricklink;

public class ItemMapping {
    private Item item;
    private Long colorId;
    private String colorName;
    private String elementId;

    public ItemMapping() {

    }

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

    public Long getColorId() {
        return colorId;
    }

    public void setColorId(Long colorId) {
        this.colorId = colorId;
    }

    public String getColorName() {
        return colorName;
    }

    public void setColorName(String colorName) {
        this.colorName = colorName;
    }

    public String getElementId() {
        return elementId;
    }

    public void setElementId(String elementId) {
        this.elementId = elementId;
    }

    @Override
    public String toString() {
        return "ItemMapping{" +
                "item=" + item +
                ", colorId=" + colorId +
                ", colorName='" + colorName + '\'' +
                ", elementId='" + elementId + '\'' +
                '}';
    }
}


text:
<?php

namespace Hawkbit\Tests\Stratigility;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hawkbit\Application;
use Hawkbit\Stratigility\MiddlewarePipeAdapter;
use Zend\Diactoros\ServerRequestFactory;

class MiddlewareAdapterTest extends \PHPUnit_Framework_TestCase
{

    public function testFunctionalPiping()
    {
        $handleRoute = false;
        $handleMiddleware = false;
        $application = new Application();
        $testCase = $this;
        $application->get('/', function ($request, ResponseInterface $response) use(&$handleRoute, $testCase) {
            $testCase->assertInstanceOf(ServerRequestInterface::class, $request);
            $testCase->assertInstanceOf(ResponseInterface::class, $response);
            $response->getBody()->write('Hello World');
            $handleRoute = true;
            return $response;
        });
        $middleware = new MiddlewarePipeAdapter($application);

        $middleware->pipe('/', function ($request, ResponseInterface $response, $next) use(&$handleMiddleware) {
            $this->assertInstanceOf(ServerRequestInterface::class, $request);
            $this->assertInstanceOf(ResponseInterface::class, $response);
            $this->assertTrue(is_callable($next));

            $response->getBody()->write('
');
            /** @var ResponseInterface $response */
            $response = $next($request, $response);
            $response->getBody()->write('
');

            $handleMiddleware = true;

            return $response;
        });

        $response = $middleware(ServerRequestFactory::fromGlobals(), $application->getResponse());

        $this->assertEquals('
Hello World
', $response->getBody()->__toString());
        $this->assertTrue($handleMiddleware);
        $this->assertTrue($handleRoute);

    }

    public function testNotFoundException()
    {
        $application = new Application();
        $application->setConfig($application::KEY_ERROR_CATCH, false);
        $middleware = new MiddlewarePipeAdapter($application);

        $response = $middleware->__invoke(ServerRequestFactory::fromGlobals(), $middleware->getApplication()->getResponse());
        $this->assertEquals(404, $response->getStatusCode());
    }
}


text:
import * as React from 'react';
import { SelectCallback } from 'react-bootstrap';

declare namespace MenuItem {
    export interface MenuItemProps extends React.HTMLProps<MenuItem> {
        active?: boolean | undefined;
        bsClass?: string | undefined;
        disabled?: boolean | undefined;
        divider?: boolean | undefined;
        eventKey?: any;
        header?: boolean | undefined;
        onClick?: React.MouseEventHandler<{}> | undefined;
        onSelect?: SelectCallback | undefined;
        target?: string | undefined;
        title?: string | undefined;
    }
}
declare class MenuItem extends React.Component<MenuItem.MenuItemProps> { }
export = MenuItem;


text:
import debugModule from "debug";
const debug = debugModule("debugger:solidity:selectors");

import { createSelectorTree, createLeaf } from "reselect-tree";
import SourceMapUtils from "@truffle/source-map-utils";

import semver from "semver";

import evm from "lib/evm/selectors";
import trace from "lib/trace/selectors";

function contextRequiresPhantomStackframes(context) {
  debug("context: %O", context);
  return (
    context.compiler !== undefined && //(do NOT just put context.compiler here,
    //we need this to be a boolean, not undefined, because it gets put in the state)
    context.compiler.name === "solc" &&
    semver.satisfies(context.compiler.version, ">=0.5.1", {
      includePrerelease: true
    }) &&
    !context.isConstructor //constructors should not get a phantom stackframe!
  );
}

//function to create selectors that need both a current and next version
function createMultistepSelectors(stepSelector) {
  return {
    /**
     * .instruction
     */
    instruction: createLeaf(
      ["/current/instructionAtProgramCounter", stepSelector.programCounter],
      //HACK: we use solidity.current.instructionAtProgramCounter
      //even if we're looking at solidity.next.
      //This is harmless... so long as the current instruction isn't a context
      //change.  So, don't use solidity.next when it is.

      (map, pc) => map[pc] || {}
    ),

    /**
     * .modifierDepth
     */
    modifierDepth: createLeaf(
      ["./instruction"],
      instruction => instruction.modifierDepth
    ),

    /**
     * .source
     */
    source: createLeaf(
      //HACK: same hack as with instruction (we use current sources).
      //but I don't need to give the same warning twice.
      ["/current/sources", "./instruction"],

      (sources, { file: index }) => (sources ? sources[index] || {} : {})
    ),

    /**
     * HACK... you get the idea
     */
    findOverlappingRange: createLeaf(
      ["./source", "/current/overlapFunctions"],
      ({ index }, functions) => (functions || {})[index]
    ),

    /**
     * .sourceRange
     */
    sourceRange: createLeaf(["./instruction"], SourceMapUtils.getSourceRange),

    /**
     * .pointerAndNode
     */
    pointerAndNode: createLeaf(
      ["./findOverlappingRange", "./sourceRange"],

      (findOverlappingRange, range) =>
        findOverlappingRange
          ? SourceMapUtils.findRange(
              findOverlappingRange,
              range.start,
              range.length
            )
          : null
    ),

    /**
     * .pointer
     */
    pointer: createLeaf(
      ["./pointerAndNode"],

      pointerAndNode => (pointerAndNode ? pointerAndNode.pointer : null)
    ),

    /**
     * .node
     */
    node: createLeaf(
      ["./source", "./pointerAndNode"],

      ({ ast }, pointerAndNode) => (pointerAndNode ? pointerAndNode.node : ast)
    )
  };
}

let solidity = createSelectorTree({
  /**
   * solidity.state
   */
  state: state => state.solidity,

  /**
   * solidity.info
   */
  info: {
    /**
     * solidity.info.sources
     */
    sources: createLeaf(["/state"], state => state.info.sources)
  },

  /**
   * solidity.transaction
   */
  transaction: {
    /**
     * solidity.transaction.bottomStackframeRequiresPhantomFrame
     */
    bottomStackframeRequiresPhantomFrame: createLeaf(
      [evm.transaction.startingContext],
      contextRequiresPhantomStackframes
    )
  },

  /**
   * solidity.current
   */
  current: {
    /**
     * solidity.current.sourceIds
     * like solidity.current.sources, but just has the IDs, not the sources
     */
    sourceIds: createLeaf(
      ["/info/sources", evm.current.context],
      (sources, context) => {
        if (!context) {
          debug("no context");
          return null; //no tx loaded, return null
        }

        const { compilationId, context: contextHash } = context;
        debug("compilationId: %o", compilationId);

        let userSources = [];
        let internalSources = [];

        if (compilationId && sources.byCompilationId[compilationId]) {
          userSources = sources.byCompilationId[compilationId].byIndex;
        }

        if (sources.byContext[contextHash]) {
          internalSources = sources.byContext[contextHash].byIndex;
        }

        //we assign to [] rather than {} because we want the result to be an array
        return Object.assign([], userSources, internalSources);
      }
    ),

    /**
     * solidity.current.sources
     * This takes the place of the old solidity.info.sources,
     * returning only the sources for the current compilation and context.
     */
    sources: createLeaf(
      ["/views/sources", "/current/sourceIds"],
      (allSources, ids) => (ids ? ids.map(id => allSources[id]) : null)
    ),

    /**
     * solidity.current.sourceMap
     */
    sourceMap: createLeaf(
      [evm.current.context],

      context => (context ? context.sourceMap : null) //null when no tx loaded
    ),

    /**
     * solidity.current.humanReadableSourceMap
     */
    humanReadableSourceMap: createLeaf(["./sourceMap"], sourceMap =>
      sourceMap ? SourceMapUtils.getHumanReadableSourceMap(sourceMap) : null
    ),

    /**
     * solidity.current.functionDepthStack
     */
    functionDepthStack: state => state.solidity.proc.functionDepthStack,

    /**
     * solidity.current.nextFrameIsPhantom
     */
    nextFrameIsPhantom: state => state.solidity.proc.nextFrameIsPhantom,

    /**
     * solidity.current.functionDepth
     */
    functionDepth: createLeaf(
      ["./functionDepthStack"],
      stack => stack[stack.length - 1]
    ),

    /**
     * solidity.current.callRequiresPhantomFrame
     */
    callRequiresPhantomFrame: createLeaf(
      [evm.current.context],
      contextRequiresPhantomStackframes
    ),

    /**
     * solidity.current.instructions
     */
    instructions: createLeaf(
      ["./sources", evm.current.context, "./humanReadableSourceMap"],

      (sources, context, sourceMap) => {
        if (!context) {
          return [];
        }

        debug("sources before processing: %O", sources);
        return SourceMapUtils.getProcessedInstructionsForBinary(
          (sources || []).map(source => (source ? source.source : undefined)),
          context.binary,
          sourceMap
        );
      }
    ),

    /**
     * solidity.current.instructionAtProgramCounter
     */
    instructionAtProgramCounter: createLeaf(
      ["./instructions"],

      instructions =>
        Object.assign(
          {},
          ...instructions.map(instruction => ({
            [instruction.pc]: instruction
          }))
        )
    ),

    ...createMultistepSelectors(evm.current.step),

    /**
     * solidity.current.isSourceRangeFinalRaw
     * the old version; doesn't account for internal-source problems
     */
    isSourceRangeFinalRaw: createLeaf(
      [
        "./instructionAtProgramCounter",
        evm.current.step.programCounter,
        evm.next.step.programCounter,
        evm.current.step.isContextChange
      ],

      (map, current, next, changesContext) => {
        if (changesContext || !map[next]) {
          return true;
        }

        current = map[current];
        next = map[next];

        return (
          current.start != next.start ||
          current.length != next.length ||
          current.file != next.file
        );
      }
    ),

    /**
     * solidity.current.isSourceRangeFinal
     * if there's no context change, then don't return final
     * on jumping from a user source to an internal source
     */
    isSourceRangeFinal: createLeaf(
      [
        "./isSourceRangeFinalRaw",
        "./source",
        "/next/source",
        evm.current.step.isContextChange
      ],

      (isFinal, currentSource, nextSource, changesContext) => {
        return (
          changesContext ||
          (isFinal && (currentSource.internal || !nextSource.internal))
        );
      }
    ),

    /*
     * solidity.current.functionsByProgramCounter
     */
    functionsByProgramCounter: createLeaf(
      [
        "./instructions",
        "./sources",
        "./overlapFunctions",
        evm.current.context
      ],
      (instructions, sources, functions, { compilationId }) =>
        //note: we can skip an explicit null check on sources here because
        //if sources is null then instructions = [] so the problematic map
        //never occurs
        SourceMapUtils.getFunctionsByProgramCounter(
          instructions,
          sources.map(({ ast }) => ast),
          functions,
          compilationId
        )
    ),

    /**
     * solidity.current.isMultiline
     */
    isMultiline: createLeaf(
      ["./sourceRange"],

      ({ lines }) => lines.start.line != lines.end.line
    ),

    /**
     * solidity.current.willJump
     */
    willJump: createLeaf([evm.current.step.isJump], isJump => isJump),

    /**
     * solidity.current.jumpDirection
     */
    jumpDirection: createLeaf(["./instruction"], (i = {}) => i.jump || "-"),

    /**
     * solidity.current.willCall
     * note: includes creations, does *not* include instareturns
     */
    willCall: createLeaf(
      [
        evm.current.step.isCall,
        evm.current.step.isCreate,
        evm.current.step.isInstantCallOrCreate
      ],
      (isCall, isCreate, isInstant) => (isCall || isCreate) && !isInstant
    ),

    /**
     * solidity.current.willReturn
     *
     * covers both normal returns & failures
     */
    willReturn: createLeaf(
      [evm.current.step.isHalting],
      isHalting => isHalting
    ),

    /**
     * solidity.current.nextUserStep
     * returns the next trace step after this one which is sourcemapped to
     * a user source (not -1 or an internal source)
     * HACK: this assumes we're not about to change context! don't use this if
     * we are!
     * ALSO, this may return undefined, so be prepared for that
     */
    nextUserStep: createLeaf(
      [
        "./instructionAtProgramCounter",
        "/current/sources",
        trace.steps,
        trace.index
      ],
      (map, sources, steps, index) =>
        steps
          .slice(index + 1)
          .find(
            ({ pc }) =>
              map[pc] &&
              map[pc].file !== -1 &&
              !(sources[map[pc].file] && sources[map[pc].file].internal)
          )
    ),

    /**
     * solidity.current.overlapFunctions
     * like solidity.views.overlapFunctions, but just returns
     * an array appropriate to the current context (like solidity.current.sources)
     */
    overlapFunctions: createLeaf(
      ["/views/overlapFunctions", "/current/sourceIds"],
      (functions, ids) => (ids ? ids.map(id => functions[id]) : null)
    )
  },

  /**
   * solidity.next
   * HACK WARNING: do not use these selectors when the current instruction is a
   * context change! (evm call or evm return)
   */
  next: createMultistepSelectors(evm.next.step),

  /**
   * solidity.views
   */
  views: {
    /**
     * solidity.views.sources
     * just the byId part of solidity.info.sources
     * (effectively flattening them)
     */
    sources: createLeaf(["/info/sources"], sources => sources.byId),

    /**
     * solidity.views.overlapFunctions
     * organized by source ID
     */
    overlapFunctions: createLeaf(["/views/sources"], sources =>
      Object.assign(
        {},
        ...Object.entries(sources).map(([id, { ast }]) => ({
          [id]: SourceMapUtils.makeOverlapFunction(ast)
        }))
      )
    )
  }
});

export default solidity;


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

var chips = {};

['atmega', 'attiny'].forEach(function(dir) {
  var basepath = path.resolve(__dirname, dir);

  fs.readdirSync(basepath).forEach(function(file) {
    if(path.extname(file) === '.js') {
      var chipname = path.basename(file, '.js');
      chips[chipname] = require(path.join(basepath, chipname));
    }
  });
});

module.exports = chips;


text:
\hypertarget{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result}{\section{Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result Class Reference}
\label{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result}\index{Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result@{Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result}}
}

Server error result for api

\subsection*{Properties}
\begin{DoxyCompactItemize}
\item
int \hyperlink{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a6d3879256e50f9c91d0de6ce3e17e127}{status}\hspace{0.3cm}{\ttfamily  \mbox{[}get, set\mbox{]}}
\begin{DoxyCompactList}\small\item\em H\+T\+T\+P Status \end{DoxyCompactList}\item
string \hyperlink{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_ad7d453c085223b5f748011ebad6fe923}{message}\hspace{0.3cm}{\ttfamily  \mbox{[}get, set\mbox{]}}
\begin{DoxyCompactList}\small\item\em Error message \end{DoxyCompactList}\item
string \hyperlink{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a5465e812baf5f4f7376fed6d44343280}{code}\hspace{0.3cm}{\ttfamily  \mbox{[}get, set\mbox{]}}
\begin{DoxyCompactList}\small\item\em Error Code \end{DoxyCompactList}\item
string \hyperlink{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a1ecd1818eb58c4ec8805d827b45dac2a}{more}\hspace{0.3cm}{\ttfamily  \mbox{[}get, set\mbox{]}}
\begin{DoxyCompactList}\small\item\em More something \end{DoxyCompactList}\item
string \hyperlink{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_ab4dde41503b018bc17e2e85718ee57e4}{trace\+Id}\hspace{0.3cm}{\ttfamily  \mbox{[}get, set\mbox{]}}
\begin{DoxyCompactList}\small\item\em Server trace Id \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
Server error result for api

\subsection{Property Documentation}
\hypertarget{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a5465e812baf5f4f7376fed6d44343280}{\index{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}!code@{code}}
\index{code@{code}!Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}}
\subsubsection[{code}]{\setlength{\rightskip}{0pt plus 5cm}string Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result.\+code\hspace{0.3cm}{\ttfamily [get]}, {\ttfamily [set]}}}\label{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a5465e812baf5f4f7376fed6d44343280}

Error Code

\hypertarget{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_ad7d453c085223b5f748011ebad6fe923}{\index{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}!message@{message}}
\index{message@{message}!Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}}
\subsubsection[{message}]{\setlength{\rightskip}{0pt plus 5cm}string Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result.\+message\hspace{0.3cm}{\ttfamily [get]}, {\ttfamily [set]}}}\label{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_ad7d453c085223b5f748011ebad6fe923}

Error message

\hypertarget{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a1ecd1818eb58c4ec8805d827b45dac2a}{\index{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}!more@{more}}
\index{more@{more}!Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}}
\subsubsection[{more}]{\setlength{\rightskip}{0pt plus 5cm}string Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result.\+more\hspace{0.3cm}{\ttfamily [get]}, {\ttfamily [set]}}}\label{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a1ecd1818eb58c4ec8805d827b45dac2a}

More something

\hypertarget{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a6d3879256e50f9c91d0de6ce3e17e127}{\index{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}!status@{status}}
\index{status@{status}!Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}}
\subsubsection[{status}]{\setlength{\rightskip}{0pt plus 5cm}int Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result.\+status\hspace{0.3cm}{\ttfamily [get]}, {\ttfamily [set]}}}\label{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_a6d3879256e50f9c91d0de6ce3e17e127}

H\+T\+T\+P Status

\hypertarget{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_ab4dde41503b018bc17e2e85718ee57e4}{\index{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}!trace\+Id@{trace\+Id}}
\index{trace\+Id@{trace\+Id}!Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result@{Accela\+::\+Windows\+Store\+S\+D\+K\+::\+Accela\+Api\+Error\+Result}}
\subsubsection[{trace\+Id}]{\setlength{\rightskip}{0pt plus 5cm}string Accela.\+Windows\+Store\+S\+D\+K.\+Accela\+Api\+Error\+Result.\+trace\+Id\hspace{0.3cm}{\ttfamily [get]}, {\ttfamily [set]}}}\label{class_accela_1_1_windows_store_s_d_k_1_1_accela_api_error_result_ab4dde41503b018bc17e2e85718ee57e4}

Server trace Id

The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
C\+:/\+Users/eyang/\+Documents/\+Windows-\/\+S\+D\+K-\/\+New/trunk/src/\+Accela\+S\+D\+K/\+Entites/Error\+Result.\+cs\end{DoxyCompactItemize}


text:
class AddImageFingerprintToTech < ActiveRecord::Migration
  def change
    add_column :techs, :image_fingerprint, :string, :null => false, :default => ''
  end
end


text:
class Profile

  attr_reader :age
  attr_writer :age

  def initialize
    @age = 27
    @name = "Kim"
    @occupation = "Cartographer"
  end

  def print_info
    puts
    puts "age: #{@age}"
    puts
    puts "name: #{@name}"
    puts
    puts "occupation: #{@occupation}"
    puts
  end

  # This code is no longer needed
  # def change_my_age=(new_age)
  #   @age = new_age
  # end

  def what_is_name
    @name
  end

  def change_my_name=(new_name)
    @name = new_name
  end

  def what_is_occupation
    @occupation
  end

  def change_my_occupation=(new_occupation)
    @occupation = new_occupation
  end

end

instance_of_profile = Profile.new

puts "--- printing age -----"
sleep 0.8
p instance_of_profile.age

puts "--- printing name ----"
sleep 0.8
p instance_of_profile.what_is_name

puts "--- printing occupation ----"
sleep 0.8
p instance_of_profile.what_is_occupation

puts "--- changing profile information ----"
10.times do
  print "."
  sleep 0.1
end

instance_of_profile.age = 28 # This method has changed! See the difference?
instance_of_profile.change_my_name = "Taylor"
instance_of_profile.change_my_occupation = "Rare Coins Trader"

puts
puts "---- printing all profile info -----"
sleep 0.8
instance_of_profile.print_info

=begin
REFLECT

What changed between the last release and this release?
Age can now be called with a writer method.

What was replaced?
change_my_age was replaced with attr_writer :age

Is this code simpler than the last?
YES!

=end


text:
package seine;

/**
 * Marker interface for PeerSim protocols that implements the Seine functionalities.
 * Used by the aspect SeineProtocolAspect for static cross-cutting.
 *
 * @author Guido Lena Cota
 */

public interface SeineProtocol {}


text:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<MIUI-Theme category="tools" size="4:2">
	<version>1</version>
	<uiVersion>1</uiVersion>
	<title>Musiikki</title>
	<titles>
		<title locale="zh_CN">Music</title>
		<title locale="zh_TW">音樂</title>
		<title locale="cs_CZ">Hudba</title>
		<title locale="sk_SK">Hudba</title>
		<title locale="pl_PL">Muzyka</title>
		<title locale="fr_FR">Musique</title>
		<title locale="hu_HU">Zene</title>
		<title locale="bg_BG">Музика</title>
		<title locale="hr_HR">Glazba</title>
		<title locale="it_IT">Musica</title>
		<title locale="pt_BR">Musica</title>
		<title locale="el_GR">Μουσική</title>
		<title locale="es_ES">Música</title>
		<title locale="fi_FI">Musiikki</title>
		</titles>
</MIUI-Theme>


text:
from flask import Flask, request, current_app, stream_with_context, Response
from argparse import ArgumentParser
from json import dumps as json
from werkzeug.wsgi import wrap_file

import os
import sys
import flask
import filecache
import magic
import re

app = Flask(__name__)
root_path = os.getcwd()

def validate_ranges(ranges, content_length):
    return all([int(r[0]) <= int(r[1]) for r in ranges]) and all([int(x) < content_length for subrange in ranges for x in subrange])

@app.route('/', defaults={'path': ''}, methods=['GET', 'HEAD'])
@app.route('/<path:path>', methods=['GET', 'HEAD'])
def get(path):
    path_components = path.split('/')
    if '.' in path_components or '..' in path_components:
        return flask.make_response("Path must be absolute.", 400)

    fullpath = '%s/%s' % (root_path, path)

    mime = magic.from_file(fullpath, mime=True)
    if mime is None:
        mime = 'application/octet-stream'
    else:
        mime = mime.replace(' [ [', '')

    if os.path.exists(fullpath):
        if (request.args.get('stat') is not None):
            stat = os.stat(fullpath)
            st = {'file' : os.path.basename(fullpath),
                  'path' : '/%s' % path,
                  'access_time' : int(stat.st_atime),
                  'modification_time' : int(stat.st_mtime),
                  'change_time' : int(stat.st_ctime),
                  'mimetype' : mime}
            if not os.path.isdir(fullpath):
                st['size'] = int(stat.st_size)
            res = flask.make_response(json(st))
            res.headers['Content-Type'] = 'application/json; charset=utf-8'
            return res

        if os.path.isdir(fullpath):
            res = flask.make_response(json(os.listdir(fullpath)))
            res.headers['Content-Type'] = 'application/json; charset=utf-8'
            return res
        else:
            stat = os.stat(fullpath)
            f = filecache.open_file(fullpath)
            r = request.headers.get('Range')
            m = re.match('bytes=((\d+-\d+,)*(\d+-\d*))', r) if r is not None else None
            if r is None or m is None:
                f.seek(0)
                def stream_data():
                    while True:
                        d = f.read(8192)
                        if len(d) > 0:
                            yield d
                        else:
                            break
                res = Response(stream_with_context(stream_data()), 200, mimetype=mime, direct_passthrough=True)
                res.headers['Content-Length'] = stat.st_size
            else:
                ranges = [x.split('-') for x in m.group(1).split(',')]
                if validate_ranges(ranges, stat.st_size):
                    content_length = 0
                    for rng in ranges:
                        if rng[1] == '':
                            content_length = content_length + stat.st_size - int(rng[0]) + 1
                        else:
                            content_length = content_length + int(rng[1]) - int(rng[0]) + 1
                    def stream_data():
                        for r in ranges:
                            f.seek(int(r[0]))
                            if r[1] == '':
                                while True:
                                    d = f.read(8192)
                                    if len(d) > 0:
                                        yield d
                                    else:
                                        break
                            else:
                                for s in [min(8192, int(r[1]) - i + 1) for i in range(int(r[0]), int(r[1]), 8192)]:
                                    d = f.read(s)
                                    yield d

                    res = Response(stream_with_context(stream_data()), 206, mimetype=mime, direct_passthrough=True)
                    res.headers['Content-Length'] = content_length
                    res.headers['Content-Range'] = 'bytes %s-%s/%d' % (ranges[0][0], ranges[0][1], stat.st_size)
                else:
                    res = flask.make_response('', 416)
            # res.headers['Accept-Ranges'] = 'bytes'
            return res
    else:
        return flask.make_response('/%s: No such file or directory.' % path, 404)

@app.route('/<path:path>', methods=['PUT', 'POST'])
def put(path):
    path_components = path.split('/')
    if '.' in path_components or '..' in path_components:
        return flask.make_response("Path must be absolute.", 400)

    fullpath = '%s/%s' % (root_path, path)
    if os.path.exists(fullpath):
        return flask.make_response('/%s: File exists.' % path, 403)
    elif request.data == '' or request.data is None:
        os.mkdir(fullpath)
        return flask.make_response('', 201)
    else:
        encoding = request.args.get('encoding')
        if encoding == 'base64':
            data = request.data.decode('base64')
        else:
            data = request.data
        with open(fullpath, "wb") as dest_file:
            dest_file.write(data)
        return flask.make_response('', 201)

@app.route('/<path:path>', methods=['DELETE'])
def delete(path):
    path_components = path.split('/')
    if '.' in path_components or '..' in path_components:
        return flask.make_response("Path must be absolute.", 400)

    fullpath = '%s/%s' % (root_path, path)
    if os.path.exists(fullpath):
        if os.path.isdir(fullpath):
            if os.listdir(fullpath) == []:
                os.rmdir(fullpath)
                return flask.make_response('', 204)
            else:
                print os.listdir(fullpath)
                return flask.make_response('/%s: Directory is not empty.' % path, 403)
        else:
            os.remove(fullpath)
            return flask.make_response('', 204)
    else:
        return flask.make_response('/%s: No such file or directory.' % path, 404)

if __name__ == "__main__":
    parser = ArgumentParser()
    parser.add_argument('--root-path', dest='root_path', action='store', help='Path to serve.')
    parser.add_argument('-d', '--debug', dest='debug', action='store_true', help='Run in debug mode.')
    parser.add_argument('host', action='store', nargs='?', help='Host to bind to.')
    parser.add_argument('port', action='store', type=int, nargs='?', help='Port to listen on.')

    args = parser.parse_args()

    if args.root_path is not None:
        root_path = args.root_path

    app.run(threaded=True, host=args.host, port=args.port, debug=args.debug)