text:
    not(any(
        feature = "vulkan",
        feature = "dx12",
        feature = "dx11",
        feature = "metal",
        feature = "gl",
    )),
    allow(dead_code)
)]

extern crate gfx_warden as warden;
#[macro_use]
extern crate serde;

use hal::{adapter::PhysicalDevice as _, Instance as _};
use std::collections::HashMap;
use std::fs::File;
use std::path::PathBuf;

use ron::de;

#[derive(Debug, Deserialize)]
enum Expectation {
    Buffer(String, Vec<u8>),
    ImageRow(String, usize, Vec<u8>),
}

#[derive(Debug, Deserialize)]
struct Test {
    jobs: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct RawTestGroup {
    features: Vec<warden::Feature>,
    tests: HashMap<String, Test>,
}

type Suite = HashMap<String, RawTestGroup>;

struct TestGroup {
    name: String,
    scene: warden::raw::Scene,
    tests: HashMap<String, Test>,
    features: hal::Features,
}

#[derive(Default)]
struct Disabilities {}

struct Harness {
    base_path: PathBuf,
    suite: Vec<TestGroup>,
}

impl Harness {
    fn new(suite_name: &str) -> Self {
        let base_path = PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/../../work"));
        println!("Parsing test suite '{}'...", suite_name);

        let suite_path = base_path
            .join("benches")
            .join(suite_name)
            .with_extension("ron");
        let suite = File::open(&suite_path)
            .map_err(de::Error::from)
            .and_then(de::from_reader::<_, Suite>)
            .expect(&format!("failed to open/parse the suite: {:?}", suite_path))
            .into_iter()
            .map(|(name, raw_group)| {
                let path = base_path.join("scenes").join(&name).with_extension("ron");
                let scene = File::open(path)
                    .map_err(de::Error::from)
                    .and_then(de::from_reader)
                    .expect("failed to open/parse the scene");
                let features = raw_group
                    .features
                    .into_iter()
                    .fold(hal::Features::empty(), |u, f| u | f.into_hal());
                TestGroup {
                    name,
                    scene,
                    tests: raw_group.tests,
                    features,
                }
            })
            .collect();

        Harness { base_path, suite }
    }

    fn run<B: hal::Backend>(&self, name: &str, disabilities: Disabilities) {
        println!("Benching {}:", name);
        let instance = B::Instance::create("warden", 1).unwrap();
        self.run_instance(instance, disabilities)
    }

    fn run_instance<B: hal::Backend, I: hal::Instance<B>>(
        &self,
        instance: I,
        _disabilities: Disabilities,
    ) {
        for tg in &self.suite {
            let mut adapters = instance.enumerate_adapters();
            let adapter = adapters.remove(0);
            let supported_features = adapter.physical_device.features();
            let limits = adapter.physical_device.properties().limits;
            //println!("\t{:?}", adapter.info);
            println!("\tScene '{}':", tg.name);

            #[cfg(not(feature = "glsl-to-spirv"))]
            {
                let all_spirv = tg.scene.resources.values().all(|res| match *res {
                    warden::raw::Resource::Shader(ref name) => name.ends_with(".spirv"),
                    _ => true,
                });
                if !all_spirv {
                    println!("\t\tskipped {} tests (GLSL shaders)", tg.tests.len());
                    continue;
                }
            }

            if !supported_features.contains(tg.features) {
                println!(
                    "\tskipped (features missing: {:?})",
                    tg.features - supported_features
                );
                continue;
            }

            let mut scene = warden::gpu::Scene::<B>::new(
                adapter,
                tg.features,
                &tg.scene,
                self.base_path.join("data"),
            )
            .unwrap();

            for (test_name, test) in &tg.tests {
                print!("\t\tTest '{}' ...", test_name);
                let mut max_compute_work_groups = [0; 3];
                for job_name in &test.jobs {
                    if let warden::raw::Job::Compute { dispatch, .. } = tg.scene.jobs[job_name] {
                        for (max, count) in max_compute_work_groups.iter_mut().zip(dispatch.iter())
                        {
                            *max = (*max).max(*count);
                        }
                    }
                }
                if max_compute_work_groups[0] > limits.max_compute_work_group_size[0]
                    || max_compute_work_groups[1] > limits.max_compute_work_group_size[1]
                    || max_compute_work_groups[2] > limits.max_compute_work_group_size[2]
                {
                    println!("\tskipped (compute {:?})", max_compute_work_groups);
                    continue;
                }

                scene.run(test.jobs.iter());
                let time = scene.measure_time();
                println!(" {} mcs", time / 1000);
            }
        }
    }
}

fn main() {
    use std::env;

    #[cfg(feature = "env_logger")]
    env_logger::init();

    let suite_name = match env::args().nth(1) {
        Some(name) => name,
        None => {
            println!("Call with the argument of the bench suite name");
            return;
        }
    };

    let harness = Harness::new(&suite_name);
    #[cfg(feature = "vulkan")]
    {
        harness.run::<gfx_backend_vulkan::Backend>("Vulkan", Disabilities::default());
    }
    #[cfg(feature = "dx12")]
    {
        harness.run::<gfx_backend_dx12::Backend>("DX12", Disabilities::default());
    }
    #[cfg(feature = "dx11")]
    {
        harness.run::<gfx_backend_dx11::Backend>("DX11", Disabilities::default());
    }
    #[cfg(feature = "metal")]
    {
        harness.run::<gfx_backend_metal::Backend>("Metal", Disabilities::default());
    }
    #[cfg(feature = "gl")]
    {
        harness.run::<gfx_backend_gl::Backend>("GL", Disabilities::default());
    }
    #[cfg(not(any(
        feature = "vulkan",
        feature = "dx12",
        feature = "dx11",
        feature = "metal",
        feature = "gl",
    )))]
    {
        println!("No backend selected!");
        let _ = harness;
    }
}


text:
Series

WordPress Maintenance Mode Without a Plugin

Part 1

Part 2

Part 3

WordPres Caching Comparisons

Part 1

Part 2

Some External Links

FreeMyFeed

Gallery

Github

                            <form class="form-search" method="get" action="http://www.google.com/search">

                                    <input class="form-search" type="text" name="q" placeholder="Search" />

                                <input type="hidden" name="sitesearch" value="sivel.net" />
                            </form>

                        Follow @sivel

redpajama_set_name: RedPajamaGithub


text:
package com.googlecode.jmxtrans.model.output;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.googlecode.jmxtrans.model.JmxProcess;
import com.googlecode.jmxtrans.model.Query;
import com.googlecode.jmxtrans.model.Result;
import com.googlecode.jmxtrans.model.Server;
import com.googlecode.jmxtrans.model.ValidationException;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;

import java.util.List;
import java.util.Map;

/**
 * This class isn't finished yet.
 *
 * @author jon
 */
public class VelocityWriter extends BaseOutputWriter {

	@JsonCreator
	public VelocityWriter(
			@JsonProperty("typeNames") ImmutableList<String> typeNames,
			@JsonProperty("booleanAsNumber") boolean booleanAsNumber,
			@JsonProperty("debug") Boolean debugEnabled,
			@JsonProperty("settings") Map<String, Object> settings) {
		super(typeNames, booleanAsNumber, debugEnabled, settings);
	}

	@Override
	public void internalWrite(Server server, Query query, ImmutableList<Result> results) {
		// TODO Auto-generated method stub
	}

	@Override
	public void validateSetup(Server server, Query query) throws ValidationException {
		// TODO
	}

	/**
	 * Uses velocity to generate output for a List of JmxProcess.
	 */
	protected void genVelocityOutput(List<JmxProcess> processes) {

		// Generate settings XML using Velocity

		// for (JmxProcess process : processes) {
		// for (Server server : process.getServers()) {

		// VelocityEngine ve = getVelocityEngine();
		// VelocityContext context = new VelocityContext();
		// context.put("results", );
		// StringWriter writer = new StringWriter();
		// ve.mergeTemplate("conf.zend/crawler_settings.xml", "UTF-8", context,
		// writer);
		// }
		// }
	}

	/**
	 * Sets velocity up to load resources from a list of paths.
	 */
	protected VelocityEngine getVelocityEngine(List<String> paths) {
		VelocityEngine ve = new VelocityEngine();
		ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
		ve.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
		ve.setProperty("cp.resource.loader.cache", "true");
		ve.setProperty("cp.resource.loader.path", StringUtils.join(paths, ","));
		ve.setProperty("cp.resource.loader.modificationCheckInterval ", "10");
		ve.setProperty("input.encoding", "UTF-8");
		ve.setProperty("output.encoding", "UTF-8");
		ve.setProperty("runtime.log", "");
		return ve;
	}
}


text:
package com.example.mac.miniprojet;

import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import Metier.Categorie;

public class ListCategoriesActivity extends AppCompatActivity {
    ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_categories);

        ListCategoriesFragment listCategoriesFragment = new ListCategoriesFragment();
        Bundle bundle = new Bundle();
        listCategoriesFragment.setArguments(bundle);

        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.frameLayoutCategories, listCategoriesFragment);
        ft.commit();

        listView = (ListView) findViewById(R.id.listView);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.v("message","message0");

                showView((Categorie) listView.getAdapter().getItem(position));
                Log.v("message","message1");

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public void showView (Categorie categorie) {
        Log.v("message","message3");

        Intent intent = new Intent(this,ListProductsActivity.class);
        intent.putExtra("categorie",categorie);
        startActivity(intent);

    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>masseuse Namespace: masseuse</title>

	<link type="text/css" rel="stylesheet" href="styles/sunlight.default.css">

	<link type="text/css" rel="stylesheet" href="styles/site.flatly.css">

			masseuse

					Namespaces

							masseuse

							masseuse/BaseView

							masseuse/channels

							masseuse/ComputedProperty

							masseuse/MasseuseModel

							masseuse/MasseuseRouter

							masseuse/ObserverProperty

							masseuse/plugins/rivets/RivetsView

							masseuse/ProxyProperty

							masseuse/utilities/createOptions

							masseuse/ViewContext

Namespace: masseuse

    masseuse

Masseuse is:
 BB helper library
     helps with
         views
             baseView
                 the BB View lifecycle - based on promises
                 child views
                 separating View definitions from View options
             rivetView
                 a baseView with built in rivetjs
         models
             allows for model specific logic to be packaged with the model
               computed properties
               proxy properties
             nested models with bubbling up of change events
         router
             with a beforeRouting method

Source:

        main.js, line 9

		SOLID Interactive 2014

		Documentation generated by JSDoc 3.3.0-alpha4
		on Fri Dec 05 2014 14:02:39 GMT-0800 (PST) using the DocStrap template.


text:
<?php
/**
 * Отображение для blog/widgets/lastpostsofblog:
 *
 *   @category YupeView
 *   @package  YupeCMS
 *   @author   Yupe Team <team@yupe.ru>
 *   @license  https://github.com/yupe/yupe/blob/master/LICENSE BSD
 *   @link     http://yupe.ru
 **/
if ($model === null) :
    echo Yii::t('BlogModule.blog', 'Блог не существует');
elseif (count($model->posts) > 0) : ?>
    <?php $c=0;?>
        <?php foreach ($model->posts as $post) : ?>
        <?php $c++;?>
        <?php
        $this->widget('application.modules.blog.widgets.ShowPostWidget', array('postID' => $post->id)); ?>
        <?php if($c>=$limit)break;?>
    <?php endforeach;?>

<?php else : ?>
    <?php echo Yii::t('BlogModule.blog', 'Записей нет'); ?>
<?php endif; ?>


text:
/*
GAME RULES:

- The game has 2 players, playing in rounds
- In each turn, a player rolls a dice as many times as he whishes. Each result get added to his ROUND score
- BUT, if the player rolls a 1, all his ROUND score gets lost. After that, it's the next player's turn
- The player can choose to 'Hold', which means that his ROUND score gets added to his GLBAL score. After that, it's the next player's turn
- The first player to reach 100 points on GLOBAL score wins the game

*/

var scores, roundScore, activePlayer, gamePlaying;

init();

document.querySelector('.btn-roll').addEventListener('click', function() {
    if (gamePlaying) {

        // 1. Random Number
        var dice = Math.floor(Math.random() * 6) + 1;

        // 2. Display the result
        var diceDOM = document.querySelector('.dice')
        diceDOM.style.display = 'block';
        diceDOM.src ='dice-' + dice + '.png';

        // 3. Update the round score IF the rolled number was NOT 1
        if (dice !== 1) {
            //Add score
            roundScore += dice;
            document.querySelector('#current-' + activePlayer).textContent = roundScore;

        } else {
            //Next Player
            nextPlayer();
        }
    }

});

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (gamePlaying) {
        // Add CURRENT score to Global score
        scores[activePlayer] += roundScore;

        // Update the UI
        document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];

        // Check if player won the game
        if (scores[activePlayer] >= 100) {
            document.querySelector('#name-' +activePlayer).textContent = 'Winner!';
            document.querySelector('.dice').style.display = 'none';
            document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
            document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
            gamePlaying = false;
        } else {
            nextPlayer();
        }
    }
});

