text:
<?php

/*
* This file is part of the MilioooFriendsBundle package.
*
* (c) Michiel boeckaert <boeckaert@gmail.com>
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/

namespace Miliooo\FriendsBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Miliooo\Friends\Model\RelationshipInterface;
use Miliooo\Friends\Repository\RelationshipRepositoryInterface;
use Miliooo\Friends\User\UserIdentifierInterface;
use Miliooo\Friends\ValueObjects\UserRelationship;

/**
 * Doctrine orm Implementation of the relationship repository interface
 *
 * @author Michiel Boeckaert <boeckaert@gmail.com>
 */
class RelationshipRepository extends EntityRepository implements RelationshipRepositoryInterface
{
    /**
     * {@inheritdoc}
     */
    public function findRelationship(UserRelationship $userRelationship)
    {
        return $this->findOneBy(
            [
                'follower' => $userRelationship->getFollower(),
                'followed' => $userRelationship->getFollowed()
            ]
        );
    }

    /**
     * {@inheritdoc}
     */
    public function saveRelationship(RelationshipInterface $relationship, $flush = true)
    {
        $em = $this->getEntityManager();
        $em->persist($relationship);

        if ($flush) {
            $em->flush();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function deleteRelationship(RelationshipInterface $relationship, $flush = true)
    {
        $em = $this->getEntityManager();
        $em->remove($relationship);

        if ($flush) {
            $em->flush();
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getFollowing(UserIdentifierInterface $user)
    {
        return $this->findBy(['follower' => $user]);
    }

    /**
     * {@inheritdoc}
     */
    public function getFollowers(UserIdentifierInterface $user)
    {
        return $this->findBy(['followed' => $user]);
    }
}


text:
DATA_DIR=~/Documents/graphhopper/core

tar -cvjf itnfull.tar.bz2 -C ~/Documents/graphhopper/core itn-gh

redpajama_set_name: RedPajamaGithub


text:
package ripo

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"
)

var FromForm FromX = &fromForm{}

type fromForm struct{}

func (f *fromForm) GetString(req ExtendedRequest, key string) (*string, error) {
	value := req.GetFormValue(key)
	if value != "" {
		return &value, nil
	}
	return nil, nil
}

func (f *fromForm) GetStringList(req ExtendedRequest, key string) ([]string, error) {
	valueStr := req.GetFormValue(key)
	if valueStr != "" {
		valueSlice := strings.Split(valueStr, ",")
		return valueSlice, nil
	}
	return nil, nil
}

func (f *fromForm) GetInt(req ExtendedRequest, key string) (*int, error) {
	valueStr := req.GetFormValue(key)
	if valueStr != "" {
		value, err := strconv.ParseInt(valueStr, 10, 64)
		if err != nil {
			return nil, NewError(
				InvalidArgument,
				fmt.Sprintf("invalid '%v', must be integer", key),
				err,
			).Add("valueStr", valueStr)
		}
		valueInt := int(value)
		return &valueInt, nil
	}
	return nil, nil
}

func (f *fromForm) GetFloat(req ExtendedRequest, key string) (*float64, error) {
	valueStr := req.GetFormValue(key)
	if valueStr != "" {
		value, err := strconv.ParseFloat(valueStr, 64)
		if err != nil {
			return nil, NewError(
				InvalidArgument,
				fmt.Sprintf("invalid '%v', must be float", key),
				err,
			).Add("valueStr", valueStr)
		}
		valueF := float64(value)
		return &valueF, nil
	}
	return nil, nil
}

func (f *fromForm) GetBool(req ExtendedRequest, key string) (*bool, error) {
	valueStr := req.GetFormValue(key)
	if valueStr != "" {
		valueStr = strings.ToLower(valueStr)
		switch valueStr {
		case "true":
			valueBool := true
			return &valueBool, nil
		case "false":
			valueBool := false
			return &valueBool, nil
		}
		return nil, NewError(
			InvalidArgument,
			fmt.Sprintf("invalid '%v', must be true or false", key),
			nil,
		).Add("valueStr", valueStr)
	}
	return nil, nil
}

func (f *fromForm) GetTime(req ExtendedRequest, key string) (*time.Time, error) {
	valueStr := req.GetFormValue(key)
	if valueStr != "" {
		valueTm, err := time.Parse(time.RFC3339, valueStr)
		if err != nil {
			return nil, NewError(
				InvalidArgument,
				fmt.Sprintf("invalid '%v', must be RFC3339 time string", key),
				err,
			).Add("valueStr", valueStr)
		}
		return &valueTm, nil
	}
	return nil, nil
}

func (f *fromForm) GetObject(req ExtendedRequest, key string, _type reflect.Type) (interface{}, error) {
	return nil, nil
}


text:
export CC=arm-linux-androideabi-gcc
export CXX=arm-linux-androideabi-g++
export AR=arm-linux-androideabi-ar
export RANLIB=arm-linux-androideabi-ranlib
export HOSTPYTHON=./hostpython
export HOSTPGEN=./Parser/hostpgen
export BLDSHARED="arm-linux-androideabi-gcc -shared"
export CROSS_export COMPILE=arm-linux-androideabi-
export CROSS_COMPILE_TARGET=yes
export HOSTARCH=ppc-linux
export BUILDARCH=x86_64-linux-gnu
export prefix=~/Python-3.2.2/_install


text:
<?php

namespace Vatsimphp\Exception;

/**
 *
 * Exception interface
 *
 */
interface ExceptionInterface
{
}


text:
package fr.openwide.core.infinispan.model;

import org.bindgen.Bindable;

@Bindable
public interface ILock extends ICacheKey {

	String getType();

}


text:
Drag and drop the following frameworks from the __plugins/ios__ folder of the `PhunwareAds` bundle into your Xcode project
>check `Copy items if needed` when adding frameworks:

> sdkbox.framework

> PluginPhunware.framework

> PWCore.framework

> PWAdvertising.framework

The above frameworks depend upon other frameworks. You also need to add the
following system frameworks
>if you don't already have them:

> SystemConfiguration.framework

> QuartsCore.framework

> CoreTelephony.framework

> MessageUI.framework

> EventKit.framework

> EventKitUI.framework

> CoreMedia.framework

> AVFoundation.framework

> MediaPlayer.framework

> AudioToolbox.framework

> AdSupport.framework

> StoreKit.framework

> CoreLocation.framework

> MobileCoreServices.framework

> QuartzCore.framework

> Security.framework

> UIKit.framework

> WebKit.framework


text:
package org.ittek14.nekoden.gui;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.InputListener;
import org.newdawn.slick.geom.Vector2f;

public abstract class Widget implements InputListener {
  protected Vector2f position;

  public Widget(GameContainer gc){
    gc.getInput().addListener(this);
    position = new Vector2f(0,0);
  }

  public Widget(GameContainer gc, Vector2f position){
    gc.getInput().addListener(this);
    this.position = position;
  }

  public abstract void update(GameContainer gc, int delta);
  public abstract void render(GameContainer gc, Graphics g);

  @Override
  public void mouseClicked(int button, int x, int y, int clickCount) {}

  @Override
  public void mouseDragged(int oldx, int oldy, int newx, int newy) {}

  @Override
  public void mouseMoved(int oldx, int oldy, int newx, int newy) {}

  @Override
  public void mousePressed(int button, int x, int y) {}

  @Override
  public void mouseReleased(int button, int x, int y) {}

  @Override
  public void mouseWheelMoved(int change) {}

  @Override
  public void inputEnded() {}

  @Override
  public void inputStarted() {}

  @Override
  public boolean isAcceptingInput() {
    return true;
  }

  @Override
  public void setInput(Input input) {}

  @Override
  public void keyPressed(int key, char c) {}

  @Override
  public void keyReleased(int key, char c) {}

  @Override
  public void controllerButtonPressed(int controller, int button) {}

  @Override
  public void controllerButtonReleased(int controller, int button) {}

  @Override
  public void controllerDownPressed(int controller) {}

  @Override
  public void controllerDownReleased(int controller) {}

  @Override
  public void controllerLeftPressed(int controller) {}

  @Override
  public void controllerLeftReleased(int controller) {}

  @Override
  public void controllerRightPressed(int controller) {}

  @Override
  public void controllerRightReleased(int controller) {}

  @Override
  public void controllerUpPressed(int controller) {}

  @Override
  public void controllerUpReleased(int controller) {}

  public void unregister(GameContainer container) {
	  container.getInput().removeListener(this);
  }
}


text:
<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Core\Cli;

/**
 * A command based on a callback.
 */
class CallbackCommand implements Command {
  /**
   * @var callable
   */
  private $callable;

  /**
   * @var string|null
   */
  private $description;

  /**
   * Construct callback command.
   * @param callable $callable Function.
   * @param string|null $description Optional description.
   */
  public function __construct($callable, $description = null) {
    $this->callable = $callable;
    $this->description = $description;
  }

  /**
   * {@inheritdoc}
   */
  public function getOptions() {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getShort($option) {
    return null;
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription($option = null) {
    if (!isset($option))
      return $this->description;
    return null;
  }

  /**
   * {@inheritdoc}
   */
  public function __invoke(array $parameters, array $options) {
    return call_user_func($this->callable, $parameters, $options);
  }
}


text:
package net.gumbix.bioinf.string.seq

import io.Source.fromFile
import scala.math._

/**
 * @author Markus Gumbel (m.gumbel@hs-mannheim.de)
 */

object BlockFormatter {
  val lineLength = 60

  def main(args: Array[String]) {
    val buffer = new StringBuffer
    val lines = fromFile(args(0)).getLines.drop(1)
    for (line <- lines) {
      val rLine = line.filter {
        c => c match {
          case 'A' => true
          case 'C' => true
          case 'T' => true
          case 'G' => true
          case _ => false
        }
      }
      buffer.append(rLine)
    }
    println(buffer)
    val p = buffer.length / lineLength
    for (s <- 0 until p) {
      val start = lineLength * s
      val end = min(lineLength * (s + 1), buffer.length)
      val line = buffer.substring(start, end)
      println(line)
    }
  }
}


text:
package org.smartx.summer.controller;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartx.summer.bean.LoginDTO;
import org.smartx.summer.bean.State;
import org.smartx.summer.bean.User;
import org.smartx.summer.bean.XUserAgent;
import org.smartx.summer.exception.AuthenticationException;
import org.smartx.summer.session.SessionAndTokenConstants;
import org.smartx.summer.session.SessionManager;
import org.smartx.summer.session.SessionUser;
import org.smartx.summer.session.TokenProvider;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import io.swagger.annotations.ApiOperation;

/**
 * Created by Ming on 2016/10/22.
 *
 * @author Ming
 */
@RestController
@RequestMapping("api")
@PropertySource("classpath:app.properties")
public class BaseResourceController {

    @Resource
    private SessionManager sessionManager;

    @Resource
    private TokenProvider tokenProvider;

    private static final Logger logger = LoggerFactory.getLogger(BaseResourceController.class);

    private Map<String, User> userMap = new HashMap<>();

    @PostConstruct
    public void dataInit() {
        User admin = new User();
        admin.setPassword("admin1");
        admin.setUserPhone("01234567891");
        admin.setId(1);
        admin.setRole("user,admin");

        User user = new User();
        user.setPassword("user11");
        user.setUserPhone("01234567892");
        user.setId(2);
        user.setRole("user");

        userMap.put("01234567891", admin);
        userMap.put("01234567892", user);
    }

    @ApiOperation(value = "注册", response = LoginDTO.class)
    @PostMapping("base/register")
    public ResponseEntity<?> register(@RequestBody LoginDTO loginDTO, HttpServletRequest request) {
        return ResponseEntity.ok(loginDTO);
    }

    @CrossOrigin(methods = RequestMethod.POST)
    @ApiOperation(value = "身份认证", response = State.class, notes = "admin 账号:{\"password\":\"admin1\",\"userPhone\":\"01234567891\"}\n" +
            "普通用户账号:{\"password\":\"user11\",\"userPhone\":\"01234567892\"}")
    @PostMapping(value = "base/authenticate")
    public ResponseEntity<?> authenticate(@Valid @RequestBody LoginDTO loginDTO,
                                          @RequestHeader("X-User-Agent") XUserAgent userAgent,
                                          HttpServletRequest request, HttpServletResponse response) {
        String userPhone = loginDTO.getUserPhone();
        User loginUser = userMap.get(userPhone);
        if (loginUser == null) {
            throw new AuthenticationException("User Not Exist");
        }

        if (!loginUser.getPassword().equals(loginDTO.getPassword())) {
            throw new AuthenticationException("Error Password");
        }

        String audience = userAgent.getCaller();
        if (StringUtils.isBlank(audience) || !tokenProvider.isValidateAudience(audience)) {
            return ResponseEntity.ok(new State(400, "error audience"));
        }

        String sessionKey = tokenProvider.generateSessionKey(audience, userPhone);
        String tokenIdInSession = tokenProvider.getTokenIdFromSession(sessionKey);
        if (null != tokenIdInSession) {
            logger.info("重复登陆,sessionKey:{},userPhone:{}", sessionKey, userPhone);
        }

        // token 的id ,可自定义,比如使用时间戳
        String jti = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        String tokenAudience = tokenProvider.buildAudIfNeed(audience, sessionKey);
        String jwt = tokenProvider.createJwt(userPhone, new Date(), jti, loginUser.getRole(), tokenAudience);

        SessionUser sessionUser = new SessionUser(loginUser.getId().toString(), jti);
        sessionManager.setSessionUser(sessionKey, sessionUser);
        tokenProvider.flushTokenExpireTimeBySessionKeyAndAud(sessionKey, audience);

        response.addHeader(SessionAndTokenConstants.AUTHORIZATION_HEADER, "Bearer ".concat(jwt));
        logger.info("来自:{} 设备的:{} 用户 认证成功, session key:{} ", audience, userPhone, sessionKey);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("token", "Bearer ".concat(jwt));
        return ResponseEntity.ok(jsonObject);
    }
}


text:
'use strict';

/**
 * Module dependencies
 */
var acl = require('acl');

// Using the memory backend
acl = new acl(new acl.memoryBackend());

/**
 * Invoke Hars Permissions
 */
exports.invokeRolesPolicies = function () {
    acl.allow([{
        roles: ['admin'],
        allows: [{
            resources: '/api/hars',
            permissions: '*'
        }, {
                resources: '/api/hars/:harId',
                permissions: '*'
            }]
    }, {
            roles: ['user'],
            allows: [{
                resources: '/api/hars',
                permissions: ['get', 'post']
            }, {
                    resources: '/api/hars/:harId',
                    permissions: ['get', 'patch']
                }, {
                    resources: '/api/hars/:harId/puml',
                    permissions: ['get', 'post']
                }, {
                    resources: '/api/hars/:harId/specs',
                    permissions: ['post']
                }]
        }, {
            roles: ['guest'],
            allows: [{
                resources: '/api/hars',
                permissions: ['get']
            }, {
                    resources: '/api/hars/:harId',
                    permissions: ['get']
                }, {
                    resources: '/api/hars/:harId/puml',
                    permissions: ['get']
                }, {
                    resources: '/api/hars/:harId/specs',
                    permissions: ['get']
                }]
        }]);
};

/**
 * Check If Hars Policy Allows
 */
exports.isAllowed = function (req, res, next) {
    var roles = (req.user) ? req.user.roles : ['guest'];

    // If an Har is being processed and the current user created it then allow any manipulation
    if (req.har && req.user && req.har.user && req.har.user.id === req.user.id) {
        return next();
    }

    // Check for user roles
    acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) {
        if (err) {
            // An authorization error occurred
            return res.status(500).send('Unexpected authorization error');
        } else {
            if (isAllowed) {
                // Access granted! Invoke next middleware
                return next();
            } else {
                return res.status(403).json({
                    message: 'User is not authorized'
                });
            }
        }
    });
};


text:
<!DOCTYPE html>

    <title>jQuery Culture Info</title>

Get By LCID

        Enter LCID (for e.g. 1033 for english United States) : <input type="text" id="txtLCID" /> <input type="button" value="Get Culture Info By LCID" onclick="GetCultureByLCID();" />

        Result:

Get By Culture Name

        Enter Culture (for e.g. en-Us for english United States) : <input type="text" id="txtCulture" /> <input type="button" value="Get Culture Info By Culture Name" onclick="GetCultureByCultureName();" />

        Result:


text:
import os
import tensorflow as tf
import numpy as np
from PIL import Image, ImageOps

g_map_filenames = {}

def add_path_to_map(han_pathname, label):
    print han_pathname
    for i in os.listdir(han_pathname):
        img_filename = os.path.join(han_pathname, i)
        if os.path.isfile(img_filename):
            g_map_filenames[img_filename] = label

def add_file_to_record(writer, img_filename, label):
    #print img_filename, label
    if os.path.isfile(img_filename):
        img = Image.open(img_filename)
        img = img.convert("L")
        img = img.resize((64, 64))
        img = ImageOps.invert(img)
        # print img.format, img.size, img.mode
        img_raw = img.tobytes()

        example = tf.train.Example(features=tf.train.Features(feature={
            'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),
            'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
        }))
        writer.write(example.SerializeToString())

def save_data(data_pathname, record_filename):
    for i in range(100):
        han_pathname = os.path.join(data_pathname, '%05d' % i)
        add_path_to_map(han_pathname, i)

    writer = tf.python_io.TFRecordWriter(record_filename)
    for each in g_map_filenames:
        print each, g_map_filenames[each]
        add_file_to_record(writer, each, g_map_filenames[each])
    writer.close()

def read_data(filename):
    for example_records in tf.python_io.tf_record_iterator(filename):
        example = tf.train.Example()
        example.ParseFromString(example_records)
        label = example.features.feature['label'].int64_list.value
        labels = tf.one_hot(label[0], 100)
        print labels

        print example.features.feature['image'].bytes_list.value
        img = tf.decode_raw(example.features.feature['image'].bytes_list.value[0], tf.uint8)
        img = tf.reshape(img, [64, 64, 1])
        img = tf.cast(img, tf.float32) * (1. / 255)
        print img
        break

#save_data('../data/han_img/train', '../records/han_train.tfrecords')
save_data('../data/han_img/test', '../records/han_test.tfrecords')

read_data('../records/han_train.tfrecords')
read_data('../records/han_test.tfrecords')


text:
using System;
using Ninject.Core;
#endregion

namespace Ninject.Tests
{
	[Transient]
	public class ObjectWithTransientBehavior
	{
	}
}


text:
title: "What if Javascript had a synchronous async flavor?"
date: 2021-08-01
slug: "nasync-javascript"
description: "What if Javascript had a synchronous async flavor? Introducing n/async Javascript"
keywords: []
draft: false
tags: ["async", "javascript", "babel"]
stylesheet: "post.css"
---
When writing asynchronous javascript your code will contain a bunch of `await` and `async`, `Promise`s and maybe callbacks.

Here's an example where we fetch a page and count the amount of `div` elements:

{{< starboardwrap >}}
{{< starboardembed >}}
# %%--- [javascript]
# properties:
#   run_on_load: true
# ---%%
async function fetchPageBody(url) {
    const response = await fetch(url);
    return response.text();
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(() => resolve(), ms))
}

const body = await fetchPageBody("https://enable-cors.org/");
const numDivs = (body.match(/<div/g) || []).length;

console.log("Number of divs:", numDivs);

await sleep(2000);
console.log("This prints after two seconds.");{{< /starboardembed >}}

As you write more and more code that is asynchronous, you will end up writing `await` quite a bit. In languages like Python and Go you write asynchronous code as if it's synchronous. What if we could do the same in Javascript? I'm tired of calling a function only to find out it returns a Promise instead of a real value.

## Introducing **n/async Javascript**
n/async Javascript takes the code you write, and puts `await` in front of every expression. That sounds crazy, and it is, but here's a demo:

{{< starboardembed >}}
---
starboard:
  plugins:
    - src: "https://cdn.jsdelivr.net/npm/nasync-js@0.1.0/dist/index.js"
---
# %%--- [nasync]
# properties:
#   run_on_load: true
# ---%%
function fetchPageBody(url) {
    return fetch(url).text();
}

function sleep(ms) {
    return new Promise(resolve => setTimeout(() => resolve(), ms))
}

const body = fetchPageBody("https://enable-cors.org/");
const numDivs = (body.match(/<div/g) || []).length;

console.log("Number of divs:", numDivs);

sleep(2000);
console.log("This prints after two seconds.");{{< /starboardembed >}}

Click the **`> Show transpiled code`** button below the code to see the transpiled version. As you can see a lot of (unnecessary) awaits got inserted, but at least we don't have to write them ourselves anymore surely increasing our productivity 10x.

The transpiler is powered by Babel and can be found [here](https://github.com/gzuidhof/nasync-js).

## Why is this a bad idea?
This flavor of Javascript allows us to write asynchronous code as if it is synchronous, but in reality of course it is still asynchronous. With this flavor of Javascript you can no longer do two asynchronous tasks at the same time, everything will be executed synchronously. For example if you want to make a request using `fetch`, but are only willing to wait for two seconds for the result, you're out of luck.

Secondly, compilers these days are really smart, but user code sprinkling in `await` everywhere (including places where it does nothing) likely was not a priority in optimization for the compiler designers.

## So what is it good for?
Use it for fun, use it in experimental code in a notebook (like the above examples), but please don't put this into production.

## Any caveats?
Member access expressions are not awaited (as `this` would lead to issues when calling a member function). For example:

```javascript
// n/async javascript input
const x = myObject.a.b.c();

// Transpiled output
(async () => {const x = await (await myObject).a.b.c();
})();

// What you may expect
(async () => {const x = await (await (await (await (await myObject).a).b).c)();
})();
```
In practice this likely what you want anyway. If you do need to await member variables you can just write await yourself.

Do edit the code blocks above and play with it :)!


text:
import febio
# create a MeshDef object, mesh, reading in simpleblock.inp in abaqus format
mesh = febio.MeshDef('simpleblock.inp','abq')

# create a Model obect, model, that will be written to test.feb
# NOTE: all steps and modules for those steps are defined here
# default if blank is 1 step with module type "solid"
model = febio.Model(modelfile='test.feb',steps=[{'Displace': 'biphasic'}])

#initialize a list to store MatDef objects in
materials = []

#Create 3 MatDef objects with types biphasic, isotropic elastic, and rigid body and append them to mats list
materials.append(febio.MatDef(matid=1,mname='Biphasic',elsets='exmymzm',mtype='biphasic'))
materials.append(febio.MatDef(mname='Elastic',elsets='exmymzp',mtype='neo-Hookean',matid=2,attributes={'E': '1.0', 'v': '0.3'}))
materials.append(febio.MatDef(mname='Elastic 2',elsets='expymzm',mtype='neo-Hookean',matid=3,attributes={'E': '2.0','v': '0.3'}))

#Append additional element sets to elset attribute of MatDef objects
materials[0].appendElset('exmypzm')
materials[1].appendElset('exmypzp')
materials[2].appendElset('expypzm')
materials[2].appendElset('expypzp')
materials[2].appendElset('expymzp')

# Add a new subelement to material definitions: note how attributes are passed in a dictionary and all entries are strings
materials[0].addBlock(branch=1,btype='solid',mtype='neo-Hookean',attributes={'E': '1.0', 'v': '0.3'})
materials[0].addBlock(branch=1,btype='permeability',mtype='perm-const-iso',attributes={'perm': '1.0e-3'})

materials.append(febio.MatDef(mname='Plane',elsets='eplane',mtype='rigid body',matid=4,attributes={'density': '1.0'}))

for mat in materials:
    model.addMaterial(mat)

#add an element to the mesh
mesh.addElement(etype='quad4',corners=[0.,1.,0.,1.,1.,0.,1.,0.,0.,0.,0.,0.],name='plane')

#add element data
mesh.addElementData(elset='eplane',attributes={'thickness': '.01,.01,.01,.01'})

#Fill in the geometry block of model: THIS MUST FOLLOW MATERIAL DEFINITIONS for a working model
model.addGeometry(mesh=mesh,mats=materials)

# create a Control object with default values: this will always work this way
ctrl = febio.Control()

# change attributes you wish: dictionary keys must match FEBio's control parameters (not case-sensitive)
ctrl.setAttributes({'title': 'example'})

# Add Control block to first step block
model.addControl(ctrl,step=0)

# Define boundary conditions
boundary = febio.Boundary(steps=1)
boundary.addFixed(nset=mesh.nsets['nxp'],dof='xyz')
boundary.addPrescribed(step=0,nset=mesh.nsets['nxm'],dof='x',lc='1',scale='0.1')
boundary.addContact(step=0,ctype='rigid',master=4,slave=mesh.nsets['nzm'])

#Add rigid body constraint
model.addConstraint(matid=4,dof={'trans_z': 'fixed','rot_x': 'fixed','rot_y': 'fixed','rot_z': 'fixed'})

# Add boudary conditions to model
model.addBoundary(boundary=boundary)

# Add load curves to model
model.addLoadCurve(lc='1',lctype='smooth',points=[0,0,.5,.33,1,1])

#Write the model to file
model.writeModel()


text:
// <copyright file="Reference.cs" company="Ninject.Features">
//   Copyright (c)  2013-2015
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>

namespace Ninject.FeatureDumper
{
    using System;

    public class Reference
    {
        public Reference(Type feature, Type neededFeature)
        {
            this.Feature = feature;
            this.NeededFeature = neededFeature;
        }

        public Type Feature { get; private set; }

        public Type NeededFeature { get; private set; }
    }
}


text:
package com.derrekyoung.urlmonitor.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.derrekyoung.urlmonitor.domain.UrlMonitor;
import com.derrekyoung.urlmonitor.domain.UrlMonitorRestRepository;
import com.derrekyoung.urlmonitor.util.UrlMonitorUtil;

@RestController
public class UrlMonitorController {

	@Autowired
	private UrlMonitorUtil util;

	@Autowired
	private UrlMonitorRestRepository repo;

	@RequestMapping(value = {"/api/urlmonitor/add"}, method = RequestMethod.POST)
	public UrlMonitor addUrlMonitor(@RequestBody UrlMonitor urlMonitor) {
		return util.validateAndSave(urlMonitor);
	}

	@RequestMapping(value = {"/api/urlmonitor/update"}, method = RequestMethod.PUT)
	public UrlMonitor updateUrlMonitor(@RequestBody UrlMonitor urlMonitor) {
		return util.validateAndSave(urlMonitor);
	}

	@RequestMapping(value = {"/api/urlmonitor/delete"}, method = RequestMethod.DELETE)
	public boolean deleteUrlMonitor(@RequestBody UrlMonitor urlMonitor) {
		repo.delete(urlMonitor);

		return true;
	}

	@RequestMapping(value = {"/api/urlmonitor/allrecords"}, method = RequestMethod.GET)
	public Iterable<UrlMonitor> validateAllUrls() {
		return util.validateAndSaveAll();
	}
}


text:
/*
    This file is part of the WebKit open source project.
    This file has been generated by generate-bindings.pl. DO NOT MODIFY!

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#ifndef V8HTMLLinkElement_h
#define V8HTMLLinkElement_h

#include "HTMLLinkElement.h"
#include "V8DOMWrapper.h"
#include "V8HTMLElement.h"
#include "WrapperTypeInfo.h"
#include <wtf/text/StringHash.h>
#include <v8.h>
#include <wtf/HashMap.h>

namespace WebCore {

class V8HTMLLinkElement {
public:
    static const bool hasDependentLifetime = V8HTMLElement::hasDependentLifetime;
    static bool HasInstance(v8::Handle<v8::Value> value);
    static v8::Persistent<v8::FunctionTemplate> GetRawTemplate();
    static v8::Persistent<v8::FunctionTemplate> GetTemplate();
    static HTMLLinkElement* toNative(v8::Handle<v8::Object> object)
    {
        return reinterpret_cast<HTMLLinkElement*>(object->GetPointerFromInternalField(v8DOMWrapperObjectIndex));
    }
    inline static v8::Handle<v8::Object> wrap(HTMLLinkElement*);
    static void derefObject(void*);
    static WrapperTypeInfo info;
    static v8::Handle<v8::Value> sizesAccessorGetter(v8::Local<v8::String> name, const v8::AccessorInfo& info);
    static void sizesAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
    static const int internalFieldCount = v8DefaultWrapperInternalFieldCount + 0;
private:
    static v8::Handle<v8::Object> wrapSlow(HTMLLinkElement*);
};

v8::Handle<v8::Object> V8HTMLLinkElement::wrap(HTMLLinkElement* impl)
{
        v8::Handle<v8::Object> wrapper = V8DOMWrapper::getWrapper(impl);
        if (!wrapper.IsEmpty())
            return wrapper;
    return V8HTMLLinkElement::wrapSlow(impl);
}

inline v8::Handle<v8::Value> toV8(HTMLLinkElement* impl)
{
    if (!impl)
        return v8::Null();
    return V8HTMLLinkElement::wrap(impl);
}
inline v8::Handle<v8::Value> toV8(PassRefPtr< HTMLLinkElement > impl)
{
    return toV8(impl.get());
}
}

#endif // V8HTMLLinkElement_h


text:
package androidx.media3.common.util;

import static androidx.media3.common.util.Assertions.checkArgument;

import androidx.annotation.Nullable;
import androidx.media3.common.C;

/** Immutable class for describing width and height dimensions in pixels. */
@UnstableApi
public final class Size {

  /** A static instance to represent an unknown size value. */
  public static final Size UNKNOWN =
      new Size(/* width= */ C.LENGTH_UNSET, /* height= */ C.LENGTH_UNSET);

  private final int width;
  private final int height;

  /**
   * Creates a new immutable Size instance.
   *
   * @param width The width of the size, in pixels, or {@link C#LENGTH_UNSET} if unknown.
   * @param height The height of the size, in pixels, or {@link C#LENGTH_UNSET} if unknown.
   * @throws IllegalArgumentException if an invalid {@code width} or {@code height} is specified.
   */
  public Size(int width, int height) {
    checkArgument(
        (width == C.LENGTH_UNSET || width >= 0) && (height == C.LENGTH_UNSET || height >= 0));

    this.width = width;
    this.height = height;
  }

  /** Returns the width of the size (in pixels), or {@link C#LENGTH_UNSET} if unknown. */
  public int getWidth() {
    return width;
  }

  /** Returns the height of the size (in pixels), or {@link C#LENGTH_UNSET} if unknown. */
  public int getHeight() {
    return height;
  }

  @Override
  public boolean equals(@Nullable Object obj) {
    if (obj == null) {
      return false;
    }
    if (this == obj) {
      return true;
    }
    if (obj instanceof Size) {
      Size other = (Size) obj;
      return width == other.width && height == other.height;
    }
    return false;
  }

  @Override
  public String toString() {
    return width + "x" + height;
  }

  @Override
  public int hashCode() {
    // assuming most sizes are <2^16, doing a rotate will give us perfect hashing
    return height ^ ((width << (Integer.SIZE / 2)) | (width >>> (Integer.SIZE / 2)));
  }
}


text:
layout: default
title: Links
lead: "Links"
slug: links
base_url: "../../"
---

        {% markdown links/links.md %}


text:
/*
  Include declarations.
*/
#include "magick/studio.h"
#include "magick/client.h"
#include "magick/configure.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/option.h"
#include "magick/policy.h"
#include "magick/semaphore.h"
#include "magick/string_.h"
#include "magick/token.h"
#include "magick/utility.h"
#include "magick/xml-tree.h"

/*
  Define declarations.
*/
#define PolicyFilename  "policy.xml"

/*
  Typedef declarations.
*/
struct _PolicyInfo
{
  char
    *path;

  PolicyDomain
    domain;

  PolicyRights
    rights;

  char
    *name,
    *pattern,
    *value;

  MagickBooleanType
    exempt,
    stealth,
    debug;

  SemaphoreInfo
    *semaphore;

  size_t
    signature;
};

typedef struct _PolicyMapInfo
{
  const PolicyDomain
    domain;

  const PolicyRights
    rights;

  const char
    *name,
    *pattern,
    *value;
} PolicyMapInfo;

/*
  Static declarations.
*/
static const PolicyMapInfo
  PolicyMap[] =
  {
    { UndefinedPolicyDomain, UndefinedPolicyRights, (const char *) NULL,
      (const char *) NULL, (const char *) NULL }
  };

static LinkedListInfo
  *policy_list = (LinkedListInfo *) NULL;

static SemaphoreInfo
  *policy_semaphore = (SemaphoreInfo *) NULL;

static volatile MagickBooleanType
  instantiate_policy = MagickFalse;

/*
  Forward declarations.
*/
static MagickBooleanType
  InitializePolicyList(ExceptionInfo *),
  LoadPolicyLists(const char *,ExceptionInfo *);

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   G e t P o l i c y I n f o                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetPolicyInfo() searches the policy list for the specified name and if found
%  returns attributes for that policy.
%
%  The format of the GetPolicyInfo method is:
%
%      PolicyInfo *GetPolicyInfo(const char *name,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o name: the policy name.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static PolicyInfo *GetPolicyInfo(const char *name,ExceptionInfo *exception)
{
  char
    policyname[MaxTextExtent];

  register PolicyInfo
    *p;

  register char
    *q;

  assert(exception != (ExceptionInfo *) NULL);
  if ((policy_list == (LinkedListInfo *) NULL) ||
      (instantiate_policy == MagickFalse))
    if (InitializePolicyList(exception) == MagickFalse)
      return((PolicyInfo *) NULL);
  if ((policy_list == (LinkedListInfo *) NULL) ||
      (IsLinkedListEmpty(policy_list) != MagickFalse))
    return((PolicyInfo *) NULL);
  if ((name == (const char *) NULL) || (LocaleCompare(name,"*") == 0))
    return((PolicyInfo *) GetValueFromLinkedList(policy_list,0));
  /*
    Strip names of whitespace.
  */
  (void) CopyMagickString(policyname,name,MaxTextExtent);
  for (q=policyname; *q != '\0'; q++)
  {
    if (isspace((int) ((unsigned char) *q)) == 0)
      continue;
    (void) CopyMagickString(q,q+1,MaxTextExtent);
    q--;
  }
  /*
    Search for policy tag.
  */
  LockSemaphoreInfo(policy_semaphore);
  ResetLinkedListIterator(policy_list);
  p=(PolicyInfo *) GetNextValueInLinkedList(policy_list);
  while (p != (PolicyInfo *) NULL)
  {
    if (LocaleCompare(policyname,p->name) == 0)
      break;
    p=(PolicyInfo *) GetNextValueInLinkedList(policy_list);
  }
  if (p != (PolicyInfo *) NULL)
    (void) InsertValueInLinkedList(policy_list,0,
      RemoveElementByValueFromLinkedList(policy_list,p));
  UnlockSemaphoreInfo(policy_semaphore);
  return(p);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t P o l i c y I n f o L i s t                                         %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetPolicyInfoList() returns any policies that match the specified pattern.
%
%  The format of the GetPolicyInfoList function is:
%
%      const PolicyInfo **GetPolicyInfoList(const char *pattern,
%        size_t *number_policies,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o pattern: Specifies a pointer to a text string containing a pattern.
%
%    o number_policies:  returns the number of policies in the list.
%
%    o exception: return any errors or warnings in this structure.
%
*/
MagickExport const PolicyInfo **GetPolicyInfoList(const char *pattern,
  size_t *number_policies,ExceptionInfo *exception)
{
  const PolicyInfo
    **policies;

  register const PolicyInfo
    *p;

  register ssize_t
    i;

  /*
    Allocate policy list.
  */
  assert(pattern != (char *) NULL);
  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
  assert(number_policies != (size_t *) NULL);
  *number_policies=0;
  p=GetPolicyInfo("*",exception);
  if (p == (const PolicyInfo *) NULL)
    return((const PolicyInfo **) NULL);
  policies=(const PolicyInfo **) AcquireQuantumMemory((size_t)
    GetNumberOfElementsInLinkedList(policy_list)+1UL,sizeof(*policies));
  if (policies == (const PolicyInfo **) NULL)
    return((const PolicyInfo **) NULL);
  /*
    Generate policy list.
  */
  LockSemaphoreInfo(policy_semaphore);
  ResetLinkedListIterator(policy_list);
  p=(const PolicyInfo *) GetNextValueInLinkedList(policy_list);
  for (i=0; p != (const PolicyInfo *) NULL; )
  {
    if ((p->stealth == MagickFalse) &&
        (GlobExpression(p->name,pattern,MagickFalse) != MagickFalse))
      policies[i++]=p;
    p=(const PolicyInfo *) GetNextValueInLinkedList(policy_list);
  }
  UnlockSemaphoreInfo(policy_semaphore);
  policies[i]=(PolicyInfo *) NULL;
  *number_policies=(size_t) i;
  return(policies);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t P o l i c y L i s t                                                 %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetPolicyList() returns any policies that match the specified pattern.
%
%  The format of the GetPolicyList function is:
%
%      char **GetPolicyList(const char *pattern,size_t *number_policies,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o pattern: a pointer to a text string containing a pattern.
%
%    o number_policies:  returns the number of policies in the list.
%
%    o exception: return any errors or warnings in this structure.
%
*/
MagickExport char **GetPolicyList(const char *pattern,
  size_t *number_policies,ExceptionInfo *exception)
{
  char
    **policies;

  register const PolicyInfo
    *p;

  register ssize_t
    i;

  /*
    Allocate policy list.
  */
  assert(pattern != (char *) NULL);
  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",pattern);
  assert(number_policies != (size_t *) NULL);
  *number_policies=0;
  p=GetPolicyInfo("*",exception);
  if (p == (const PolicyInfo *) NULL)
    return((char **) NULL);
  policies=(char **) AcquireQuantumMemory((size_t)
    GetNumberOfElementsInLinkedList(policy_list)+1UL,sizeof(*policies));
  if (policies == (char **) NULL)
    return((char **) NULL);
  /*
    Generate policy list.
  */
  LockSemaphoreInfo(policy_semaphore);
  ResetLinkedListIterator(policy_list);
  p=(const PolicyInfo *) GetNextValueInLinkedList(policy_list);
  for (i=0; p != (const PolicyInfo *) NULL; )
  {
    if ((p->stealth == MagickFalse) &&
        (GlobExpression(p->name,pattern,MagickFalse) != MagickFalse))
      policies[i++]=ConstantString(p->name);
    p=(const PolicyInfo *) GetNextValueInLinkedList(policy_list);
  }
  UnlockSemaphoreInfo(policy_semaphore);
  policies[i]=(char *) NULL;
  *number_policies=(size_t) i;
  return(policies);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   G e t P o l i c y V a l u e                                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  GetPolicyValue() returns the value associated with the named policy.
%
%  The format of the GetPolicyValue method is:
%
%      char *GetPolicyValue(const char *name)
%
%  A description of each parameter follows:
%
%    o policy_info:  The policy info.
%
*/
MagickExport char *GetPolicyValue(const char *name)
{
  const char
    *value;

  const PolicyInfo
    *policy_info;

  ExceptionInfo
    *exception;

  assert(name != (const char *) NULL);
  (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",name);
  exception=AcquireExceptionInfo();
  policy_info=GetPolicyInfo(name,exception);
  exception=DestroyExceptionInfo(exception);
  if (policy_info == (PolicyInfo *) NULL)
    return((char *) NULL);
  value=policy_info->value;
  if ((value == (const char *) NULL) || (*value == '\0'))
    return((char *) NULL);
  return(ConstantString(value));
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   I n i t i a l i z e P o l i c y L i s t                                   %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  InitializePolicyList() initializes the policy list.
%
%  The format of the InitializePolicyList method is:
%
%      MagickBooleanType InitializePolicyList(ExceptionInfo *exception)
%
%  A description of each parameter follows.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType InitializePolicyList(ExceptionInfo *exception)
{
  if ((policy_list == (LinkedListInfo *) NULL) &&
      (instantiate_policy == MagickFalse))
    {
      if (policy_semaphore == (SemaphoreInfo *) NULL)
        AcquireSemaphoreInfo(&policy_semaphore);
      LockSemaphoreInfo(policy_semaphore);
      if ((policy_list == (LinkedListInfo *) NULL) &&
          (instantiate_policy == MagickFalse))
        {
          (void) LoadPolicyLists(PolicyFilename,exception);
          instantiate_policy=MagickTrue;
        }
      UnlockSemaphoreInfo(policy_semaphore);
    }
  return(policy_list != (LinkedListInfo *) NULL ? MagickTrue : MagickFalse);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%   I s R i g h t s A u t h o r i z e d                                       %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  IsRightsAuthorized() returns MagickTrue if the policy authorizes the
%  requested rights for the specified domain.
%
%  The format of the IsRightsAuthorized method is:
%
%      MagickBooleanType IsRightsAuthorized(const PolicyDomain domain,
%        const PolicyRights rights,const char *pattern)
%
%  A description of each parameter follows:
%
%    o domain: the policy domain.
%
%    o rights: the policy rights.
%
%    o pattern: the coder, delegate, filter, or path pattern.
%
*/
MagickExport MagickBooleanType IsRightsAuthorized(const PolicyDomain domain,
  const PolicyRights rights,const char *pattern)
{
  const PolicyInfo
    *policy_info;

  ExceptionInfo
    *exception;

  MagickBooleanType
    authorized;

  register PolicyInfo
    *p;

  (void) LogMagickEvent(PolicyEvent,GetMagickModule(),
    "Domain: %s; rights=%s; pattern=\"%s\" ...",
    CommandOptionToMnemonic(MagickPolicyDomainOptions,domain),
    CommandOptionToMnemonic(MagickPolicyRightsOptions,rights),pattern);
  exception=AcquireExceptionInfo();
  policy_info=GetPolicyInfo("*",exception);
  exception=DestroyExceptionInfo(exception);
  if (policy_info == (PolicyInfo *) NULL)
    return(MagickTrue);
  authorized=MagickTrue;
  LockSemaphoreInfo(policy_semaphore);
  ResetLinkedListIterator(policy_list);
  p=(PolicyInfo *) GetNextValueInLinkedList(policy_list);
  while ((p != (PolicyInfo *) NULL) && (authorized != MagickFalse))
  {
    if ((p->domain == domain) &&
        (GlobExpression(pattern,p->pattern,MagickFalse) != MagickFalse))
      {
        if (((rights & ReadPolicyRights) != 0) &&
            ((p->rights & ReadPolicyRights) == 0))
          authorized=MagickFalse;
        if (((rights & WritePolicyRights) != 0) &&
            ((p->rights & WritePolicyRights) == 0))
          authorized=MagickFalse;
        if (((rights & ExecutePolicyRights) != 0) &&
            ((p->rights & ExecutePolicyRights) == 0))
          authorized=MagickFalse;
      }
    p=(PolicyInfo *) GetNextValueInLinkedList(policy_list);
  }
  UnlockSemaphoreInfo(policy_semaphore);
  return(authorized);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%  L i s t P o l i c y I n f o                                                %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  ListPolicyInfo() lists policies to the specified file.
%
%  The format of the ListPolicyInfo method is:
%
%      MagickBooleanType ListPolicyInfo(FILE *file,ExceptionInfo *exception)
%
%  A description of each parameter follows.
%
%    o file:  List policy names to this file handle.
%
%    o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType ListPolicyInfo(FILE *file,
  ExceptionInfo *exception)
{
  const char
    *path,
    *domain;

  const PolicyInfo
    **policy_info;

  register ssize_t
    i;

  size_t
    number_policies;

  /*
    List name and attributes of each policy in the list.
  */
  if (file == (const FILE *) NULL)
    file=stdout;
  policy_info=GetPolicyInfoList("*",&number_policies,exception);
  if (policy_info == (const PolicyInfo **) NULL)
    return(MagickFalse);
  path=(const char *) NULL;
  for (i=0; i < (ssize_t) number_policies; i++)
  {
    if (policy_info[i]->stealth != MagickFalse)
      continue;
    if (((path == (const char *) NULL) ||
         (LocaleCompare(path,policy_info[i]->path) != 0)) &&
         (policy_info[i]->path != (char *) NULL))
      (void) FormatLocaleFile(file,"\nPath: %s\n",policy_info[i]->path);
    path=policy_info[i]->path;
    domain=CommandOptionToMnemonic(MagickPolicyDomainOptions,
      policy_info[i]->domain);
    (void) FormatLocaleFile(file,"  Policy: %s\n",domain);
    if ((policy_info[i]->domain == ResourcePolicyDomain) ||
        (policy_info[i]->domain == SystemPolicyDomain))
      {
        if (policy_info[i]->name != (char *) NULL)
          (void) FormatLocaleFile(file,"    name: %s\n",policy_info[i]->name);
        if (policy_info[i]->value != (char *) NULL)
          (void) FormatLocaleFile(file,"    value: %s\n",policy_info[i]->value);
      }
    else
      {
        (void) FormatLocaleFile(file,"    rights: ");
        if (policy_info[i]->rights == NoPolicyRights)
          (void) FormatLocaleFile(file,"None ");
        if ((policy_info[i]->rights & ReadPolicyRights) != 0)
          (void) FormatLocaleFile(file,"Read ");
        if ((policy_info[i]->rights & WritePolicyRights) != 0)
          (void) FormatLocaleFile(file,"Write ");
        if ((policy_info[i]->rights & ExecutePolicyRights) != 0)
          (void) FormatLocaleFile(file,"Execute ");
        (void) FormatLocaleFile(file,"\n");
        if (policy_info[i]->pattern != (char *) NULL)
          (void) FormatLocaleFile(file,"    pattern: %s\n",
            policy_info[i]->pattern);
      }
  }
  policy_info=(const PolicyInfo **) RelinquishMagickMemory((void *)
    policy_info);
  (void) fflush(file);
  return(MagickTrue);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   L o a d P o l i c y L i s t                                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  LoadPolicyList() loads the policy configuration file which provides a mapping
%  between policy attributes and a policy domain.
%
%  The format of the LoadPolicyList method is:
%
%      MagickBooleanType LoadPolicyList(const char *xml,const char *filename,
%        const size_t depth,ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o xml:  The policy list in XML format.
%
%    o filename:  The policy list filename.
%
%    o depth: depth of <include /> statements.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType LoadPolicyList(const char *xml,const char *filename,
  const size_t depth,ExceptionInfo *exception)
{
  char
    keyword[MaxTextExtent],
    *token;

  PolicyInfo
    *policy_info;

  const char
    *q;

  MagickBooleanType
    status;

  /*
    Load the policy map file.
  */
  (void) LogMagickEvent(ConfigureEvent,GetMagickModule(),
    "Loading policy file \"%s\" ...",filename);
  if (xml == (char *) NULL)
    return(MagickFalse);
  if (policy_list == (LinkedListInfo *) NULL)
    {
      policy_list=NewLinkedList(0);
      if (policy_list == (LinkedListInfo *) NULL)
        {
          ThrowFileException(exception,ResourceLimitError,
            "MemoryAllocationFailed",filename);
          return(MagickFalse);
        }
    }
  status=MagickTrue;
  policy_info=(PolicyInfo *) NULL;
  token=AcquireString(xml);
  for (q=(const char *) xml; *q != '\0'; )
  {
    /*
      Interpret XML.
    */
    GetMagickToken(q,&q,token);
    if (*token == '\0')
      break;
    (void) CopyMagickString(keyword,token,MaxTextExtent);
    if (LocaleNCompare(keyword,"<!DOCTYPE",9) == 0)
      {
        /*
          Docdomain element.
        */
        while ((LocaleNCompare(q,"]>",2) != 0) && (*q != '\0'))
          GetMagickToken(q,&q,token);
        continue;
      }
    if (LocaleNCompare(keyword,"<!--",4) == 0)
      {
        /*
          Comment element.
        */
        while ((LocaleNCompare(q,"->",2) != 0) && (*q != '\0'))
          GetMagickToken(q,&q,token);
        continue;
      }
    if (LocaleCompare(keyword,"<include") == 0)
      {
        /*
          Include element.
        */
        while (((*token != '/') && (*(token+1) != '>')) && (*q != '\0'))
        {
          (void) CopyMagickString(keyword,token,MaxTextExtent);
          GetMagickToken(q,&q,token);
          if (*token != '=')
            continue;
          GetMagickToken(q,&q,token);
          if (LocaleCompare(keyword,"file") == 0)
            {
              if (depth > 200)
                (void) ThrowMagickException(exception,GetMagickModule(),
                  ConfigureError,"IncludeElementNestedTooDeeply","`%s'",token);
              else
                {
                  char
                    path[MaxTextExtent],
                    *xml;

                  GetPathComponent(filename,HeadPath,path);
                  if (*path != '\0')
                    (void) ConcatenateMagickString(path,DirectorySeparator,
                      MaxTextExtent);
                  if (*token == *DirectorySeparator)
                    (void) CopyMagickString(path,token,MaxTextExtent);
                  else
                    (void) ConcatenateMagickString(path,token,MaxTextExtent);
                  xml=FileToString(path,~0,exception);
                  if (xml != (char *) NULL)
                    {
                      status=LoadPolicyList(xml,path,depth+1,exception);
                      xml=(char *) RelinquishMagickMemory(xml);
                    }
                }
            }
        }
        continue;
      }
    if (LocaleCompare(keyword,"<policy") == 0)
      {
        /*
          Policy element.
        */
        policy_info=(PolicyInfo *) AcquireMagickMemory(sizeof(*policy_info));
        if (policy_info == (PolicyInfo *) NULL)
          ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
        (void) ResetMagickMemory(policy_info,0,sizeof(*policy_info));
        policy_info->path=ConstantString(filename);
        policy_info->exempt=MagickFalse;
        policy_info->signature=MagickSignature;
        continue;
      }
    if (policy_info == (PolicyInfo *) NULL)
      continue;
    if (LocaleCompare(keyword,"/>") == 0)
      {
        status=AppendValueToLinkedList(policy_list,policy_info);
        if (status == MagickFalse)
          (void) ThrowMagickException(exception,GetMagickModule(),
            ResourceLimitError,"MemoryAllocationFailed","`%s'",
            policy_info->name);
        policy_info=(PolicyInfo *) NULL;
      }
    GetMagickToken(q,(const char **) NULL,token);
    if (*token != '=')
      continue;
    GetMagickToken(q,&q,token);
    GetMagickToken(q,&q,token);
    switch (*keyword)
    {
      case 'D':
      case 'd':
      {
        if (LocaleCompare((char *) keyword,"domain") == 0)
          {
            policy_info->domain=(PolicyDomain) ParseCommandOption(
              MagickPolicyDomainOptions,MagickTrue,token);
            break;
          }
        break;
      }
      case 'N':
      case 'n':
      {
        if (LocaleCompare((char *) keyword,"name") == 0)
          {
            policy_info->name=ConstantString(token);
            break;
          }
        break;
      }
      case 'P':
      case 'p':
      {
        if (LocaleCompare((char *) keyword,"pattern") == 0)
          {
            policy_info->pattern=ConstantString(token);
            break;
          }
        break;
      }
      case 'R':
      case 'r':
      {
        if (LocaleCompare((char *) keyword,"rights") == 0)
          {
            policy_info->rights=(PolicyRights) ParseCommandOption(
              MagickPolicyRightsOptions,MagickTrue,token);
            break;
          }
        break;
      }
      case 'S':
      case 's':
      {
        if (LocaleCompare((char *) keyword,"stealth") == 0)
          {
            policy_info->stealth=IsMagickTrue(token);
            break;
          }
        break;
      }
      case 'V':
      case 'v':
      {
        if (LocaleCompare((char *) keyword,"value") == 0)
          {
            policy_info->value=ConstantString(token);
            break;
          }
        break;
      }
      default:
        break;
    }
  }
  token=(char *) RelinquishMagickMemory(token);
  return(status);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
%  L o a d P o l i c y L i s t s                                              %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  LoadPolicyList() loads one or more policy configuration file which provides a
%  mapping between policy attributes and a policy name.
%
%  The format of the LoadPolicyLists method is:
%
%      MagickBooleanType LoadPolicyLists(const char *filename,
%        ExceptionInfo *exception)
%
%  A description of each parameter follows:
%
%    o filename: the font file name.
%
%    o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType LoadPolicyLists(const char *filename,
  ExceptionInfo *exception)
{
  const StringInfo
    *option;

  LinkedListInfo
    *options;

  MagickStatusType
    status;

  register ssize_t
    i;

  /*
    Load built-in policy map.
  */
  status=MagickFalse;
  if (policy_list == (LinkedListInfo *) NULL)
    {
      policy_list=NewLinkedList(0);
      if (policy_list == (LinkedListInfo *) NULL)
        {
          ThrowFileException(exception,ResourceLimitError,
            "MemoryAllocationFailed",filename);
          return(MagickFalse);
        }
    }
  for (i=0; i < (ssize_t) (sizeof(PolicyMap)/sizeof(*PolicyMap)); i++)
  {
    PolicyInfo
      *policy_info;

    register const PolicyMapInfo
      *p;

    p=PolicyMap+i;
    policy_info=(PolicyInfo *) AcquireMagickMemory(sizeof(*policy_info));
    if (policy_info == (PolicyInfo *) NULL)
      {
        (void) ThrowMagickException(exception,GetMagickModule(),
          ResourceLimitError,"MemoryAllocationFailed","`%s'",policy_info->name);
        continue;
      }
    (void) ResetMagickMemory(policy_info,0,sizeof(*policy_info));
    policy_info->path=(char *) "[built-in]";
    policy_info->domain=p->domain;
    policy_info->rights=p->rights;
    policy_info->name=(char *) p->name;
    policy_info->pattern=(char *) p->pattern;
    policy_info->value=(char *) p->value;
    policy_info->exempt=MagickTrue;
    policy_info->signature=MagickSignature;
    status=AppendValueToLinkedList(policy_list,policy_info);
    if (status == MagickFalse)
      (void) ThrowMagickException(exception,GetMagickModule(),
        ResourceLimitError,"MemoryAllocationFailed","`%s'",policy_info->name);
  }
  /*
    Load external policy map.
  */
  options=GetConfigureOptions(filename,exception);
  option=(const StringInfo *) GetNextValueInLinkedList(options);
  while (option != (const StringInfo *) NULL)
  {
    status|=LoadPolicyList((const char *) GetStringInfoDatum(option),
      GetStringInfoPath(option),0,exception);
    option=(const StringInfo *) GetNextValueInLinkedList(options);
  }
  options=DestroyConfigureOptions(options);
  return(status != 0 ? MagickTrue : MagickFalse);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   P o l i c y C o m p o n e n t G e n e s i s                               %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  PolicyComponentGenesis() instantiates the policy component.
%
%  The format of the PolicyComponentGenesis method is:
%
%      MagickBooleanType PolicyComponentGenesis(void)
%
*/
MagickExport MagickBooleanType PolicyComponentGenesis(void)
{
  AcquireSemaphoreInfo(&policy_semaphore);
  return(MagickTrue);
}

/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                                                             %
%                                                                             %
%                                                                             %
+   P o l i c y C o m p o n e n t T e r m i n u s                             %
%                                                                             %
%                                                                             %
%                                                                             %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%  PolicyComponentTerminus() destroys the policy component.
%
%  The format of the PolicyComponentTerminus method is:
%
%      PolicyComponentTerminus(void)
%
*/

static void *DestroyPolicyElement(void *policy_info)
{
  register PolicyInfo
    *p;

  p=(PolicyInfo *) policy_info;
  if (p->exempt == MagickFalse)
    {
      if (p->value != (char *) NULL)
        p->value=DestroyString(p->value);
      if (p->pattern != (char *) NULL)
        p->pattern=DestroyString(p->pattern);
      if (p->name != (char *) NULL)
        p->name=DestroyString(p->name);
      if (p->path != (char *) NULL)
        p->path=DestroyString(p->path);
    }
  p=(PolicyInfo *) RelinquishMagickMemory(p);
  return((void *) NULL);
}

MagickExport void PolicyComponentTerminus(void)
{
  if (policy_semaphore == (SemaphoreInfo *) NULL)
    AcquireSemaphoreInfo(&policy_semaphore);
  LockSemaphoreInfo(policy_semaphore);
  if (policy_list != (LinkedListInfo *) NULL)
    policy_list=DestroyLinkedList(policy_list,DestroyPolicyElement);
  instantiate_policy=MagickFalse;
  UnlockSemaphoreInfo(policy_semaphore);
  DestroySemaphoreInfo(&policy_semaphore);
}


text:
package org.cloudfoundry.operations.buildpacks;

import org.junit.Test;

import java.nio.file.Paths;

public class UpdateBuildpackRequestTest {

    @Test(expected = IllegalStateException.class)
    public void noName() {
        UpdateBuildpackRequest.builder()
            .build();
    }

    @Test
    public void valid() {
        UpdateBuildpackRequest.builder()
            .buildpack(Paths.get("test-buildpack"))
            .enable(false)
            .lock(true)
            .name("test-name")
            .position(0)
            .build();
    }

}


text:
package org.jnbis.internal.record.reader;

import org.jnbis.internal.NistHelper;
import org.jnbis.api.model.record.MinutiaeData;

/**
 * @author ericdsoto
 */
public class MinutiaeDataReader extends RecordReader {

    @Override
    public MinutiaeData read(NistHelper.Token token) {
        if (token.pos >= token.buffer.length) {
            throw new RuntimeException("T9::NULL pointer to T9 record");
        }

        MinutiaeData minutiaeData = new MinutiaeData();

        int start = token.pos;

        NistHelper.Tag tag = getTagInfo(token);
        if (tag.field != 1) {
            throw new RuntimeException("T9::Invalid Record type = " + tag.type);
        }

        int length = Integer.parseInt(nextWord(token, NistHelper.TAG_SEP_GSFS, NistHelper.FIELD_MAX_LENGTH - 1, false));

        //while (true) {

        token.pos++;

        tag = getTagInfo(token);

        //if (tag.field == 999) {
        byte[] data = new byte[length - (token.pos - start)];
        System.arraycopy(token.buffer, token.pos, data, 0, data.length);
        token.pos = token.pos + data.length;
        //facialRecord.setImageData(data);
        //break;
        //}

        //String word = nextWord(token, NistHelper.TAG_SEP_GSFS, NistHelper.FIELD_MAX_LENGTH - 1, false);

        //}

        return minutiaeData;
    }

    protected NistHelper.Tag getTagInfo(NistHelper.Token token) {
        String type = nextWord(token, NistHelper.TAG_SEP_DOT, 2, false);
        token.pos++;
        String field = nextWord(token, NistHelper.TAG_SEP_COLN, 10, false);
        token.pos++;

        return new NistHelper.Tag(Integer.parseInt(type), Integer.parseInt(field));
    }

}


text:
import { makeFetchAction } from 'redux-api-call';
import config from '../../../configs/config';
import { isEmpty } from 'lodash';

export const FETCH_USER_SUCCESS = 'FETCH_USER_SUCCESS';
export const FETCH_USER_FAILURE = 'FETCH_USER_FAILURE';
export const INIT_LOGIN = 'INIT_LOGIN';
export const SET_USER_DATA = 'SET_USER_DATA';
export const UPDATE_FARMER_SUCCESS = 'UPDATE_FARMER_SUCCESS';

export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_FAILURE = 'LOGIN_FAILURE';
export const LOG_OUT = 'LOG_OUT';
export const LOG_IN = 'LOG_IN';

import headerAttachToken, { randomString }  from '../../util/setAuthorizationToken';

export function initLogin() {
  return {
    type: INIT_LOGIN,
    payload: [],
  };
}

export function checkUserLogin(userData) {
  const {
    actionCreator: checkUserLogin,
  } = makeFetchAction(
    'checkUserLogin',
    () => ({
      endpoint: config.api_url + 'public_api/users/login',
      headers: {
        'Content-Type': 'application/json',
      },
      method: 'POST',
      body: JSON.stringify(userData),
    })
  );
  return checkUserLogin();
}

export function setUserData(userData) {
  return {
    type: SET_USER_DATA,
    payload: userData,
  };
}

export function updateFarmer(id, data) {
  if (isEmpty(data.images))
    data.images = null;
  const {
    actionCreator: updateFarmer,
  } = makeFetchAction(
    'updateFarmer',
    () => ({
      endpoint: `${config.api_url}api/farmers/update/${id}`,
      headers: headerAttachToken,
      method: 'PUT',
      body: JSON.stringify(data),
    })
  );
  return updateFarmer();
}

export function logOut() {
  return {
    type: LOG_OUT,
    payload: false,
  };
}

export function logIn() {
  return {
    type: LOG_IN,
    payload: true,
  };
}


text:
extern CBaseEntity				*g_pLastSpawn;
void InitBodyQue(void);
extern void W_Precache(void);
extern void ActivityList_Free( void );
extern CMemoryPool g_EntityListPool;

#define SF_DECAL_NOTINDEATHMATCH		2048

class CDecal : public CPointEntity
{
public:
	DECLARE_CLASS( CDecal, CPointEntity );

	void	Spawn( void );
	bool	KeyValue( const char *szKeyName, const char *szValue );

	// Need to apply static decals here to get them into the signon buffer for the server appropriately
	virtual void Activate();

	void	TriggerDecal( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );

	// Input handlers.
	void	InputActivate( inputdata_t &inputdata );

	DECLARE_DATADESC();

public:
	int		m_nTexture;
	bool	m_bLowPriority;

private:

	void	StaticDecal( void );
};

BEGIN_DATADESC( CDecal )

	DEFINE_FIELD( m_nTexture, FIELD_INTEGER ),
	DEFINE_KEYFIELD( m_bLowPriority, FIELD_BOOLEAN, "LowPriority" ), // Don't mark as FDECAL_PERMANENT so not save/restored and will be reused on the client preferentially

	// Function pointers
	DEFINE_FUNCTION( StaticDecal ),
	DEFINE_FUNCTION( TriggerDecal ),

	DEFINE_INPUTFUNC( FIELD_VOID, "Activate", InputActivate ),

END_DATADESC()

LINK_ENTITY_TO_CLASS( infodecal, CDecal );

// UNDONE:  These won't get sent to joining players in multi-player
void CDecal::Spawn( void )
{
	if ( m_nTexture < 0 ||
		(gpGlobals->deathmatch && HasSpawnFlags( SF_DECAL_NOTINDEATHMATCH )) )
	{
		UTIL_Remove( this );
		return;
	}
}

void CDecal::Activate()
{
	BaseClass::Activate();

	if ( !GetEntityName() )
	{
		StaticDecal();
	}
	else
	{
		// if there IS a targetname, the decal sprays itself on when it is triggered.
		SetThink ( &CDecal::SUB_DoNothing );
		SetUse(&CDecal::TriggerDecal);
	}
}

void CDecal::TriggerDecal ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
	// this is set up as a USE function for info_decals that have targetnames, so that the
	// decal doesn't get applied until it is fired. (usually by a scripted sequence)
	trace_t		trace;
	int			entityIndex;

	UTIL_TraceLine( GetAbsOrigin() - Vector(5,5,5), GetAbsOrigin() + Vector(5,5,5), MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &trace );

	entityIndex = trace.m_pEnt ? trace.m_pEnt->entindex() : 0;

	CBroadcastRecipientFilter filter;

	te->BSPDecal( filter, 0.0,
		&GetAbsOrigin(), entityIndex, m_nTexture );

	SetThink( &CDecal::SUB_Remove );
	SetNextThink( gpGlobals->curtime + 0.1f );
}

void CDecal::InputActivate( inputdata_t &inputdata )
{
	TriggerDecal( inputdata.pActivator, inputdata.pCaller, USE_ON, 0 );
}

void CDecal::StaticDecal( void )
{
	class CTraceFilterValidForDecal : public CTraceFilterSimple
	{
	public:
		CTraceFilterValidForDecal(const IHandleEntity *passentity, int collisionGroup )
		 :	CTraceFilterSimple( passentity, collisionGroup )
		{
		}

		virtual bool ShouldHitEntity( IHandleEntity *pServerEntity, int contentsMask )
		{
			static const char *ppszIgnoredClasses[] =
			{
				"weapon_*",
				"item_*",
				"prop_ragdoll",
				"prop_dynamic",
				"prop_static",
				"prop_physics",
				"npc_bullseye",  // Tracker 15335
			};

			CBaseEntity *pEntity = EntityFromEntityHandle( pServerEntity );

			// Tracker 15335:  Never impact decals against entities which are not rendering, either.
			if ( pEntity->IsEffectActive( EF_NODRAW ) )
				return false;

			for ( int i = 0; i < ARRAYSIZE(ppszIgnoredClasses); i++ )
			{
				if ( pEntity->ClassMatches( ppszIgnoredClasses[i] ) )
					return false;
			}

			return CTraceFilterSimple::ShouldHitEntity( pServerEntity, contentsMask );
		}
	};

	trace_t trace;
	CTraceFilterValidForDecal traceFilter( this, COLLISION_GROUP_NONE );
	int entityIndex, modelIndex = 0;

	Vector position = GetAbsOrigin();
	UTIL_TraceLine( position - Vector(5,5,5), position + Vector(5,5,5),  MASK_SOLID, &traceFilter, &trace );

	bool canDraw = true;

	entityIndex = (short)trace.m_pEnt ? trace.m_pEnt->entindex() : 0;
	if ( entityIndex )
	{
		CBaseEntity *ent = trace.m_pEnt;
		if ( ent )
		{
			modelIndex = ent->GetModelIndex();
			VectorITransform( GetAbsOrigin(), ent->EntityToWorldTransform(), position );

			canDraw = ( modelIndex != 0 );
			if ( !canDraw )
			{
				Warning( "Suppressed StaticDecal which would have hit entity %i (class:%s, name:%s) with modelindex = 0\n",
					ent->entindex(),
					ent->GetClassname(),
					STRING( ent->GetEntityName() ) );
			}
		}
	}

	if ( canDraw )
	{
		engine->StaticDecal( position, m_nTexture, entityIndex, modelIndex, m_bLowPriority );
	}

	SUB_Remove();
}

bool CDecal::KeyValue( const char *szKeyName, const char *szValue )
{
	if (FStrEq(szKeyName, "texture"))
	{
		// FIXME:  should decals all be preloaded?
		m_nTexture = UTIL_PrecacheDecal( szValue, true );

		// Found
		if (m_nTexture >= 0 )
			return true;
		Warning( "Can't find decal %s\n", szValue );
	}
	else
	{
		return BaseClass::KeyValue( szKeyName, szValue );
	}

	return true;
}

//-----------------------------------------------------------------------------
// Purpose: Projects a decal against a prop
//-----------------------------------------------------------------------------
class CProjectedDecal : public CPointEntity
{
public:
	DECLARE_CLASS( CProjectedDecal, CPointEntity );

	void	Spawn( void );
	bool	KeyValue( const char *szKeyName, const char *szValue );

	// Need to apply static decals here to get them into the signon buffer for the server appropriately
	virtual void Activate();

	void	TriggerDecal( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );

	// Input handlers.
	void	InputActivate( inputdata_t &inputdata );

	DECLARE_DATADESC();

public:
	int		m_nTexture;
	float	m_flDistance;

private:
	void	ProjectDecal( CRecipientFilter& filter );

	void	StaticDecal( void );
};

BEGIN_DATADESC( CProjectedDecal )

	DEFINE_FIELD( m_nTexture, FIELD_INTEGER ),

	DEFINE_KEYFIELD( m_flDistance, FIELD_FLOAT, "Distance" ),

	// Function pointers
	DEFINE_FUNCTION( StaticDecal ),
	DEFINE_FUNCTION( TriggerDecal ),

	DEFINE_INPUTFUNC( FIELD_VOID, "Activate", InputActivate ),

END_DATADESC()

LINK_ENTITY_TO_CLASS( info_projecteddecal, CProjectedDecal );

// UNDONE:  These won't get sent to joining players in multi-player
void CProjectedDecal::Spawn( void )
{
	if ( m_nTexture < 0 ||
		(gpGlobals->deathmatch && HasSpawnFlags( SF_DECAL_NOTINDEATHMATCH )) )
	{
		UTIL_Remove( this );
		return;
	}
}

void CProjectedDecal::Activate()
{
	BaseClass::Activate();

	if ( !GetEntityName() )
	{
		StaticDecal();
	}
	else
	{
		// if there IS a targetname, the decal sprays itself on when it is triggered.
		SetThink ( &CProjectedDecal::SUB_DoNothing );
		SetUse(&CProjectedDecal::TriggerDecal);
	}
}

void CProjectedDecal::InputActivate( inputdata_t &inputdata )
{
	TriggerDecal( inputdata.pActivator, inputdata.pCaller, USE_ON, 0 );
}

void CProjectedDecal::ProjectDecal( CRecipientFilter& filter )
{
	te->ProjectDecal( filter, 0.0,
		&GetAbsOrigin(), &GetAbsAngles(), m_flDistance, m_nTexture );
}

void CProjectedDecal::TriggerDecal ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
	CBroadcastRecipientFilter filter;

	ProjectDecal( filter );

	SetThink( &CProjectedDecal::SUB_Remove );
	SetNextThink( gpGlobals->curtime + 0.1f );
}

void CProjectedDecal::StaticDecal( void )
{
	CBroadcastRecipientFilter initFilter;
	initFilter.MakeInitMessage();

	ProjectDecal( initFilter );

	SUB_Remove();
}

bool CProjectedDecal::KeyValue( const char *szKeyName, const char *szValue )
{
	if (FStrEq(szKeyName, "texture"))
	{
		// FIXME:  should decals all be preloaded?
		m_nTexture = UTIL_PrecacheDecal( szValue, true );

		// Found
		if (m_nTexture >= 0 )
			return true;
		Warning( "Can't find decal %s\n", szValue );
	}
	else
	{
		return BaseClass::KeyValue( szKeyName, szValue );
	}

	return true;
}

//=======================
// CWorld
//
// This spawns first when each level begins.
//=======================
LINK_ENTITY_TO_CLASS( worldspawn, CWorld );

BEGIN_DATADESC( CWorld )

	DEFINE_FIELD( m_flWaveHeight, FIELD_FLOAT ),

	// keyvalues are parsed from map, but not saved/loaded
	DEFINE_KEYFIELD( m_iszChapterTitle, FIELD_STRING, "chaptertitle" ),
	DEFINE_KEYFIELD( m_bStartDark,		FIELD_BOOLEAN, "startdark" ),
	DEFINE_KEYFIELD( m_bDisplayTitle,	FIELD_BOOLEAN, "gametitle" ),
	DEFINE_FIELD( m_WorldMins, FIELD_VECTOR ),
	DEFINE_FIELD( m_WorldMaxs, FIELD_VECTOR ),
	DEFINE_KEYFIELD( m_flMaxOccludeeArea, FIELD_FLOAT, "maxoccludeearea" ),
	DEFINE_KEYFIELD( m_flMinOccluderArea, FIELD_FLOAT, "minoccluderarea" ),
	DEFINE_KEYFIELD( m_flMaxPropScreenSpaceWidth, FIELD_FLOAT, "maxpropscreenwidth" ),
	DEFINE_KEYFIELD( m_flMinPropScreenSpaceWidth, FIELD_FLOAT, "minpropscreenwidth" ),
	DEFINE_KEYFIELD( m_iszDetailSpriteMaterial, FIELD_STRING, "detailmaterial" ),
	DEFINE_KEYFIELD( m_bColdWorld,		FIELD_BOOLEAN, "coldworld" ),

END_DATADESC()

// SendTable stuff.
IMPLEMENT_SERVERCLASS_ST(CWorld, DT_WORLD)
	SendPropFloat	(SENDINFO(m_flWaveHeight), 8, SPROP_ROUNDUP,	0.0f,	8.0f),
	SendPropVector	(SENDINFO(m_WorldMins),	-1,	SPROP_COORD),
	SendPropVector	(SENDINFO(m_WorldMaxs),	-1,	SPROP_COORD),
	SendPropInt		(SENDINFO(m_bStartDark), 1, SPROP_UNSIGNED ),
	SendPropInt		(SENDINFO(m_bRoundRestartCleanup), 1, SPROP_UNSIGNED),
	SendPropFloat	(SENDINFO(m_flMaxOccludeeArea), 0, SPROP_NOSCALE ),
	SendPropFloat	(SENDINFO(m_flMinOccluderArea), 0, SPROP_NOSCALE ),
	SendPropFloat	(SENDINFO(m_flMaxPropScreenSpaceWidth), 0, SPROP_NOSCALE ),
	SendPropFloat	(SENDINFO(m_flMinPropScreenSpaceWidth), 0, SPROP_NOSCALE ),
	SendPropStringT (SENDINFO(m_iszDetailSpriteMaterial) ),
	SendPropInt		(SENDINFO(m_bColdWorld), 1, SPROP_UNSIGNED ),
END_SEND_TABLE()

//
// Just to ignore the "wad" field.
//
bool CWorld::KeyValue( const char *szKeyName, const char *szValue )
{
	if ( FStrEq(szKeyName, "skyname") )
	{
		// Sent over net now.
		ConVar *skyname = ( ConVar * )cvar->FindVar( "sv_skyname" );
		if ( skyname )
		{
			skyname->SetValue( szValue );
		}
	}
	else if ( FStrEq(szKeyName, "newunit") )
	{
		// Single player only.  Clear save directory if set
		if ( atoi(szValue) )
		{
			extern void Game_SetOneWayTransition();
			Game_SetOneWayTransition();
		}
	}
	else if ( FStrEq(szKeyName, "world_mins") )
	{
		Vector vec;
		sscanf(	szValue, "%f %f %f", &vec.x, &vec.y, &vec.z );
		m_WorldMins = vec;
	}
	else if ( FStrEq(szKeyName, "world_maxs") )
	{
		Vector vec;
		sscanf(	szValue, "%f %f %f", &vec.x, &vec.y, &vec.z );
		m_WorldMaxs = vec;
	}
	else
		return BaseClass::KeyValue( szKeyName, szValue );

	return true;
}

extern bool		g_fGameOver;
static CWorld *g_WorldEntity = NULL;

CWorld* GetWorldEntity()
{
	return g_WorldEntity;
}

CWorld::CWorld( )
{
	AddEFlags( EFL_NO_AUTO_EDICT_ATTACH | EFL_KEEP_ON_RECREATE_ENTITIES );
	NetworkProp()->AttachEdict( INDEXENT(RequiredEdictIndex()) );
	ActivityList_Init();
	EventList_Init();

	SetSolid( SOLID_BSP );
	SetMoveType( MOVETYPE_NONE );

	m_bColdWorld = false;
}

CWorld::~CWorld( )
{
	EventList_Free();
	ActivityList_Free();
	if ( g_pGameRules )
	{
		g_pGameRules->LevelShutdown();
		delete g_pGameRules;
		g_pGameRules = NULL;
	}
	g_WorldEntity = NULL;
}

//------------------------------------------------------------------------------
// Purpose : Add a decal to the world
// Input   :
// Output  :
//------------------------------------------------------------------------------
void CWorld::DecalTrace( trace_t *pTrace, char const *decalName)
{
	int index = decalsystem->GetDecalIndexForName( decalName );
	if ( index < 0 )
		return;

	CBroadcastRecipientFilter filter;
	if ( pTrace->hitbox != 0 )
	{
		te->Decal( filter, 0.0f, &pTrace->endpos, &pTrace->startpos, 0, pTrace->hitbox, index );
	}
	else
	{
		te->WorldDecal( filter, 0.0, &pTrace->endpos, index );
	}
}

void CWorld::RegisterSharedActivities( void )
{
	ActivityList_RegisterSharedActivities();
}

void CWorld::RegisterSharedEvents( void )
{
	EventList_RegisterSharedEvents();
}

void CWorld::Spawn( void )
{
	SetLocalOrigin( vec3_origin );
	SetLocalAngles( vec3_angle );
	// NOTE:  SHOULD NEVER BE ANYTHING OTHER THAN 1!!!
	SetModelIndex( 1 );
	// world model
	SetModelName( AllocPooledString( modelinfo->GetModelName( GetModel() ) ) );
	AddFlag( FL_WORLDBRUSH );

	g_EventQueue.Init();
	Precache( );
}

static const char *g_DefaultLightstyles[] =
{
	// 0 normal
	"m",
	// 1 FLICKER (first variety)
	"mmnmmommommnonmmonqnmmo",
	// 2 SLOW STRONG PULSE
	"abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba",
	// 3 CANDLE (first variety)
	"mmmmmaaaaammmmmaaaaaabcdefgabcdefg",
	// 4 FAST STROBE
	"mamamamamama",
	// 5 GENTLE PULSE 1
	"jklmnopqrstuvwxyzyxwvutsrqponmlkj",
	// 6 FLICKER (second variety)
	"nmonqnmomnmomomno",
	// 7 CANDLE (second variety)
	"mmmaaaabcdefgmmmmaaaammmaamm",
	// 8 CANDLE (third variety)
	"mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa",
	// 9 SLOW STROBE (fourth variety)
	"aaaaaaaazzzzzzzz",
	// 10 FLUORESCENT FLICKER
	"mmamammmmammamamaaamammma",
	// 11 SLOW PULSE NOT FADE TO BLACK
	"abcdefghijklmnopqrrqponmlkjihgfedcba",
	// 12 UNDERWATER LIGHT MUTATION
	// this light only distorts the lightmap - no contribution
	// is made to the brightness of affected surfaces
	"mmnnmmnnnmmnn",
};

const char *GetDefaultLightstyleString( int styleIndex )
{
	if ( styleIndex < ARRAYSIZE(g_DefaultLightstyles) )
	{
		return g_DefaultLightstyles[styleIndex];
	}
	return "m";
}

void CWorld::Precache( void )
{
	g_WorldEntity = this;
	g_fGameOver = false;
	g_pLastSpawn = NULL;

	ConVar *stepsize = ( ConVar * )cvar->FindVar( "sv_stepsize" );
	if ( stepsize )
	{
		stepsize->SetValue( 18 );
	}

	ConVar *roomtype = ( ConVar * )cvar->FindVar( "room_type" );
	if ( roomtype )
	{
		roomtype->SetValue( 0 );
	}

	// Set up game rules
	Assert( !g_pGameRules );
	if (g_pGameRules)
	{
		delete g_pGameRules;
	}

	InstallGameRules();
	Assert( g_pGameRules );

	CSoundEnt::InitSoundEnt();

	// Only allow precaching between LevelInitPreEntity and PostEntity
	CBaseEntity::SetAllowPrecache( true );
	IGameSystem::LevelInitPreEntityAllSystems( STRING( GetModelName() ) );

	// Create the player resource
	g_pGameRules->CreateStandardEntities();

	// UNDONE: Make most of these things server systems or precache_registers
	// =================================================
	//	Activities
	// =================================================
	ActivityList_Free();
	RegisterSharedActivities();

	EventList_Free();
	RegisterSharedEvents();

	InitBodyQue();
// init sentence group playback stuff from sentences.txt.
// ok to call this multiple times, calls after first are ignored.

	SENTENCEG_Init();

// the area based ambient sounds MUST be the first precache_sounds

// player precaches
	W_Precache ();									// get weapon precaches
	ClientPrecache();
	g_pGameRules->Precache();
	// precache all temp ent stuff
	CBaseTempEntity::PrecacheTempEnts();

	g_Language.SetValue( LANGUAGE_ENGLISH );	// TODO use VGUI to get current language

	if ( g_Language.GetInt() == LANGUAGE_GERMAN )
	{
		PrecacheModel( "models/germangibs.mdl" );
	}
	else
	{
		PrecacheModel( "models/gibs/hgibs.mdl" );
	}

	PrecacheScriptSound( "BaseEntity.EnterWater" );
	PrecacheScriptSound( "BaseEntity.ExitWater" );

//
// Setup light animation tables. 'a' is total darkness, 'z' is maxbright.
//
	for ( int i = 0; i < ARRAYSIZE(g_DefaultLightstyles); i++ )
	{
		engine->LightStyle( i, GetDefaultLightstyleString(i) );
	}

	// styles 32-62 are assigned by the light program for switchable lights

	// 63 testing
	engine->LightStyle(63, "a");

	// =================================================
	//	Load and Init AI Networks
	// =================================================
	CAI_NetworkManager::InitializeAINetworks();
	// =================================================
	//	Load and Init AI Schedules
	// =================================================
	g_AI_SchedulesManager.LoadAllSchedules();
	// =================================================
	//	Initialize NPC Relationships
	// =================================================
	g_pGameRules->InitDefaultAIRelationships();
	CBaseCombatCharacter::InitInteractionSystem();

	// Call all registered precachers.
	CPrecacheRegister::Precache();

	if ( m_iszChapterTitle != NULL_STRING )
	{
		DevMsg( 2, "Chapter title: %s\n", STRING(m_iszChapterTitle) );
		CMessage *pMessage = (CMessage *)CBaseEntity::Create( "env_message", vec3_origin, vec3_angle, NULL );
		if ( pMessage )
		{
			pMessage->SetMessage( m_iszChapterTitle );
			m_iszChapterTitle = NULL_STRING;

			// send the message entity a play message command, delayed by 1 second
			pMessage->AddSpawnFlags( SF_MESSAGE_ONCE );
			pMessage->SetThink( &CMessage::SUB_CallUseToggle );
			pMessage->SetNextThink( gpGlobals->curtime + 1.0f );
		}
	}

	g_iszFuncBrushClassname = AllocPooledString("func_brush");
}

//-----------------------------------------------------------------------------
// Purpose:
// Output : float
//-----------------------------------------------------------------------------
float GetRealTime()
{
	return engine->Time();
}

bool CWorld::GetDisplayTitle() const
{
	return m_bDisplayTitle;
}

bool CWorld::GetStartDark() const
{
	return m_bStartDark;
}

void CWorld::SetDisplayTitle( bool display )
{
	m_bDisplayTitle = display;
}

void CWorld::SetStartDark( bool startdark )
{
	m_bStartDark = startdark;
}

bool CWorld::IsColdWorld( void )
{
	return m_bColdWorld;
}

//qck edit
void CWorld::ToggleRoundRestart()
{
	m_bRoundRestartCleanup = !m_bRoundRestartCleanup;
}


text:
namespace Zirpl.Stats.EloRating
{
    public class EloMatch
    {
        public double Team1CurrentRating { get; set; }
        public double Team2CurrentRating { get; set; }
        public double Team1MatchScore { get; set; }
        public double Team2MatchScore { get; set; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:paddingTop="0dip"
            android:paddingBottom="15dip"
            android:paddingLeft="15dip"
            android:paddingRight="15dip"

    >

  <LinearLayout android:id="@android:id/list"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center_horizontal">

    <TextView android:id="@+id/translation"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:gravity="left"
              android:textAppearance="@style/Translation"
              android:paddingBottom="10dip"
        />

    <TableLayout android:id="@+id/detailed"
                 android:layout_width="fill_parent"
                 android:layout_height="fill_parent"
        >

      <TableRow android:id="@+id/row1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:paddingBottom="15dip"
          >

        <TextView android:id="@+id/infinitive_label"
                  android:minWidth="100dip"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="right"
                  android:text="@string/infinitive"
                  android:textAppearance="@style/Labels"
                  android:paddingRight="5dip"
            />

        <TextView android:id="@+id/infinitive"
                  android:minWidth="100dip"
                  android:layout_width="wrap_content"
                  android:gravity="left"
                  android:paddingLeft="5dip"
                  android:layout_height="wrap_content"
                  android:textAppearance="@style/DialogLike"
            />
      </TableRow>

      <TableRow android:id="@+id/row2"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:paddingBottom="15dip"
          >

        <TextView android:id="@+id/past_singular_label"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:paddingRight="5dip"
                  android:gravity="right"
                  android:text="@string/past_singular"
                  android:textAppearance="@style/Labels"
            />

        <TextView android:id="@+id/past_singular"
                  android:layout_width="wrap_content"
                  android:gravity="left"
                  android:layout_height="wrap_content"
                  android:paddingLeft="5dip"
                  android:textAppearance="@style/DialogLike"
            />

      </TableRow>

      <TableRow android:id="@+id/row43"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:paddingBottom="15dip"
          >

        <TextView android:id="@+id/past_plural_label"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="right"
                  android:paddingRight="5dip"
                  android:text="@string/past_plural"
                  android:textAppearance="@style/Labels"
            />

        <TextView android:id="@+id/past_plural"
                  android:layout_width="wrap_content"
                  android:gravity="left"
                  android:layout_height="wrap_content"
                  android:paddingLeft="5dip"
                  android:textAppearance="@style/DialogLike"
            />

      </TableRow>

      <TableRow android:id="@+id/row4"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:paddingBottom="25dip"
          >

        <TextView android:id="@+id/past_participle_label"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:gravity="right"
                  android:paddingRight="5dip"
                  android:text="@string/past_participle"
                  android:textAppearance="@style/Labels"
            />

        <TextView android:id="@+id/past_participle"
                  android:layout_width="wrap_content"
                  android:gravity="left"
                  android:layout_height="wrap_content"
                  android:paddingLeft="5dip"
                  android:textAppearance="@style/DialogLike"
            />

      </TableRow>

      <ImageButton
          android:id="@+id/close_info"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:paddingTop="2dp"
          android:paddingBottom="2dp"
          android:src="@android:drawable/ic_menu_revert"
          />

    </TableLayout>

  </LinearLayout>
</ScrollView>


text:
package org.apache.camel.spring.config;

import org.apache.camel.spring.SpringTestSupport;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CamelPropertiesTest extends SpringTestSupport {

    protected AbstractXmlApplicationContext createApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/camel/spring/config/CamelPropertiesTest.xml");
    }

    public void testProperties() throws Exception {
        assertNotNull(context.getProperties());
        assertEquals(2, context.getProperties().size());
        assertEquals("123", context.getProperties().get("foo"));
        assertEquals("cheese", context.getProperties().get("bar"));
    }

}


text:
import base64
from xdrlib import Packer, Unpacker

from .bucket_entry_type import BucketEntryType
from .bucket_metadata import BucketMetadata
from .ledger_entry import LedgerEntry
from .ledger_key import LedgerKey

__all__ = ["BucketEntry"]

class BucketEntry:
    """
    XDR Source Code::

        union BucketEntry switch (BucketEntryType type)
        {
        case LIVEENTRY:
        case INITENTRY:
            LedgerEntry liveEntry;

        case DEADENTRY:
            LedgerKey deadEntry;
        case METAENTRY:
            BucketMetadata metaEntry;
        };
    """

    def __init__(
        self,
        type: BucketEntryType,
        live_entry: LedgerEntry = None,
        dead_entry: LedgerKey = None,
        meta_entry: BucketMetadata = None,
    ) -> None:
        self.type = type
        self.live_entry = live_entry
        self.dead_entry = dead_entry
        self.meta_entry = meta_entry

    def pack(self, packer: Packer) -> None:
        self.type.pack(packer)
        if self.type == BucketEntryType.LIVEENTRY:
            if self.live_entry is None:
                raise ValueError("live_entry should not be None.")
            self.live_entry.pack(packer)
            return
        if self.type == BucketEntryType.INITENTRY:
            if self.live_entry is None:
                raise ValueError("live_entry should not be None.")
            self.live_entry.pack(packer)
            return
        if self.type == BucketEntryType.DEADENTRY:
            if self.dead_entry is None:
                raise ValueError("dead_entry should not be None.")
            self.dead_entry.pack(packer)
            return
        if self.type == BucketEntryType.METAENTRY:
            if self.meta_entry is None:
                raise ValueError("meta_entry should not be None.")
            self.meta_entry.pack(packer)
            return

    @classmethod
    def unpack(cls, unpacker: Unpacker) -> "BucketEntry":
        type = BucketEntryType.unpack(unpacker)
        if type == BucketEntryType.LIVEENTRY:
            live_entry = LedgerEntry.unpack(unpacker)
            return cls(type=type, live_entry=live_entry)
        if type == BucketEntryType.INITENTRY:
            live_entry = LedgerEntry.unpack(unpacker)
            return cls(type=type, live_entry=live_entry)
        if type == BucketEntryType.DEADENTRY:
            dead_entry = LedgerKey.unpack(unpacker)
            return cls(type=type, dead_entry=dead_entry)
        if type == BucketEntryType.METAENTRY:
            meta_entry = BucketMetadata.unpack(unpacker)
            return cls(type=type, meta_entry=meta_entry)
        return cls(type=type)

    def to_xdr_bytes(self) -> bytes:
        packer = Packer()
        self.pack(packer)
        return packer.get_buffer()

    @classmethod
    def from_xdr_bytes(cls, xdr: bytes) -> "BucketEntry":
        unpacker = Unpacker(xdr)
        return cls.unpack(unpacker)

    def to_xdr(self) -> str:
        xdr_bytes = self.to_xdr_bytes()
        return base64.b64encode(xdr_bytes).decode()

    @classmethod
    def from_xdr(cls, xdr: str) -> "BucketEntry":
        xdr_bytes = base64.b64decode(xdr.encode())
        return cls.from_xdr_bytes(xdr_bytes)

    def __eq__(self, other: object):
        if not isinstance(other, self.__class__):
            return NotImplemented
        return (
            self.type == other.type
            and self.live_entry == other.live_entry
            and self.dead_entry == other.dead_entry
            and self.meta_entry == other.meta_entry
        )

    def __str__(self):
        out = []
        out.append(f"type={self.type}")
        out.append(
            f"live_entry={self.live_entry}"
        ) if self.live_entry is not None else None
        out.append(
            f"dead_entry={self.dead_entry}"
        ) if self.dead_entry is not None else None
        out.append(
            f"meta_entry={self.meta_entry}"
        ) if self.meta_entry is not None else None
        return f"<BucketEntry [{', '.join(out)}]>"


text:
package main

import (
	"os"

	"github.com/kdar/factorlog"
)

var (
	format = factorlog.NewStdFormatter("[%{Date} %{Time}] [%{SEVERITY}] %{Message}")
	logger = factorlog.New(os.Stdout, format)
)


text:
    <button type="button" class="close" ng-click="vm.cancel()" aria-label="Close">×</button>

Share Post

            John Smith
            <textarea placeholder="Say something about this..." class="form-control"></textarea>

Looks like team "Giggle Waters" had the last giggle after all! Congratulations to the Champion

    <button type="button" class="btn btn-grey" ng-click="vm.cancel()">Cancel</button>
    <button type="button" class="btn btn-blue">Share</button>