function nextPlayer () {
    //Next Player
    activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
    roundScore = 0;
    document.getElementById('current-0').textContent ='0';
    document.getElementById('current-1').textContent ='0';

    document.querySelector('.player-0-panel').classList.toggle('active');
    document.querySelector('.player-1-panel').classList.toggle('active');

    //document.querySelector('.player-0-panel').classList.remove('active');
    //document.querySelector('.player-1-panel').classList.add('active');

    document.querySelector('.dice').style.display = 'none';
}

document.querySelector('.btn-new').addEventListener('click', init);

function init() {
    scores = [0,0];
    roundScore = 0;
    activePlayer = 0;
    gamePlaying = true;

    document.querySelector('.dice').style.display ='none';
    document.getElementById('score-0').textContent = '0';
    document.getElementById('score-1').textContent = '0';
    document.getElementById('current-0').textContent = '0';
    document.getElementById('current-1').textContent = '0';
    document.getElementById('name-0').textContent = 'Player 1';
    document.getElementById('name-1').textContent = 'Player 2';
    document.querySelector('.player-0-panel').classList.remove('winner');
    document.querySelector('.player-1-panel').classList.remove('winner');
    document.querySelector('.player-0-panel').classList.remove('active');
    document.querySelector('.player-1-panel').classList.remove('active');
    document.querySelector('.player-0-panel').classList.add('active');

}


text:
<?php

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

class AddConfirmationAttributesToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function($table)
        {
            $table->boolean('confirmed')->after('frequency')->default(false);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table)
        {
            $table->dropColumn('confirmed');
        });
    }
}


text:
import React from 'react';

function formatDate(date) {
  return new Date(date).toLocaleDateString('en-US', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });
}

const ReviewItem = (props) => (

{props.overallRating}

{props.title}

{props.review}

    {props.screenName}
    {formatDate(props.datePosted)}

);

ReviewItem.propTypes = {
  overallRating: React.PropTypes.oneOfType([
    React.PropTypes.string,
    React.PropTypes.number,
  ]),
  title: React.PropTypes.string,
  review: React.PropTypes.string,
  screenName: React.PropTypes.string,
  datePosted: React.PropTypes.string,
};

export default ReviewItem;


text:
/*
Package aws_role may be used by service code to obtain Keymaster-issued identity
certificates. The identity certificate will contain the AWS IAM role that the
service code is able to assume (i.e. EC2 instance profile, EKS IRSA, Lambda
role). The full AWS Role ARN is stored in a certificate URI SAN extension and a
simplified form of the ARN is stored in the certificate CN.

The full AWS Role ARN will reflect the actual role ARN, rather than an ARN
showing how the credentials were obtained. This mirrors the way AWS policy
documents are written. The ARN will have the form:
arn:aws:iam::$AccountId:role/$RoleName

The service code does not require any extra permissions. It uses the
sts:GetCallerIdentity permission that is available to all AWS identities. Thus,
no policy configuration is required.

This code uses the AWS IAM credentials to request a pre-signed URL from the AWS
Security Token Service (STS). This pre-signed URL is passed to Keymaster which
can make a request using the URL to verify the identity of the caller. No
credentials are sent.

The protocol is a simple HTTPS/REST interface, typically located on the path:
/aws/requestRoleCertificate/v1
The client issues a POST request with the following headers:

Claimed-Arn:      the full AWS Role ARN
Presigned-Method: the method type specified in the pre-signing response
Presigned-URL:    the URL specified in the pre-signing response

The body of the request must contain a PEM-encoded Public Key DER.
On success, the response body will contain a signed, PEM-encoded X.509
Certificate.
*/
package aws_role

import (
	"context"
	"crypto"
	"crypto/tls"
	"net/http"
	"sync"

	"github.com/Cloud-Foundations/golib/pkg/awsutil/presignauth/presigner"
	"github.com/Cloud-Foundations/golib/pkg/log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sts"
)

type Params struct {
	// Required parameters.
	KeymasterServer string
	Logger          log.DebugLogger
	// Optional parameters.
	AwsConfig        *aws.Config
	Context          context.Context
	HttpClient       *http.Client
	Signer           crypto.Signer
	StsClient        *sts.Client
	StsPresignClient *sts.PresignClient
	derPubKey        []byte
	isSetup          bool
	pemPubKey        []byte
	presigner        presigner.Presigner
}

type Manager struct {
	params    Params
	mutex     sync.RWMutex // Protect everything below.
	certError error
	certPEM   []byte
	certTLS   *tls.Certificate
	waiters   map[chan<- struct{}]struct{}
}

// GetRoleCertificate requests an AWS role identify certificate from the
// Keymaster server specified in params. It returns the certificate PEM.
func GetRoleCertificate(params Params) ([]byte, error) {
	return params.getRoleCertificate()
}

// GetRoleCertificateTLS requests an AWS role identify certificate from the
// Keymaster server specified in params. It returns the certificate.
func GetRoleCertificateTLS(params Params) (*tls.Certificate, error) {
	_, certTLS, err := params.getRoleCertificateTLS()
	return certTLS, err
}

// NewManager returns a certificate manager which provides AWS role identity
// certificates from the Keymaster server specified in params. Certificates
// are refreshed in the background.
func NewManager(params Params) (*Manager, error) {
	return newManager(params)
}

// GetClientCertificate returns a valid, cached certificate. The method
// value may be assigned to the crypto/tls.Config.GetClientCertificate field.
func (m *Manager) GetClientCertificate(cri *tls.CertificateRequestInfo) (
	*tls.Certificate, error) {
	return m.getClientCertificate(cri)
}

// GetRoleCertificate returns a valid, cached certificate. It returns the
// certificate PEM, TLS certificate and error.
func (m *Manager) GetRoleCertificate() ([]byte, *tls.Certificate, error) {
	return m.getRoleCertificate()
}

// WaitForRefresh waits until a successful certificate refresh.
func (m *Manager) WaitForRefresh() {
	m.waitForRefresh()
}


text:
package org.openkilda.messaging.info.grpc;

import org.openkilda.messaging.model.grpc.PacketInOutStatsDto;
import org.openkilda.model.SwitchId;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class ResponseSerialisationTest {

    private ObjectMapper mapper = new ObjectMapper();

    @Test
    public void getPacketInOutStatsResponseTest() throws IOException {
        GetPacketInOutStatsResponse response = new GetPacketInOutStatsResponse(new SwitchId(1),
                new PacketInOutStatsDto(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, true, 11));

        String jsonString = mapper.writeValueAsString(response);
        GetPacketInOutStatsResponse objectFromJson = mapper.readValue(jsonString, GetPacketInOutStatsResponse.class);
        Assert.assertEquals(response, objectFromJson);
    }
}


text:
<?php
declare(strict_types=1);

namespace TileLand\Unit;

use TileLand\Entity\UnitAttributes;

class Explorer implements Unit
{
    public function getName(): string
    {
        return Units::EXPLORER;
    }

    public function getBaseProductionCost(): int
    {
        return 10;
    }

    public function createEntity(): \TileLand\Entity\Unit
    {
        return new \TileLand\Entity\Unit(
            $this,
            new UnitAttributes(
                10,
                3,
                1,
                0,
                '1d5'
            )
        );
    }
}


text:
import path from 'path'
import webpack from 'webpack'

const { NODE_ENV } = process.env

const plugins = [
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(NODE_ENV),
  }),
]

const filename = `redux-promise-bind${NODE_ENV === 'production' ? '.min' : ''}.js`

NODE_ENV === 'production' && plugins.push(
  new webpack.optimize.UglifyJsPlugin({
    compressor: {
      pure_getters: true,
      unsafe: true,
      unsafe_comps: true,
      screw_ie8: true,
      warnings: false,
    },
  })
)

export default {
  entry: ['./src/index'],

  output: {
    path: path.join(__dirname, 'dist'),
    filename,
    library: 'ReduxPromiseBind',
    libraryTarget: 'umd',
  },

  resolve: {
    modules: [path.resolve(__dirname, 'src'), 'node_modules'],
    extensions: ['.js', '.jsx'],
  },

  plugins,

  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
    ],
  },
}


text:
#region License

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

#endregion

using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Unity;
using Wide.Interfaces;
using Wide.Interfaces.Events;

namespace Wide.Tools.Logger
{
    [Module(ModuleName = "Wide.Tools.Logger")]
    public sealed class LoggerModule : IModule
    {
        private readonly IUnityContainer _container;

        public LoggerModule(IUnityContainer container)
        {
            _container = container;
        }

        private IEventAggregator EventAggregator
        {
            get { return _container.Resolve<IEventAggregator>(); }
        }

        #region IModule Members

        public void Initialize()
        {
            EventAggregator.GetEvent<SplashMessageUpdateEvent>().Publish(new SplashMessageUpdateEvent
                                                                             {Message = "Loading Logger Module"});
            _container.RegisterType<LoggerViewModel>();
            IWorkspace workspace = _container.Resolve<AbstractWorkspace>();
            workspace.Tools.Add(_container.Resolve<LoggerViewModel>());
        }

        #endregion
    }
}


text:
package com.pie.tlatoani.WorldBorder;

import ch.njol.skript.classes.Changer;
import com.pie.tlatoani.Core.Skript.ChangeablePropertyExpression;
import org.bukkit.Location;
import org.bukkit.World;

/**
 * Created by Tlatoani on 8/18/17.
 */
public class ExprCenterOfBorder extends ChangeablePropertyExpression<World, Location> {

    @Override
    public void change(World world, Location location, Changer.ChangeMode changeMode) {
        if (changeMode == Changer.ChangeMode.SET) {
            world.getWorldBorder().setCenter(location);
        }
    }

    @Override
    public Changer.ChangeMode[] getChangeModes() {
        return new Changer.ChangeMode[]{Changer.ChangeMode.SET};
    }

    @Override
    public Location convert(World world) {
        return world.getWorldBorder().getCenter();
    }
}


text:
#ifndef SHARE_VM_MEMORY_REFRERENCETYPE_HPP
#define SHARE_VM_MEMORY_REFRERENCETYPE_HPP

#include "utilities/debug.hpp"

// ReferenceType is used to distinguish between java/lang/ref/Reference subclasses

enum ReferenceType {
  REF_NONE,      // Regular class
  REF_OTHER,     // Subclass of java/lang/ref/Reference, but not subclass of one of the classes below
  REF_SOFT,      // Subclass of java/lang/ref/SoftReference
  REF_WEAK,      // Subclass of java/lang/ref/WeakReference
  REF_FINAL,     // Subclass of java/lang/ref/FinalReference
  REF_PHANTOM    // Subclass of java/lang/ref/PhantomReference
};

#endif // SHARE_VM_MEMORY_REFRERENCETYPE_HPP


text:
// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the MIT License https://raw.github.com/mit-cml/app-inventor/master/mitlicense.txt

package com.google.appinventor.components.runtime;

import junit.framework.TestCase;
import java.util.Calendar;
import java.util.TimeZone;

/**
 * Tests Clock.java.
 *
 */

public class ClockTest extends TestCase {

  private final Calendar tc = Clock.MakeInstant("10/11/1941 09:30:00");

  public void testNow() throws Exception {
    assertTrue(0 > Clock.Duration(Clock.Now(), tc));
  }

  public void testMakeInstant() throws Exception {
    assertEquals("Oct 11, 1941 9:30:00 AM", Clock.FormatDateTime(tc));
  }

  public void testMakeInstantFromMillis() throws Exception {
    assertEquals("Jan 1, 1970 12:00:00 AM",
        Clock.FormatDateTime(Clock.MakeInstantFromMillis(0
                                      - TimeZone.getDefault().getRawOffset())));
  }

  public void testGetMillis() throws Exception {
    assertEquals(-TimeZone.getDefault().getRawOffset(),
        Clock.GetMillis(Clock.MakeInstant("1/1/1970 00:00:00")));
  }

  public void testAddYears() throws Exception {
    assertEquals("Oct 11, 1943 9:30:00 AM", Clock.FormatDateTime(Clock.AddYears(tc, 2)));
  }

  public void testAddYears2() throws Exception {
    assertEquals("Oct 11, 1931 9:30:00 AM", Clock.FormatDateTime(Clock.AddYears(tc, -10)));
  }

  public void testAddMonths() throws Exception {
    assertEquals("Dec 11, 1941 9:30:00 AM", Clock.FormatDateTime(Clock.AddMonths(tc, 2)));
  }

  public void testAddMonths2() throws Exception {
    assertEquals("Oct 11, 1942 9:30:00 AM", Clock.FormatDateTime(Clock.AddMonths(tc, 12)));
  }

  public void testAddWeeks() throws Exception {
    assertEquals("Sep 10, 2002 12:00:00 AM", Clock.FormatDateTime(
        Clock.AddWeeks(Clock.MakeInstant("9/11/2001 00:00:00"), 52)));
  }

  public void testAddWeeks2() throws Exception {
    assertEquals("Sep 18, 2001 12:00:00 AM", Clock.FormatDateTime(
        Clock.AddWeeks(Clock.MakeInstant("9/11/2001 00:00:00"), 1)));
  }

  public void testAddDays() throws Exception {
    assertEquals("Oct 9, 1941", Clock.FormatDate(Clock.AddDays(tc, -2)));
  }

  public void testAddDays2() throws Exception {
    assertEquals("Nov 1, 1941", Clock.FormatDate(Clock.AddDays(tc, 21)));
  }

  public void testAddHours() throws Exception {
    assertEquals("Oct 11, 1941 7:30:00 AM", Clock.FormatDateTime(Clock.AddHours(tc, -2)));
  }

  public void testAddHours2() throws Exception {
    assertEquals("Oct 12, 1941 9:30:00 AM", Clock.FormatDateTime(Clock.AddHours(tc, 24)));
  }

  public void testAddMinutes() throws Exception {
    assertEquals("Oct 11, 1941 9:32:00 AM", Clock.FormatDateTime(Clock.AddMinutes(tc, 2)));
  }

  public void testAddSeconds() throws Exception {
    assertEquals("9:31:01 AM", Clock.FormatTime(Clock.AddSeconds(tc, 61)));
  }

  public void testSecond() throws Exception {
    assertEquals(0, Clock.Second(tc));
  }

  public void testMinute() throws Exception {
    assertEquals(30, Clock.Minute(tc));
  }

  public void testHour() throws Exception {
    assertEquals(9, Clock.Hour(tc));
  }

  public void testWeekday() throws Exception {
    assertEquals(2, Clock.Weekday(Clock.MakeInstant("11/2/2009")));
  }

  public void testWeekdayName() throws Exception {
    assertEquals("Monday", Clock.WeekdayName(Clock.MakeInstant("11/2/2009")));
  }

  public void testDayOfMonth() throws Exception {
    assertEquals(11, Clock.DayOfMonth(tc));
  }

  public void testMonth() throws Exception {
    assertEquals(10, Clock.Month(tc));
  }

  public void testMonthName() throws Exception {
    assertEquals("October", Clock.MonthName(tc));
  }

  public void testYear() throws Exception {
    assertEquals(1941, Clock.Year(tc));
  }
}


text:
#pragma once
#include <aws/appmesh/AppMesh_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace AppMesh
{
namespace Model
{

  /**
   *
An object that represents a target and its relative weight. Traffic is
   * distributed across targets according to their relative weight. For example, a
   * weighted target with a relative weight of 50 receives five times as much traffic
   * as one with a relative weight of 10. The total weight for all targets combined
   * must be less than or equal to 100.

See Also:
   AWS
   * API Reference

   */
  class AWS_APPMESH_API WeightedTarget
  {
  public:
    WeightedTarget();
    WeightedTarget(Aws::Utils::Json::JsonView jsonValue);
    WeightedTarget& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline const Aws::String& GetVirtualNode() const{ return m_virtualNode; }

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline bool VirtualNodeHasBeenSet() const { return m_virtualNodeHasBeenSet; }

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline void SetVirtualNode(const Aws::String& value) { m_virtualNodeHasBeenSet = true; m_virtualNode = value; }

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline void SetVirtualNode(Aws::String&& value) { m_virtualNodeHasBeenSet = true; m_virtualNode = std::move(value); }

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline void SetVirtualNode(const char* value) { m_virtualNodeHasBeenSet = true; m_virtualNode.assign(value); }

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline WeightedTarget& WithVirtualNode(const Aws::String& value) { SetVirtualNode(value); return *this;}

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline WeightedTarget& WithVirtualNode(Aws::String&& value) { SetVirtualNode(std::move(value)); return *this;}

    /**
     *
The virtual node to associate with the weighted target.

     */
    inline WeightedTarget& WithVirtualNode(const char* value) { SetVirtualNode(value); return *this;}

    /**
     *
The relative weight of the weighted target.

     */
    inline int GetWeight() const{ return m_weight; }

    /**
     *
The relative weight of the weighted target.

     */
    inline bool WeightHasBeenSet() const { return m_weightHasBeenSet; }

    /**
     *
The relative weight of the weighted target.

     */
    inline void SetWeight(int value) { m_weightHasBeenSet = true; m_weight = value; }

    /**
     *
The relative weight of the weighted target.

     */
    inline WeightedTarget& WithWeight(int value) { SetWeight(value); return *this;}

  private:

    Aws::String m_virtualNode;
    bool m_virtualNodeHasBeenSet;

    int m_weight;
    bool m_weightHasBeenSet;
  };

} // namespace Model
} // namespace AppMesh
} // namespace Aws


text:
module TokyoMetro::Modules::ToFactory::Api::Convert::Patch::StationFacility::EscalatorOperationDay::Generate::Info
end


text:
{% load hq_shared_tags %}
{% load i18n %}

{% with slug="app_manager_v2" name="New App Builder" %}

        {% blocktrans %}

              {{ name }} Available!

              We're about to release a new look for the app builder.

                Check it out here.

              These changes will be rolled out permanently in July, but if
              you'd like, you can turn them on now.

                <button class="btn btn-lg btn-primary btn-full-width flag-enable">
                  Yes, turn on {{ name }}!
                </button>

                <button class="btn btn-lg btn-default btn-full-width flag-snooze">
                  No, remind me later
                </button>

        {% endblocktrans %}

{% endwith %}


text:
import React from 'react';
import { Link } from 'react-router';
import { RouteTransition } from 'react-router-transition';

const App = React.createClass({
  propTypes: {
    route: React.PropTypes.object,
    location: React.PropTypes.object
  },

  contextTypes: {
    router: React.PropTypes.object
  },

  render() {
    return (
      <div>
        <Link to="/" key="home">Home</Link>
        {this.props.route.childRoutes.map(({ path }) => {
          const isActive = this.context.router.isActive(path);
          return (
            <Link
              to={`/${path}`}
              key={path}
              className={isActive ? 'link active' : 'link'}
            >
              {path}
            </Link>
          );
        })}
        <RouteTransition
          component={false}
          pathname={this.props.location.pathname}
          className="transition-wrapper"
          atEnter={{ opacity: 0 }}
          atLeave={{ opacity: 0 }}
          atActive={{ opacity: 1 }}
        >
          {this.props.children}
        </RouteTransition>
      </div>
    );
  }
});

export default App;


text:
<!---
The github issues tracker is for bug reports and feature requests _ONLY_. Please use stackoverflow or read the documentation and examples for support issues, as well as checking previous issues.

Issues that ignore this template will be closed without notice!
-->
### Bug description / Feature request:

### Link to minimally-working plunker that reproduces the issue (starter template: http://plnkr.co/edit/LE4F4U7AnnD3tjM9ZH4G?p=preview)

### Versions

Angular:

Calendar library:

Browser name and version:


text:
set -e

usage() {
    msg "

    Usage: $pn -img 3d-image.nii.gz -mask brainmask.nii.gz -icv icvmask.nii.gz \\
           -dir atlas-directory

    Options:

    [-base basename] Base name for subject.  Image name root is used if not specified

    [-affinenorm norm.dof.gz] Affine transformation normalizing entry to a common space.
                              If not supplied, a neutral transformation is copied.

    Prepare a pincram-compatible atlas directory

    Note: at least 20 sets are needed for a pincram atlas

    If only -base basename and -dir atlas-directory are supplied, the script generates
    contents of atlas-directory/cache using data in atlas-directory/base for the
    corresponding entry. The idea is that the cache directory can be deleted for a
    compact atlas representation and recreated as and when pincram is to be run.

    If an image, a brain mask, and an intracranial volume mask are supplied,
    the script generates contents of atlas-directory/base and atlas-directory/cache.

    If atlas-directory/base/refspace/brainmask-dm.nii.gz does not exist, the script
    copies brainmask.nii.gz and 3d-image.nii.gz to this location. When a new atlas
    directory is created, the first participant's image set serves as the reference for
    pre-alignment.

    "
}

ppath=$(realpath "$BASH_SOURCE")
cdir=$(dirname "$ppath")
pn=$(basename "$ppath")

. "$cdir"/functions

td=$(tempdir)
trap 'rm -rf $td' EXIT

type mirtk >/dev/null 2>&1 || fatal "MIRTK not on $PATH"

eucmap() {
    local mask=$1 ; shift
    local map=$1
    mirtk calculate-distance-map $mask dm.nii.gz -threads $par
    mirtk calculate-element-wise dm.nii.gz -mul -1 -threads $par -o $map
}

[[ $# -lt 4 ]] && fatal "Parameter error"
img=
msk=
icv=
atlasdir=
bname=
inorm=
par=1
while [[ $# -gt 0 ]]
do
    case "$1" in
        -img)               img=$(realpath "$2"); shift;;
        -mask)              msk=$(realpath "$2"); shift;;
        -icv)               icv=$(realpath "$2"); shift;;
	-affinenorm)      inorm=$(realpath "$2"); shift;;
	-dir)          atlasdir=$(realpath "$2"); shift;;
        -base)            bname="$2" ; shift ;;
        -par)               par="$2" ; shift ;;
        --) shift; break;;
        -*)
            fatal "Parameter error" ;;
        *)  break;;
    esac
    shift
done

launchdir="$PWD"
cd $td

[[ -z $bname ]] && bname=$(basename $img .nii.gz)
entree="$atlasdir"/etc/entry-$bname

mkdir -p \
      "$atlasdir"/base/images \
      "$atlasdir"/base/brainmasks \
      "$atlasdir"/base/icvmasks \
      "$atlasdir"/base/refspace \
      "$atlasdir"/cache/brainmasks-dm \
      "$atlasdir"/cache/icvmasks-dm \
      "$atlasdir"/cache/affinenorm \
      "$atlasdir"/etc || fatal "Could not create directory structure"

if [[ -e $entree ]] ; then
    msg "Re-creating cache content for $bname"
else
    cp "$img" "$atlasdir"/base/images/$bname.nii.gz
    cp "$msk" "$atlasdir"/base/brainmasks/$bname.nii.gz
    cp "$icv" "$atlasdir"/base/icvmasks/$bname.nii.gz
fi

mskdm="$atlasdir"/cache/brainmasks-dm/$bname.nii.gz
eucmap "$atlasdir"/base/brainmasks/$bname.nii.gz "$mskdm"
eucmap "$atlasdir"/base/icvmasks/$bname.nii.gz "$atlasdir"/cache/icvmasks-dm/$bname.nii.gz

affnorm="$atlasdir"/cache/affinenorm/$bname.dof.gz
dmtarget="$atlasdir"/base/refspace/brainmask-dm.nii.gz
if [[ -e "$dmtarget" ]] ; then
    if [[ -n "$inorm" ]] ; then
	cp "$inorm" "$affnorm"
    else
	mirtk register "$dmtarget" "$mskdm" -model Affine -sim SSD -dofout $affnorm -threads $par
    fi
else
    cp $cdir/neutral.dof.gz "$affnorm"
    cp "$mskdm" "$dmtarget"
    cp "$img" "$atlasdir"/base/refspace/img.nii.gz
fi

echo $bname >$entree

exit 0


text:
package net.java.sip.communicator.service.muc;

import java.util.*;

/**
 * Parent class for gui chat room events indicating addition and removal of
 * chat rooms in the gui chat rooms list.
 *
 * @author Yana Stamcheva
 */
public class ChatRoomListChangeEvent
    extends EventObject
{
    private int eventID = -1;

    /**
     * Indicates that the ChatRoomListChangeEvent instance was triggered by
     * adding a ChatRoom in the gui.
     */
    public static final int CHAT_ROOM_ADDED = 1;

    /**
     * Indicates that the ChatRoomListChangeEvent instance was triggered by
     * removing a ChatRoom from the gui.
     */
    public static final int CHAT_ROOM_REMOVED = 2;

    /**
     * Indicates that the ChatRoomListChangeEvent instance was triggered by
     * changing a ChatRoom in the gui (like changing its status, etc.).
     */
    public static final int CHAT_ROOM_CHANGED = 3;

    /**
     * Creates a new <tt>ChatRoom</tt> event according to the specified parameters.
     * @param source the <tt>ChatRoom</tt> instance that is added to the
     * ChatRoomsList
     * @param eventID one of the CHAT_ROOM_XXX static fields indicating the
     * nature of the event.
     */
    public ChatRoomListChangeEvent(    ChatRoomWrapper source,
                               int eventID)
    {
        super(source);
        this.eventID = eventID;
    }

    /**
     * Returns the source <tt>ChatRoom</tt>.
     * @return the source <tt>ChatRoom</tt>.
     */
    public ChatRoomWrapper getSourceChatRoom()
    {
        return (ChatRoomWrapper) getSource();
    }

    /**
     * Returns a String representation of this <tt>GuiChatRoomEvent</tt>.
     *
     * @return  A String representation of this <tt>GuiChatRoomEvent</tt>.
     */
    @Override
    public String toString()
    {
        StringBuffer buff
            = new StringBuffer("GuiChatRoomEvent-[ ChatRoomID=");
        buff.append(getSourceChatRoom().getChatRoomName());
        buff.append(", eventID=").append(getEventID());
        buff.append(", ProtocolProvider=");

        return buff.toString();
    }

    /**
     * Returns an event id specifying whether the type of this event (e.g.
     * CHAT_ROOM_ADDED or CHAT_ROOM_REMOVED)
     * @return one of the CHAT_ROOM_XXX int fields of this class.
     */
    public int getEventID()
    {
        return eventID;
    }
}


text:
var config = require('../../infrastructure/configurationManager').config;

module.exports = function Authentication(req, res, next) {
    if(!config.authentication || !config.authentication.enabled) {
        return next();
    }

    if(req.get('Auth-Key') === config.authentication.key) {
        return next();
    }

    res.status(401);
    res.send('Unauthorized');
};


text:
<?php

declare(strict_types=1);

namespace App\Monitor;

use Laminas\Diagnostics\Check\CheckInterface;
use Laminas\Diagnostics\Result\Failure;
use Laminas\Diagnostics\Result\ResultInterface;
use Laminas\Diagnostics\Result\Success;

class RequiredENV implements CheckInterface
{
    private const REQUIRED_ENV = [
        'ILIOS_DATABASE_URL',
        'ILIOS_LOCALE',
        'ILIOS_SECRET',
        'MAILER_DSN'
    ];
    private const INSTRUCTIONS_URL = 'https://github.com/ilios/ilios/blob/master/docs/env_vars_and_config.md';
    private const UPDATE_URL = 'https://github.com/ilios/ilios/blob/master/docs/update.md';

    /**
     * Perform the actual check and return a ResultInterface
     */
    public function check(): ResultInterface
    {
        $missingVariables = array_filter(self::REQUIRED_ENV, fn($name) => !getenv($name) && !isset($_ENV[$name]));

        if ($missingVariables !== []) {
            $missing = implode("\n", $missingVariables);

            return new Failure(
                "\nMissing:\n" . $missing . "\n For help see: \n " . self::INSTRUCTIONS_URL
            );
        }

        if (getenv('ILIOS_DATABASE_MYSQL_VERSION') || isset($_ENV['ILIOS_DATABASE_MYSQL_VERSION'])) {
            return new Failure(
                "\nILIOS_DATABASE_MYSQL_VERSION should be migrated. See \n " . self::UPDATE_URL .
                " for details.\n"
            );
        }
        return new Success('All required ENV variables are setup');
    }

    /**
     * Return a label describing this test instance.
     */
    public function getLabel(): string
    {
        return 'ENV variables';
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <ListPreference
        android:key="stream_usb_baudrate"
        android:title="@string/usb_device_baudrate_title"
        android:entries="@array/usb_device_baudrate_entries"
        android:entryValues="@array/usb_device_baudrate_entries"
        android:defaultValue="38400" />

    <ListPreference
        android:key="stream_usb_data_bits"
        android:title="@string/usb_device_data_bits_title"
        android:entries="@array/usb_device_data_bits_entries"
        android:entryValues="@array/usb_device_data_bits_entries"
        android:defaultValue="8" />

    <ListPreference
        android:key="stream_usb_parity"
        android:title="@string/usb_device_parity_title"
        android:entries="@array/usb_device_parity_entries"
        android:entryValues="@array/usb_device_parity_values"
        android:defaultValue="N" />

    <ListPreference
	android:key="stream_usb_stop_bits"
        android:title="@string/usb_device_stop_bits_title"
        android:entries="@array/usb_device_stop_bits_entries"
        android:entryValues="@array/usb_device_stop_bits_entries"
        android:defaultValue="1" />

</PreferenceScreen>


text:
title: Year 9 Lesson 2
layout: post
author: charlie.line
permalink: /year-9-lesson-2/
source-id: 1CNf8gJvUOK-54eHJecthSOSpztk8CwaFPYibGWN6lBc
published: true
---
**Year 9 Lesson 2**

**In today's lesson we carried on using google sheets learning more interesting things. We have 2 sheets, An order form for when someone orders saying what they want, the quantity and the price. The other one is the stock sheet which had the code,what type of clothing, quantity ,cost price and sale price which we had  to work out.**

**We did this by writing the amount of profit we wanted to make. I put 35%, we then timesed  it by how much the clothing cost to get (sale price) and then added that as well. This meant we knew how much are clothes needed to be to be able to make 35% profit.**

**Then we made it so that when an order came through just buy the codes e.g SJ for supreme jumper. Automatically google sheets would say how much the individual price is.**


text:
using IronText.Reflection;
namespace IronText.Runtime
{
    public class NullProducer<T> : IProducer<T>
    {
        public static readonly NullProducer<T> Instance = new NullProducer<T>();

        public ReductionOrder ReductionOrder { get { return ReductionOrder.Unordered; } }

        public T Result
        {
            get { return default(T); }
            set { }
        }

        public T CreateLeaf(Msg envelope, MsgData msg) { return default(T); }

        public T CreateBranch(Production rule, Algorithm.ArraySlice<T> parts, IStackLookback<T> lookback)
        {
            return default(T);
        }

        public T Merge(T alt1, T alt2, IStackLookback<T> lookback) { return default(T); }

        public T GetDefault(int nonTerm, IStackLookback<T> lookback) { return default(T); }

        public void FillEpsilonSuffix(
            int ruleId,
            int prefixSize,
            T[] buffer,
            int destIndex,
            IStackLookback<T> lookback)
        {
        }

        public IProducer<T> GetErrorRecoveryProducer() { return this; }
    }
}


text:
#ifndef __RING_BUFFER_H__
#define __RING_BUFFER_H__

#include <stdint.h>
#include <stdlib.h>
#include <string.h>

/**
 * @file
 * Simple ring buffer implementation.
 *
 * @author    Alexandru Csete
 * @date      2014/12/29
 * @copyright Simplified BSD License
 *
 * This file implements a simple ring buffer that can hold data of unsigned
 * char type. The present implementation does not contain any boundary checks
 * and the callers must ensure that (1) the number of elemets written is less
 * than or equal to the buffer size and (2) the umber of elements read from
 * the buffer is less than or equal to the number of elements currently in the
 * buffer.
 *
 * Furthermore, the buffer does not check how much empty space there is during
 * write operations, i.e. old data will be overwritten if writing happens
 * faster than reading.
 */

/**
 * The ring buffer structure.
 *
 * @buffer  The array of elements stored in the buffer.
 * @size    The sizeof the buffer.
 * @start   Index of the oldest element.
 * @count   Number of elements currently in the buffer.
 */
typedef struct {
    unsigned char  *buffer;
    uint_fast32_t   size;
    uint_fast32_t   start;
    uint_fast32_t   count;
} ring_buffer_t;

/**
 * Initialize the ring buffer.
 *
 * @param rb Pointer to a newly allocated ring_buffer_t structure.
 * @param size The size of the buffer.
 *
 * This function will allocate the memory for the internal buffer and
 * initialize the bookkeeping parameters.
 */
static inline void ring_buffer_init(ring_buffer_t * rb, uint_fast32_t size)
{
    rb->size = size;
    rb->start = 0;
    rb->count = 0;
    rb->buffer = (unsigned char *)malloc(rb->size);
}

static inline void ring_buffer_free(ring_buffer_t * rb)
{
    free(rb->buffer);
}

/**
 * Resize the ring buffer.
 *
 * @param  rb  Pointer to the ring buffer
 * @param  newsize The new size desired for the buffer.
 *
 * @warning The internal buffer will be reallocated and all data lost during
 *          this process.
 */
static inline void ring_buffer_resize(ring_buffer_t * rb,
                                      uint_fast32_t newsize)
{
    ring_buffer_free(rb);
    ring_buffer_init(rb, newsize);
}

/**
 * Check whether the buffer is full.
 *
 * @param rb Pointer to the ring buffer.
 * @return 1 if the buffer is full, otherwise 0.
 */
static inline int ring_buffer_is_full(ring_buffer_t * rb)
{
    return (rb->count == rb->size);
}

/** Check whether the buffer is empty. */
static inline int ring_buffer_is_empty(ring_buffer_t * rb)
{
    return (rb->count == 0);
}

/** Get number of elements in the buffer. */
static inline uint_fast32_t ring_buffer_count(ring_buffer_t * rb)
{
    return rb->count;
}

/** Get size of the ring buffer. */
static inline uint_fast32_t ring_buffer_size(ring_buffer_t * rb)
{
    return rb->size;
}

/**
 * Write data into the buffer.
 *
 * @param rb   The ring buffer handle.
 * @param src  The source array.
 * @param num  The the number of elements in the input buffer. Must be less
 *             than or equal to @ref rb->size.
 */
static inline void ring_buffer_write(ring_buffer_t * rb, unsigned char *src,
                                     uint_fast32_t num)
{
    if (!num)
        return;

    /* write pointer to first available slot */
    uint_fast32_t   wp = (rb->start + rb->count) % rb->size;

    /* new write pointer after successful write */
    uint_fast32_t   new_wp = (wp + num) % rb->size;

    if (new_wp > wp)
    {
        /* we can write in a single pass */
        memcpy(&rb->buffer[wp], src, num);
    }
    else
    {
        /* we need to wrap around the end */
        memcpy(&rb->buffer[wp], src, num - new_wp);
        memcpy(rb->buffer, &src[num - new_wp], new_wp);
    }

    /* Update count and check if overwrite has occurred, if yes, adjust
     * count and read pointer (rb->start)
     */
    rb->count += num;
    if (rb->count > rb->size)
    {
        rb->count = rb->size;
        rb->start = new_wp;
    }
}

/**
 * Read data from the riung buffer.
 *
 * @param  rb    The ring buffer handle.
 * @param  dest  Pointer to the preallocated destination buffer.
 * @param  num   The number of elements to read. Must be less than or equal to
 *               @ref rb->count.
 */
static inline void ring_buffer_read(ring_buffer_t * rb, unsigned char *dest,
                                    uint_fast32_t num)
{
    if (!num)
        return;

    /* index of the last value to read */
    uint_fast32_t   end = (rb->start + num - 1) % rb->size;

    if (end < rb->start)
    {
        /* we need to read in two passes */
        uint_fast32_t   split = rb->size - rb->start;

        memcpy(dest, &rb->buffer[rb->start], split);
        memcpy(&dest[split], rb->buffer, end + 1);
    }
    else
    {
        /* can read in a single pass */
        memcpy(dest, &rb->buffer[rb->start], num);
    }

    rb->count -= num;
    rb->start = (end + 1) % rb->size;
}

/**
 * Clear the buffer.
 *
 * @param rb The ring buffer handle.
 *
 * This function will clear the buffer by setting the start and the count to 0.
 */
static inline void ring_buffer_clear(ring_buffer_t * rb)
{
    rb->start = 0;
    rb->count = 0;
}

#endif // __RING_BUFFER_H__


text:
from __future__ import unicode_literals

from django.contrib.auth.models import User

from .base import BaseTest
from ..query import QueryBuilder

class LookupConvertionTest(BaseTest):
    def setUp(self):
        self.batman = User.objects.create_user(username='batman',
                                               email='batman@gotham.us')
        self.joker = User.objects.create_user(username='joker',
                                              email='joker@gotham.us')
        self.builder = QueryBuilder(context={
            'username': self.batman.username,
            'email': self.batman.email,
        })

    def test_process_macros(self):
        lookup_dict = {'username': '%username%',
                       'email': '%email%',
                       'some_field': 'some_value'}

        self.builder.process_macros(lookup_dict)

        self.assertEqual(lookup_dict, {
            'username': 'batman',
            'email': 'batman@gotham.us',
            'some_field': 'some_value'
        })

    def test_convert_lookup_dict_to_Q(self):
        lookup_dict = {'username__startswith': 'bat',
                       'email__endswith': 'us'}

        query = self.builder.convert_lookup_dict_to_Q(lookup_dict)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.batman]
        )

    def test_convert_lookup_dicts_list_to_Q(self):
        lookup_dicts = [
            {'username__startswith': 'bat'},
            {'email__endswith': 'gotham.us'},
        ]
        query = self.builder.convert_lookup_dicts_list_to_Q(lookup_dicts)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.batman, self.joker]
        )

    def test_convert_lookup_dicts_list_to_Q_not_list(self):
        alone_dict = {'username__startswith': 'bat'}

        query = self.builder.convert_lookup_dicts_list_to_Q(alone_dict)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.batman]
        )

    def test_merge_conditions_and_exclusions_to_Q(self):
        lookup_pair = {
            'conditions': [{'email__endswith': 'gotham.us'}],
            'exclusions': [{'username__startswith': 'bat'}],
        }
        query = self.builder.merge_conditions_and_exclusions_to_Q(lookup_pair)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.joker]
        )

    def test_merge_conditions_and_exclusions_to_Q_conditions_only(self):
        lookup_pair = {
            'conditions': [{'email__endswith': 'gotham.us'}],
            'exclusions': None,
        }
        query = self.builder.merge_conditions_and_exclusions_to_Q(lookup_pair)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.batman, self.joker]
        )

    def test_merge_conditions_and_exclusions_to_Q_exclusions_only(self):
        lookup_pair = {
            'conditions': None,
            'exclusions': [{'username__startswith': 'bat'}],
        }

        query = self.builder.merge_conditions_and_exclusions_to_Q(lookup_pair)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.joker]
        )

    def test_convert_lookups_to_Q(self):
        lookups = [{
            'conditions': [{'username__startswith': 'batman'}],
            'exclusions': [{'email__startswith': 'j'}],
        },{
            'conditions': [{'username__startswith': 'joker'}],
            'exclusions': None,
        }]

        query = self.builder.convert_lookups_to_Q(lookups)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.batman, self.joker]
        )

    def test_convert_lookups_to_Q_with_blank_filters(self):
        lookups = [{
            'conditions': [{'username__startswith': 'batman'}],
            'exclusions': [{'email__startswith': 'j'}],
        },{
            'conditions': None,
            'exclusions': None,
        }]

        query = self.builder.convert_lookups_to_Q(lookups)

        self.assertQuerysetEqualsList(
            User.objects.filter(query),
            [self.batman]
        )


text:
package orm

import (
	"reflect"
)

// model to model struct
type queryM2M struct {
	md  interface{}
	mi  *modelInfo
	fi  *fieldInfo
	qs  *querySet
	ind reflect.Value
}

// add models to origin models when creating queryM2M.
// example:
// 	m2m := orm.QueryM2M(post,"Tag")
// 	m2m.Add(&Tag1{},&Tag2{})
//  for _,tag := range post.Tags{}
//
// make sure the relation is defined in post model struct tag.
func (o *queryM2M) Add(mds ...interface{}) (int64, error) {
	fi := o.fi
	mi := fi.relThroughModelInfo
	mfi := fi.reverseFieldInfo
	rfi := fi.reverseFieldInfoTwo

	orm := o.qs.orm
	dbase := orm.alias.DbBaser

	var models []interface{}
	var other_values []interface{}
	var other_names []string

	for _, colname := range mi.fields.dbcols {
		if colname != mfi.column && colname != rfi.column && colname != fi.mi.fields.pk.column {
			other_names = append(other_names, colname)
		}
	}
	for i, md := range mds {
		if reflect.Indirect(reflect.ValueOf(md)).Kind() != reflect.Struct && i > 0 {
			other_values = append(other_values, md)
			mds = append(mds[:i], mds[i+1:]...)
		}
	}
	for _, md := range mds {
		val := reflect.ValueOf(md)
		if val.Kind() == reflect.Slice || val.Kind() == reflect.Array {
			for i := 0; i < val.Len(); i++ {
				v := val.Index(i)
				if v.CanInterface() {
					models = append(models, v.Interface())
				}
			}
		} else {
			models = append(models, md)
		}
	}

	_, v1, exist := getExistPk(o.mi, o.ind)
	if exist == false {
		panic(ErrMissPK)
	}

	names := []string{mfi.column, rfi.column}

	values := make([]interface{}, 0, len(models)*2)
	for _, md := range models {

		ind := reflect.Indirect(reflect.ValueOf(md))
		var v2 interface{}
		if ind.Kind() != reflect.Struct {
			v2 = ind.Interface()
		} else {
			_, v2, exist = getExistPk(fi.relModelInfo, ind)
			if exist == false {
				panic(ErrMissPK)
			}
		}
		values = append(values, v1, v2)

	}
	names = append(names, other_names...)
	values = append(values, other_values...)
	return dbase.InsertValue(orm.db, mi, true, names, values)
}

// remove models following the origin model relationship
func (o *queryM2M) Remove(mds ...interface{}) (int64, error) {
	fi := o.fi
	qs := o.qs.Filter(fi.reverseFieldInfo.name, o.md)

	nums, err := qs.Filter(fi.reverseFieldInfoTwo.name+ExprSep+"in", mds).Delete()
	if err != nil {
		return nums, err
	}
	return nums, nil
}

// check model is existed in relationship of origin model
func (o *queryM2M) Exist(md interface{}) bool {
	fi := o.fi
	return o.qs.Filter(fi.reverseFieldInfo.name, o.md).
		Filter(fi.reverseFieldInfoTwo.name, md).Exist()
}

// clean all models in related of origin model
func (o *queryM2M) Clear() (int64, error) {
	fi := o.fi
	return o.qs.Filter(fi.reverseFieldInfo.name, o.md).Delete()
}

// count all related models of origin model
func (o *queryM2M) Count() (int64, error) {
	fi := o.fi
	return o.qs.Filter(fi.reverseFieldInfo.name, o.md).Count()
}

var _ QueryM2Mer = new(queryM2M)

// create new M2M queryer.
func newQueryM2M(md interface{}, o *orm, mi *modelInfo, fi *fieldInfo, ind reflect.Value) QueryM2Mer {
	qm2m := new(queryM2M)
	qm2m.md = md
	qm2m.mi = mi
	qm2m.fi = fi
	qm2m.ind = ind
	qm2m.qs = newQuerySet(o, fi.relThroughModelInfo).(*querySet)
	return qm2m
}


text:
using Examine;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Umbraco.Cms.Infrastructure.Examine;
using Umbraco.Cms.ManagementApi.Factories;
using Umbraco.Cms.ManagementApi.ViewModels.ExamineManagement;
using Umbraco.Cms.ManagementApi.ViewModels.Pagination;
using Umbraco.Extensions;

namespace Umbraco.Cms.ManagementApi.Controllers.ExamineManagement;

[ApiVersion("1.0")]
public class IndexesExamineManagementController : ExamineManagementControllerBase
{
    private readonly IExamineManager _examineManager;
    private readonly IExamineIndexViewModelFactory _examineIndexViewModelFactory;

    public IndexesExamineManagementController(
        IExamineManager examineManager,
        IExamineIndexViewModelFactory examineIndexViewModelFactory)
    {
        _examineManager = examineManager;
        _examineIndexViewModelFactory = examineIndexViewModelFactory;
    }

    /// <summary>
    ///     Get the details for indexers
    /// </summary>
    /// <returns></returns>
    [HttpGet("indexes")]
    [MapToApiVersion("1.0")]
    [ProducesResponseType(typeof(PagedViewModel<ExamineIndexViewModel>), StatusCodes.Status200OK)]
    public async Task<PagedViewModel<ExamineIndexViewModel>> Indexes(int skip, int take)
    {
        ExamineIndexViewModel[] indexes = _examineManager.Indexes
            .Select(_examineIndexViewModelFactory.Create)
            .OrderBy(examineIndexModel => examineIndexModel.Name?.TrimEnd("Indexer")).ToArray();

        var viewModel = new PagedViewModel<ExamineIndexViewModel> { Items = indexes.Skip(skip).Take(take), Total = indexes.Length };
        return viewModel;
    }
}


text:
module ErrorTracking
  class ListIssuesService < ::BaseService
    DEFAULT_ISSUE_STATUS = 'unresolved'
    DEFAULT_LIMIT = 20

    def execute
      return error('not enabled') unless enabled?
      return error('access denied') unless can_read?

      result = project_error_tracking_setting
        .list_sentry_issues(issue_status: issue_status, limit: limit)

      # our results are not yet ready
      unless result
        return error('not ready', :no_content)
      end

      success(issues: result[:issues])
    end

    def external_url
      project_error_tracking_setting&.sentry_external_url
    end

    private

    def project_error_tracking_setting
      project.error_tracking_setting
    end

    def issue_status
      params[:issue_status] || DEFAULT_ISSUE_STATUS
    end

    def limit
      params[:limit] || DEFAULT_LIMIT
    end

    def enabled?
      project_error_tracking_setting&.enabled?
    end

    def can_read?
      can?(current_user, :read_sentry_issue, project)
    end
  end
end


text:
package org.usfirst.frc620.Warbot2017.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class BlueBalls extends CommandGroup {

    public BlueBalls() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
    }
}


text:
<?php

namespace WebPlatform\AseagleBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class CompanyCertificationControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'seller{seller_id}/company_certification');
    }

    public function testNew()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'seller/{seller_id}/company_certification/new');
    }

    public function testEdit()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'seller/{seller_id}/company_certification/{id}/edit');
    }

    public function testDestroy()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', 'seller/{seller_id}/company_certification/{id}/destroy');
    }

}


text:
import os
import datetime

import tabulate
from modularodm import Q
from dateutil.relativedelta import relativedelta

from website import settings
from website.models import User, PrivateLink
from website.addons.dropbox.model import DropboxUserSettings

from scripts.analytics import profile, tabulate_emails

def get_active_users():
    return User.find(
        Q('is_registered', 'eq', True) &
        Q('password', 'ne', None) &
        Q('is_merged', 'ne', True) &
        Q('date_confirmed', 'ne', None)
    )

def get_dropbox_metrics():
    metrics = {
        'enabled': [],
        'authorized': [],
        'linked': [],
    }
    for node_settings in DropboxUserSettings.find():
        metrics['enabled'].append(node_settings)
        if node_settings.has_auth:
            metrics['authorized'].append(node_settings)
        if node_settings.nodes_authorized:
            metrics['linked'].append(node_settings)
    return metrics

def get_private_links():
    return PrivateLink.find(
        Q('is_deleted', 'ne', True)
    )

def count_user_nodes(users=None):
    users = users or get_active_users()
    return [
        len(
            user.node__contributed.find(
                Q('is_deleted', 'eq', False) &
                Q('is_folder', 'ne', True)
            )
        )
        for user in users
    ]

def count_user_logs(user, query=None):
    if query:
        return len(user.nodelog__created.find(query))
    return len(user.nodelog__created)

def count_users_logs(users=None, query=None):
    users = users or get_active_users()
    return [
        count_user_logs(user, query)
        for user in users
    ]

def count_at_least(counts, at_least):
    return len([
        count for count in counts
        if count >= at_least
    ])

def main():
    active_users = get_active_users()
    dropbox_metrics = get_dropbox_metrics()
    extended_profile_counts = profile.get_profile_counts()
    private_links = get_private_links()

    node_counts = count_user_nodes(active_users)
    nodes_at_least_1 = count_at_least(node_counts, 1)
    nodes_at_least_3 = count_at_least(node_counts, 3)

    log_counts = count_users_logs(active_users)
    logs_at_least_1 = count_at_least(log_counts, 1)
    logs_at_least_11 = count_at_least(log_counts, 11)

    log_counts_3months = count_users_logs(
        active_users,
        Q('date', 'gte', datetime.datetime.now() - relativedelta(months=3)),
    )
    logs_at_least_1_3months = count_at_least(log_counts_3months, 1)
    logs_at_least_11_3months = count_at_least(log_counts_3months, 11)

    table = tabulate.tabulate(
        [
            ['active-users', active_users.count()],
            ['dropbox-users-enabled', len(dropbox_metrics['enabled'])],
            ['dropbox-users-authorized', len(dropbox_metrics['authorized'])],
            ['dropbox-users-linked', len(dropbox_metrics['linked'])],
            ['profile-edits', extended_profile_counts['any']],
            ['view-only-links', private_links.count()],
            ['nodes-gte-1', nodes_at_least_1],
            ['nodes-gte-3', nodes_at_least_3],
            ['logs-gte-1', logs_at_least_1],
            ['logs-gte-11', logs_at_least_11],
            ['logs-gte-1-last-3m', logs_at_least_1_3months],
            ['logs-gte-11-last-3m', logs_at_least_11_3months],
        ],
        headers=['label', 'value']
    )

    with open(os.path.join(settings.ANALYTICS_PATH, 'main.txt'), 'w') as fp:
        fp.write(table)

    tabulate_emails.main()

if __name__ == '__main__':
    main()


text:
from panda3d.core import *
from panda3d.direct import *
from direct.interval.IntervalGlobal import *
from toontown.battle.BattleProps import *
from GoonGlobals import *
from direct.fsm import FSM
from direct.distributed import ClockDelta
from otp.level import BasicEntities
from otp.level import DistributedEntity
from direct.directnotify import DirectNotifyGlobal
from toontown.coghq import DistributedCrushableEntity
from toontown.toonbase import ToontownGlobals
from toontown.coghq import MovingPlatform
import Goon
from direct.task.Task import Task
from otp.level import PathEntity
import GoonDeath
import random

class DistributedGoon(DistributedCrushableEntity.DistributedCrushableEntity, Goon.Goon, FSM.FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory('DistributedGoon')

    def __init__(self, cr):
        try:
            self.DistributedGoon_initialized
        except:
            self.DistributedGoon_initialized = 1
            DistributedCrushableEntity.DistributedCrushableEntity.__init__(self, cr)
            Goon.Goon.__init__(self)
            FSM.FSM.__init__(self, 'DistributedGoon')

        self.setCacheable(0)
        self.rayNode = None
        self.checkForWalls = 0
        self.triggerEvent = None
        self.animTrack = None
        self.walkTrack = None
        self.pauseTime = 0
        self.paused = 0
        self.path = None
        self.dir = GOON_FORWARD
        self.animMultiplier = 1.0
        self.isDead = 0
        self.isStunned = 0
        self.collapseSound = loader.loadSfx('phase_9/audio/sfx/CHQ_GOON_hunker_down.ogg')
        self.recoverSound = loader.loadSfx('phase_9/audio/sfx/CHQ_GOON_rattle_shake.ogg')
        self.attackSound = loader.loadSfx('phase_9/audio/sfx/CHQ_GOON_tractor_beam_alarmed.ogg')
        return

    def announceGenerate(self):
        DistributedCrushableEntity.DistributedCrushableEntity.announceGenerate(self)
        if hasattr(self, 'goonType'):
            self.initGoon(self.goonType)
        else:
            self.initGoon('pg')
        self.scaleRadar()
        self.colorHat()
        if self.level:
            self.initClipPlanes()
            self.level.setEntityCreateCallback(self.parentEntId, self.initPath)
        else:
            self.enterOff()
            taskMgr.doMethodLater(0.1, self.makeCollidable, self.taskName('makeCollidable'))
        self.setGoonScale(self.scale)
        self.animMultiplier = self.velocity / (ANIM_WALK_RATE * self.scale)
        self.setPlayRate(self.animMultiplier, 'walk')

    def initPath(self):
        self.enterOff()
        self.setPath()
        taskMgr.doMethodLater(0.1, self.makeCollidable, self.taskName('makeCollidable'))

    def makeCollidable(self, task):
        self.initCollisions()
        self.initializeBodyCollisions()
        triggerName = self.uniqueName('GoonTrigger')
        self.trigger.setName(triggerName)
        self.triggerEvent = 'enter%s' % triggerName
        self.startToonDetect()

    def generate(self):
        DistributedCrushableEntity.DistributedCrushableEntity.generate(self)

    def scaleRadar(self):
        Goon.Goon.scaleRadar(self)
        self.trigger = self.radar.find('**/trigger')
        triggerName = self.uniqueName('GoonTrigger')
        self.trigger.setName(triggerName)

    def initCollisions(self):
        self.cSphere = CollisionSphere(0.0, 0.0, 1.0, 1.0)
        self.cSphereNode = CollisionNode('goonCollSphere')
        self.cSphereNode.addSolid(self.cSphere)
        self.cSphereNodePath = self.head.attachNewNode(self.cSphereNode)
        self.cSphereNodePath.hide()
        self.cSphereBitMask = ToontownGlobals.WallBitmask
        self.cSphereNode.setCollideMask(self.cSphereBitMask)
        self.cSphere.setTangible(1)
        self.sSphere = CollisionSphere(0.0, 0.0, self.headHeight + 0.8, 1.2)
        self.sSphereNode = CollisionNode('toonSphere')
        self.sSphereNode.addSolid(self.sSphere)
        self.sSphereNodePath = self.head.attachNewNode(self.sSphereNode)
        self.sSphereNodePath.hide()
        self.sSphereBitMask = ToontownGlobals.WallBitmask
        self.sSphereNode.setCollideMask(self.sSphereBitMask)
        self.sSphere.setTangible(1)

    def initializeBodyCollisions(self):
        self.cSphereNode.setName(self.uniqueName('goonCollSphere'))
        self.sSphereNode.setName(self.uniqueName('toonSphere'))
        self.accept(self.uniqueName('entertoonSphere'), self.__handleStun)

    def disableBodyCollisions(self):
        self.ignore(self.uniqueName('entertoonSphere'))

    def deleteCollisions(self):
        if hasattr(self, 'sSphereNodePath'):
            self.sSphereNodePath.removeNode()
            del self.sSphereNodePath
            del self.sSphereNode
            del self.sSphere
        if hasattr(self, 'cSphereNodePath'):
            self.cSphereNodePath.removeNode()
            del self.cSphereNodePath
            del self.cSphereNode
            del self.cSphere

    def initClipPlanes(self):
        zoneNum = self.getZoneEntity().getZoneNum()
        clipList = self.level.goonClipPlanes.get(zoneNum)
        if clipList:
            for id in clipList:
                clipPlane = self.level.getEntity(id)
                self.radar.setClipPlane(clipPlane.getPlane())

    def disableClipPlanes(self):
        if self.radar:
            self.radar.clearClipPlane()

    if __dev__:

        def refreshPath(self):
            self.setPath()
            self.request('Off')
            self.request('Walk')

    def setPath(self):
        self.path = self.level.getEntity(self.parentEntId)
        if __dev__:
            if hasattr(self, 'pathChangeEvent'):
                self.ignore(self.pathChangeEvent)
            self.pathChangeEvent = self.path.getChangeEvent()
            self.accept(self.pathChangeEvent, self.refreshPath)
        if self.walkTrack:
            self.walkTrack.pause()
            self.walkTrack = None
        self.walkTrack = self.path.makePathTrack(self, self.velocity, self.uniqueName('goonWalk'), turnTime=T_TURN)
        if self.gridId != None:
            self.sendUpdate('setParameterize', [self.path.pos[0],
             self.path.pos[1],
             self.path.pos[2],
             self.path.pathIndex])
        return

    def disable(self):
        self.notify.debug('DistributedGoon %d: disabling' % self.getDoId())
        self.ignoreAll()
        self.stopToonDetect()
        taskMgr.remove(self.taskName('resumeWalk'))
        taskMgr.remove(self.taskName('recoveryDone'))
        self.request('Off')
        self.disableBodyCollisions()
        self.disableClipPlanes()
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        if self.walkTrack:
            self.walkTrack.pause()
            self.walkTrack = None
        DistributedCrushableEntity.DistributedCrushableEntity.disable(self)
        return

    def delete(self):
        try:
            self.DistributedSuit_deleted
        except:
            self.DistributedSuit_deleted = 1
            self.notify.debug('DistributedGoon %d: deleting' % self.getDoId())
            taskMgr.remove(self.taskName('makeCollidable'))
            self.deleteCollisions()
            self.head.removeNode()
            del self.head
            del self.attackSound
            del self.collapseSound
            del self.recoverSound
            DistributedCrushableEntity.DistributedCrushableEntity.delete(self)
            Goon.Goon.delete(self)

    def enterOff(self, *args):
        self.hideNametag3d()
        self.hideNametag2d()
        self.hide()
        self.isStunned = 0
        self.isDead = 0
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        if self.walkTrack:
            self.walkTrack.pause()
            self.walkTrack = None
        return

    def exitOff(self):
        self.show()
        self.showNametag3d()
        self.showNametag2d()

    def enterWalk(self, avId = None, ts = 0):
        self.notify.debug('enterWalk, ts = %s' % ts)
        self.startToonDetect()
        self.loop('walk', 0)
        self.isStunned = 0
        if self.path:
            if not self.walkTrack:
                self.walkTrack = self.path.makePathTrack(self, self.velocity, self.uniqueName('goonWalk'), turnTime=T_TURN)
            self.startWalk(ts)

    def startWalk(self, ts):
        tOffset = ts % self.walkTrack.getDuration()
        self.walkTrack.loop()
        self.walkTrack.pause()
        self.walkTrack.setT(tOffset)
        self.walkTrack.resume()
        self.paused = 0

    def exitWalk(self):
        self.notify.debug('exitWalk')
        self.stopToonDetect()
        if self.walkTrack and not self.paused:
            self.pauseTime = self.walkTrack.pause()
            self.paused = 1
        self.stop()

    def enterBattle(self, avId = None, ts = 0):
        self.notify.debug('enterBattle')
        self.stopToonDetect()
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        self.isStunned = 0
        if avId == base.localAvatar.doId:
            if self.level:
                self.level.b_setOuch(self.strength)
        self.animTrack = self.makeAttackTrack()
        self.animTrack.loop()
        return

    def exitBattle(self):
        self.notify.debug('exitBattle')
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        self.head.setHpr(0, 0, 0)
        return

    def enterStunned(self, ts = 0):
        self.ignore(self.uniqueName('entertoonSphere'))
        self.isStunned = 1
        self.notify.debug('enterStunned')
        if self.radar:
            self.radar.hide()
        self.animTrack = Parallel(Sequence(ActorInterval(self, 'collapse'), Func(self.pose, 'collapse', 48)), SoundInterval(self.collapseSound, node=self))
        self.animTrack.start(ts)

    def exitStunned(self):
        self.notify.debug('exitStunned')
        if self.radar:
            self.radar.show()
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        self.accept(self.uniqueName('entertoonSphere'), self.__handleStun)
        return

    def enterRecovery(self, ts = 0, pauseTime = 0):
        self.notify.debug('enterRecovery')
        self.ignore(self.uniqueName('entertoonSphere'))
        self.isStunned = 1
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        self.animTrack = self.getRecoveryTrack()
        duration = self.animTrack.getDuration()
        self.animTrack.start(ts)
        delay = max(0, duration - ts)
        taskMgr.remove(self.taskName('recoveryDone'))
        taskMgr.doMethodLater(delay, self.recoveryDone, self.taskName('recoveryDone'), extraArgs=(pauseTime,))
        return

    def getRecoveryTrack(self):
        return Parallel(Sequence(ActorInterval(self, 'recovery'), Func(self.pose, 'recovery', 96)), Func(base.playSfx, self.recoverSound, node=self))

    def recoveryDone(self, pauseTime):
        self.request('Walk', None, pauseTime)
        return

    def exitRecovery(self):
        self.notify.debug('exitRecovery')
        taskMgr.remove(self.taskName('recoveryDone'))
        if self.animTrack:
            self.animTrack.finish()
            self.animTrack = None
        self.accept(self.uniqueName('entertoonSphere'), self.__handleStun)
        return

    def makeAttackTrack(self):
        h = self.head.getH()
        freakDeg = 60
        hatZ = self.hat.getZ()
        track = Parallel(Sequence(LerpColorScaleInterval(self.eye, 0.2, Vec4(1, 0, 0, 1)), LerpColorScaleInterval(self.eye, 0.2, Vec4(0, 0, 1, 1)), LerpColorScaleInterval(self.eye, 0.2, Vec4(1, 0, 0, 1)), LerpColorScaleInterval(self.eye, 0.2, Vec4(0, 0, 1, 1)), Func(self.eye.clearColorScale)), SoundInterval(self.attackSound, node=self, volume=0.4))
        return track

    def doDetect(self):
        pass

    def doAttack(self, avId):
        pass

    def __startResumeWalkTask(self, ts):
        resumeTime = 1.5
        if ts < resumeTime:
            taskMgr.remove(self.taskName('resumeWalk'))
            taskMgr.doMethodLater(resumeTime - ts, self.request, self.taskName('resumeWalk'), extraArgs=('Walk',))
        else:
            self.request('Walk', ts - resumeTime)

    def __reverseWalk(self, task):
        self.request('Walk')
        return Task.done

    def __startRecoverTask(self, ts):
        stunTime = 4.0
        if ts < stunTime:
            taskMgr.remove(self.taskName('resumeWalk'))
            taskMgr.doMethodLater(stunTime - ts, self.request, self.taskName('resumeWalk'), extraArgs=('Recovery',))
        else:
            self.request('Recovery', ts - stunTime)

    def startToonDetect(self):
        self.radar.show()
        if self.triggerEvent:
            self.accept(self.triggerEvent, self.handleToonDetect)

    def stopToonDetect(self):
        if self.triggerEvent:
            self.ignore(self.triggerEvent)

    def handleToonDetect(self, collEntry = None):
        if base.localAvatar.isStunned:
            return
        if self.state == 'Off':
            return
        self.stopToonDetect()
        self.request('Battle', base.localAvatar.doId)
        if self.walkTrack:
            self.pauseTime = self.walkTrack.pause()
            self.paused = 1
        if self.dclass and hasattr(self, 'dclass'):
            self.sendUpdate('requestBattle', [self.pauseTime])
        else:
            self.notify.info('Goon deleted and still trying to call handleToonDetect()')

    def __handleStun(self, collEntry):
        toon = base.localAvatar
        if toon:
            toonDistance = self.getPos(toon).length()
            if toonDistance > self.attackRadius:
                self.notify.warning('Stunned a good, but outside of attack radius')
                return
            else:
                self.request('Stunned')
        if self.walkTrack:
            self.pauseTime = self.walkTrack.pause()
            self.paused = 1
        self.sendUpdate('requestStunned', [self.pauseTime])

    def setMovie(self, mode, avId, pauseTime, timestamp):
        if self.isDead:
            return
        ts = ClockDelta.globalClockDelta.localElapsedTime(timestamp)
        self.notify.debug('%s: setMovie(%s,%s,%s,%s)' % (self.doId,
         mode,
         avId,
         pauseTime,
         ts))
        if mode == GOON_MOVIE_BATTLE:
            if self.state != 'Battle':
                self.request('Battle', avId, ts)
        elif mode == GOON_MOVIE_STUNNED:
            if self.state != 'Stunned':
                toon = base.cr.doId2do.get(avId)
                if toon:
                    toonDistance = self.getPos(toon).length()
                    if toonDistance > self.attackRadius:
                        self.notify.warning('Stunned a goon, but outside of attack radius')
                        return
                    else:
                        self.request('Stunned', ts)
        elif mode == GOON_MOVIE_RECOVERY:
            if self.state != 'Recovery':
                self.request('Recovery', ts, pauseTime)
        elif mode == GOON_MOVIE_SYNC:
            if self.walkTrack:
                self.walkTrack.pause()
                self.paused = 1
            if self.state == 'Off' or self.state == 'Walk':
                self.request('Walk', avId, pauseTime + ts)
        else:
            if self.walkTrack:
                self.walkTrack.pause()
                self.walkTrack = None
            self.request('Walk', avId, pauseTime + ts)
        return

    def stunToon(self, avId):
        self.notify.debug('stunToon(%s)' % avId)
        av = base.cr.doId2do.get(avId)
        if av != None:
            av.stunToon()
        return

    def isLocalToon(self, avId):
        if avId == base.localAvatar.doId:
            return 1
        return 0

    def playCrushMovie(self, crusherId, axis):
        goonPos = self.getPos()
        sx = random.uniform(0.3, 0.8) * self.scale
        sz = random.uniform(0.3, 0.8) * self.scale
        crushTrack = Sequence(GoonDeath.createGoonExplosion(self.getParent(), goonPos, VBase3(sx, 1, sz)), name=self.uniqueName('crushTrack'), autoFinish=1)
        self.dead()
        crushTrack.start()

    def setVelocity(self, velocity):
        self.velocity = velocity
        self.animMultiplier = velocity / (ANIM_WALK_RATE * self.scale)
        self.setPlayRate(self.animMultiplier, 'walk')

    def dead(self):
        if not self.isDead and not self.isDisabled():
            self.stopToonDetect()
            self.detachNode()
            self.isDead = 1

    def undead(self):
        if self.isDead:
            self.startToonDetect()
            self.reparentTo(render)
            self.isDead = 0

    def resync(self):
        if not self.isDead:
            self.sendUpdate('requestResync')

    def setHFov(self, hFov):
        if hFov != self.hFov:
            self.hFov = hFov
            if self.isGenerated():
                self.scaleRadar()

    def setAttackRadius(self, attackRadius):
        if attackRadius != self.attackRadius:
            self.attackRadius = attackRadius
            if self.isGenerated():
                self.scaleRadar()

    def setStrength(self, strength):
        if strength != self.strength:
            self.strength = strength
            if self.isGenerated():
                self.colorHat()

    def setGoonScale(self, scale):
        if scale != self.scale:
            self.scale = scale
            if self.isGenerated():
                self.getGeomNode().setScale(self.scale)
                self.scaleRadar()

    def setupGoon(self, velocity, hFov, attackRadius, strength, scale):
        self.setVelocity(velocity)
        self.setHFov(hFov)
        self.setAttackRadius(attackRadius)
        self.setStrength(strength)
        self.setGoonScale(scale)


text:
<?php

namespace Seboettg\CiteProc\Style;

use Seboettg\CiteProc\Data\DataList;
use Seboettg\CiteProc\Exception\CiteProcException;
use Seboettg\CiteProc\Rendering\HasParent;
use Seboettg\CiteProc\Rendering\Rendering;
use Seboettg\CiteProc\Root\Root;
use Seboettg\CiteProc\Styles\ConsecutivePunctuationCharacterTrait;
use Seboettg\CiteProc\Util\Factory;
use Seboettg\Collection\ArrayList;
use SimpleXMLElement;

/**
 * Class Macro
 *
 * Macros, defined with cs:macro elements, contain formatting instructions. Macros can be called with cs:text from
 * within other macros and the cs:layout element of cs:citation and cs:bibliography, and with cs:key from within cs:sort
 * of cs:citation and cs:bibliography. It is recommended to place macros after any cs:locale elements and before the
 * cs:citation element.
 *
 * Macros are referenced by the value of the required name attribute on cs:macro. The cs:macro element must contain one
 * or more rendering elements.
 *
 * @package Seboettg\CiteProc\Rendering
 *
 * @author Sebastian Böttger <seboettg@gmail.com>
 */
class Macro implements Rendering, HasParent
{
    use ConsecutivePunctuationCharacterTrait;

    /**
     * @var ArrayList
     */
    private $children;

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

    /**
     * @var Root
     */
    private $parent;
    /**
     * Macro constructor.
     * @param SimpleXMLElement $node
     * @param Root $parent
     * @throws CiteProcException
     */
    public function __construct(SimpleXMLElement $node, $parent)
    {
        $this->parent = $parent;
        $attr = $node->attributes();
        if (!isset($attr['name'])) {
            throw new CiteProcException("Attribute \"name\" needed.");
        }
        $this->name = (string) $attr['name'];

        $this->children = new ArrayList();
        foreach ($node->children() as $child) {
            $this->children->append(Factory::create($child, $this));
        }
    }

    /**
     * @param array|DataList $data
     * @param int|null $citationNumber
     * @return string
     */
    public function render($data, $citationNumber = null)
    {
        $ret = [];
        /** @var Rendering $child */
        foreach ($this->children as $child) {
            $res = $child->render($data, $citationNumber);
            $this->getChildrenAffixesAndDelimiter($child);
            if (!empty($res)) {
                $ret[] = $res;
            }
        }
        $res = implode("", $ret);
        if (!empty($res)) {
            $res = $this->removeConsecutiveChars($res);
        }
        return $res;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return Root
     */
    public function getParent()
    {
        return $this->parent;
    }
}


text:
<?php

declare(strict_types=1);

namespace spec\Zlikavac32\Rick\Collector;

use PhpSpec\ObjectBehavior;
use Zlikavac32\Rick\Collector\AndPathMatcher;
use Zlikavac32\Rick\Collector\ArrayPrefixPathMatcher;
use Zlikavac32\Rick\Collector\DefaultSkipPathMatcherFactory;
use Zlikavac32\Rick\Collector\ExtensionPathMatcher;
use Zlikavac32\Rick\Collector\InvertedPathMatcher;
use Zlikavac32\Rick\Collector\IsDirPathMatcher;
use Zlikavac32\Rick\Collector\OrPathMatcher;

class DefaultSkipPathMatcherFactorySpec extends ObjectBehavior
{
    public function it_is_initializable(): void
    {
        $this->shouldHaveType(DefaultSkipPathMatcherFactory::class);
    }

    public function it_should_construct_valid_object(): void
    {
        $this->create(
            [
                'first-path',
                'second-path',
            ],
            [
                '.f',
                '.s',
            ]
        )
            ->shouldBeLike(
                new OrPathMatcher(
                    new AndPathMatcher(
                        new InvertedPathMatcher(new IsDirPathMatcher()),
                        new InvertedPathMatcher(new ExtensionPathMatcher('.f', '.s'))
                    ),
                    new ArrayPrefixPathMatcher('first-path', 'second-path')
                )
            );
    }
}


text:
@class DBFILESDimensions;
@class DBFILESGpsCoordinates;
@class DBFILESPhotoMetadata;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - API Object

///
/// The `PhotoMetadata` struct.
///
/// Metadata for a photo.
///
/// This class implements the `DBSerializable` protocol (serialize and
/// deserialize instance methods), which is required for all Obj-C SDK API route
/// objects.
///
@interface DBFILESPhotoMetadata : DBFILESMediaMetadata <DBSerializable, NSCopying>

#pragma mark - Instance fields

#pragma mark - Constructors

///
/// Full constructor for the struct (exposes all instance variables).
///
/// @param dimensions Dimension of the photo/video.
/// @param location The GPS coordinate of the photo/video.
/// @param timeTaken The timestamp when the photo/video is taken.
///
/// @return An initialized instance.
///
- (instancetype)initWithDimensions:(nullable DBFILESDimensions *)dimensions
                          location:(nullable DBFILESGpsCoordinates *)location
                         timeTaken:(nullable NSDate *)timeTaken;

///
/// Convenience constructor (exposes only non-nullable instance variables with
/// no default value).
///
///
/// @return An initialized instance.
///
- (instancetype)initDefault;

@end

#pragma mark - Serializer Object

///
/// The serialization class for the `PhotoMetadata` struct.
///
@interface DBFILESPhotoMetadataSerializer : NSObject

///
/// Serializes `DBFILESPhotoMetadata` instances.
///
/// @param instance An instance of the `DBFILESPhotoMetadata` API object.
///
/// @return A json-compatible dictionary representation of the
/// `DBFILESPhotoMetadata` API object.
///
+ (nullable NSDictionary<NSString *, id> *)serialize:(DBFILESPhotoMetadata *)instance;

///
/// Deserializes `DBFILESPhotoMetadata` instances.
///
/// @param dict A json-compatible dictionary representation of the
/// `DBFILESPhotoMetadata` API object.
///
/// @return An instantiation of the `DBFILESPhotoMetadata` object.
///
+ (DBFILESPhotoMetadata *)deserialize:(NSDictionary<NSString *, id> *)dict;

@end

NS_ASSUME_NONNULL_END


text:
INCLUDE_DIRECTORIES("${CMAKE_SOURCE_DIR}/third-party/sqlite3")
ADD_SUBDIRECTORY("${CMAKE_SOURCE_DIR}/third-party/sqlite3")


text:
package loadbalancer

import "github.com/sacloud/libsacloud/v2/sacloud"

// Service provides a high-level API of for LoadBalancer
type Service struct {
	caller sacloud.APICaller
}

// New returns new service instance of LoadBalancer
func New(caller sacloud.APICaller) *Service {
	return &Service{caller: caller}
}


text: require "rom/http"


text:
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}

module V1.Api (Api, server) where

import Servant
import qualified V1.Projects.Api as Projects (Api, server)

type Api = "projects" :> Projects.Api

server :: Server Api
server = Projects.server


text:
import { action, observable } from 'mobx';

import { GetCurrentLoginInformations } from '../services/session/dto/getCurrentLoginInformations';
import sessionService from '../services/session/sessionService';

class SessionStore {
  @observable currentLogin: GetCurrentLoginInformations = new GetCurrentLoginInformations();

  @action
  async getCurrentLoginInformations() {
    let result = await sessionService.getCurrentLoginInformations();
    this.currentLogin = result;
  }
}

export default SessionStore;


text:
'use strict';
let passport = require('passport');
let BearerStrategy = require('passport-http-bearer');

module.exports = {
  configure: function() {
    let User = require('mongoose').model('User');

    passport.use(new BearerStrategy(
      function(token, done) {
        User.findOne({
          token: token
        }, function(err, user) {
          if (err) {
            return done(err);
          }

          if (!user) {
            return done(null, false);
          }

          return done(null, user, {
            scope: 'all'
          });
        });
      }
    ));
  }
};


text:
require 'spec_helper'

module Notify
  describe Receiver do

    let(:notification_class) { class ::FooNotification; extend Notification; end }
    after { Object.send(:remove_const, :FooNotification) if Object.constants.include?(:FooNotification) }

    let(:receiver_class) do
      class FooReceiver
        def self.has_many(*args); end
        include Receiver
      end
    end
    after { Notify.send(:remove_const, :FooReceiver) if Notify.constants.include?(:FooReceiver) }

    describe '#notify' do
      subject { receiver_class.new }

      it 'calls create on the notification_class' do
        expect(notification_class).to receive(:create).with(subject, {})
        subject.notify :foo
      end

      it 'passes the rules on to the create method' do
        rules = { foo: :bar }
        expect(notification_class).to receive(:create).with(subject, rules)
        subject.notify :foo, rules
      end

    end
  end
end