code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
/*
Lodo is a layered to-do list (Outliner)
Copyright (C) 2015 Keith Morrow.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License v3 as
published by the Free Software Foundation.
This program 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package lodo
import java.util.UUID
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import Helper._
object NotebookSelector {
case class Props(b: Dashboard.Backend, itemMap: ItemMap,
selectedNotebook: Option[UUID],
isAdding: Boolean,
isCompleteHidden: Boolean,
isQuickAdd: Boolean)
case class State(isNotebookAdding: Boolean = false,
addText: String = "",
isDragOver: Boolean = false)
class Backend(t: BackendScope[Props, State]) {
def onClickAdd() = {
t.modState(s => s.copy(isNotebookAdding = !s.isNotebookAdding))
}
def onFocus(e: ReactEventI) =
e.currentTarget.select()
def onEdit(e: ReactEventI) =
t.modState(s => s.copy(addText = e.currentTarget.value))
def onSubmit(e: ReactEvent) = {
e.preventDefault()
t.modState(s => {
t.props.b.onNotebookAddComplete(AddOp(Item(UUID.randomUUID, None, time(), s.addText)))
s.copy(isNotebookAdding = t.props.isQuickAdd, addText = "")
})
}
def onDragEnter(e: ReactDragEvent) = {
e.stopPropagation()
e.preventDefault()
t.modState(_.copy(isDragOver = true))
}
def onDragLeave(e: ReactDragEvent) = {
e.stopPropagation()
e.preventDefault()
t.modState(_.copy(isDragOver = false))
}
def onDragOver(e: ReactDragEvent) = {
e.stopPropagation()
e.preventDefault()
}
def onDrop(e: ReactDragEvent): Unit = {
e.stopPropagation()
e.preventDefault()
t.modState(_.copy(isDragOver = false))
val src = UUID.fromString(e.dataTransfer.getData("lodo"))
val item = t.props.itemMap(Some(src))
item.map(item => {
t.props.b.moveAndSelectNotebook(MoveOp(item, None, time()), item.id)
})
}
}
val notebookSelector = ReactComponentB[Props]("NotebookSelector")
.initialState(State())
.backend(new Backend(_))
.render((P, S, B) =>
<.ul(^.cls := "nav nav-sidebar",
P.itemMap.notebooks()
.zipWithIndex
.map { case (c, i) =>
Notebook(Notebook.Props(P.b, P.selectedNotebook, P.isAdding, P.itemMap, c, i))
},
if (S.isNotebookAdding)
<.li(
<.a(^.href := "#",
<.form(^.onSubmit ==> B.onSubmit,
<.input(^.onFocus ==> B.onFocus, ^.autoFocus := true,
^.onChange ==> B.onEdit)
)
)
)
else
<.li(
^.classSet(("dragover", S.isDragOver)),
^.onDragEnter ==> B.onDragEnter,
^.onDragLeave ==> B.onDragLeave,
^.onDragOver ==> B.onDragOver,
^.onDrop ==> B.onDrop,
^.title := "Create new notebook",
<.a(^.href := "#", ^.onClick --> B.onClickAdd(),
<.span(^.cls := "glyphicon glyphicon-plus"),
<.span(^.classSet(("draghidden", !S.isDragOver)),
" Create notebook from item"
)
)
)
)
)
.build
def apply(props: Props) = notebookSelector(props)
}
| Java |
<?php
/*
This file is part of Incipio.
Incipio is an enterprise resource planning for Junior Enterprise
Copyright (C) 2012-2014 Florian Lefevre.
Incipio is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Incipio 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Incipio as the file LICENSE. If not, see <http://www.gnu.org/licenses/>.
*/
namespace mgate\PersonneBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use JMS\SecurityExtraBundle\Annotation\Secure;
use mgate\PersonneBundle\Entity\Poste;
use mgate\PersonneBundle\Entity\Personne;
use mgate\PersonneBundle\Form\PosteType;
class PosteController extends Controller
{
/**
* @Secure(roles="ROLE_SUIVEUR")
*/
public function ajouterAction()
{
$em = $this->getDoctrine()->getManager();
$poste = new Poste;
$form = $this->createForm(new PosteType, $poste);
if( $this->get('request')->getMethod() == 'POST' )
{
$form->bind($this->get('request'));
if( $form->isValid() )
{
$em->persist($poste);
$em->flush();
return $this->redirect( $this->generateUrl('mgatePersonne_poste_voir', array('id' => $poste->getId())) );
}
}
return $this->render('mgatePersonneBundle:Poste:ajouter.html.twig', array(
'form' => $form->createView(),
));
}
/**
* Affiche la liste des pages et permet aux admin d'ajouter un poste
* @Secure(roles="ROLE_MEMBRE")
*/
public function indexAction($page)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('mgatePersonneBundle:Poste')->findAll();
// On récupère le service
$security = $this->get('security.context');
// On récupère le token
$token = $security->getToken();
// on récupère l'utilisateur
$user = $token->getUser();
if($security->isGranted('ROLE_ADMIN')){
$poste = new Poste;
$form = $this->createForm(new PosteType, $poste);
return $this->render('mgatePersonneBundle:Poste:index.html.twig', array(
'postes' => $entities,
'form' => $form->createView()
));
}
return $this->render('mgatePersonneBundle:Poste:index.html.twig', array(
'postes' => $entities,
));
}
/**
* @Secure(roles="ROLE_MEMBRE")
*/
public function voirAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('mgatePersonneBundle:Poste')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Le poste demandé n\'existe pas !');
}
//$deleteForm = $this->createDeleteForm($id);
return $this->render('mgatePersonneBundle:Poste:voir.html.twig', array(
'poste' => $entity,
/*'delete_form' => $deleteForm->createView(), */));
}
/**
* @Secure(roles="ROLE_SUIVEUR")
*/
public function modifierAction($id)
{
$em = $this->getDoctrine()->getManager();
if( ! $poste = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) )
throw $this->createNotFoundException('Le poste demandé n\'existe pas !');
// On passe l'$article récupéré au formulaire
$form = $this->createForm(new PosteType, $poste);
$deleteForm = $this->createDeleteForm($id);
if( $this->get('request')->getMethod() == 'POST' )
{
$form->bind($this->get('request'));
if( $form->isValid() )
{
$em->persist($poste);
$em->flush();
return $this->redirect( $this->generateUrl('mgatePersonne_poste_voir', array('id' => $poste->getId())) );
}
}
return $this->render('mgatePersonneBundle:Poste:modifier.html.twig', array(
'form' => $form->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* @Secure(roles="ROLE_SUIVEUR")
*/
public function deleteAction($id)
{
$form = $this->createDeleteForm($id);
$request = $this->getRequest();
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
if( ! $entity = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) )
throw $this->createNotFoundException('Le poste demandé n\'existe pas !');
foreach($entity->getMembres() as $membre)
$membre->setPoste(null);
//$entity->setMembres(null);
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('mgatePersonne_poste_homepage'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
| Java |
// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package state
import (
"math/big"
"github.com/ethereumproject/go-ethereum/common"
)
type journalEntry interface {
undo(*StateDB)
}
type journal []journalEntry
type (
// Changes to the account trie.
createObjectChange struct {
account *common.Address
}
resetObjectChange struct {
prev *StateObject
}
suicideChange struct {
account *common.Address
prev bool // whether account had already suicided
prevbalance *big.Int
}
// Changes to individual accounts.
balanceChange struct {
account *common.Address
prev *big.Int
}
nonceChange struct {
account *common.Address
prev uint64
}
storageChange struct {
account *common.Address
key, prevalue common.Hash
}
codeChange struct {
account *common.Address
prevcode, prevhash []byte
}
// Changes to other state values.
refundChange struct {
prev *big.Int
}
addLogChange struct {
txhash common.Hash
}
)
func (ch createObjectChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).deleted = true
delete(s.stateObjects, *ch.account)
delete(s.stateObjectsDirty, *ch.account)
}
func (ch resetObjectChange) undo(s *StateDB) {
s.setStateObject(ch.prev)
}
func (ch suicideChange) undo(s *StateDB) {
obj := s.GetStateObject(*ch.account)
if obj != nil {
obj.suicided = ch.prev
obj.setBalance(ch.prevbalance)
}
}
func (ch balanceChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setBalance(ch.prev)
}
func (ch nonceChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setNonce(ch.prev)
}
func (ch codeChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setCode(common.BytesToHash(ch.prevhash), ch.prevcode)
}
func (ch storageChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setState(ch.key, ch.prevalue)
}
func (ch refundChange) undo(s *StateDB) {
s.refund = ch.prev
}
func (ch addLogChange) undo(s *StateDB) {
logs := s.logs[ch.txhash]
if len(logs) == 1 {
delete(s.logs, ch.txhash)
} else {
s.logs[ch.txhash] = logs[:len(logs)-1]
}
}
| Java |
using NetEOC.Auth.Data;
using NetEOC.Auth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetEOC.Auth.Services
{
public class OrganizationService
{
public OrganizationRepository OrganizationRepository { get; set; }
public OrganizationMemberRepository OrganizationMemberRepository { get; set; }
public OrganizationAdminRepository OrganizationAdminRepository { get; set; }
public OrganizationService()
{
OrganizationRepository = new OrganizationRepository();
OrganizationAdminRepository = new OrganizationAdminRepository();
OrganizationMemberRepository = new OrganizationMemberRepository();
}
public async Task<Organization> Create(Organization organization)
{
if (!ValidateOrganization(organization)) throw new ArgumentException("Invalid Organization!");
if(organization.Id != Guid.Empty)
{
Organization existing = await Update(organization);
if (existing != null) return existing;
}
return await OrganizationRepository.Create(organization);
}
public async Task<Organization> GetById(Guid id)
{
return await OrganizationRepository.Get(id);
}
public async Task<Organization[]> GetByOwnerId(Guid ownerId)
{
return await OrganizationRepository.GetByOwnerId(ownerId);
}
public async Task<Organization> Update(Organization organization)
{
if (!ValidateOrganization(organization)) throw new ArgumentException("Invalid Organization!");
if (organization.Id == Guid.Empty) throw new ArgumentException("Organization has no id!");
//merge organization
Organization existing = await GetById(organization.Id);
if (existing == null) return null;
if (!string.IsNullOrWhiteSpace(organization.Name)) existing.Name = organization.Name;
if (!string.IsNullOrWhiteSpace(organization.Description)) existing.Description = organization.Description;
if (organization.Data != null)
{
foreach (var kv in organization.Data)
{
if (existing.Data.ContainsKey(kv.Key))
{
existing.Data[kv.Key] = kv.Value;
}
else
{
existing.Data.Add(kv.Key, kv.Value);
}
}
}
return await OrganizationRepository.Update(existing);
}
public async Task<bool> Delete(Guid organizationId)
{
return await OrganizationRepository.Delete(organizationId);
}
public async Task<Guid[]> GetOrganizationMembers(Guid organizationId)
{
return (await OrganizationMemberRepository.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray();
}
public async Task<Guid[]> GetOrganizationAdmins(Guid organizationId)
{
return (await OrganizationAdminRepository.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray();
}
public async Task<OrganizationMember> AddMemberToOrganization(Guid organizationId, Guid userId)
{
OrganizationMember[] memberships = await OrganizationMemberRepository.GetByUserId(userId);
OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
if (membership == null)
{
membership = new OrganizationMember { OrganizationId = organizationId, UserId = userId };
membership = await OrganizationMemberRepository.Create(membership);
}
return membership;
}
public async Task<bool> RemoveMemberFromOrganization(Guid organizationId, Guid userId)
{
OrganizationMember[] memberships = await OrganizationMemberRepository.GetByUserId(userId);
OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
bool success = false;
if (membership != null)
{
success = await OrganizationMemberRepository.Delete(membership.Id);
}
return success;
}
public async Task<OrganizationAdmin> AddAdminToOrganization(Guid organizationId, Guid userId)
{
OrganizationAdmin[] memberships = await OrganizationAdminRepository.GetByUserId(userId);
OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
if (membership == null)
{
membership = new OrganizationAdmin { OrganizationId = organizationId, UserId = userId };
membership = await OrganizationAdminRepository.Create(membership);
}
return membership;
}
public async Task<bool> RemoveAdminFromOrganization(Guid organizationId, Guid userId)
{
OrganizationAdmin[] memberships = await OrganizationAdminRepository.GetByUserId(userId);
OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
bool success = false;
if (membership != null)
{
success = await OrganizationAdminRepository.Delete(membership.Id);
}
return success;
}
private bool ValidateOrganization(Organization organization)
{
if (organization.OwnerId == Guid.Empty) throw new ArgumentException("Organization must have an owner!");
if (string.IsNullOrWhiteSpace(organization.Name)) throw new ArgumentException("Organization must have a name!");
return true;
}
}
}
| Java |
.form-field { overflow: hidden; }
/* Order of the field attributes */
.form-wrap.form-builder .frmb .form-elements { display: flex; flex-direction: column; }
.form-wrap.form-builder .frmb .form-field .form-group { order: 100; }
.required-wrap { order: 0 !important; }
.name-wrap { order: 1 !important; }
.label-wrap { order: 2 !important; }
.subtype-wrap { order: 3 !important; }
.separator-wrap {
order: 50 !important;
margin-top: 10px;
border-top: 1px dashed grey;
padding-top: 10px;
}
.access-wrap { order: 110 !important; }
.separator-field label, .separator-field .copy-button, .separator-field .toggle-form { display: none !important; }
.separator-wrap label, .separator-wrap .input-wrap { display: none !important; }
.separator-wrap {
order: 50 !important;
margin-top: 10px;
border-top: 1px dashed grey;
padding-top: 10px;
}
.form-wrap.form-builder .frmb .form-elements .input-wrap { width: 70%; }
.form-wrap.form-builder .frmb .form-elements .false-label:first-child, .form-wrap.form-builder .frmb .form-elements label:first-child { width: 25%; }
.titre-field .required-wrap,
.titre-field .name-wrap {
display: none !important;
}
.map-field .label-wrap,
.map-field .value-wrap,
.map-field .name-wrap {
display: none !important;
}
.date-field .value-wrap { display: none !important; }
.image-field .value-wrap, .image-field .name-wrap { display: none !important; }
.image-field .name2-wrap { order: 1 !important; }
.select-field .field-options, .radio-group-field .field-options, .checkbox-group-field .field-options { display: none !important; }
.form-wrap.form-builder .frmb .form-elements .false-label:first-child, .form-wrap.form-builder .frmb .form-elements label:first-child {
white-space: normal;
text-overflow: initial;
}
.form-wrap.form-builder .form-elements .form-group > label {
white-space: normal !important;
}
.listId-wrap, .formId-wrap { display: none !important; }
.textarea-field .maxlength-wrap,
.textarea-field .subtype-wrap {
display: none !important;
}
.file-field .subtype-wrap { display: none !important; }
.inscriptionliste-field .required-wrap,
.inscriptionliste-field .name-wrap,
.inscriptionliste-field .value-wrap {
display: none !important;
}
.labelhtml-field .required-wrap,
.labelhtml-field .name-wrap,
.labelhtml-field .value-wrap,
.labelhtml-field .label-wrap {
display: none !important;
}
.utilisateur_wikini-field .required-wrap,
.utilisateur_wikini-field .name-wrap,
.utilisateur_wikini-field .value-wrap,
.utilisateur_wikini-field .label-wrap {
display: none !important;
}
.acls-field .required-wrap,
.acls-field .name-wrap,
.acls-field .value-wrap,
.acls-field .label-wrap {
display: none !important;
}
.metadatas-field .required-wrap,
.metadatas-field .name-wrap,
.metadatas-field .value-wrap,
.metadatas-field .label-wrap {
display: none !important;
}
.listefichesliees-field .required-wrap,
.listefichesliees-field .name-wrap,
.listefichesliees-field .value-wrap,
.listefichesliees-field .label-wrap {
display: none !important;
}
.bookmarklet-field .required-wrap {
display: none !important;
}
.custom-field .required-wrap,
.custom-field .name-wrap,
.custom-field .value-wrap,
.custom-field .label-wrap {
display: none !important;
}
xmp { overflow: auto; }
/* Redefine .fa class when icon- class exists, because redefined by form-builder.min.js*/
.fa[class*=" icon-"]::before, .fa[class^="icon-"]::before {
font-family: inherit;
font-weight: inherit;
font-style: inherit;
margin: 0;
font-variant: inherit;
line-height: inherit;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
width: inherit;
text-transform: inherit;
}
/* Make the list of fields smaller */
.form-wrap.form-builder .frmb-control li {
padding: 5px 10px;
font-size: 15px;
}
.form-wrap.form-builder .frmb li {
padding: 5px 10px;
}
.form-wrap.form-builder .frmb li:first-child {
padding-top: 10px;
}
.form-wrap.form-builder .frmb .field-label {
font-weight: bold;
}
.form-wrap.form-builder .frmb .prev-holder {
font-size: 15px;
}
.form-wrap.form-builder .frmb .prev-holder input:not([type=file]),
.form-wrap.form-builder .frmb .prev-holder textarea {
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: none;
}
| Java |
package com.wirecard.acqp.two;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
@SuppressWarnings("javadoc")
public class ThreadingLongrunningTest {
/**
* The number of threads to use in this test.
*/
private static final int NUM_THREADS = 12;
/**
* Flag to indicate the concurrent test has failed.
*/
private boolean failed;
@Test
public void testConcurrently() {
final ParserHardeningLongrunningTest pt = new ParserHardeningLongrunningTest();
final String msg = "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2";
Runnable runnable = new Runnable() {
public void run() {
try {
pt.testParserHardeningJCB();
pt.testParserHardeningMC();
String fieldValue = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD",
"2");
assertEquals("PAN (Field 2) was not read correctly.",
"5405620000000000014", fieldValue);
String mti = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD",
"0");
assertEquals("mti was not read correctly.",
"0100", mti);
pt.testParserHardeningVisa();
} catch (Exception e) {
failed = true;
}
}
};
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < NUM_THREADS; i++) {
threads[i].start();
}
for (int i = 0; i < NUM_THREADS; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
failed = true;
}
}
assertFalse(failed);
}
// @Test obsolet but temp
// public void testGetFieldValueMixedgetFieldMethods()
// throws IllegalArgumentException, ISOException,
// IllegalStateException, UnsupportedEncodingException {
//
// // UtilityMethodAccess after construktor
// String msg =
// "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2";
// assertEquals("PAN (Field 2) was not read correctly.",
// "5405620000000000014",
// msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2"));
//
// assertEquals("PAN (Field 2) was not equal.",
// "5400041234567898",
// msgAccessoryInitial.getFieldValue("2"));
//
// // UtilityMethodAccess after construktor
// assertEquals("PAN (Field 2) was not read correctly.",
// "5405620000000000014",
// msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2"));
//
// }
}
| Java |
/* gzlib.c -- zlib functions common to reading and writing gzip files
* Copyright (C) 2004-2017 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "gzguts.h"
#if defined(_WIN32) && !defined(__BORLANDC__)
# define LSEEK _lseeki64
#else
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
# define LSEEK lseek64
#else
# define LSEEK lseek
#endif
#endif
/* Local functions */
local void gz_reset OF((gz_statep));
local gzFile gz_open OF((const void *, int, const char *));
#if defined UNDER_CE
/* Map the Windows error number in ERROR to a locale-dependent error message
string and return a pointer to it. Typically, the values for ERROR come
from GetLastError.
The string pointed to shall not be modified by the application, but may be
overwritten by a subsequent call to gz_strwinerror
The gz_strwinerror function does not change the current setting of
GetLastError. */
char ZLIB_INTERNAL *gz_strwinerror (error)
DWORD error;
{
static char buf[1024];
wchar_t *msgbuf;
DWORD lasterr = GetLastError();
DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
error,
0, /* Default language */
(LPVOID)&msgbuf,
0,
NULL);
if (chars != 0) {
/* If there is an \r\n appended, zap it. */
if (chars >= 2
&& msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
chars -= 2;
msgbuf[chars] = 0;
}
if (chars > sizeof (buf) - 1) {
chars = sizeof (buf) - 1;
msgbuf[chars] = 0;
}
wcstombs(buf, msgbuf, chars + 1);
LocalFree(msgbuf);
}
else {
sprintf(buf, "unknown win32 error (%ld)", error);
}
SetLastError(lasterr);
return buf;
}
#endif /* UNDER_CE */
/* Reset gzip file state */
local void gz_reset(state)
gz_statep state;
{
state->x.have = 0; /* no output data available */
if (state->mode == GZ_READ) { /* for reading ... */
state->eof = 0; /* not at end of file */
state->past = 0; /* have not read past end yet */
state->how = LOOK; /* look for gzip header */
}
else /* for writing ... */
state->reset = 0; /* no deflateReset pending */
state->seek = 0; /* no seek request pending */
gz_error(state, Z_OK, NULL); /* clear error */
state->x.pos = 0; /* no uncompressed data yet */
state->strm.avail_in = 0; /* no input data yet */
}
/* Open a gzip file either by name or file descriptor. */
local gzFile gz_open(path, fd, mode)
const void *path;
int fd;
const char *mode;
{
gz_statep state;
z_size_t len;
int oflag;
#ifdef O_CLOEXEC
int cloexec = 0;
#endif
#ifdef O_EXCL
int exclusive = 0;
#endif
/* check input */
if (path == NULL)
return NULL;
/* allocate gzFile structure to return */
state = (gz_statep)malloc(sizeof(gz_state));
if (state == NULL)
return NULL;
state->size = 0; /* no buffers allocated yet */
state->want = GZBUFSIZE; /* requested buffer size */
state->msg = NULL; /* no error message yet */
/* interpret mode */
state->mode = GZ_NONE;
state->level = Z_DEFAULT_COMPRESSION;
state->strategy = Z_DEFAULT_STRATEGY;
state->direct = 0;
while (*mode) {
if (*mode >= '0' && *mode <= '9')
state->level = *mode - '0';
else
switch (*mode) {
case 'r':
state->mode = GZ_READ;
break;
#ifndef NO_GZCOMPRESS
case 'w':
state->mode = GZ_WRITE;
break;
case 'a':
state->mode = GZ_APPEND;
break;
#endif
case '+': /* can't read and write at the same time */
free(state);
return NULL;
case 'b': /* ignore -- will request binary anyway */
break;
#ifdef O_CLOEXEC
case 'e':
cloexec = 1;
break;
#endif
#ifdef O_EXCL
case 'x':
exclusive = 1;
break;
#endif
case 'f':
state->strategy = Z_FILTERED;
break;
case 'h':
state->strategy = Z_HUFFMAN_ONLY;
break;
case 'R':
state->strategy = Z_RLE;
break;
case 'F':
state->strategy = Z_FIXED;
break;
case 'T':
state->direct = 1;
break;
default: /* could consider as an error, but just ignore */
;
}
mode++;
}
/* must provide an "r", "w", or "a" */
if (state->mode == GZ_NONE) {
free(state);
return NULL;
}
/* can't force transparent read */
if (state->mode == GZ_READ) {
if (state->direct) {
free(state);
return NULL;
}
state->direct = 1; /* for empty file */
}
/* save the path name for error messages */
#ifdef WIDECHAR
if (fd == -2) {
len = wcstombs(NULL, path, 0);
if (len == (z_size_t)-1)
len = 0;
}
else
#endif
len = strlen((const char *)path);
state->path = (char *)malloc(len + 1);
if (state->path == NULL) {
free(state);
return NULL;
}
#ifdef WIDECHAR
if (fd == -2)
if (len)
wcstombs(state->path, path, len + 1);
else
*(state->path) = 0;
else
#endif
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(state->path, len + 1, "%s", (const char *)path);
#else
strcpy(state->path, path);
#endif
/* compute the flags for open() */
oflag =
#ifdef O_LARGEFILE
O_LARGEFILE |
#endif
#ifdef O_BINARY
O_BINARY |
#endif
#ifdef O_CLOEXEC
(cloexec ? O_CLOEXEC : 0) |
#endif
(state->mode == GZ_READ ?
O_RDONLY :
(O_WRONLY | O_CREAT |
#ifdef O_EXCL
(exclusive ? O_EXCL : 0) |
#endif
(state->mode == GZ_WRITE ?
O_TRUNC :
O_APPEND)));
/* open the file with the appropriate flags (or just use fd) */
state->fd = fd > -1 ? fd : (
#ifdef WIDECHAR
fd == -2 ? _wopen(path, oflag, 0666) :
#endif
open((const char *)path, oflag, 0666));
if (state->fd == -1) {
free(state->path);
free(state);
return NULL;
}
if (state->mode == GZ_APPEND) {
LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */
state->mode = GZ_WRITE; /* simplify later checks */
}
/* save the current position for rewinding (only if reading) */
if (state->mode == GZ_READ) {
state->start = LSEEK(state->fd, 0, SEEK_CUR);
if (state->start == -1) state->start = 0;
}
/* initialize stream */
gz_reset(state);
/* return stream */
return (gzFile)state;
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen64(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzdopen(fd, mode)
int fd;
const char *mode;
{
char *path; /* identifier for error messages */
gzFile gz;
if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
return NULL;
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd);
#else
sprintf(path, "<fd:%d>", fd); /* for debugging */
#endif
gz = gz_open(path, fd, mode);
free(path);
return gz;
}
/* -- see zlib.h -- */
#ifdef WIDECHAR
gzFile ZEXPORT gzopen_w(path, mode)
const wchar_t *path;
const char *mode;
{
return gz_open(path, -2, mode);
}
#endif
/* -- see zlib.h -- */
int ZEXPORT gzbuffer(file, size)
gzFile file;
unsigned size;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* make sure we haven't already allocated memory */
if (state->size != 0)
return -1;
/* check and set requested size */
if ((size << 1) < size)
return -1; /* need to be able to double it */
if (size < 2)
size = 2; /* need two bytes to check magic header */
state->want = size;
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzrewind(file)
gzFile file;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ ||
(state->err != Z_OK && state->err != Z_BUF_ERROR))
return -1;
/* back up and start over */
if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
return -1;
gz_reset(state);
return 0;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzseek64(file, offset, whence)
gzFile file;
z_off64_t offset;
int whence;
{
unsigned n;
z_off64_t ret;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* check that there's no error */
if (state->err != Z_OK && state->err != Z_BUF_ERROR)
return -1;
/* can only seek from start or relative to current position */
if (whence != SEEK_SET && whence != SEEK_CUR)
return -1;
/* normalize offset to a SEEK_CUR specification */
if (whence == SEEK_SET)
offset -= state->x.pos;
else if (state->seek)
offset += state->skip;
state->seek = 0;
/* if within raw area while reading, just go there */
if (state->mode == GZ_READ && state->how == COPY &&
state->x.pos + offset >= 0) {
ret = LSEEK(state->fd, offset - (z_off64_t)state->x.have, SEEK_CUR);
if (ret == -1)
return -1;
state->x.have = 0;
state->eof = 0;
state->past = 0;
state->seek = 0;
gz_error(state, Z_OK, NULL);
state->strm.avail_in = 0;
state->x.pos += offset;
return state->x.pos;
}
/* calculate skip amount, rewinding if needed for back seek when reading */
if (offset < 0) {
if (state->mode != GZ_READ) /* writing -- can't go backwards */
return -1;
offset += state->x.pos;
if (offset < 0) /* before start of file! */
return -1;
if (gzrewind(file) == -1) /* rewind, then skip to offset */
return -1;
}
/* if reading, skip what's in output buffer (one less gzgetc() check) */
if (state->mode == GZ_READ) {
n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
(unsigned)offset : state->x.have;
state->x.have -= n;
state->x.next += n;
state->x.pos += n;
offset -= n;
}
/* request skip (if not zero) */
if (offset) {
state->seek = 1;
state->skip = offset;
}
return state->x.pos + offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzseek(file, offset, whence)
gzFile file;
z_off_t offset;
int whence;
{
z_off64_t ret;
ret = gzseek64(file, (z_off64_t)offset, whence);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gztell64(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* return position */
return state->x.pos + (state->seek ? state->skip : 0);
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gztell(file)
gzFile file;
{
z_off64_t ret;
ret = gztell64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzoffset64(file)
gzFile file;
{
z_off64_t offset;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* compute and return effective offset in file */
offset = LSEEK(state->fd, 0, SEEK_CUR);
if (offset == -1)
return -1;
if (state->mode == GZ_READ) /* reading */
offset -= state->strm.avail_in; /* don't count buffered input */
return offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzoffset(file)
gzFile file;
{
z_off64_t ret;
ret = gzoffset64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
int ZEXPORT gzeof(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return 0;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return 0;
/* return end-of-file state */
return state->mode == GZ_READ ? state->past : 0;
}
/* -- see zlib.h -- */
const char * ZEXPORT gzerror(file, errnum)
gzFile file;
int *errnum;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return NULL;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return NULL;
/* return error information */
if (errnum != NULL)
*errnum = state->err;
return state->err == Z_MEM_ERROR ? "out of memory" :
(state->msg == NULL ? "" : state->msg);
}
/* -- see zlib.h -- */
void ZEXPORT gzclearerr(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return;
/* clear error and end-of-file */
if (state->mode == GZ_READ) {
state->eof = 0;
state->past = 0;
}
gz_error(state, Z_OK, NULL);
}
/* Create an error message in allocated memory and set state->err and
state->msg accordingly. Free any previous error message already there. Do
not try to free or allocate space if the error is Z_MEM_ERROR (out of
memory). Simply save the error message as a static string. If there is an
allocation failure constructing the error message, then convert the error to
out of memory. */
void ZLIB_INTERNAL gz_error(state, err, msg)
gz_statep state;
int err;
const char *msg;
{
/* free previously allocated message and clear */
if (state->msg != NULL) {
if (state->err != Z_MEM_ERROR)
free(state->msg);
state->msg = NULL;
}
/* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
if (err != Z_OK && err != Z_BUF_ERROR)
state->x.have = 0;
/* set error code, and if no message, then done */
state->err = err;
if (msg == NULL)
return;
/* for an out of memory error, return literal string when requested */
if (err == Z_MEM_ERROR)
return;
/* construct error message with path */
if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
NULL) {
state->err = Z_MEM_ERROR;
return;
}
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
"%s%s%s", state->path, ": ", msg);
#else
strcpy(state->msg, state->path);
strcat(state->msg, ": ");
strcat(state->msg, msg);
#endif
}
#ifndef INT_MAX
/* portably return maximum value for an int (when limits.h presumed not
available) -- we need to do this to cover cases where 2's complement not
used, since C standard permits 1's complement and sign-bit representations,
otherwise we could just use ((unsigned)-1) >> 1 */
unsigned ZLIB_INTERNAL gz_intmax()
{
unsigned p, q;
p = 1;
do {
q = p;
p <<= 1;
p++;
} while (p > q);
return q >> 1;
}
#endif
| Java |
<?php
class m151218_144423_update_et_operationnote_biometry_view extends CDbMigration
{
public function up()
{
$this->execute('CREATE OR REPLACE VIEW et_ophtroperationnote_biometry AS SELECT
eol.id, eol.eye_id, eol.last_modified_date, target_refraction_left, target_refraction_right,
(SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_left,
(SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_description_left,
(SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) AS lens_acon_left,
(SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_right,
(SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_description_right,
(SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) AS lens_acon_right,
k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right,
snr_left, snr_right, iol_power_left, iol_power_right, predicted_refraction_left, predicted_refraction_right, patient_id,
k2_axis_left, k2_axis_right, delta_k_left, delta_k_right, delta_k_axis_left, delta_k_axis_right, acd_left, acd_right,
(SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_left) as status_left,
(SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_right) as status_right,
comments, eoc.event_id
FROM et_ophinbiometry_measurement eol
JOIN et_ophinbiometry_calculation eoc ON eoc.event_id=eol.event_id
JOIN et_ophinbiometry_selection eos ON eos.event_id=eol.event_id
JOIN event ev ON ev.id=eol.event_id
JOIN episode ep ON ep.id=ev.episode_id
ORDER BY eol.last_modified_date;');
}
public function down()
{
$this->execute('CREATE OR REPLACE VIEW et_ophtroperationnote_biometry AS SELECT
eol.id, eol.eye_id, eol.last_modified_date, target_refraction_left, target_refraction_right,
(SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_left,
(SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) as lens_description_left,
(SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_left) AS lens_acon_left,
(SELECT name FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_right,
(SELECT description FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) as lens_description_right,
(SELECT acon FROM ophinbiometry_lenstype_lens oll WHERE oll.id=lens_id_right) AS lens_acon_right,
k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right,
snr_left, snr_right, iol_power_left, iol_power_right, predicted_refraction_left, predicted_refraction_right, patient_id
FROM et_ophinbiometry_measurement eol
JOIN et_ophinbiometry_calculation eoc ON eoc.event_id=eol.event_id
JOIN et_ophinbiometry_selection eos ON eos.event_id=eol.event_id
JOIN event ev ON ev.id=eol.event_id
JOIN episode ep ON ep.id=ev.episode_id
ORDER BY eol.last_modified_date;');
}
}
| Java |
#!/bin/bash
# cve <file1> [<file2> ...]
#
# Pour éditer un ou plusieurs fichier(s) existant(s) sous CVS.
# - fait un "cvs update" si besoin (status "Needs patch")
# - fait un "cvs edit" pour déclarer aux autres users qu'on édite le fichier
# (voir la commande "cvs editors")
# - utilise l'éditeur préféré déclaré dans la variable $EDITOR
# (c) 2003-2005 Julien Moreau
# 2002-03 Creation
# 2005-01 Updates
# Last version under CVS (GMT):
# $Header: /cvs/CVS-tools/cve.sh,v 1.6 2012-11-23 10:08:38 jmoreau Exp $
nbps=1 # Nombre de paramètres souhaités (sans option)
nom_cmde=`basename $0` # Nom de la commande
usage="Usage: $nom_cmde [-h]" # Message d'aide
usage=$usage"\n\tAffiche ce message d'aide.\n"
usage=$usage"\nUsage: $nom_cmde <filename> [...]"
usage=$usage"\n\tÉdite des fichiers CVS en posant des verrous d'écriture."
if test `uname` != "HP-UX" ; then e="-e" ; fi # Compatibilité HP-UX/Linux
if [ $# -lt 0 -o "$1" = "-h" -o "$1" = "--help" ] ; then # Vérif params
echo $e $usage 1>&2 ; exit 2 # Aide puis fin
fi
if test -z "$EDITOR"
then
if test -z "$USER"
then export USER=`whoami`
fi
echo "$USER"|grep -q moreau
if [ -n "$DISPLAY" -a "$?" -eq 0 ]
then export EDITOR='gvim -geom 128x50'
else export EDITOR=vi
fi
fi
while [ "$#" -ge 1 ]
do
file="$1"
lstatus=`cvs status "$file"|grep ^'File:'`
status=`echo "$lstatus"|sed 's|.*Status: ||'`
if test -n "$lstatus" ; then echo "$lstatus" ; fi
case "$status" in
'Up-to-date') ;;
'Locally Modified') ;;
'Locally Added') ;;
'Needs Patch') cvs update ;;
'Needs Checkout') cvs update "$file" ;;
*) exit 3 ;;
esac
editors=`cvs editors "$file"|cut -f-4`
nb_editors=`echo $editors|grep -v ^$|wc -l`
if [ $nb_editors -eq 0 ] ; then
cvs edit "$file" && $EDITOR "$file"
else
ki=""
if [ "$nb_editors" -eq 1 ] ; then ki=`cvs editors "$file"|cut -f2` ; fi
if test "$ki" = `whoami` ; then
echo "Vous êtes déjà éditeur de ce fichier."
sleep 2
$EDITOR "$file"
else
echo -e "Il y a déjà $nb_editors éditeur(s) de $file !\n$editors"
fi
fi
shift
done
| Java |
"""
Application file for the code snippets app.
"""
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class SnippetsConfig(AppConfig):
"""
Application configuration class for the code snippets app.
"""
name = 'apps.snippets'
verbose_name = _('Code snippets')
| Java |
{"":{"domain":"ckan","lang":"no","plural-forms":"nplurals=2; plural=(n != 1);"},"Cancel":[null,"Avbryt"],"Edit":[null,"Rediger"],"Follow":[null,"Følg"],"Loading...":[null,"Laster..."],"URL":[null,"URL"],"Unfollow":[null,"Ikke følg"],"Upload a file":[null,"Last opp en fil"]} | Java |
#ifndef __SEGMENTER_H__
#define __SEGMENTER_H__
// includes
#include "media_set.h"
#include "common.h"
// constants
#define INVALID_SEGMENT_COUNT UINT_MAX
#define SEGMENT_FROM_TIMESTAMP_MARGIN (100) // in case of clipping, a segment may start up to 2 frames before the segment boundary
#define MIN_SEGMENT_DURATION (500)
#define MAX_SEGMENT_DURATION (600000)
// enums
enum {
MDP_MAX,
MDP_MIN,
};
// typedefs
struct segmenter_conf_s;
typedef struct segmenter_conf_s segmenter_conf_t;
typedef struct {
uint32_t segment_index;
uint32_t repeat_count;
uint64_t time;
uint64_t duration;
bool_t discontinuity;
} segment_duration_item_t;
typedef struct {
segment_duration_item_t* items;
uint32_t item_count;
uint32_t segment_count;
uint32_t timescale;
uint32_t discontinuities;
uint64_t start_time;
uint64_t end_time;
uint64_t duration;
} segment_durations_t;
typedef struct {
request_context_t* request_context;
segmenter_conf_t* conf;
media_clip_timing_t timing;
uint32_t segment_index;
int64_t first_key_frame_offset;
vod_array_part_t* key_frame_durations;
bool_t allow_last_segment;
// no discontinuity
uint64_t last_segment_end;
// discontinuity
uint32_t initial_segment_index;
// gop
uint64_t time;
} get_clip_ranges_params_t;
typedef struct {
uint32_t min_clip_index;
uint32_t max_clip_index;
uint64_t clip_time;
media_range_t* clip_ranges;
uint32_t clip_count;
uint32_t clip_relative_segment_index;
} get_clip_ranges_result_t;
typedef uint32_t (*segmenter_get_segment_count_t)(segmenter_conf_t* conf, uint64_t duration_millis);
typedef vod_status_t (*segmenter_get_segment_durations_t)(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
uint32_t media_type,
segment_durations_t* result);
struct segmenter_conf_s {
// config fields
uintptr_t segment_duration;
vod_array_t* bootstrap_segments; // array of vod_str_t
bool_t align_to_key_frames;
intptr_t live_window_duration;
segmenter_get_segment_count_t get_segment_count; // last short / last long / last rounded
segmenter_get_segment_durations_t get_segment_durations; // estimate / accurate
vod_uint_t manifest_duration_policy;
uintptr_t gop_look_behind;
uintptr_t gop_look_ahead;
// derived fields
uint32_t parse_type;
uint32_t bootstrap_segments_count;
uint32_t* bootstrap_segments_durations;
uint32_t max_segment_duration;
uint32_t max_bootstrap_segment_duration;
uint32_t bootstrap_segments_total_duration;
uint32_t* bootstrap_segments_start;
uint32_t* bootstrap_segments_mid;
uint32_t* bootstrap_segments_end;
};
typedef struct {
request_context_t* request_context;
vod_array_part_t* part;
int64_t* cur_pos;
int64_t offset;
} align_to_key_frames_context_t;
// init
vod_status_t segmenter_init_config(segmenter_conf_t* conf, vod_pool_t* pool);
// get segment count modes
uint32_t segmenter_get_segment_count_last_short(segmenter_conf_t* conf, uint64_t duration_millis);
uint32_t segmenter_get_segment_count_last_long(segmenter_conf_t* conf, uint64_t duration_millis);
uint32_t segmenter_get_segment_count_last_rounded(segmenter_conf_t* conf, uint64_t duration_millis);
// key frames
int64_t segmenter_align_to_key_frames(
align_to_key_frames_context_t* context,
int64_t offset,
int64_t limit);
// live window
vod_status_t segmenter_get_live_window(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
bool_t parse_all_clips,
get_clip_ranges_result_t* clip_ranges,
uint32_t* base_clip_index);
// manifest duration
uint64_t segmenter_get_total_duration(
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
media_sequence_t* sequences_end,
uint32_t media_type);
// get segment durations modes
vod_status_t segmenter_get_segment_durations_estimate(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
uint32_t media_type,
segment_durations_t* result);
vod_status_t segmenter_get_segment_durations_accurate(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
uint32_t media_type,
segment_durations_t* result);
// get segment index
uint32_t segmenter_get_segment_index_no_discontinuity(
segmenter_conf_t* conf,
uint64_t time_millis);
vod_status_t segmenter_get_segment_index_discontinuity(
request_context_t* request_context,
segmenter_conf_t* conf,
uint32_t initial_segment_index,
media_clip_timing_t* timing,
uint64_t time_millis,
uint32_t* result);
// get start end ranges
vod_status_t segmenter_get_start_end_ranges_gop(
get_clip_ranges_params_t* params,
get_clip_ranges_result_t* result);
vod_status_t segmenter_get_start_end_ranges_no_discontinuity(
get_clip_ranges_params_t* params,
get_clip_ranges_result_t* result);
vod_status_t segmenter_get_start_end_ranges_discontinuity(
get_clip_ranges_params_t* params,
get_clip_ranges_result_t* result);
#endif // __SEGMENTER_H__
| Java |
/*
* dmroom.cpp
* Staff functions related to rooms.
* ____ _
* | _ \ ___ __ _| |_ __ ___ ___
* | |_) / _ \/ _` | | '_ ` _ \/ __|
* | _ < __/ (_| | | | | | | \__ \
* |_| \_\___|\__,_|_|_| |_| |_|___/
*
* Permission to use, modify and distribute is granted via the
* GNU Affero General Public License v3 or later
*
* Copyright (C) 2007-2021 Jason Mitchell, Randi Mitchell
* Contributions by Tim Callahan, Jonathan Hseu
* Based on Mordor (C) Brooke Paul, Brett J. Vickers, John P. Freeman
*
*/
#include <dirent.h> // for opendir, readdir, dirent
#include <fmt/format.h> // for format
#include <libxml/parser.h> // for xmlDocSetRootElement
#include <unistd.h> // for unlink
#include <boost/algorithm/string/replace.hpp> // for replace_all
#include <boost/iterator/iterator_traits.hpp> // for iterator_value<>::type
#include <cstdio> // for sprintf
#include <cstdlib> // for atoi, exit
#include <cstring> // for strcmp, strlen, strcpy
#include <ctime> // for time, ctime, time_t
#include <deque> // for _Deque_iterator
#include <iomanip> // for operator<<, setw
#include <iostream> // for operator<<, char_traits
#include <list> // for operator==, list, _Lis...
#include <map> // for operator==, map, map<>...
#include <string> // for string, operator==
#include <string_view> // for operator==, string_view
#include <utility> // for pair
#include "area.hpp" // for Area, MapMarker, AreaZone
#include "async.hpp" // for Async, AsyncExternal
#include "catRef.hpp" // for CatRef
#include "catRefInfo.hpp" // for CatRefInfo
#include "cmd.hpp" // for cmd
#include "commands.hpp" // for getFullstrText, cmdNoAuth
#include "config.hpp" // for Config, gConfig, Deity...
#include "deityData.hpp" // for DeityData
#include "dice.hpp" // for Dice
#include "dm.hpp" // for dmAddMob, dmAddObj
#include "effects.hpp" // for EffectInfo, Effects
#include "factions.hpp" // for Faction
#include "flags.hpp" // for R_TRAINING_ROOM, R_SHO...
#include "free_crt.hpp" // for free_crt
#include "global.hpp" // for CreatureClass, Creatur...
#include "hooks.hpp" // for Hooks
#include "lasttime.hpp" // for crlasttime
#include <libxml/xmlstring.h> // for BAD_CAST
#include "location.hpp" // for Location
#include "monType.hpp" // for getHitdice, getName
#include "money.hpp" // for Money, GOLD
#include "mudObjects/areaRooms.hpp" // for AreaRoom
#include "mudObjects/creatures.hpp" // for Creature
#include "mudObjects/exits.hpp" // for Exit, getDir, getDirName
#include "mudObjects/monsters.hpp" // for Monster
#include "mudObjects/objects.hpp" // for Object
#include "mudObjects/players.hpp" // for Player
#include "mudObjects/rooms.hpp" // for BaseRoom, ExitList
#include "mudObjects/uniqueRooms.hpp" // for UniqueRoom
#include "os.hpp" // for merror
#include "paths.hpp" // for checkDirExists, AreaRoom
#include "proc.hpp" // for ChildType, ChildType::...
#include "property.hpp" // for Property
#include "proto.hpp" // for log_immort, low, needU...
#include "raceData.hpp" // for RaceData
#include "range.hpp" // for Range
#include "server.hpp" // for Server, gServer
#include "size.hpp" // for getSizeName, getSize
#include "startlocs.hpp" // for StartLoc
#include "stats.hpp" // for Stat
#include "swap.hpp" // for SwapRoom
#include "track.hpp" // for Track
#include "traps.hpp" // for TRAP_ACID, TRAP_ALARM
#include "utils.hpp" // for MAX, MIN
#include "wanderInfo.hpp" // for WanderInfo
#include "xml.hpp" // for loadRoom, loadMonster
//*********************************************************************
// checkTeleportRange
//*********************************************************************
void checkTeleportRange(const Player* player, const CatRef& cr) {
// No warning for the test range
if(cr.isArea("test"))
return;
const CatRefInfo* cri = gConfig->getCatRefInfo(cr.area);
if(!cri) {
player->printColor("^yNo CatRefInfo zone found for this room's area. Contact a dungeonmaster to fix this.\n");
return;
}
if(cr.id > cri->getTeleportWeight()) {
player->printColor("^yThis room is outside the CatRefInfo zone's teleport range.\n");
return;
}
}
//*********************************************************************
// isCardinal
//*********************************************************************
bool isCardinal(std::string_view xname) {
return( xname == "north" ||
xname == "east" ||
xname == "south" ||
xname == "west" ||
xname == "northeast" ||
xname == "northwest" ||
xname == "southeast" ||
xname == "southwest"
);
}
//*********************************************************************
// wrapText
//*********************************************************************
std::string wrapText(std::string_view text, int wrap) {
if(text.empty())
return("");
std::string wrapped = "";
int len = text.length(), i=0, sp=0, spLast=0, spLen=0;
char ch, chLast;
// find our starting position
while(text.at(i) == ' ' || text.at(i) == '\n' || text.at(i) == '\r')
i++;
for(; i < len; i++) {
ch = text.at(i);
// convert linebreaks to spaces
if(ch == '\r')
ch = ' ';
if(ch == '\n')
ch = ' ';
// skiping 2x spacing (or greater)
if(ch == ' ' && chLast == ' ') {
do {
i++;
} while(i+1 < len && (text.at(i+1) == ' ' || text.at(i+1) == '\n' || text.at(i+1) == '\r'));
if(i < len)
ch = text.at(i);
}
// don't add trailing spaces
if(ch != ' ' || i+1 < len) {
// If there is color in the room description, the color characters
// shouldn't count toward string length.
if(ch == '^')
spLen += 2;
// wrap
if(ch == ' ') {
// We went over! spLast points to the last non-overboard space.
if(wrap <= (sp - spLen)) {
wrapped.replace(spLast, 1, "\n");
spLen = spLast;
}
spLast = sp;
}
wrapped += ch;
sp++;
chLast = ch;
}
}
return(wrapped);
}
//*********************************************************************
// expand_exit_name
//*********************************************************************
std::string expand_exit_name(const std::string &name) {
if(name == "n")
return("north");
if(name == "s")
return("south");
if(name == "e")
return("east");
if(name == "w")
return("west");
if(name == "sw")
return("southwest");
if(name == "nw")
return("northwest");
if(name == "se")
return("southeast");
if(name == "ne")
return("northeast");
if(name == "d")
return("door");
if(name == "o")
return("out");
if(name == "p")
return("passage");
if(name == "t")
return("trap door");
if(name == "a")
return("arch");
if(name == "g")
return("gate");
if(name == "st")
return("stairs");
return(name);
}
//*********************************************************************
// opposite_exit_name
//*********************************************************************
std::string opposite_exit_name(const std::string &name) {
if(name == "south")
return("north");
if(name == "north")
return("south");
if(name == "west")
return("east");
if(name == "east")
return("west");
if(name == "northeast")
return("southwest");
if(name == "southeast")
return("northwest");
if(name == "northwest")
return("southeast");
if(name == "southwest")
return("northeast");
if(name == "up")
return("down");
if(name == "down")
return("up");
return(name);
}
//*********************************************************************
// dmPurge
//*********************************************************************
// This function allows staff to purge a room of all its objects and
// monsters.
int dmPurge(Player* player, cmd* cmnd) {
BaseRoom* room = player->getRoomParent();
if(!player->canBuildMonsters() && !player->canBuildObjects())
return(cmdNoAuth(player));
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: this room is out of your range; you cannot *purge here.\n");
return(0);
}
room->purge(false);
player->print("Purged.\n");
if(!player->isDm())
log_immort(false,player, "%s purged room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str());
return(0);
}
//*********************************************************************
// dmEcho
//*********************************************************************
// This function allows a staff specified by the socket descriptor in
// the first parameter to echo the rest of their command line to all
// the other people in the room.
int dmEcho(Player* player, cmd* cmnd) {
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: room number not in any of your allotted ranges.\n");
return(0);
}
std::string text = getFullstrText(cmnd->fullstr, 1);
if(text.empty() || Pueblo::is(text)) {
player->print("Echo what?\n");
return(0);
}
if(!player->isCt())
broadcast(isStaff, "^G*** %s (%s) echoed: %s",
player->getCName(), player->getRoomParent()->fullName().c_str(), text.c_str());
broadcast(nullptr, player->getRoomParent(), "%s", text.c_str());
return(0);
}
//*********************************************************************
// dmReloadRoom
//*********************************************************************
// This function allows a staff to reload a room from disk.
int dmReloadRoom(Player* player, cmd* cmnd) {
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: this room is out of your range; you cannot reload this room.\n");
return(0);
}
if(gServer->reloadRoom(player->getRoomParent()))
player->print("Ok.\n");
else
player->print("Reload failed.\n");
return(0);
}
//*********************************************************************
// resetPerms
//*********************************************************************
// This function allows a staff to reset perm timeouts in the room
int dmResetPerms(Player* player, cmd* cmnd) {
std::map<int, crlasttime>::iterator it;
crlasttime* crtm=nullptr;
std::map<int, long> tempMonsters;
std::map<int, long> tempObjects;
UniqueRoom *room = player->getUniqueRoomParent();
//long temp_obj[10], temp_mon[10];
if(!needUniqueRoom(player))
return(0);
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: this room is out of your range; you cannot reload this room.\n");
return(0);
}
for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) {
crtm = &(*it).second;
tempMonsters[(*it).first] = crtm->interval;
crtm->ltime = time(nullptr);
crtm->interval = 0;
}
for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) {
crtm = &(*it).second;
tempObjects[(*it).first] = crtm->interval;
crtm->ltime = time(nullptr);
crtm->interval = 0;
}
player->print("Permanent object and creature timeouts reset.\n");
room->addPermCrt();
for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) {
crtm = &(*it).second;
crtm->interval = tempMonsters[(*it).first];
crtm->ltime = time(nullptr);
}
for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) {
crtm = &(*it).second;
crtm->interval = tempObjects[(*it).first];
crtm->ltime = time(nullptr);
}
log_immort(true, player, "%s reset perm timeouts in room %s\n", player->getCName(), player->getRoomParent()->fullName().c_str());
if(gServer->resaveRoom(room->info) < 0)
player->print("Room fail saved.\n");
else
player->print("Room saved.\n");
return(0);
}
//*********************************************************************
// stat_rom_exits
//*********************************************************************
// Display information on room given to staff.
void stat_rom_exits(Creature* player, BaseRoom* room) {
char str[1024], temp[25], tempstr[32];
int i=0, flagcount=0;
UniqueRoom* uRoom = room->getAsUniqueRoom();
if(room->exits.empty())
return;
player->print("Exits:\n");
for(Exit* exit : room->exits) {
if(!exit->getLevel())
player->print(" %s: ", exit->getCName());
else
player->print(" %s(L%d): ", exit->getCName(), exit->getLevel());
if(!exit->target.mapmarker.getArea())
player->printColor("%s ", exit->target.room.str(uRoom ? uRoom->info.area : "", 'y').c_str());
else
player->print(" A:%d X:%d Y:%d Z:%d ",
exit->target.mapmarker.getArea(), exit->target.mapmarker.getX(),
exit->target.mapmarker.getY(), exit->target.mapmarker.getZ());
*str = 0;
strcpy(str, "Flags: ");
for(i=0; i<MAX_EXIT_FLAGS; i++) {
if(exit->flagIsSet(i)) {
sprintf(tempstr, "%s(%d), ", gConfig->getXFlag(i).c_str(), i+1);
strcat(str, tempstr);
flagcount++;
}
}
if(flagcount) {
str[strlen(str) - 2] = '.';
str[strlen(str) - 1] = 0;
}
if(flagcount)
player->print("%s", str);
if(exit->flagIsSet(X_LOCKABLE)) {
player->print(" Key#: %d ", exit->getKey());
if(!exit->getKeyArea().empty())
player->printColor(" Area: ^y%s^x ", exit->getKeyArea().c_str());
}
if(exit->flagIsSet(X_TOLL_TO_PASS))
player->print(" Toll: %d ", exit->getToll());
player->print("\n");
if(!exit->getDescription().empty())
player->print(" Description: \"%s\"\n", exit->getDescription().c_str());
if( (exit->flagIsSet(X_CAN_LOOK) || exit->flagIsSet(X_LOOK_ONLY)) &&
exit->flagIsSet(X_NO_SCOUT)
)
player->printColor("^rExit is flagged as no-scout, but it flagged as lookable.\n");
if(exit->flagIsSet(X_PLEDGE_ONLY)) {
for(i=1; i<15; i++)
if(exit->flagIsSet(i+40)) {
sprintf(temp, "Clan: %d, ",i);
strcat(str, temp);
}
player->print(" Clan: %s\n", temp);
}
if(exit->flagIsSet(X_PORTAL)) {
player->printColor(" Owner: ^c%s^x Uses: ^c%d^x\n", exit->getPassPhrase().c_str(), exit->getKey());
} else if(!exit->getPassPhrase().empty()) {
player->print(" Passphrase: \"%s\"\n", exit->getPassPhrase().c_str());
if(exit->getPassLanguage())
player->print(" Passlang: %s\n", get_language_adj(exit->getPassLanguage()));
}
if(!exit->getEnter().empty())
player->print(" OnEnter: \"%s\"\n", exit->getEnter().c_str());
if(!exit->getOpen().empty())
player->print(" OnOpen: \"%s\"\n", exit->getOpen().c_str());
if(exit->getSize() || exit->getDirection()) {
if(exit->getSize())
player->print(" Size: %s", getSizeName(exit->getSize()).c_str());
if(exit->getDirection()) {
player->print(" Direction: %s", getDirName(exit->getDirection()).c_str());
if(getDir(exit->getName()) != NoDirection)
player->printColor("\n^rThis exit has a direction set, but the exit is a cardinal exit.");
}
player->print("\n");
}
if(!exit->effects.effectList.empty())
player->printColor(" Effects:\n%s", exit->effects.getEffectsString(player).c_str());
player->printColor("%s", exit->hooks.display().c_str());
}
}
//*********************************************************************
// trainingFlagSet
//*********************************************************************
bool trainingFlagSet(const BaseRoom* room, const TileInfo *tile, const AreaZone *zone, int flag) {
return( (room && room->flagIsSet(flag)) ||
(tile && tile->flagIsSet(flag)) ||
(zone && zone->flagIsSet(flag))
);
}
//*********************************************************************
// whatTraining
//*********************************************************************
// determines what class can train here
int whatTraining(const BaseRoom* room, const TileInfo *tile, const AreaZone *zone, int extra) {
int i = 0;
if(R_TRAINING_ROOM - 1 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM - 1))
i += 16;
if(R_TRAINING_ROOM == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM))
i += 8;
if(R_TRAINING_ROOM + 1 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 1))
i += 4;
if(R_TRAINING_ROOM + 2 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 2))
i += 2;
if(R_TRAINING_ROOM + 3 == extra || trainingFlagSet(room, tile, zone, R_TRAINING_ROOM + 3))
i += 1;
return(i > static_cast<int>(CreatureClass::CLASS_COUNT) - 1 ? 0 : i);
}
bool BaseRoom::hasTraining() const {
return(whatTraining() != CreatureClass::NONE);
}
CreatureClass BaseRoom::whatTraining(int extra) const {
return(static_cast<CreatureClass>(::whatTraining(this, (const TileInfo*)nullptr, (const AreaZone*)nullptr, extra)));
}
//*********************************************************************
// showRoomFlags
//*********************************************************************
void showRoomFlags(const Player* player, const BaseRoom* room, const TileInfo *tile, const AreaZone *zone) {
bool flags=false;
int i=0;
std::ostringstream oStr;
oStr << "^@Flags set: ";
for(; i<MAX_ROOM_FLAGS; i++) {
if(i >=2 && i <= 6) // skips training flags
continue;
if( (room && room->flagIsSet(i)) ||
(tile && tile->flagIsSet(i)) ||
(zone && zone->flagIsSet(i))
) {
if(flags)
oStr << ", ";
flags = true;
oStr << gConfig->getRFlag(i) << "(" << (int)(i+1) << ")";
}
}
if(!flags)
oStr << "None";
oStr << ".^x\n";
i = whatTraining(room, tile, zone, 0);
if(i)
oStr << "^@Training: " << get_class_string(i) << "^x\n";
player->printColor("%s", oStr.str().c_str());
// inform user of redundant flags
if(room && room->getAsConstUniqueRoom()) {
bool hasTraining = room->hasTraining();
bool limboOrCoven = room->flagIsSet(R_LIMBO) || room->flagIsSet(R_VAMPIRE_COVEN);
if(room->flagIsSet(R_NO_TELEPORT)) {
if( limboOrCoven ||
room->flagIsSet(R_JAIL) ||
room->flagIsSet(R_ETHEREAL_PLANE) ||
hasTraining
)
player->printColor("^rThis room does not need flag 13-No Teleport set.\n");
}
if(room->flagIsSet(R_NO_SUMMON_OUT)) {
if( room->flagIsSet(R_IS_STORAGE_ROOM) ||
room->flagIsSet(R_LIMBO)
)
player->printColor("^rThis room does not need flag 29-No Summon Out set.\n");
}
if(room->flagIsSet(R_NO_LOGIN)) {
if( room->flagIsSet(R_LOG_INTO_TRAP_ROOM) ||
hasTraining
)
player->printColor("^rThis room does not need flag 34-No Log set.\n");
}
if(room->flagIsSet(R_NO_CLAIR_ROOM)) {
if(limboOrCoven)
player->printColor("^rThis room does not need flag 43-No Clair set.\n");
}
if(room->flagIsSet(R_NO_TRACK_TO)) {
if( limboOrCoven ||
room->flagIsSet(R_IS_STORAGE_ROOM) ||
room->flagIsSet(R_NO_TELEPORT) ||
hasTraining
)
player->printColor("^rThis room does not need flag 52-No Track To set.\n");
}
if(room->flagIsSet(R_NO_SUMMON_TO)) {
if( limboOrCoven ||
room->flagIsSet(R_NO_TELEPORT) ||
room->flagIsSet(R_ONE_PERSON_ONLY) ||
hasTraining
)
player->printColor("^rThis room does not need flag 54-No Summon To set.\n");
}
if(room->flagIsSet(R_NO_TRACK_OUT)) {
if( room->flagIsSet(R_LIMBO) ||
room->flagIsSet(R_ETHEREAL_PLANE)
)
player->printColor("^rThis room does not need flag 54-No Summon To set.\n");
}
if(room->flagIsSet(R_OUTLAW_SAFE)) {
if( limboOrCoven ||
hasTraining
)
player->printColor("^rThis room does not need flag 57-Outlaw Safe set.\n");
}
if(room->flagIsSet(R_LOG_INTO_TRAP_ROOM)) {
if(hasTraining)
player->printColor("^rThis room does not need flag 63-Log To Trap Exit set.\n");
}
if(room->flagIsSet(R_LIMBO)) {
if(room->flagIsSet(R_POST_OFFICE))
player->printColor("^rThis room does not need flag 11-Post Office set.\n");
if(room->flagIsSet(R_FAST_HEAL))
player->printColor("^rThis room does not need flag 14-Fast Heal set.\n");
if(room->flagIsSet(R_NO_POTION))
player->printColor("^rThis room does not need flag 32-No Potion set.\n");
if(room->flagIsSet(R_NO_CAST_TELEPORT))
player->printColor("^rThis room does not need flag 38-No Cast Teleport set.\n");
if(room->flagIsSet(R_NO_FLEE))
player->printColor("^rThis room does not need flag 44-No Flee set.\n");
if(room->flagIsSet(R_BANK))
player->printColor("^rThis room does not need flag 58-Bank set.\n");
if(room->flagIsSet(R_MAGIC_MONEY_MACHINE))
player->printColor("^rThis room does not need flag 59-Magic Money Machine set.\n");
}
}
}
//*********************************************************************
// stat_rom
//*********************************************************************
int stat_rom(Player* player, AreaRoom* room) {
std::list<AreaZone*>::iterator it;
AreaZone* zone=nullptr;
TileInfo* tile=nullptr;
if(!player->checkBuilder(nullptr))
return(0);
if(player->getClass() == CreatureClass::CARETAKER)
log_immort(false,player, "%s statted room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str());
player->print("Room: %s %s\n\n",
room->area->name.c_str(), room->fullName().c_str());
tile = room->area->getTile(room->area->getTerrain(nullptr, &room->mapmarker, 0, 0, 0, true), false);
for(it = room->area->zones.begin() ; it != room->area->zones.end() ; it++) {
zone = (*it);
if(zone->inside(room->area, &room->mapmarker)) {
player->printColor("^yZone:^x %s\n", zone->name.c_str());
if(zone->wander.getTraffic()) {
zone->wander.show(player);
} else {
player->print(" No monsters come in this zone.\n");
}
player->print("\n");
}
}
if(room->getSize())
player->printColor("Size: ^y%s\n", getSizeName(room->getSize()).c_str());
if(tile->wander.getTraffic())
tile->wander.show(player);
player->print("Terrain: %c\n", tile->getDisplay());
if(room->isWater())
player->printColor("Water: ^gyes\n");
if(room->isRoad())
player->printColor("Road: ^gyes\n");
player->printColor("Generic Room: %s\n", room->canSave() ? "^rNo" : "^gYes");
if(room->unique.id) {
player->printColor("Links to unique room ^y%s^x.\n", room->unique.str().c_str());
player->printColor("needsCompass: %s^x decCompass: %s",
room->getNeedsCompass() ? "^gYes" : "^rNo", room->getDecCompass() ? "^gYes" : "^rNo");
}
player->print("\n");
showRoomFlags(player, room, nullptr, nullptr);
if(!room->effects.effectList.empty())
player->printColor("Effects:\n%s", room->effects.getEffectsString(player).c_str());
player->printColor("%s", room->hooks.display().c_str());
stat_rom_exits(player, room);
return(0);
}
//*********************************************************************
// validateShop
//*********************************************************************
void validateShop(const Player* player, const UniqueRoom* shop, const UniqueRoom* storage) {
// basic checks
if(!shop) {
player->printColor("^rThe shop associated with this storage room does not exist.\n");
return;
}
if(!storage) {
player->printColor("^rThe storage room associated with this shop does not exist.\n");
return;
}
if(shop->info == storage->info) {
player->printColor("^rThe shop and the storage room cannot be the same room. Set the shop's trap exit appropriately.\n");
return;
}
CatRef cr = shopStorageRoom(shop);
if(shop->info == cr) {
player->printColor("^rThe shop and the storage room cannot be the same room. Set the shop's trap exit appropriately.\n");
return;
}
std::string name = "Storage: ";
name += shop->getName();
if(cr != storage->info)
player->printColor("^rThe shop's storage room of %s does not match the storage room %s.\n", cr.str().c_str(), storage->info.str().c_str());
if(storage->getTrapExit() != shop->info)
player->printColor("^yThe storage room's trap exit of %s does not match the shop room %s.\n", storage->info.str().c_str(), shop->info.str().c_str());
if(!shop->flagIsSet(R_SHOP))
player->printColor("^rThe shop's flag 1-Shoppe is not set.\n");
if(!storage->flagIsSet(R_SHOP_STORAGE))
player->printColor("^rThe storage room's flag 97-Shop Storage is not set.\n");
// what DOESN'T the storage room need?
if(storage->flagIsSet(R_NO_LOGIN))
player->printColor("^rThe storage room does not need flag 34-No Log set.\n");
if(storage->flagIsSet(R_LOG_INTO_TRAP_ROOM))
player->printColor("^rThe storage room does not need flag 63-Log To Trap Exit set.\n");
if(storage->flagIsSet(R_NO_TELEPORT))
player->printColor("^rThe storage room does not need flag 13-No Teleport set.\n");
if(storage->flagIsSet(R_NO_SUMMON_TO))
player->printColor("^rThe storage room does not need flag 54-No Summon To set.\n");
if(storage->flagIsSet(R_NO_TRACK_TO))
player->printColor("^rThe storage room does not need flag 52-No Track To set.\n");
if(storage->flagIsSet(R_NO_CLAIR_ROOM))
player->printColor("^rThe storage room does not need flag 43-No Clair set.\n");
if(storage->exits.empty()) {
player->printColor("^yThe storage room does not have an out exit pointing to the shop.\n");
} else {
const Exit* exit = storage->exits.front();
if( exit->target.room != shop->info || exit->getName() != "out")
player->printColor("^yThe storage room does not have an out exit pointing to the shop.\n");
else if(storage->exits.size() > 1)
player->printColor("^yThe storage room has more than one exit - it only needs one out exit pointing to the shop.\n");
}
}
//*********************************************************************
// stat_rom
//*********************************************************************
int stat_rom(Player* player, UniqueRoom* room) {
std::map<int, crlasttime>::iterator it;
crlasttime* crtm=nullptr;
CatRef cr;
Monster* monster=nullptr;
Object* object=nullptr;
UniqueRoom* shop=nullptr;
time_t t = time(nullptr);
if(!player->checkBuilder(room))
return(0);
if(player->getClass() == CreatureClass::CARETAKER)
log_immort(false,player, "%s statted room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str());
player->printColor("Room: %s", room->info.str("", 'y').c_str());
if(gConfig->inSwapQueue(room->info, SwapRoom, true))
player->printColor(" ^eThis room is being swapped.");
player->print("\nTimes People have entered this room: %d\n", room->getBeenHere());
player->print("Name: %s\n", room->getCName());
Property *p = gConfig->getProperty(room->info);
if(p) {
player->printColor("Property Belongs To: ^y%s^x\nProperty Type: ^y%s\n",
p->getOwner().c_str(), p->getTypeStr().c_str());
}
if(player->isCt()) {
if(room->last_mod[0])
player->printColor("^cLast modified by: %s on %s\n", room->last_mod, stripLineFeeds(room->lastModTime));
if(room->lastPly[0])
player->printColor("^cLast player here: %s on %s\n", room->lastPly, stripLineFeeds(room->lastPlyTime));
} else
player->print("\n");
if(room->getSize())
player->printColor("Size: ^y%s\n", getSizeName(room->getSize()).c_str());
if(room->getRoomExperience())
player->print("Experience for entering this room: %d\n", room->getRoomExperience());
if(!room->getFaction().empty())
player->printColor("Faction: ^g%s^x\n", room->getFaction().c_str());
if(!room->getFishingStr().empty())
player->printColor("Fishing: ^g%s^x\n", room->getFishingStr().c_str());
if(room->getMaxMobs() > 0)
player->print("Max mob allowance: %d\n", room->getMaxMobs());
room->wander.show(player, room->info.area);
player->print("\n");
player->print("Perm Objects:\n");
for(it = room->permObjects.begin(); it != room->permObjects.end() ; it++) {
crtm = &(*it).second;
loadObject((*it).second.cr, &object);
player->printColor("^y%2d) ^x%14s ^y::^x %-30s ^yInterval:^x %-5d ^yTime Until Spawn:^x %-5d", (*it).first+1,
crtm->cr.str("", 'y').c_str(), object ? object->getCName() : "", crtm->interval, MAX<long>(0, crtm->ltime + crtm->interval-t));
if(room->flagIsSet(R_SHOP_STORAGE) && object)
player->printColor(" ^yCost:^x %s", object->value.str().c_str());
player->print("\n");
// warning about deeds in improper areas
if(object && object->deed.low.id && !object->deed.isArea(room->info.area))
player->printColor(" ^YCaution:^x this object's deed area does not match the room's area.\n");
if(object) {
delete object;
object = nullptr;
}
}
player->print("\n");
player->print("Perm Monsters:\n");
for(it = room->permMonsters.begin(); it != room->permMonsters.end() ; it++) {
crtm = &(*it).second;
loadMonster((*it).second.cr, &monster);
player->printColor("^m%2d) ^x%14s ^m::^x %-30s ^mInterval:^x %d ^yTime until Spawn:^x %-5d\n", (*it).first+1,
crtm->cr.str("", 'm').c_str(), monster ? monster->getCName() : "", crtm->interval, MAX<long>(0, crtm->ltime + crtm->interval-t));
if(monster) {
free_crt(monster);
monster = nullptr;
}
}
player->print("\n");
if(!room->track.getDirection().empty() && room->flagIsSet(R_PERMENANT_TRACKS))
player->print("Perm Tracks: %s.\n", room->track.getDirection().c_str());
if(room->getLowLevel() || room->getHighLevel()) {
player->print("Level Boundary: ");
if(room->getLowLevel())
player->print("%d+ level ", room->getLowLevel());
if(room->getHighLevel())
player->print("%d- level ", room->getHighLevel());
player->print("\n");
}
if( room->flagIsSet(R_LOG_INTO_TRAP_ROOM) ||
room->flagIsSet(R_SHOP_STORAGE) ||
room->hasTraining()
) {
if(room->getTrapExit().id)
player->print("Players will relog into room %s from here.\n", room->getTrapExit().str(room->info.area).c_str());
else
player->printColor("^rTrap exit needs to be set to %s room number.\n", room->flagIsSet(R_SHOP_STORAGE) ? "shop" : "relog");
}
if( room->getSize() == NO_SIZE && (
room->flagIsSet(R_INDOORS) ||
room->flagIsSet(R_UNDERGROUND)
)
)
player->printColor("^yThis room does not have a size set.\n");
checkTeleportRange(player, room->info);
// isShopValid
if(room->flagIsSet(R_SHOP)) {
cr = shopStorageRoom(room);
player->print("Shop storage room: %s (%s)\n", cr.str().c_str(),
cr.id == room->info.id+1 && cr.isArea(room->info.area) ? "default" : "trapexit");
if(room->getFaction().empty() && room->info.area != "shop")
player->printColor("^yThis shop does not have a faction set.\n");
loadRoom(cr, &shop);
validateShop(player, room, shop);
} else if(room->flagIsSet(R_PAWN_SHOP)) {
if(room->getFaction().empty())
player->printColor("^yThis pawn shop does not have a faction set.\n");
}
if(room->flagIsSet(R_SHOP_STORAGE)) {
loadRoom(room->getTrapExit(), &shop);
validateShop(player, shop, room);
}
if(room->getTrap()) {
if(room->getTrapWeight())
player->print("Trap weight: %d/%d lbs\n", room->getWeight(), room->getTrapWeight());
player->print("Trap type: ");
switch(room->getTrap()) {
case TRAP_PIT:
player->print("Pit Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_DART:
player->print("Poison Dart Trap\n");
break;
case TRAP_BLOCK:
player->print("Falling Block Trap\n");
break;
case TRAP_MPDAM:
player->print("MP Damage Trap\n");
break;
case TRAP_RMSPL:
player->print("Negate Spell Trap\n");
break;
case TRAP_NAKED:
player->print("Naked Trap\n");
break;
case TRAP_TPORT:
player->print("Teleport Trap\n");
break;
case TRAP_ARROW:
player->print("Arrow Trap\n");
break;
case TRAP_SPIKED_PIT:
player->print("Spiked Pit Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_WORD:
player->print("Word of Recall Trap\n");
break;
case TRAP_FIRE:
player->print("Fire Trap\n");
break;
case TRAP_FROST:
player->print("Frost Trap\n");
break;
case TRAP_ELEC:
player->print("Electricity Trap\n");
break;
case TRAP_ACID:
player->print("Acid Trap\n");
break;
case TRAP_ROCKS:
player->print("Rockslide Trap\n");
break;
case TRAP_ICE:
player->print("Icicle Trap\n");
break;
case TRAP_SPEAR:
player->print("Spear Trap\n");
break;
case TRAP_CROSSBOW:
player->print("Crossbow Trap\n");
break;
case TRAP_GASP:
player->print("Poison Gas Trap\n");
break;
case TRAP_GASB:
player->print("Blinding Gas Trap\n");
break;
case TRAP_GASS:
player->print("Stun Gas Trap\n");
break;
case TRAP_MUD:
player->print("Mud Trap\n");
break;
case TRAP_DISP:
player->print("Room Displacement Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_FALL:
player->print("Deadly Fall Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_CHUTE:
player->print("Chute Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_ALARM:
player->print("Alarm Trap (guard rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_BONEAV:
player->print("Bone Avalanche Trap (exit rm %s)\n", room->getTrapExit().str(room->info.area).c_str());
break;
case TRAP_PIERCER:
player->print("Piercer trap (%d piercers)\n", room->getTrapStrength());
break;
case TRAP_ETHEREAL_TRAVEL:
player->print("Ethereal travel trap.\n");
break;
case TRAP_WEB:
player->print("Sticky spider web trap.\n");
break;
default:
player->print("Invalid trap #\n");
break;
}
}
if(room->flagIsSet(R_CAN_SHOPLIFT))
player->print("Store guardroom: rm %s\n", cr.str(room->info.area).c_str());
showRoomFlags(player, room, nullptr, nullptr);
if(!room->effects.effectList.empty())
player->printColor("Effects:\n%s", room->effects.getEffectsString(player).c_str());
player->printColor("%s", room->hooks.display().c_str());
stat_rom_exits(player, room);
return(0);
}
//*********************************************************************
// dmAddRoom
//*********************************************************************
// This function allows staff to add a new, empty room to the current
// database of rooms.
int dmAddRoom(Player* player, cmd* cmnd) {
UniqueRoom *newRoom=nullptr;
char file[80];
int i=1;
if(!strcmp(cmnd->str[1], "c") && (cmnd->num > 1)) {
dmAddMob(player, cmnd);
return(0);
}
if(!strcmp(cmnd->str[1], "o") && (cmnd->num > 1)) {
dmAddObj(player, cmnd);
return(0);
}
CatRef cr;
bool extra = !strcmp(cmnd->str[1], "r");
getCatRef(getFullstrText(cmnd->fullstr, extra ? 2 : 1), &cr, player);
if(cr.id < 1) {
player->print("Index error: please specify room number.\n");
return(0);
}
if(!player->checkBuilder(cr, false)) {
player->print("Error: Room number not inside any of your alotted ranges.\n");
return(0);
}
if(gConfig->moveRoomRestrictedArea(cr.area)) {
player->print("Error: ""%s"" is a restricted range. You cannot create unique rooms in that area.\n");
return(0);
}
Path::checkDirExists(cr.area, roomPath);
if(!strcmp(cmnd->str[extra ? 3 : 2], "loop"))
i = MAX(1, MIN(100, (int)cmnd->val[extra ? 3 : 2]));
for(; i; i--) {
if(!player->checkBuilder(cr, false)) {
player->print("Error: Room number not inside any of your alotted ranges.\n");
return(0);
}
sprintf(file, "%s", roomPath(cr));
if(file_exists(file)) {
player->print("Room already exists.\n");
return(0);
}
newRoom = new UniqueRoom;
if(!newRoom)
merror("dmAddRoom", FATAL);
newRoom->info = cr;
newRoom->setFlag(R_CONSTRUCTION);
newRoom->setName("New Room");
if(newRoom->saveToFile(0) < 0) {
player->print("Write failed.\n");
return(0);
}
delete newRoom;
log_immort(true, player, "%s created room %s.\n", player->getCName(), cr.str().c_str());
player->print("Room %s created.\n", cr.str().c_str());
checkTeleportRange(player, cr);
cr.id++;
}
return(0);
}
//*********************************************************************
// dmSetRoom
//*********************************************************************
// This function allows staff to set a characteristic of a room.
int dmSetRoom(Player* player, cmd* cmnd) {
BaseRoom *room = player->getRoomParent();
int a=0, num=0;
CatRef cr;
if(cmnd->num < 3) {
player->print("Syntax: *set r [option] [<value>]\n");
return(0);
}
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: Room number not inside any of your alotted ranges.\n");
return(0);
}
switch(low(cmnd->str[2][0])) {
case 'b':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
if(low(cmnd->str[2][1]) == 'l') {
player->getUniqueRoomParent()->setLowLevel(cmnd->val[2]);
player->print("Low level boundary %d\n", player->getUniqueRoomParent()->getLowLevel());
} else if(low(cmnd->str[2][1]) == 'h') {
player->getUniqueRoomParent()->setHighLevel(cmnd->val[2]);
player->print("Upper level boundary %d\n", player->getUniqueRoomParent()->getHighLevel());
}
break;
case 'd':
if(!player->inAreaRoom()) {
player->print("Error: You need to be in an area room to do that.\n");
return(0);
}
if(!player->getAreaRoomParent()->unique.id) {
player->print("Error: The area room must have the unique field set [*set r unique #].\n");
return(0);
}
player->getAreaRoomParent()->setDecCompass(!player->getAreaRoomParent()->getDecCompass());
player->printColor("DecCompass toggled, set to %s^x.\n",
player->getAreaRoomParent()->getDecCompass() ? "^gYes" : "^rNo");
log_immort(true, player, "%s set decCompass to %s in room %s.\n", player->getCName(),
player->getAreaRoomParent()->getDecCompass() ? "true" : "false", room->fullName().c_str());
break;
case 'e':
if(cmnd->str[2][1] == 'f') {
if(cmnd->num < 4) {
player->print("Set what effect to what?\n");
return(0);
}
long duration = -1;
int strength = 1;
std::string txt = getFullstrText(cmnd->fullstr, 4);
if(!txt.empty())
duration = atoi(txt.c_str());
txt = getFullstrText(cmnd->fullstr, 5);
if(!txt.empty())
strength = atoi(txt.c_str());
if(duration > EFFECT_MAX_DURATION || duration < -1) {
player->print("Duration must be between -1 and %d.\n", EFFECT_MAX_DURATION);
return(0);
}
if(strength < 0 || strength > EFFECT_MAX_STRENGTH) {
player->print("Strength must be between 0 and %d.\n", EFFECT_MAX_STRENGTH);
return(0);
}
std::string effectStr = cmnd->str[3];
EffectInfo* toSet = nullptr;
if((toSet = room->getExactEffect(effectStr))) {
// We have an existing effect we're modifying
if(duration == 0) {
// Duration is 0, so remove it
room->removeEffect(toSet, true);
player->print("Effect '%s' (room) removed.\n", effectStr.c_str());
} else {
// Otherwise modify as appropriate
toSet->setDuration(duration);
if(strength != -1)
toSet->setStrength(strength);
player->print("Effect '%s' (room) set to duration %d and strength %d.\n", effectStr.c_str(), toSet->getDuration(), toSet->getStrength());
}
break;
} else {
// No existing effect, add a new one
if(strength == -1)
strength = 1;
if(room->addEffect(effectStr, duration, strength, nullptr, true) != nullptr){
player->print("Effect '%s' (room) added with duration %d and strength %d.\n", effectStr.c_str(), duration, strength);
} else {
player->print("Unable to add effect '%s' (room)\n", effectStr.c_str());
}
break;
}
} else if(cmnd->str[2][1] == 'x') {
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
player->getUniqueRoomParent()->setRoomExperience(cmnd->val[2]);
player->print("Room experience set to %d.\n", player->getUniqueRoomParent()->getRoomExperience());
log_immort(true, player, "%s set roomExp to %d in room %s.\n", player->getCName(),
player->getUniqueRoomParent()->getRoomExperience(), room->fullName().c_str());
} else {
player->print("Invalid option.\n");
return(0);
}
break;
case 'f':
if(low(cmnd->str[2][1]) == 'i') {
if(!strcmp(cmnd->str[3], "")) {
player->getUniqueRoomParent()->setFishing("");
player->print("Fishing list cleared.\n");
log_immort(true, player, "%s cleared fishing list in room %s.\n", player->getCName(),
room->fullName().c_str());
} else {
const Fishing* list = gConfig->getFishing(cmnd->str[3]);
if(!list) {
player->print("Fishing list \"%s\" does not exist!\n", cmnd->str[3]);
return(0);
}
player->getUniqueRoomParent()->setFishing(cmnd->str[3]);
player->print("Fishing list set to %s.\n", player->getUniqueRoomParent()->getFishingStr().c_str());
log_immort(true, player, "%s set fishing list to %s in room %s.\n", player->getCName(),
player->getUniqueRoomParent()->getFishingStr().c_str(), room->fullName().c_str());
}
} else if(low(cmnd->str[2][1]) == 'a') {
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
if(cmnd->num < 3) {
player->print("Set faction to what?\n");
return(0);
} else if(cmnd->num == 3) {
player->getUniqueRoomParent()->setFaction("");
player->print("Faction cleared.\n");
log_immort(true, player, "%s cleared faction in room %s.\n", player->getCName(),
room->fullName().c_str());
return(0);
}
Property* p = gConfig->getProperty(player->getUniqueRoomParent()->info);
if(p && p->getType() == PROP_SHOP) {
player->print("You can't set room faction on player shops!\n");
return(0);
}
const Faction* faction = gConfig->getFaction(cmnd->str[3]);
if(!faction) {
player->print("'%s' is an invalid faction.\n", cmnd->str[3]);
return(0);
}
player->getUniqueRoomParent()->setFaction(faction->getName());
player->print("Faction set to %s.\n", player->getUniqueRoomParent()->getFaction().c_str());
log_immort(true, player, "%s set faction to %s in room %s.\n", player->getCName(),
player->getUniqueRoomParent()->getFaction().c_str(), room->fullName().c_str());
break;
} else {
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
num = cmnd->val[2];
if(num < 1 || num > MAX_ROOM_FLAGS) {
player->print("Error: outside of range.\n");
return(0);
}
if(!player->isCt() && num == R_CONSTRUCTION+1) {
player->print("Error: you cannot set/clear that flag.\n");
return(0);
}
if(!strcmp(cmnd->str[3], "del")) {
for(a=0;a<MAX_ROOM_FLAGS;a++)
player->getUniqueRoomParent()->clearFlag(a);
player->print("All room flags cleared.\n");
log_immort(true, player, "%s cleared all flags in room %s.\n",
player->getCName(), room->fullName().c_str());
break;
}
if(player->getUniqueRoomParent()->flagIsSet(num - 1)) {
player->getUniqueRoomParent()->clearFlag(num - 1);
player->print("Room flag #%d(%s) off.\n", num, gConfig->getRFlag(num-1).c_str());
log_immort(true, player, "%s cleared flag #%d(%s) in room %s.\n", player->getCName(), num, gConfig->getRFlag(num-1).c_str(),
room->fullName().c_str());
} else {
if(num >= R_TRAINING_ROOM && num - 4 <= R_TRAINING_ROOM) {
// setting a training flag - do we let them?
if(player->getUniqueRoomParent()->whatTraining(num-1) == CreatureClass::NONE) {
player->print("You are setting training for a class that does not exist.\n");
return(0);
}
}
player->getUniqueRoomParent()->setFlag(num - 1);
player->print("Room flag #%d(%s) on.\n", num, gConfig->getRFlag(num-1).c_str());
log_immort(true, player, "%s set flag #%d(%s) in room %s.\n", player->getCName(), num, gConfig->getRFlag(num-1).c_str(),
room->fullName().c_str());
if(num-1 == R_SHOP)
player->printColor("^YNote:^x you must set the Shop Storage (97) to use this room as a shop.\n");
if((num-1 == R_INDOORS || num-1 == R_VAMPIRE_COVEN || num-1 == R_UNDERGROUND) && player->getUniqueRoomParent()->getSize() == NO_SIZE)
player->printColor("^YNote:^x don't forget to set the size for this room.\n");
}
// try and be smart
if( num-1 == R_SHOP_STORAGE &&
player->getUniqueRoomParent()->getName() == "New Room" &&
player->getUniqueRoomParent()->exits.empty())
{
cr = player->getUniqueRoomParent()->info;
UniqueRoom* shop=nullptr;
std::string storageName = "Storage: ";
cr.id--;
if(loadRoom(cr, &shop)) {
if( shop->flagIsSet(R_SHOP) &&
(!shop->getTrapExit().id || shop->getTrapExit() == cr)
) {
player->printColor("^ySetting up this storage room for you...\n");
player->printColor("^y * ^xSetting the trap exit to %s...\n", cr.str().c_str());
player->getUniqueRoomParent()->setTrapExit(cr);
player->printColor("^y * ^xCreating exit ""out"" to %s...\n", cr.str().c_str());
link_rom(player->getUniqueRoomParent(), cr, "out");
player->getUniqueRoomParent()->setTrapExit(cr);
player->printColor("^y * ^xNaming this room...\n");
storageName += shop->getName();
player->getUniqueRoomParent()->setName(storageName);
player->print("Done!\n");
}
}
}
}
break;
case 'l':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
if(strcmp(cmnd->str[3], "clear") != 0) {
player->print("Are you sure?\nType \"*set r last clear\" to clear last-arrived info.\n");
return(0);
}
strcpy(player->getUniqueRoomParent()->lastPly, "");
strcpy(player->getUniqueRoomParent()->lastPlyTime, "");
player->print("Last-arrived info cleared.\n");
break;
case 'm':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
player->getUniqueRoomParent()->setMaxMobs(cmnd->val[2]);
if(!player->getUniqueRoomParent()->getMaxMobs())
player->print("The limit on the number of creatures that can be here has been removed.\n");
else
player->print("Only %d creature%s can now be in here at a time.\n", player->getUniqueRoomParent()->getMaxMobs(), player->getUniqueRoomParent()->getMaxMobs() != 1 ? "s" : "");
log_immort(true, player, "%s set max %d mobs in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getMaxMobs(),
room->fullName().c_str());
break;
case 'n':
if(!player->inAreaRoom()) {
player->print("Error: You need to be in an area room to do that.\n");
return(0);
}
if(!player->getAreaRoomParent()->unique.id) {
player->print("Error: The area room must have the unique field set [*set r unique #].\n");
return(0);
}
player->getAreaRoomParent()->setNeedsCompass(!player->getAreaRoomParent()->getNeedsCompass());
player->printColor("NeedsCompass toggled, set to %s^x.\n",
player->getAreaRoomParent()->getNeedsCompass() ? "^gYes" : "^rNo");
log_immort(true, player, "%s set needsCompass to %s in room %s.\n", player->getCName(),
player->getAreaRoomParent()->getNeedsCompass() ? "true" : "false", room->fullName().c_str());
break;
case 'r':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
num = atoi(&cmnd->str[2][1]);
if(num < 1 || num > NUM_RANDOM_SLOTS) {
player->print("Error: outside of range.\n");
return(PROMPT);
}
getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player);
if(!cr.id) {
player->getUniqueRoomParent()->wander.random.erase(num-1);
player->print("Random #%d has been cleared.\n", num);
} else {
player->getUniqueRoomParent()->wander.random[num-1] = cr;
player->print("Random #%d is now %s.\n", num, cr.str().c_str());
}
log_immort(false,player, "%s set mob slot %d to mob %s in room %s.\n",
player->getCName(), num, cr.str().c_str(),
room->fullName().c_str());
break;
case 's':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
player->getUniqueRoomParent()->setSize(getSize(cmnd->str[3]));
player->print("Size set to %s.\n", getSizeName(player->getUniqueRoomParent()->getSize()).c_str());
log_immort(true, player, "%s set room %s's %s to %s.\n",
player->getCName(), room->fullName().c_str(), "Size", getSizeName(player->getUniqueRoomParent()->getSize()).c_str());
break;
case 't':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
player->getUniqueRoomParent()->wander.setTraffic(cmnd->val[2]);
log_immort(true, player, "%s set room %s's traffic to %ld.\n", player->getCName(),
player->getUniqueRoomParent()->info.str().c_str(), player->getUniqueRoomParent()->wander.getTraffic());
player->print("Traffic is now %d%%.\n", player->getUniqueRoomParent()->wander.getTraffic());
break;
case 'x':
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
if(low(cmnd->str[2][1]) == 'x') {
getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player);
if(!player->checkBuilder(cr)) {
player->print("Trap's exit must be within an assigned range.\n");
return(0);
}
player->getUniqueRoomParent()->setTrapExit(cr);
player->print("Room's trap exit is now %s.\n", player->getUniqueRoomParent()->getTrapExit().str().c_str());
log_immort(true, player, "%s set trapexit to %s in room %s.\n", player->getCName(),
player->getUniqueRoomParent()->getTrapExit().str().c_str(), room->fullName().c_str());
} else if(low(cmnd->str[2][1]) == 'w') {
num = (int)cmnd->val[2];
if(num < 0 || num > 5000) {
player->print("Trap weight cannot be less than 0 or greater than 5000.\n");
return(0);
}
player->getUniqueRoomParent()->setTrapWeight(num);
player->print("Room's trap weight is now %d.\n", player->getUniqueRoomParent()->getTrapWeight());
log_immort(true, player, "%s set trapweight to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapWeight(),
room->fullName().c_str());
} else if(low(cmnd->str[2][1]) == 's') {
num = (int)cmnd->val[2];
if(num < 0 || num > 5000) {
player->print("Trap strength cannot be less than 0 or greater than 5000.\n");
return(0);
}
player->getUniqueRoomParent()->setTrapStrength(num);
player->print("Room's trap strength is now %d.\n", player->getUniqueRoomParent()->getTrapStrength());
log_immort(true, player, "%s set trapstrength to %d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrapStrength(),
room->fullName().c_str());
} else {
player->getUniqueRoomParent()->setTrap(cmnd->val[2]);
player->print("Room has trap #%d set.\n", player->getUniqueRoomParent()->getTrap());
log_immort(true, player, "%s set trap #%d in room %s.\n", player->getCName(), player->getUniqueRoomParent()->getTrap(),
room->fullName().c_str());
}
break;
case 'u':
if(!player->inAreaRoom()) {
player->print("Error: You need to be in an area room to do that.\n");
return(0);
}
getCatRef(getFullstrText(cmnd->fullstr, 3), &cr, player);
player->getAreaRoomParent()->unique = cr;
player->print("Unique room set to %s.\n", player->getAreaRoomParent()->unique.str().c_str());
if(player->getAreaRoomParent()->unique.id)
player->print("You'll need to use *teleport to get to this room in the future.\n");
log_immort(true, player, "%s set unique room to %s in room %s.\n",
player->getCName(), player->getAreaRoomParent()->unique.str().c_str(),
room->fullName().c_str());
break;
default:
player->print("Invalid option.\n");
return(0);
}
if(player->inUniqueRoom())
player->getUniqueRoomParent()->escapeText();
room_track(player);
return(0);
}
//*********************************************************************
// dmSetExit
//*********************************************************************
// This function allows staff to set a characteristic of an exit.
int dmSetExit(Player* player, cmd* cmnd) {
BaseRoom* room = player->getRoomParent();
int num=0;
//char orig_exit[30];
short n=0;
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: Room number not inside any of your alotted ranges.\n");
return(0);
}
// setting something on the exit
if(cmnd->str[1][1]) {
if(cmnd->num < 3) {
player->print("Invalid syntax.\n");
return(0);
}
Exit* exit = findExit(player, cmnd->str[2], 1);
if(!exit) {
player->print("Exit not found.\n");
return(0);
}
switch(cmnd->str[1][1]) {
case 'd':
{
if(cmnd->str[1][2] == 'i') {
Direction dir = getDir(cmnd->str[3]);
if(getDir(exit->getName()) != NoDirection && dir != NoDirection) {
player->print("This exit does not need a direction set on it.\n");
return(0);
}
exit->setDirection(dir);
player->printColor("%s^x's %s set to %s.\n", exit->getCName(), "Direction", getDirName(exit->getDirection()).c_str());
log_immort(true, player, "%s set %s %s^g's %s to %s.\n",
player->getCName(), "exit", exit->getCName(), "Direction", getDirName(exit->getDirection()).c_str());
} else if(cmnd->str[1][2] == 'e') {
std::string desc = getFullstrText(cmnd->fullstr, 3);
boost::replace_all(desc, "*CR*", "\n");
exit->setDescription(desc);
if(exit->getDescription().empty()) {
player->print("Description cleared.\n");
log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Description");
} else {
player->print("Description set to \"%s\".\n", exit->getDescription().c_str());
log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Description", exit->getDescription().c_str());
}
} else {
player->print("Description or direction?\n");
return(0);
}
break;
}
case 'e':
if(cmnd->str[1][2] == 'f') {
if(cmnd->num < 4) {
player->print("Set what effect to what?\n");
return(0);
}
long duration = -1;
int strength = 1;
std::string txt = getFullstrText(cmnd->fullstr, 4);
if(!txt.empty())
duration = atoi(txt.c_str());
txt = getFullstrText(cmnd->fullstr, 5);
if(!txt.empty())
strength = atoi(txt.c_str());
if(duration > EFFECT_MAX_DURATION || duration < -1) {
player->print("Duration must be between -1 and %d.\n", EFFECT_MAX_DURATION);
return(0);
}
if(strength < 0 || strength > EFFECT_MAX_STRENGTH) {
player->print("Strength must be between 0 and %d.\n", EFFECT_MAX_STRENGTH);
return(0);
}
std::string effectStr = cmnd->str[3];
EffectInfo* toSet = nullptr;
if((toSet = exit->getExactEffect(effectStr))) {
// We have an existing effect we're modifying
if(duration == 0) {
// Duration is 0, so remove it
exit->removeEffect(toSet, true);
player->print("Effect '%s' (exit) removed.\n", effectStr.c_str());
} else {
// Otherwise modify as appropriate
toSet->setDuration(duration);
if(strength != -1)
toSet->setStrength(strength);
player->print("Effect '%s' (exit) set to duration %d and strength %d.\n", effectStr.c_str(), toSet->getDuration(), toSet->getStrength());
}
} else {
// No existing effect, add a new one
if(strength == -1)
strength = 1;
if(exit->addEffect(effectStr, duration, strength, nullptr, true) != nullptr) {
player->print("Effect '%s' (exit) added with duration %d and strength %d.\n", effectStr.c_str(), duration, strength);
} else {
player->print("Unable to add effect '%s' (exit)\n", effectStr.c_str());
}
}
break;
} else {
exit->setEnter(getFullstrText(cmnd->fullstr, 3));
if(exit->getEnter().empty() || Pueblo::is(exit->getEnter())) {
exit->setEnter("");
player->print("OnEnter cleared.\n");
log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "OnEnter");
} else {
player->print("OnEnter set to \"%s\".\n", exit->getEnter().c_str());
log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "OnEnter", exit->getEnter().c_str());
}
}
break;
case 'f':
num = cmnd->val[2];
if(num < 1 || num > MAX_EXIT_FLAGS) {
player->print("Error: flag out of range.\n");
return(PROMPT);
}
if(exit->flagIsSet(num - 1)) {
exit->clearFlag(num - 1);
player->printColor("%s^x exit flag #%d off.\n", exit->getCName(), num);
log_immort(true, player, "%s cleared %s^g exit flag #%d(%s) in room %s.\n", player->getCName(), exit->getCName(), num, gConfig->getXFlag(num-1).c_str(),
room->fullName().c_str());
} else {
exit->setFlag(num - 1);
player->printColor("%s^x exit flag #%d on.\n", exit->getCName(), num);
log_immort(true, player, "%s turned on %s^g exit flag #%d(%s) in room %s.\n", player->getCName(), exit->getCName(), num, gConfig->getXFlag(num-1).c_str(),
room->fullName().c_str());
}
break;
case 'k':
if(cmnd->str[1][2] == 'a') {
exit->setKeyArea(cmnd->str[3]);
if(exit->getKeyArea().empty()) {
player->print("Key Area cleared.\n");
log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Key Area");
} else {
player->print("Key Area set to \"%s\".\n", exit->getKeyArea().c_str());
log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Key Area", exit->getKeyArea().c_str());
}
} else {
if(cmnd->val[2] > 255 || cmnd->val[2] < 0) {
player->print("Error: key out of range.\n");
return(0);
}
exit->setKey(cmnd->val[2]);
player->printColor("Exit %s^x key set to %d.\n", exit->getCName(), exit->getKey());
log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Key", exit->getKey());
}
break;
case 'l':
if(cmnd->val[2] > MAXALVL || cmnd->val[2] < 0) {
player->print("Level must be from 0 to %d.\n", MAXALVL);
return(0);
}
exit->setLevel(cmnd->val[2]);
player->printColor("Exit %s^x's level is now set to %d.\n", exit->getCName(), exit->getLevel());
log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Pick Level", exit->getLevel());
break;
case 'o':
exit->setOpen(getFullstrText(cmnd->fullstr, 3));
if(exit->getOpen().empty() || Pueblo::is(exit->getOpen())) {
exit->setOpen("");
player->print("OnOpen cleared.\n");
log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "OnOpen");
} else {
player->print("OnOpen set to \"%s\".\n", exit->getOpen().c_str());
log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "OnOpen", exit->getOpen().c_str());
}
break;
case 'p':
if(low(cmnd->str[1][2]) == 'p') {
exit->setPassPhrase(getFullstrText(cmnd->fullstr, 3));
if(exit->getPassPhrase().empty()) {
player->print("Passphrase cleared.\n");
log_immort(true, player, "%s cleared %s^g's %s.\n", player->getCName(), exit->getCName(), "Passphrase");
} else {
player->print("Passphrase set to \"%s\".\n", exit->getPassPhrase().c_str());
log_immort(true, player, "%s set %s^g's %s to \"%s\".\n", player->getCName(), exit->getCName(), "Passphrase", exit->getPassPhrase().c_str());
}
} else if(low(cmnd->str[1][2]) == 'l') {
n = cmnd->val[2];
if(n < 0 || n > LANGUAGE_COUNT) {
player->print("Error: pass language out of range.\n");
return(0);
}
n--;
if(n < 0)
n = 0;
exit->setPassLanguage(n);
player->print("Pass language %s.\n", n ? "set" : "cleared");
log_immort(true, player, "%s set %s^g's %s to %s(%ld).\n", player->getCName(), exit->getCName(), "Passlang", n ? get_language_adj(n) : "Nothing", n+1);
} else {
player->print("Passphrase (xpp) or passlang (xpl)?\n");
return(0);
}
break;
case 's':
exit->setSize(getSize(cmnd->str[3]));
player->printColor("%s^x's %s set to %s.\n", exit->getCName(), "Size", getSizeName(exit->getSize()).c_str());
log_immort(true, player, "%s set %s %s^g's %s to %s.\n",
player->getCName(), "exit", exit->getCName(), "Size", getSizeName(exit->getSize()).c_str());
break;
case 't':
n = (short)cmnd->val[2];
if(n > 30000 || n < 0) {
player->print("Must be between 0-30000.\n");
return(0);
}
exit->setToll(n);
player->printColor("Exit %s^x's toll is now set to %d.\n", exit->getCName(), exit->getToll());
log_immort(true, player, "%s set %s^g's %s to %ld.\n", player->getCName(), exit->getCName(), "Toll", exit->getToll());
break;
default:
player->print("Invalid syntax.\n");
return(0);
}
if(player->inUniqueRoom())
player->getUniqueRoomParent()->escapeText();
room_track(player);
return(0);
}
// otherwise, we have other plans for this function
if(cmnd->num < 3) {
player->print("Syntax: *set x <name> <#> [. or name]\n");
return(0);
}
// we need more variables to continue our work
MapMarker mapmarker;
BaseRoom* room2=nullptr;
AreaRoom* aRoom=nullptr;
UniqueRoom *uRoom=nullptr;
Area *area=nullptr;
CatRef cr;
std::string returnExit = getFullstrText(cmnd->fullstr, 4);
getDestination(getFullstrText(cmnd->fullstr, 3).c_str(), &mapmarker, &cr, player);
if(!mapmarker.getArea() && !cr.id) {
// if the expanded exit wasnt found
// and the exit was expanded, check to delete the original
if(room->delExit(cmnd->str[2]))
player->print("Exit %s deleted.\n", cmnd->str[2]);
else
player->print("Exit %s not found.\n", cmnd->str[2]);
return(0);
}
if(cr.id) {
if(!player->checkBuilder(cr))
return(0);
if(!loadRoom(cr, &uRoom)) {
player->print("Room %s does not exist.\n", cr.str().c_str());
return(0);
}
room2 = uRoom;
} else {
if(player->getClass() == CreatureClass::BUILDER) {
player->print("Sorry, builders cannot link exits to the overland.\n");
return(0);
}
area = gServer->getArea(mapmarker.getArea());
if(!area) {
player->print("Area does not exist.\n");
return(0);
}
aRoom = area->loadRoom(nullptr, &mapmarker, false);
room2 = aRoom;
}
std::string newName = getFullstrText(cmnd->fullstr, 2, ' ', false, true);
if(newName.length() > 20) {
player->print("Exit names must be 20 characters or less in length.\n");
return(0);
}
newName = expand_exit_name(newName);
if(!returnExit.empty()) {
if(returnExit == ".")
returnExit = opposite_exit_name(newName);
if(cr.id) {
link_rom(room, cr, newName);
if(player->inUniqueRoom())
link_rom(uRoom, player->getUniqueRoomParent()->info, returnExit);
else
link_rom(uRoom, &player->getAreaRoomParent()->mapmarker, returnExit);
gServer->resaveRoom(cr);
} else {
link_rom(room, &mapmarker, newName);
if(player->inUniqueRoom())
link_rom(aRoom, player->getUniqueRoomParent()->info, returnExit);
else
link_rom(aRoom, &player->getAreaRoomParent()->mapmarker, returnExit);
aRoom->save();
}
log_immort(true, player, "%s linked room %s to room %s in %s^g direction, both ways.\n",
player->getCName(), room->fullName().c_str(), room2->fullName().c_str(), newName.c_str());
player->printColor("Room %s linked to room %s in %s^x direction, both ways.\n",
room->fullName().c_str(), room2->fullName().c_str(), newName.c_str());
} else {
if(cr.id)
link_rom(room, cr, newName);
else
link_rom(room, &mapmarker, newName);
player->printColor("Room %s linked to room %s in %s^x direction.\n",
room->fullName().c_str(), room2->fullName().c_str(), newName.c_str());
log_immort(true, player, "%s linked room %s to room %s in %s^g direction.\n",
player->getCName(), room->fullName().c_str(), room2->fullName().c_str(), newName.c_str());
}
if(player->inUniqueRoom())
gServer->resaveRoom(player->getUniqueRoomParent()->info);
if(aRoom && aRoom->canDelete())
area->remove(aRoom);
room_track(player);
return(0);
}
//*********************************************************************
// room_track
//*********************************************************************
int room_track(Creature* player) {
long t = time(nullptr);
if(player->isMonster() || !player->inUniqueRoom())
return(0);
strcpy(player->getUniqueRoomParent()->last_mod, player->getCName());
strcpy(player->getUniqueRoomParent()->lastModTime, ctime(&t));
return(0);
}
//*********************************************************************
// dmReplace
//*********************************************************************
// this command lets staff replace words or phrases in a room description
int dmReplace(Player* player, cmd* cmnd) {
UniqueRoom *room = player->getUniqueRoomParent();
int n=0, skip=0, skPos=0;
std::string::size_type i=0, pos=0;
char delim = ' ';
bool sdesc=false, ldesc=false;
std::string search = "", temp = "";
if(!needUniqueRoom(player))
return(0);
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
if(cmnd->num < 3) {
player->print("syntax: *replace [-SL#<num>] <search> <replace>\n");
return(0);
}
// we have flags!
// let's find out what they are
if(cmnd->str[1][0] == '-') {
i=1;
while(i < strlen(cmnd->str[1])) {
switch(cmnd->str[1][i]) {
case 'l':
ldesc = true;
break;
case 's':
sdesc = true;
break;
case '#':
skip = atoi(&cmnd->str[1][++i]);
break;
default:
break;
}
i++;
}
}
// we need to get fullstr into a nicer format
i = strlen(cmnd->str[0]);
if(ldesc || sdesc || skip)
i += strlen(cmnd->str[1]) + 1;
// which deliminator should we use?
if(cmnd->fullstr[i+1] == '\'' || cmnd->fullstr[i+1] == '"' || cmnd->fullstr[i+1] == '*') {
delim = cmnd->fullstr[i+1];
i++;
}
// fullstr is now our search text and replace text seperated by a space
cmnd->fullstr = cmnd->fullstr.substr(i+1);
//strcpy(cmnd->fullstr, &cmnd->fullstr[i+1]);
// we search until we find the deliminator we're looking for
pos=0;
i = cmnd->fullstr.length();
while(pos < i) {
if(cmnd->fullstr[pos] == delim)
break;
pos++;
}
if(pos == i) {
if(delim != ' ')
player->print("Deliminator not found.\n");
else
player->print("No replace text found.\n");
return(0);
}
// cut the string apart
cmnd->fullstr[pos] = 0;
search = cmnd->fullstr;
// if it's not a space, we need to add 2 to get rid of the space and
// next deliminator
if(delim != ' ') {
pos += 2;
// although we don't have to, we're enforcing that the deliminators
// equal each other so people are consistent with the usage of this function
if(cmnd->fullstr[pos] != delim) {
player->print("Deliminators do not match up.\n");
return(0);
}
}
// fullstr now has our replace text
//strcpy(cmnd->fullstr, &cmnd->fullstr[pos+1]);
cmnd->fullstr = cmnd->fullstr.substr(pos+1);
if(delim != ' ') {
if(cmnd->fullstr[cmnd->fullstr.length()-1] != delim) {
player->print("Deliminators do not match up.\n");
return(0);
}
cmnd->fullstr[cmnd->fullstr.length()-1] = 0;
}
// the text we are searching for is in "search"
// the text we are replacing it with is in "fullstr"
// we will use i to help us reuse code
// 0 = sdesc, 1 = ldesc
i = 0;
// if only long desc, skip short desc
if(ldesc && !sdesc)
i++;
// loop for the short and long desc
do {
// loop for skip
do {
if(!i)
n = room->getShortDescription().find(search.c_str(), skPos);
else
n = room->getLongDescription().find(search.c_str(), skPos);
if(n >= 0) {
if(--skip > 0)
skPos = n + 1;
else {
if(!i) {
temp = room->getShortDescription().substr(0, n);
temp += cmnd->fullstr;
temp += room->getShortDescription().substr(n + search.length(), room->getShortDescription().length());
room->setShortDescription(temp);
} else {
temp = room->getLongDescription().substr(0, n);
temp += cmnd->fullstr;
temp += room->getLongDescription().substr(n + search.length(), room->getLongDescription().length());
room->setLongDescription(temp);
}
player->print("Replaced.\n");
room->escapeText();
return(0);
}
}
} while(n >= 0 && skip);
// if we're on long desc (i=1), we'll stop after this, so no worries
// if we're on short desc and not doing long desc, we need to stop
if(sdesc && !ldesc)
i++;
i++;
} while(i<2);
player->print("Pattern not found.\n");
return(0);
}
//*********************************************************************
// dmDelete
//*********************************************************************
// Allows staff to delete some/all of the room description
int dmDelete(Player* player, cmd* cmnd) {
UniqueRoom *room = player->getUniqueRoomParent();
int pos=0;
int unsigned i=0;
bool sdesc=false, ldesc=false, phrase=false, after=false;
if(!needUniqueRoom(player))
return(0);
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
if(cmnd->num < 2) {
player->print("syntax: *delete [-ASLPE] <delete_word>\n");
return(0);
}
// take care of the easy one
if(!strcmp(cmnd->str[1], "-a")) {
room->setShortDescription("");
room->setLongDescription("");
} else {
// determine our flags
i=1;
while(i < strlen(cmnd->str[1])) {
switch(cmnd->str[1][i]) {
case 'l':
ldesc = true;
break;
case 's':
sdesc = true;
break;
case 'p':
phrase = true;
break;
case 'e':
after = true;
break;
default:
break;
}
i++;
}
// a simple delete operation
if(!phrase && !after) {
if(sdesc)
room->setShortDescription("");
if(ldesc)
room->setLongDescription("");
if(!sdesc && !ldesc) {
player->print("Invalid syntax.\n");
return(0);
}
} else {
// we need to figure out what our phrase is
// turn fullstr into what we want to delete
i = strlen(cmnd->str[0]) + strlen(cmnd->str[1]) + 1;
if( i >= cmnd->fullstr.length() ) {
player->print("Pattern not found.\n");
return(0);
}
// fullstr is now our phrase
cmnd->fullstr = cmnd->fullstr.substr(i+1);
// we will use i to help us reuse code
// 0 = sdesc, 1 = ldesc
i = 0;
// if only long desc, skip short desc
if(ldesc && !sdesc)
i++;
// loop!
do {
if(!i)
pos = room->getShortDescription().find(cmnd->fullstr);
else
pos = room->getLongDescription().find(cmnd->fullstr);
if(pos >= 0)
break;
// if we're on long desc (i=1), we'll stop after this, so no worries
// if we're on short desc and not doing long desc, we need to stop
if(sdesc && !ldesc)
i++;
i++;
} while(i<2);
// did we find it?
if(pos < 0) {
player->print("Pattern not found.\n");
return(0);
}
// we delete everything after the phrase
if(after) {
if(!phrase)
pos += cmnd->fullstr.length();
// if it's in the short desc, and they wanted to delete
// from both short and long, then delete all of long
if(!i && !(sdesc ^ ldesc))
room->setLongDescription("");
if(!i)
room->setShortDescription(room->getShortDescription().substr(0, pos));
else
room->setLongDescription(room->getLongDescription().substr(0, pos));
// only delete the phrase
} else {
if(!i)
room->setShortDescription(room->getShortDescription().substr(0, pos) + room->getShortDescription().substr(pos + cmnd->fullstr.length(), room->getShortDescription().length()));
else
room->setLongDescription(room->getLongDescription().substr(0, pos) + room->getLongDescription().substr(pos + cmnd->fullstr.length(), room->getLongDescription().length()));
}
} // phrase && after
} // *del -A
log_immort(true, player, "%s deleted description in room %s.\n", player->getCName(),
player->getUniqueRoomParent()->info.str().c_str());
player->print("Deleted.\n");
return(0);
}
//*********************************************************************
// dmNameRoom
//*********************************************************************
int dmNameRoom(Player* player, cmd* cmnd) {
if(!needUniqueRoom(player))
return(0);
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
std::string name = getFullstrText(cmnd->fullstr, 1);
if(name.empty() || Pueblo::is(name)) {
player->print("Rename room to what?\n");
return(0);
}
if(name.length() > 79)
name = name.substr(0, 79);
player->getUniqueRoomParent()->setName(name);
log_immort(true, player, "%s renamed room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str());
player->print("Done.\n");
return(0);
}
//*********************************************************************
// dmDescription
//*********************************************************************
// Allows a staff to add the given text to the room description.
int dmDescription(Player* player, cmd* cmnd, bool append) {
UniqueRoom *room = player->getUniqueRoomParent();
int unsigned i=0;
bool sdesc=false, newline=false;
if(!needUniqueRoom(player))
return(0);
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
if(cmnd->num < 2) {
player->print("syntax: *%s [-sn] <text>\n", append ? "append" : "prepend");
return(0);
}
// turn fullstr into what we want to append
i = strlen(cmnd->str[0]);
sdesc = cmnd->str[1][0] == '-' && (cmnd->str[1][1] == 's' || cmnd->str[1][2] == 's');
newline = !(cmnd->str[1][0] == '-' && (cmnd->str[1][1] == 'n' || cmnd->str[1][2] == 'n'));
// keep chopping
if(sdesc || !newline)
i += strlen(cmnd->str[1]) + 1;
cmnd->fullstr = cmnd->fullstr.substr(i+1);
// strcpy(cmnd->fullstr, &cmnd->fullstr[i+1]);
if(cmnd->fullstr.find(" ") != std::string::npos)
player->printColor("Do not use double spaces in room descriptions! Use ^W*wrap^x to fix this.\n");
if(sdesc) {
// short descriptions
newline = newline && !room->getShortDescription().empty();
if(append) {
room->appendShortDescription(newline ? "\n" : "");
room->appendShortDescription(cmnd->fullstr);
} else {
if(newline)
cmnd->fullstr += "\n";
room->setShortDescription(cmnd->fullstr + room->getShortDescription());
}
player->print("Short description %s.\n", append ? "appended" : "prepended");
} else {
// long descriptions
newline = newline && !room->getLongDescription().empty();
if(append) {
room->appendLongDescription(newline ? "\n" : "");
room->appendLongDescription(cmnd->fullstr);
} else {
if(newline)
cmnd->fullstr += "\n";
room->setLongDescription(cmnd->fullstr + room->getLongDescription());
}
player->print("Long description %s.\n", append ? "appended" : "prepended");
}
player->getUniqueRoomParent()->escapeText();
log_immort(true, player, "%s descripted in room %s.\n", player->getCName(),
player->getUniqueRoomParent()->info.str().c_str());
return(0);
}
//*********************************************************************
// dmAppend
//*********************************************************************
int dmAppend(Player* player, cmd* cmnd) {
return(dmDescription(player, cmnd, true));
}
//*********************************************************************
// dmPrepend
//*********************************************************************
int dmPrepend(Player* player, cmd* cmnd) {
return(dmDescription(player, cmnd, false));
}
//*********************************************************************
// dmMobList
//*********************************************************************
// Display information about what mobs will randomly spawn.
void showMobList(Player* player, WanderInfo *wander, std::string_view type) {
std::map<int, CatRef>::iterator it;
Monster *monster=nullptr;
bool found=false, maybeAggro=false;
std::ostringstream oStr;
for(it = wander->random.begin(); it != wander->random.end() ; it++) {
if(!found)
oStr << "^cTraffic = " << wander->getTraffic() << "\n";
found=true;
if(!(*it).second.id)
continue;
if(!loadMonster((*it).second, &monster))
continue;
if(monster->flagIsSet(M_AGGRESSIVE))
oStr << "^r";
else {
maybeAggro = monster->flagIsSet(M_AGGRESSIVE_EVIL) ||
monster->flagIsSet(M_AGGRESSIVE_GOOD) ||
monster->flagIsSet(M_AGGRESSIVE_AFTER_TALK) ||
monster->flagIsSet(M_CLASS_AGGRO_INVERT) ||
monster->flagIsSet(M_RACE_AGGRO_INVERT) ||
monster->flagIsSet(M_DEITY_AGGRO_INVERT);
if(!maybeAggro) {
RaceDataMap::iterator rIt;
for(rIt = gConfig->races.begin() ; rIt != gConfig->races.end() ; rIt++) {
if(monster->isRaceAggro((*rIt).second->getId(), false)) {
maybeAggro = true;
break;
}
}
}
if(!maybeAggro) {
for(int n=1; n<static_cast<int>(STAFF); n++) {
if(monster->isClassAggro(n, false)) {
maybeAggro = true;
break;
}
}
}
if(!maybeAggro) {
DeityDataMap::iterator dIt;
for(dIt = gConfig->deities.begin() ; dIt != gConfig->deities.end() ; dIt++) {
if(monster->isDeityAggro((*dIt).second->getId(), false)) {
maybeAggro = true;
break;
}
}
}
if(maybeAggro)
oStr << "^y";
else
oStr << "^g";
}
oStr << "Slot " << std::setw(2) << (*it).first+1 << ": " << monster->getName() << " "
<< "[" << monType::getName(monster->getType()) << ":" << monType::getHitdice(monster->getType()) << "HD]\n"
<< " ^x[I:" << monster->info.str() << " L:" << monster->getLevel()
<< " X:" << monster->getExperience() << " G:" << monster->coins[GOLD]
<< " H:" << monster->hp.getMax() << " M:" << monster->mp.getMax()
<< " N:" << (monster->getNumWander() ? monster->getNumWander() : 1)
<< (monster->getAlignment() > 0 ? "^g" : "") << (monster->getAlignment() < 0 ? "^r" : "")
<< " A:" << monster->getAlignment()
<< "^x D:" << monster->damage.average() << "]\n";
free_crt(monster);
}
if(!found)
oStr << " No random monsters currently come in this " << type << ".";
player->printColor("%s\n", oStr.str().c_str());
}
int dmMobList(Player* player, cmd* cmnd) {
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: Room number not inside any of your alotted ranges.\n");
return(0);
}
player->print("Random monsters which come in this room:\n");
if(player->inUniqueRoom())
showMobList(player, &player->getUniqueRoomParent()->wander, "room");
else if(player->inAreaRoom()) {
Area* area = player->getAreaRoomParent()->area;
std::list<AreaZone*>::iterator it;
AreaZone *zone=nullptr;
for(it = area->zones.begin() ; it != area->zones.end() ; it++) {
zone = (*it);
if(zone->inside(area, &player->getAreaRoomParent()->mapmarker)) {
player->print("Zone: %s\n", zone->name.c_str());
showMobList(player, &zone->wander, "zone");
}
}
TileInfo* tile = area->getTile(area->getTerrain(nullptr, &player->getAreaRoomParent()->mapmarker, 0, 0, 0, true),
area->getSeasonFlags(&player->getAreaRoomParent()->mapmarker));
if(tile && tile->wander.getTraffic()) {
player->print("Tile: %s\n", tile->getName().c_str());
showMobList(player, &tile->wander, "tile");
}
}
return(0);
}
//*********************************************************************
// dmWrap
//*********************************************************************
// dmWrap will either wrap the short or long desc of a room to the
// specified length, for sanity, a range of 60 - 78 chars is the limit.
int dmWrap(Player* player, cmd* cmnd) {
UniqueRoom *room = player->getUniqueRoomParent();
int wrap=0;
bool err=false, which=false;
std::string text = "";
if(!needUniqueRoom(player))
return(0);
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
// parse the input command for syntax/range problems
if(cmnd->num < 2)
err = true;
else {
switch(cmnd->str[1][0]) {
case 'l':
which = true;
text = room->getLongDescription();
break;
case 's':
which = false;
text = room->getShortDescription();
break;
default:
err = true;
break;
}
if(!err) {
wrap = cmnd->val[1];
if(wrap < 60 || wrap > 78)
err = true;
}
}
if(err) {
player->print("*wrap <s | l> <len> where len is between 60 and 78 >\n");
return(0);
}
if((!which && room->getShortDescription().empty()) || (which && room->getLongDescription().empty())) {
player->print("No text to wrap!\n");
return(0);
}
// adjust!
wrap++;
// replace!
if(!which)
room->setShortDescription(wrapText(room->getShortDescription(), wrap));
else
room->setLongDescription(wrapText(room->getLongDescription(), wrap));
player->print("Text wrapped.\n");
player->getUniqueRoomParent()->escapeText();
log_immort(false, player, "%s wrapped the description in room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str());
return(0);
}
//*********************************************************************
// dmDeleteAllExits
//*********************************************************************
int dmDeleteAllExits(Player* player, cmd* cmnd) {
if(player->getRoomParent()->exits.empty()) {
player->print("No exits to delete.\n");
return(0);
}
player->getRoomParent()->clearExits();
// sorry, can't delete exits in overland
if(player->inAreaRoom())
player->getAreaRoomParent()->updateExits();
player->print("All exits deleted.\n");
log_immort(true, player, "%s deleted all exits in room %s.\n", player->getCName(), player->getRoomParent()->fullName().c_str());
room_track(player);
return(0);
}
//*********************************************************************
// exit_ordering
//*********************************************************************
// 1 mean exit2 goes in front of exit1
// 0 means keep looking
int exit_ordering(const char *exit1, const char *exit2) {
// always skip if they're the same name
if(!strcmp(exit1, exit2)) return(0);
// north east south west
if(!strcmp(exit1, "north")) return(0);
if(!strcmp(exit2, "north")) return(1);
if(!strcmp(exit1, "east")) return(0);
if(!strcmp(exit2, "east")) return(1);
if(!strcmp(exit1, "south")) return(0);
if(!strcmp(exit2, "south")) return(1);
if(!strcmp(exit1, "west")) return(0);
if(!strcmp(exit2, "west")) return(1);
// northeast northwest southeast southwest
if(!strcmp(exit1, "northeast")) return(0);
if(!strcmp(exit2, "northeast")) return(1);
if(!strcmp(exit1, "northwest")) return(0);
if(!strcmp(exit2, "northwest")) return(1);
if(!strcmp(exit1, "southeast")) return(0);
if(!strcmp(exit2, "southeast")) return(1);
if(!strcmp(exit1, "southwest")) return(0);
if(!strcmp(exit2, "southwest")) return(1);
if(!strcmp(exit1, "up")) return(0);
if(!strcmp(exit2, "up")) return(1);
if(!strcmp(exit1, "down")) return(0);
if(!strcmp(exit2, "down")) return(1);
// alphabetic
return strcmp(exit1, exit2) > 0 ? 1 : 0;
}
//*********************************************************************
// dmArrangeExits
//*********************************************************************
bool exitCompare( const Exit* left, const Exit* right ){
return(!exit_ordering(left->getCName(), right->getCName()));
}
void BaseRoom::arrangeExits(Player* player) {
if(exits.size() <= 1) {
if(player)
player->print("No exits to rearrange!\n");
return;
}
exits.sort(exitCompare);
if(player)
player->print("Exits rearranged!\n");
}
int dmArrangeExits(Player* player, cmd* cmnd) {
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Error: Room number not inside any of your alotted ranges.\n");
return(0);
}
player->getRoomParent()->arrangeExits(player);
return(0);
}
//*********************************************************************
// link_rom
//*********************************************************************
// from this room to unique room
void link_rom(BaseRoom* room, const Location& l, std::string_view str) {
for(Exit* ext : room->exits) {
if(ext->getName() == str) {
ext->target = l;
return;
}
}
Exit* exit = new Exit;
exit->setRoom(room);
exit->setName(str);
exit->target = l;
room->exits.push_back(exit);
}
void link_rom(BaseRoom* room, short tonum, std::string_view str) {
Location l;
l.room.id = tonum;
link_rom(room, l, str);
}
void link_rom(BaseRoom* room, const CatRef& cr, std::string_view str) {
Location l;
l.room = cr;
link_rom(room, l, str);
}
void link_rom(BaseRoom* room, MapMarker *mapmarker, std::string_view str) {
Location l;
l.mapmarker = *mapmarker;
link_rom(room, l, str);
}
//*********************************************************************
// dmFix
//*********************************************************************
int dmFix(Player* player, cmd* cmnd, std::string_view name, char find, char replace) {
Exit *exit=nullptr;
int i=0;
bool fixed=false;
if(cmnd->num < 2) {
player->bPrint(fmt::format("Syntax: *{}up <exit>\n", name));
return(0);
}
exit = findExit(player, cmnd);
if(!exit) {
player->print("You don't see that exit.\n");
return(0);
}
std::string newName = exit->getName();
for(i=newName.length(); i>0; i--) {
if(newName[i] == find) {
newName[i] = replace;
fixed = true;
}
}
if(fixed) {
exit->setName(newName);
log_immort(true, player, fmt::format("{} {}ed the exit '{}' in room {}.\n",
player->getName(), name, exit->getName(), player->getRoomParent()->fullName()).c_str());
player->print("Done.\n");
} else
player->print("Couldn't find any underscores.\n");
return(0);
}
//*********************************************************************
// dmUnfixExit
//*********************************************************************
int dmUnfixExit(Player* player, cmd* cmnd) {
return(dmFix(player, cmnd, "unfix", ' ', '_'));
}
//*********************************************************************
// dmFixExit
//*********************************************************************
int dmFixExit(Player* player, cmd* cmnd) {
return(dmFix(player, cmnd, "fix", '_', ' '));
}
//*********************************************************************
// dmRenameExit
//*********************************************************************
int dmRenameExit(Player* player, cmd* cmnd) {
Exit *exit=nullptr;
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
if(cmnd->num < 3) {
player->print("Syntax: *xrename <old exit>[#] <new exit>\n");
return(0);
}
exit = findExit(player, cmnd);
if(!exit) {
player->print("There is no exit here by that name.\n");
return(0);
}
std::string newName = getFullstrText(cmnd->fullstr, 2);
if(newName.length() > 20) {
player->print("New exit name must be 20 characters or less in length.\n");
return(0);
}
player->printColor("Exit \"%s^x\" renamed to \"%s^x\".\n", exit->getCName(), newName.c_str());
log_immort(false, player, "%s renamed exit %s^g to %s^g in room %s.\n",
player->getCName(), exit->getCName(), newName.c_str(), player->getRoomParent()->fullName().c_str());
room_track(player);
if(getDir(newName) != NoDirection)
exit->setDirection(NoDirection);
exit->setName( newName.c_str());
return(0);
}
//*********************************************************************
// dmDestroyRoom
//*********************************************************************
int dmDestroyRoom(Player* player, cmd* cmnd) {
if(!player->inUniqueRoom()) {
player->print("Error: You need to be in a unique room to do that.\n");
return(0);
}
if(!player->checkBuilder(player->getUniqueRoomParent())) {
player->print("Room is not in any of your alotted room ranges.\n");
return(0);
}
if( player->getUniqueRoomParent()->info.isArea("test") &&
player->getUniqueRoomParent()->info.id == 1
) {
player->print("Sorry, you cannot destroy this room.\n");
player->print("It is the Builder Waiting Room.\n");
return(0);
}
if(player->bound.room == player->currentLocation.room) {
player->print("Sorry, you cannot destroy this room.\n");
player->print("It is your bound room.\n");
return(0);
}
std::map<std::string, StartLoc*>::iterator sIt;
for(sIt = gConfig->start.begin() ; sIt != gConfig->start.end() ; sIt++) {
if( player->getUniqueRoomParent()->info == (*sIt).second->getBind().room ||
player->getUniqueRoomParent()->info == (*sIt).second->getRequired().room
) {
player->print("Sorry, you cannot destroy this room.\n");
player->print("It is important to starting locations.\n");
return(0);
}
}
std::list<CatRefInfo*>::const_iterator crIt;
for(crIt = gConfig->catRefInfo.begin() ; crIt != gConfig->catRefInfo.end() ; crIt++) {
if(player->getUniqueRoomParent()->info.isArea((*crIt)->getArea())) {
if((*crIt)->getLimbo() == player->getUniqueRoomParent()->info.id) {
player->print("Sorry, you cannot destroy this room.\n");
player->print("It is a Limbo room.\n");
return(0);
}
if((*crIt)->getRecall() == player->getUniqueRoomParent()->info.id) {
player->print("Sorry, you cannot destroy this room.\n");
player->print("It is a recall room.\n");
return(0);
}
}
}
log_immort(true, player, "%s destroyed room %s.\n",
player->getCName(), player->getRoomParent()->fullName().c_str());
player->getUniqueRoomParent()->destroy();
return(0);
}
//*********************************************************************
// findRoomsWithFlag
//*********************************************************************
void findRoomsWithFlag(const Player* player, const Range& range, int flag) {
Async async;
if(async.branch(player, ChildType::PRINT) == AsyncExternal) {
std::ostringstream oStr;
bool found = false;
if(range.low.id <= range.high) {
UniqueRoom* room=nullptr;
CatRef cr;
int high = range.high;
cr.setArea(range.low.area);
cr.id = range.low.id;
if(range.low.id == -1 && range.high == -1) {
cr.id = 1;
high = RMAX;
}
for(; cr.id < high; cr.id++) {
if(!loadRoom(cr, &room))
continue;
if(room->flagIsSet(flag)) {
if(player->isStaff())
oStr << room->info.rstr() << " - ";
oStr << room->getName() << "^x\n";
found = true;
}
}
}
std::cout << "^YLocations found:^x\n";
if(!found) {
std::cout << "No available locations were found.";
} else {
std::cout << oStr.str();
}
exit(0);
}
}
void findRoomsWithFlag(const Player* player, CatRef area, int flag) {
Async async;
if(async.branch(player, ChildType::PRINT) == AsyncExternal) {
struct dirent *dirp=nullptr;
DIR *dir=nullptr;
std::ostringstream oStr;
bool found = false;
char filename[250];
UniqueRoom *room=nullptr;
// This tells us just to get the path, not the file,
// and tells loadRoomFromFile to ignore the CatRef
area.id = -1;
std::string path = roomPath(area);
if((dir = opendir(path.c_str())) != nullptr) {
while((dirp = readdir(dir)) != nullptr) {
// is this a room file?
if(dirp->d_name[0] == '.')
continue;
sprintf(filename, "%s/%s", path.c_str(), dirp->d_name);
if(!loadRoomFromFile(area, &room, filename))
continue;
if(room->flagIsSet(flag)) {
if(player->isStaff())
oStr << room->info.rstr() << " - ";
oStr << room->getName() << "^x\n";
found = true;
}
// TODO: Memleak (even though it is forked), room is not deleted
}
}
std::cout << "^YLocations found:^x\n";
if(!found) {
std::cout << "No available locations were found.";
} else {
std::cout << oStr.str();
}
exit(0);
}
}
//*********************************************************************
// dmFind
//*********************************************************************
int dmFind(Player* player, cmd* cmnd) {
std::string type = getFullstrText(cmnd->fullstr, 1);
CatRef cr;
if(player->inUniqueRoom())
cr = player->getUniqueRoomParent()->info;
else
cr.setArea("area");
if(type == "r")
type = "room";
else if(type == "o")
type = "object";
else if(type == "m")
type = "monster";
if(type.empty() || (type != "room" && type != "object" && type != "monster")) {
if(!type.empty())
player->print("\"%s\" is not a valid type.\n", type.c_str());
player->print("Search for next available of the following: room, object, monster.\n");
return(0);
}
if(!player->checkBuilder(cr)) {
player->print("Error: this area is out of your range; you cannot *find here.\n");
return(0);
}
if(type == "monster" && !player->canBuildMonsters()) {
player->print("Error: you cannot work with monsters.\n");
return(0);
}
if(type == "object" && !player->canBuildObjects()) {
player->print("Error: you cannot work with objects.\n");
return(0);
}
Async async;
if(async.branch(player, ChildType::PRINT) == AsyncExternal) {
cr = findNextEmpty(type, cr.area);
std::cout << "^YNext available " << type << " in area " << cr.area << "^x\n";
if(cr.id == -1)
std::cout << "No empty %ss found.", type.c_str();
else {
std::cout << cr.rstr();
}
exit(0);
} else {
player->printColor("Searching for next available %s in ^W%s^x.\n", type.c_str(), cr.area.c_str());
}
return(0);
}
//*********************************************************************
// findNextEmpty
//*********************************************************************
// searches for the next empty room/object/monster in the area
CatRef findNextEmpty(const std::string &type, const std::string &area) {
CatRef cr;
cr.setArea(area);
if(type == "room") {
UniqueRoom* room=nullptr;
for(cr.id = 1; cr.id < RMAX; cr.id++)
if(!loadRoom(cr, &room))
return(cr);
} else if(type == "object") {
Object *object=nullptr;
for(cr.id = 1; cr.id < OMAX; cr.id++) {
if(!loadObject(cr, &object))
return(cr);
else
delete object;
}
} else if(type == "monster") {
Monster *monster=nullptr;
for(cr.id = 1; cr.id < MMAX; cr.id++) {
if(!loadMonster(cr, &monster))
return(cr);
else
free_crt(monster);
}
}
// -1 indicates failure
cr.id = -1;
return(cr);
}
//*********************************************************************
// save
//*********************************************************************
void AreaRoom::save(Player* player) const {
char filename[256];
sprintf(filename, "%s/%d/", Path::AreaRoom, area->id);
Path::checkDirExists(filename);
strcat(filename, mapmarker.filename().c_str());
if(!canSave()) {
if(file_exists(filename)) {
if(player)
player->print("Restoring this room to generic status.\n");
unlink(filename);
} else {
if(player)
player->print("There is no reason to save this room!\n\n");
}
return;
}
// record rooms saved during swap
if(gConfig->swapIsInteresting(this))
gConfig->swapLog((std::string)"a" + mapmarker.str(), false);
xmlDocPtr xmlDoc;
xmlNodePtr rootNode, curNode;
xmlDoc = xmlNewDoc(BAD_CAST "1.0");
rootNode = xmlNewDocNode(xmlDoc, nullptr, BAD_CAST "AreaRoom", nullptr);
xmlDocSetRootElement(xmlDoc, rootNode);
unique.save(rootNode, "Unique", false);
xml::saveNonZeroNum(rootNode, "NeedsCompass", needsCompass);
xml::saveNonZeroNum(rootNode, "DecCompass", decCompass);
effects.save(rootNode, "Effects");
hooks.save(rootNode, "Hooks");
curNode = xml::newStringChild(rootNode, "MapMarker");
mapmarker.save(curNode);
curNode = xml::newStringChild(rootNode, "Exits");
saveExitsXml(curNode);
xml::saveFile(filename, xmlDoc);
xmlFreeDoc(xmlDoc);
if(player)
player->print("Room saved.\n");
}
| Java |
mod actor_state;
mod character;
mod openable;
mod respawnable;
mod stats_item;
pub use actor_state::*;
pub use character::*;
pub use openable::*;
pub use respawnable::*;
pub use stats_item::*;
| Java |
import React from 'react';
import { Card } from 'bm-kit';
import './_pillar.schedule.source.scss';
const friday = [
{
start: '6:00 PM',
name: '📋 Check in begins'
},
{
start: '8:00 PM',
name: '🎤 Opening Ceremonies'
},
{
start: '9:00 PM',
name: '🤝 Team assembly'
},
{
start: '9:30 PM',
name: '🌮 Dinner'
},
{
start: '10:00 PM',
name: '💻 Hacking Begins'
},
{
start: '10:00 PM',
name: '🤖 Fundamentals of AI with Intel'
},
{
start: '12:00 AM',
name: '🥋 Ninja'
}
];
let saturday = [
{
start: '3:00 AM',
name: '🍿 Late Night Snack'
},
{
start: '8:00 AM',
name: '🥓 Breakfast'
},
{
start: '9:00 AM',
name: '🏗 Workshop'
},
{
start: '12:30 PM',
name: '🍝 Lunch'
},
{
start: '1:00 PM',
name: '👪 Facebook Tech Talk'
},
{
start: '2:00 PM',
name: '🐶 Doggos/Woofers'
},
{
start: '2:30 PM',
name: '✈️ Rockwell Collins Talk'
},
{
start: '3:00 PM',
name: '🍿 Snack'
},
{
start: '3:00 PM',
name: '🚣🏽 Activity'
},
{
start: '4:00 PM',
name: '📈 Startups with T.A. MaCann'
},
{
start: '6:00 PM',
name: '🍕 Dinner'
},
{
start: '9:00 PM',
name: '🥤 Cup stacking with MLH'
},
{
start: '10:00 PM',
name: '🍩 Donuts and Kona Ice'
},
{
start: '10:00 PM',
name: '🏗️ Jenga'
}
];
let sunday = [
{
start: '1:00 AM',
name: '🍿 Late Night Snack'
},
{
start: '8:00 AM',
name: '🍳 Breakfast'
},
{
start: '9:30 AM',
name: '🛑 Hacking Ends'
},
{
start: '10:00 AM',
name: '📔 Expo Begins'
},
{
start: '11:30 AM',
name: '🍞 Lunch'
},
{
start: '1:00 PM',
name: '🎭 Closing Ceremonies'
},
{
start: '2:30 PM',
name: '🚌 Buses Depart'
}
];
const ScheduleDay = ({ dayData, title }) => (
<Card className="p-schedule__day">
<h3 className="text-center">{title}</h3>
{dayData.map(item => (
<div className="p-schedule__item" key={item.name + item.start}>
<div className="p-schedule__item_about">
<span className="p-schedule__item_time">{item.start}</span>
<span className="p-schedule__item_title">{item.name}</span>
</div>
<div className="p-schedule__item_info">{item.info}</div>
</div>
))}
</Card>
);
const Schedule = ({ small }) => (
<div className="p-schedule">
{small ? <h3 style={{ marginTop: 0 }}>Schedule</h3> : <h1>Schedule</h1>}
<div className="p-schedule__days">
<ScheduleDay dayData={friday} title="Friday (10/19)" />
<ScheduleDay dayData={saturday} title="Saturday (10/20)" />
<ScheduleDay dayData={sunday} title="Sunday (10/21)" />
</div>
</div>
);
export default Schedule;
| Java |
//
// Copyright (C) 2015-2016 University of Amsterdam
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef INTEGERINFORECORD_H
#define INTEGERINFORECORD_H
#include "datainforecord.h"
namespace spss
{
/**
* @brief The IntegerInfoRecord class
*
* Associated with record type rectype_value_labels = rectype_meta_data = 7, sub type recsubtype_integer = 3,
*/
class IntegerInfoRecord : public DataInfoRecord<recsubtype_integer>
{
public:
/**
* @brief IntegerInfoRecord default Ctor
*/
IntegerInfoRecord();
/**
* @brief IntegerInfoRecord Ctor
* @param Converters fixer Fixes endainness.
* @param fileSubType The record subtype value, as found in the file.
* @param fileType The record type value, as found in the file.
* @param fromStream The file to read from.
*
* NB This constructor will modify the contents of fixer!
*/
IntegerInfoRecord(NumericConverter &fixer, RecordSubTypes fileSubType, RecordTypes fileType, SPSSStream &fromStream);
virtual ~IntegerInfoRecord();
/*
* Data!
*/
SPSSIMPORTER_READ_ATTRIB(int32_t, version_major)
SPSSIMPORTER_READ_ATTRIB(int32_t, version_minor)
SPSSIMPORTER_READ_ATTRIB(int32_t, version_revision)
SPSSIMPORTER_READ_ATTRIB(int32_t, machine_code)
SPSSIMPORTER_READ_ATTRIB(int32_t, floating_point_rep)
SPSSIMPORTER_READ_ATTRIB(int32_t, compression_code)
SPSSIMPORTER_READ_ATTRIB(int32_t, endianness)
SPSSIMPORTER_READ_ATTRIB(int32_t, character_code)
/**
* @brief process Manipulates columns by adding the contents of thie record.
* @param columns
*
* Implematations should examine columns to determine the record history.
*/
virtual void process(SPSSColumns & columns);
};
}
#endif // INTEGERINFORECORD_H
| Java |
window.addEventListener("DOMContentLoaded", () => {
let watchers = {};
new DOM('@Dialog').forEach((dialog) => {
dialogPolyfill.registerDialog(dialog);
if (dialog.querySelector('Button[Data-Action="Dialog_Submit"]')) {
dialog.addEventListener("keydown", (event) => {
if (event.ctrlKey && event.keyCode == 13) dialog.querySelector('Button[Data-Action="Dialog_Submit"]').click();
});
}
dialog.querySelectorAll('Dialog *[Required]').forEach((input) => {
input.addEventListener("input", () => {
let result = true;
dialog.querySelectorAll('Dialog *[Required]').forEach(requiredField => {
if (requiredField.value.replace(/\s/g, "").length == 0) {
result = false;
return;
}
});
if (result) {
dialog.querySelector('Button[Data-Action="Dialog_Submit"]').classList.remove("mdl-button--disabled");
} else {
dialog.querySelector('Button[Data-Action="Dialog_Submit"]').classList.add("mdl-button--disabled");
}
});
});
dialog.querySelectorAll('Dialog Button[Data-Action="Dialog_Close"]').forEach((btn) => {
btn.addEventListener("click", () => {
btn.offsetParent.close();
});
});
});
new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").addEventListener("input", () => {
if (new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").value == base.user.email) {
new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").classList.remove("mdl-button--disabled");
} else {
new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").classList.add("mdl-button--disabled");
}
});
new DOM("#Dialogs_Profile_DeleteConfirmer_Btns_Yes").addEventListener("click", (event) => {
if (new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email-Input").value == base.user.email) {
base.delete();
} else {
new DOM("#Dialogs_Profile_DeleteConfirmer_Content_Email").classList.add("is-invalid");
}
});
watchers["Dialogs_Profile_InfoViewer_UID"] = {
valueObj: { value: "" },
watcher: null
}; watchers["Dialogs_Profile_InfoViewer_UID"].watcher = new DOM.Watcher({
target: watchers["Dialogs_Profile_InfoViewer_UID"].valueObj,
onGet: () => { watchers["Dialogs_Profile_InfoViewer_UID"].valueObj.value = new DOM("#Dialogs_Profile_InfoViewer_UID").value },
onChange: (watcher) => {
base.Database.get(base.Database.ONCE, `users/${watcher.newValue}`, (res) => {
new DOM("#Dialogs_Profile_InfoViewer_Content_Photo").dataset.uid = watcher.newValue,
new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Name").textContent = res.userName,
new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Detail").textContent = res.detail;
while (new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").childNodes.length > 0) new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").childNodes[0].remove();
if (res.links) {
for (let i = 0; i < res.links.length; i++) {
let link = new Component.Dialogs.Profile.InfoViewer.Links.Link(res.links[i].name, res.links[i].url);
new DOM("#Dialogs_Profile_InfoViewer_Content_Info_Links").appendChild(link);
}
}
});
}
});
new DOM("#Dialogs_Thread_DeleteConfirmer_Btns_Yes").addEventListener("click", () => {
base.Database.delete(`threads/${new DOM("#Dialogs_Thread_DeleteConfirmer_TID").value}/`);
parent.document.querySelector("IFrame.mdl-layout__content").contentWindow.postMessage({ code: "Code-Refresh" }, "*");
new DOM("#Dialogs_Thread_EditNotify").showModal();
});
new DOM("@#Dialogs_Thread_InfoInputter *[Required]").forEach((input) => {
input.addEventListener("input", () => {
let result = true;
let list = [
new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"),
new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input")
];
if (new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked) list.push(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input"));
list.forEach(requiredField => {
if (requiredField.value.replace(/\s/g, "").length == 0) {
result = false;
return;
}
});
if (result) {
new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => {
btn.classList.remove("mdl-button--disabled");
});
} else {
new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => {
btn.classList.add("mdl-button--disabled");
});
}
});
});
new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").addEventListener("change", (event) => {
let result = true;
switch (event.target.checked) {
case true:
new DOM("#Dialogs_Thread_InfoInputter_Content_Password").classList.remove("mdl-switch__child-hide");
[new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input")].forEach(requiredField => {
if (requiredField.value.replace(/\s/g, "").length == 0) {
result = false;
return;
}
});
break;
case false:
new DOM("#Dialogs_Thread_InfoInputter_Content_Password").classList.add("mdl-switch__child-hide");
[new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input"), new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input")].forEach(requiredField => {
if (requiredField.value.replace(/\s/g, "").length == 0) {
result = false;
return;
}
});
break;
}
if (result) {
new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => {
btn.classList.remove("mdl-button--disabled");
});
} else {
new DOM("#Dialogs_Thread_InfoInputter").querySelectorAll('Button[Data-Action="Dialog_Submit"]').forEach(btn => {
btn.classList.add("mdl-button--disabled");
});
}
});
new DOM("#Dialogs_Thread_InfoInputter_Btns_Create").addEventListener("click", (event) => {
base.Database.transaction("threads", (res) => {
let now = new Date().getTime();
base.Database.set("threads/" + res.length, {
title: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value,
overview: new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input").value,
detail: new DOM("#Dialogs_Thread_InfoInputter_Content_Detail-Input").value,
jobs: {
Owner: (() => {
let owner = {}; owner[base.user.uid] = "";
return owner;
})(),
Admin: {
}
},
createdAt: now,
data: [
{
uid: "!SYSTEM_INFO",
content: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value,
createdAt: now
}
],
password: new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked ? Encrypter.encrypt(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input").value) : ""
});
new DOM("#Dialogs_Thread_InfoInputter").close();
parent.document.querySelector("IFrame.mdl-layout__content").src = "Thread/Viewer/?tid=" + res.length;
});
});
new DOM("#Dialogs_Thread_InfoInputter_Btns_Edit").addEventListener("click", (event) => {
base.Database.update(`threads/${new DOM("#Dialogs_Thread_InfoInputter_TID").value}/`, {
title: new DOM("#Dialogs_Thread_InfoInputter_Content_Name-Input").value,
overview: new DOM("#Dialogs_Thread_InfoInputter_Content_Overview-Input").value,
detail: new DOM("#Dialogs_Thread_InfoInputter_Content_Detail-Input").value,
password: new DOM("#Dialogs_Thread_InfoInputter_Content_Secured-Input").checked ? Encrypter.encrypt(new DOM("#Dialogs_Thread_InfoInputter_Content_Password-Input").value) : ""
});
new DOM("#Dialogs_Thread_InfoInputter").close();
new DOM("#Dialogs_Thread_EditNotify").showModal();
});
new DOM("#Dialogs_Thread_PasswordConfirmer_Btns_OK").addEventListener("click", (event) => {
if (Encrypter.encrypt(new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password-Input").value) == new DOM("#Dialogs_Thread_PasswordConfirmer_Password").value) {
sessionStorage.setItem("com.GenbuProject.SimpleThread.currentPassword", new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password-Input").value);
new DOM("$IFrame.mdl-layout__content").src = new DOM("#Dialogs_Thread_PasswordConfirmer_Link").value;
new DOM("#Dialogs_Thread_PasswordConfirmer_Link").value = "",
new DOM("#Dialogs_Thread_PasswordConfirmer_Password").value = "";
} else {
new DOM("#Dialogs_Thread_PasswordConfirmer_Content_Password").classList.add("is-invalid");
}
});
new DOM("#Dialogs_Thread_PasswordConfirmer_Btns_Cancel").addEventListener("click", (event) => {
new DOM("$IFrame.mdl-layout__content").src = "/SimpleThread/Thread/";
});
watchers["Dialogs_Thread_InfoViewer_TID"] = {
valueObj: { value: "0" },
watcher: null
}; watchers["Dialogs_Thread_InfoViewer_TID"].watcher = new DOM.Watcher({
target: watchers["Dialogs_Thread_InfoViewer_TID"].valueObj,
onGet: () => { watchers["Dialogs_Thread_InfoViewer_TID"].valueObj.value = new DOM("#Dialogs_Thread_InfoViewer_TID").value },
onChange: (watcher) => {
base.Database.get(base.Database.ONCE, `threads/${watcher.newValue}`, (res) => {
new DOM("#Dialogs_Thread_InfoViewer_Content_Name").textContent = res.title,
new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").textContent = res.overview,
new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").textContent = res.detail;
URL.filter(new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").textContent).forEach((urlString) => {
new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").innerHTML = new DOM("#Dialogs_Thread_InfoViewer_Content_Overview").innerHTML.replace(urlString, `<A Href = "${urlString}" Target = "_blank">${urlString}</A>`);
});
URL.filter(new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").textContent).forEach((urlString) => {
new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").innerHTML = new DOM("#Dialogs_Thread_InfoViewer_Content_Detail").innerHTML.replace(urlString, `<A Href = "${urlString}" Target = "_blank">${urlString}</A>`);
});
});
}
});
new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedLink").addEventListener("click", () => {
new DOM("#Dialogs_Thread_Poster_LinkEmbedder").showModal();
});
new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedImage").addEventListener("click", () => {
new DOM("#Dialogs_Thread_Poster").close();
let picker = new Picker.PhotoPicker(data => {
console.log(data);
switch (data[google.picker.Response.ACTION]) {
case google.picker.Action.CANCEL:
case google.picker.Action.PICKED:
new DOM("#Dialogs_Thread_Poster").showModal();
break;
}
});
picker.show();
});
new DOM("#Dialogs_Thread_Poster_Menu_MenuItem-EmbedFile").addEventListener("click", () => {
new DOM("#Dialogs_Thread_Poster").close();
let picker = new Picker.FilePicker(data => {
console.log(data);
switch (data[google.picker.Response.ACTION]) {
case google.picker.Action.CANCEL:
case google.picker.Action.PICKED:
new DOM("#Dialogs_Thread_Poster").showModal();
break;
}
});
picker.show();
});
new DOM("#Dialogs_Thread_Poster_Content_Text-Input").addEventListener("keydown", (event) => {
let inputter = event.target;
let selectionStart = inputter.selectionStart,
selectionEnd = inputter.selectionEnd;
switch (event.keyCode) {
case 9:
event.preventDefault();
inputter.value = `${inputter.value.slice(0, selectionStart)}\t${inputter.value.slice(selectionEnd)}`;
inputter.setSelectionRange(selectionStart + 1, selectionStart + 1);
new DOM("#Dialogs_Thread_Poster_Content_Text").classList.add("is-dirty");
break;
}
});
new DOM("#Dialogs_Thread_Poster_Btns_OK").addEventListener("click", (event) => {
base.Database.transaction("threads/" + new DOM("#Dialogs_Thread_Poster_TID").value + "/data", (res) => {
base.Database.set("threads/" + new DOM("#Dialogs_Thread_Poster_TID").value + "/data/" + res.length, {
uid: base.user.uid,
content: new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value,
createdAt: new Date().getTime()
});
new DOM("#Dialogs_Thread_Poster_Btns_OK").classList.add("mdl-button--disabled"),
new DOM("#Dialogs_Thread_Poster_Content_Text").classList.remove("is-dirty"),
new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value = "";
new DOM("#Page").contentDocument.querySelector("#FlowPanel_Btns_CreatePost").removeAttribute("Disabled");
new DOM("#Dialogs_Thread_Poster").close();
});
});
new DOM("#Dialogs_Thread_Poster_Btns_Cancel").addEventListener("click", () => {
new DOM("#Dialogs_Thread_Poster_Btns_OK").classList.add("mdl-button--disabled"),
new DOM("#Dialogs_Thread_Poster_Content_Text").classList.remove("is-dirty"),
new DOM("#Dialogs_Thread_Poster_Content_Text-Input").value = "";
new DOM("#Page").contentDocument.querySelector("#FlowPanel_Btns_CreatePost").removeAttribute("Disabled");
});
for (let watcherName in watchers) DOM.Watcher.addWatcher(watchers[watcherName].watcher);
}); | Java |
{% extends "happyapp/base.html" %}
{% load i18n %}
{% block title %}{% trans "Good for you, continue beeing happy :D" %}{% endblock %}
{% block content %}
<h1 class="ok">
{% blocktrans %}
Good for you, continue beeing happy, you are doing it ok.
{% endblocktrans %}
</h1>
{% include "happyapp/makead.html" %}
{% endblock %}
| Java |
package com.simplyian.superplots.actions;
import static org.mockito.Matchers.contains;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.simplyian.superplots.EconHook;
import com.simplyian.superplots.SPSettings;
import com.simplyian.superplots.SuperPlotsPlugin;
import com.simplyian.superplots.plot.Plot;
import com.simplyian.superplots.plot.PlotManager;
public class ActionWithdrawTest {
private SuperPlotsPlugin main;
private ActionWithdraw action;
private PlotManager plotManager;
private Player player;
private EconHook econ;
@Before
public void setup() {
main = mock(SuperPlotsPlugin.class);
action = new ActionWithdraw(main);
econ = mock(EconHook.class);
when(main.getEconomy()).thenReturn(econ);
plotManager = mock(PlotManager.class);
when(main.getPlotManager()).thenReturn(plotManager);
SPSettings settings = mock(SPSettings.class);
when(main.getSettings()).thenReturn(settings);
when(settings.getInfluenceMultiplier()).thenReturn(1.5);
when(settings.getInitialPlotSize()).thenReturn(10);
player = mock(Player.class);
when(player.getName()).thenReturn("albireox");
}
@After
public void tearDown() {
main = null;
action = null;
plotManager = null;
player = null;
}
@Test
public void test_perform_notInPlot() {
World world = mock(World.class);
Location playerLoc = new Location(world, 0, 0, 0);
when(plotManager.getPlotAt(playerLoc)).thenReturn(null);
List<String> args = Arrays.asList("asdf");
action.perform(player, args);
verify(player).sendMessage(contains("not in a plot"));
}
@Test
public void test_perform_mustBeAdministrator() {
World world = mock(World.class);
Location playerLoc = new Location(world, 0, 0, 0);
when(player.getLocation()).thenReturn(playerLoc);
Plot plot = mock(Plot.class);
when(plotManager.getPlotAt(playerLoc)).thenReturn(plot);
when(plot.isAdministrator("albireox")).thenReturn(false);
when(player.getName()).thenReturn("albireox");
List<String> args = Arrays.asList();
action.perform(player, args);
verify(player).sendMessage(contains("must be an administrator"));
}
@Test
public void test_perform_noAmount() {
World world = mock(World.class);
Location playerLoc = new Location(world, 0, 0, 0);
when(player.getLocation()).thenReturn(playerLoc);
Plot plot = mock(Plot.class);
when(plotManager.getPlotAt(playerLoc)).thenReturn(plot);
when(plot.isAdministrator("albireox")).thenReturn(true);
when(player.getName()).thenReturn("albireox");
List<String> args = Arrays.asList();
action.perform(player, args);
verify(player).sendMessage(contains("did not specify"));
}
@Test
public void test_perform_notANumber() {
World world = mock(World.class);
Location playerLoc = new Location(world, 0, 0, 0);
when(player.getLocation()).thenReturn(playerLoc);
Plot plot = mock(Plot.class);
when(plotManager.getPlotAt(playerLoc)).thenReturn(plot);
when(plot.isAdministrator("albireox")).thenReturn(true);
when(player.getName()).thenReturn("albireox");
when(econ.getBalance("albireox")).thenReturn(200.0);
List<String> args = Arrays.asList("400x");
action.perform(player, args);
verify(player).sendMessage(contains("not a valid amount"));
}
@Test
public void test_perform_notEnoughMoney() {
World world = mock(World.class);
Location playerLoc = new Location(world, 0, 0, 0);
when(player.getLocation()).thenReturn(playerLoc);
Plot plot = mock(Plot.class);
when(plotManager.getPlotAt(playerLoc)).thenReturn(plot);
when(plot.isAdministrator("albireox")).thenReturn(true);
when(player.getName()).thenReturn("albireox");
when(plot.getFunds()).thenReturn(200);
List<String> args = Arrays.asList("400");
action.perform(player, args);
verify(player).sendMessage(contains("doesn't have that much money"));
}
@Test
public void test_perform_success() {
World world = mock(World.class);
Location playerLoc = new Location(world, 0, 0, 0);
when(player.getLocation()).thenReturn(playerLoc);
Plot plot = mock(Plot.class);
when(plotManager.getPlotAt(playerLoc)).thenReturn(plot);
when(plot.isAdministrator("albireox")).thenReturn(true);
when(player.getName()).thenReturn("albireox");
when(plot.getFunds()).thenReturn(400);
List<String> args = Arrays.asList("400");
action.perform(player, args);
verify(player).sendMessage(contains("has been withdrawn"));
verify(plot).subtractFunds(400);
verify(econ).addBalance("albireox", 400);
}
}
| Java |
# -*- encoding: utf-8 -*-
from . import res_partner_bank
from . import account_bank_statement_import
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template basic_stream</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Convert 2.0">
<link rel="up" href="../../header/boost/convert/stream_hpp.html" title="Header <boost/convert/stream.hpp>">
<link rel="prev" href="../../header/boost/convert/stream_hpp.html" title="Header <boost/convert/stream.hpp>">
<link rel="next" href="basic_stream/ibuffer_type.html" title="Struct ibuffer_type">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="basic_stream/ibuffer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.cnv.basic_stream"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template basic_stream</span></h2>
<p>boost::cnv::basic_stream</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/convert/stream_hpp.html" title="Header <boost/convert/stream.hpp>">boost/convert/stream.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> Char<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="basic_stream.html" title="Struct template basic_stream">basic_stream</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">noncopyable</span> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">Char</span> <a name="boost.cnv.basic_stream.char_type"></a><span class="identifier">char_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <a class="link" href="basic_stream.html" title="Struct template basic_stream">boost::cnv::basic_stream</a><span class="special"><</span> <span class="identifier">char_type</span> <span class="special">></span> <a name="boost.cnv.basic_stream.this_type"></a><span class="identifier">this_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_stringstream</span><span class="special"><</span> <span class="identifier">char_type</span> <span class="special">></span> <a name="boost.cnv.basic_stream.stream_type"></a><span class="identifier">stream_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">char_type</span> <span class="special">></span> <a name="boost.cnv.basic_stream.istream_type"></a><span class="identifier">istream_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_streambuf</span><span class="special"><</span> <span class="identifier">char_type</span> <span class="special">></span> <a name="boost.cnv.basic_stream.buffer_type"></a><span class="identifier">buffer_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_string</span><span class="special"><</span> <span class="identifier">char_type</span> <span class="special">></span> <a name="boost.cnv.basic_stream.stdstr_type"></a><span class="identifier">stdstr_type</span><span class="special">;</span>
<span class="keyword">typedef</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">ios_base</span> <span class="special">&</span><span class="special">(</span><span class="special">*</span> <a name="boost.cnv.basic_stream.manipulator_type"></a><span class="identifier">manipulator_type</span><span class="special">;</span>
<span class="comment">// member classes/structs/unions</span>
<span class="keyword">struct</span> <a class="link" href="basic_stream/ibuffer_type.html" title="Struct ibuffer_type">ibuffer_type</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">buffer_type</span> <span class="special">{</span>
<span class="comment">// <a class="link" href="basic_stream/ibuffer_type.html#boost.cnv.basic_stream.ibuffer_typeconstruct-copy-destruct">construct/copy/destruct</a></span>
<a class="link" href="basic_stream/ibuffer_type.html#idp35843504-bb"><span class="identifier">ibuffer_type</span></a><span class="special">(</span><span class="identifier">char_type</span> <span class="keyword">const</span> <span class="special">*</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span>
<span class="keyword">struct</span> <a class="link" href="basic_stream/obuffer_type.html" title="Struct obuffer_type">obuffer_type</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">buffer_type</span> <span class="special">{</span>
<span class="special">}</span><span class="special">;</span>
<span class="comment">// <a class="link" href="basic_stream.html#boost.cnv.basic_streamconstruct-copy-destruct">construct/copy/destruct</a></span>
<a class="link" href="basic_stream.html#idp35899760-bb"><span class="identifier">basic_stream</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35900048-bb"><span class="identifier">basic_stream</span></a><span class="special">(</span><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&&</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="basic_stream.html#idp35852432-bb">public member functions</a></span>
<a class="link" href="basic_stream.html#idp35852992-bb"><span class="identifier">BOOST_CNV_STRING_ENABLE</span></a><span class="special">(</span><span class="identifier">type</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35855344-bb"><span class="identifier">BOOST_CNV_STRING_ENABLE</span></a><span class="special">(</span><span class="identifier">string_type</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> type<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35857680-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">char_type</span> <span class="keyword">const</span> <span class="special">*</span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> type<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35861024-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">stdstr_type</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> manipulator<span class="special">></span> <a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&</span> <a class="link" href="basic_stream.html#idp35864368-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">manipulator</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&</span> <a class="link" href="basic_stream.html#idp35867040-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">manipulator_type</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&</span> <a class="link" href="basic_stream.html#idp35868864-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35870688-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">locale</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35872752-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35874816-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35876880-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">width</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35878944-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">fill</span><span class="special">,</span> <span class="keyword">char</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35881008-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">uppercase</span><span class="special">,</span> <span class="keyword">bool</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35883072-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><span class="identifier">skipws</span><span class="special">,</span> <span class="keyword">bool</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35885136-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><a class="link" href="adjust.html" title="Struct adjust">adjust</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">adjust</span><span class="special">::</span><span class="identifier">type</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35887344-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><a class="link" href="base.html" title="Struct base">base</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">base</span><span class="special">::</span><span class="identifier">type</span><span class="special">)</span><span class="special">;</span>
<a class="link" href="basic_stream.html#idp35889536-bb"><span class="identifier">BOOST_CNV_PARAM</span></a><span class="special">(</span><a class="link" href="notation.html" title="Struct notation">notation</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">notation</span><span class="special">::</span><span class="identifier">type</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35891744-bb"><span class="identifier">to_str</span></a><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35895664-bb"><span class="identifier">str_to</span></a><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span><span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span> <span class="identifier">out_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="comment">// <a class="link" href="basic_stream.html#idp35901312-bb">private member functions</a></span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35901888-bb"><span class="identifier">str_to</span></a><span class="special">(</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">out_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">></span>
<span class="keyword">void</span> <a class="link" href="basic_stream.html#idp35905808-bb"><span class="identifier">to_str</span></a><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp102043712"></a><h2>Description</h2>
<div class="refsect2">
<a name="idp102044128"></a><h3>
<a name="boost.cnv.basic_streamconstruct-copy-destruct"></a><code class="computeroutput">basic_stream</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><a name="idp35899760-bb"></a><span class="identifier">basic_stream</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><a name="idp35900048-bb"></a><span class="identifier">basic_stream</span><span class="special">(</span><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&&</span> other<span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
<div class="refsect2">
<a name="idp102055104"></a><h3>
<a name="idp35852432-bb"></a><code class="computeroutput">basic_stream</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"> <a name="idp35852992-bb"></a><span class="identifier">BOOST_CNV_STRING_ENABLE</span><span class="special">(</span><span class="identifier">type</span> <span class="keyword">const</span> <span class="special">&</span> v<span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> <span class="special">&</span> s<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35855344-bb"></a><span class="identifier">BOOST_CNV_STRING_ENABLE</span><span class="special">(</span><span class="identifier">string_type</span> <span class="keyword">const</span> <span class="special">&</span> s<span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">type</span> <span class="special">></span> <span class="special">&</span> r<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> type<span class="special">></span>
<span class="keyword">void</span> <a name="idp35857680-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">char_type</span> <span class="keyword">const</span> <span class="special">*</span> s<span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">type</span> <span class="special">></span> <span class="special">&</span> r<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> type<span class="special">></span>
<span class="keyword">void</span> <a name="idp35861024-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">stdstr_type</span> <span class="keyword">const</span> <span class="special">&</span> s<span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">type</span> <span class="special">></span> <span class="special">&</span> r<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> manipulator<span class="special">></span> <a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&</span> <a name="idp35864368-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">manipulator</span> m<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&</span> <a name="idp35867040-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">manipulator_type</span> m<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><a class="link" href="basic_stream.html#boost.cnv.basic_stream.this_type">this_type</a> <span class="special">&</span> <a name="idp35868864-bb"></a><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span> <span class="keyword">const</span> <span class="special">&</span> l<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35870688-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">locale</span><span class="special">,</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">locale</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35872752-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35874816-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">precision</span><span class="special">,</span> <span class="keyword">int</span><span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35876880-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">width</span><span class="special">,</span> <span class="keyword">int</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35878944-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">fill</span><span class="special">,</span> <span class="keyword">char</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35881008-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">uppercase</span><span class="special">,</span> <span class="keyword">bool</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35883072-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><span class="identifier">skipws</span><span class="special">,</span> <span class="keyword">bool</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35885136-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><a class="link" href="adjust.html" title="Struct adjust">adjust</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">adjust</span><span class="special">::</span><span class="identifier">type</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35887344-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><a class="link" href="base.html" title="Struct base">base</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">base</span><span class="special">::</span><span class="identifier">type</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"> <a name="idp35889536-bb"></a><span class="identifier">BOOST_CNV_PARAM</span><span class="special">(</span><a class="link" href="notation.html" title="Struct notation">notation</a><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">notation</span><span class="special">::</span><span class="identifier">type</span> const<span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">></span>
<span class="keyword">void</span> <a name="idp35891744-bb"></a><span class="identifier">to_str</span><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&</span> value_in<span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> <span class="special">&</span> string_out<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">></span>
<span class="keyword">void</span> <a name="idp35895664-bb"></a><span class="identifier">str_to</span><span class="special">(</span><span class="identifier">boost</span><span class="special">::</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> string_in<span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">optional</span><span class="special"><</span> <span class="identifier">out_type</span> <span class="special">></span> <span class="special">&</span> result_out<span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
</ol></div>
</div>
<div class="refsect2">
<a name="idp102235440"></a><h3>
<a name="idp35901312-bb"></a><code class="computeroutput">basic_stream</code> private member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> out_type<span class="special">></span>
<span class="keyword">void</span> <a name="idp35901888-bb"></a><span class="identifier">str_to</span><span class="special">(</span><span class="identifier">cnv</span><span class="special">::</span><span class="identifier">range</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">out_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> string_type<span class="special">,</span> <span class="keyword">typename</span> in_type<span class="special">></span>
<span class="keyword">void</span> <a name="idp35905808-bb"></a><span class="identifier">to_str</span><span class="special">(</span><span class="identifier">in_type</span> <span class="keyword">const</span> <span class="special">&</span><span class="special">,</span> <span class="identifier">optional</span><span class="special"><</span> <span class="identifier">string_type</span> <span class="special">></span> <span class="special">&</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre></li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2009-2016 Vladimir Batov<p>
Distributed under the Boost Software License, Version 1.0. See copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>.
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/convert/stream_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="basic_stream/ibuffer_type.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
import {login, signup} from '../../src/app/actions/authActions';
import ActionsConstants from '../../src/common/constants/actionsConstants';
describe('auth actions', () => {
describe('if we create a login action', () => {
let userId = 'TestUser';
it('should generate action with payload', () => {
expect(login(userId)).toEqual({
type: ActionsConstants.Login,
payload: userId
});
});
});
describe('if we create a login action without a userId', () => {
const error = new TypeError('not a string');
it('should fail', () => {
expect(login(error)).toEqual({
type: ActionsConstants.Login,
payload: error,
error: true
});
});
});
describe('if we create a signup action', () => {
it('should generate action with payload', () => {
expect(signup()).toEqual({
type: ActionsConstants.SignUp
});
});
});
}); | Java |
"""
Tests course_creators.admin.py.
"""
from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.admin.sites import AdminSite
from django.http import HttpRequest
import mock
from course_creators.admin import CourseCreatorAdmin
from course_creators.models import CourseCreator
from django.core import mail
from student.roles import CourseCreatorRole
from student import auth
def mock_render_to_string(template_name, context):
"""Return a string that encodes template_name and context"""
return str((template_name, context))
class CourseCreatorAdminTest(TestCase):
"""
Tests for course creator admin.
"""
def setUp(self):
""" Test case setup """
super(CourseCreatorAdminTest, self).setUp()
self.user = User.objects.create_user('test_user', 'test_user+courses@edx.org', 'foo')
self.table_entry = CourseCreator(user=self.user)
self.table_entry.save()
self.admin = User.objects.create_user('Mark', 'admin+courses@edx.org', 'foo')
self.admin.is_staff = True
self.request = HttpRequest()
self.request.user = self.admin
self.creator_admin = CourseCreatorAdmin(self.table_entry, AdminSite())
self.studio_request_email = 'mark@marky.mark'
self.enable_creator_group_patch = {
"ENABLE_CREATOR_GROUP": True,
"STUDIO_REQUEST_EMAIL": self.studio_request_email
}
@mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True))
@mock.patch('django.contrib.auth.models.User.email_user')
def test_change_status(self, email_user):
"""
Tests that updates to state impact the creator group maintained in authz.py and that e-mails are sent.
"""
def change_state_and_verify_email(state, is_creator):
""" Changes user state, verifies creator status, and verifies e-mail is sent based on transition """
self._change_state(state)
self.assertEqual(is_creator, auth.user_has_role(self.user, CourseCreatorRole()))
context = {'studio_request_email': self.studio_request_email}
if state == CourseCreator.GRANTED:
template = 'emails/course_creator_granted.txt'
elif state == CourseCreator.DENIED:
template = 'emails/course_creator_denied.txt'
else:
template = 'emails/course_creator_revoked.txt'
email_user.assert_called_with(
mock_render_to_string('emails/course_creator_subject.txt', context),
mock_render_to_string(template, context),
self.studio_request_email
)
with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch):
# User is initially unrequested.
self.assertFalse(auth.user_has_role(self.user, CourseCreatorRole()))
change_state_and_verify_email(CourseCreator.GRANTED, True)
change_state_and_verify_email(CourseCreator.DENIED, False)
change_state_and_verify_email(CourseCreator.GRANTED, True)
change_state_and_verify_email(CourseCreator.PENDING, False)
change_state_and_verify_email(CourseCreator.GRANTED, True)
change_state_and_verify_email(CourseCreator.UNREQUESTED, False)
change_state_and_verify_email(CourseCreator.DENIED, False)
@mock.patch('course_creators.admin.render_to_string', mock.Mock(side_effect=mock_render_to_string, autospec=True))
def test_mail_admin_on_pending(self):
"""
Tests that the admin account is notified when a user is in the 'pending' state.
"""
def check_admin_message_state(state, expect_sent_to_admin, expect_sent_to_user):
""" Changes user state and verifies e-mail sent to admin address only when pending. """
mail.outbox = []
self._change_state(state)
# If a message is sent to the user about course creator status change, it will be the first
# message sent. Admin message will follow.
base_num_emails = 1 if expect_sent_to_user else 0
if expect_sent_to_admin:
context = {'user_name': "test_user", 'user_email': u'test_user+courses@edx.org'}
self.assertEquals(base_num_emails + 1, len(mail.outbox), 'Expected admin message to be sent')
sent_mail = mail.outbox[base_num_emails]
self.assertEquals(
mock_render_to_string('emails/course_creator_admin_subject.txt', context),
sent_mail.subject
)
self.assertEquals(
mock_render_to_string('emails/course_creator_admin_user_pending.txt', context),
sent_mail.body
)
self.assertEquals(self.studio_request_email, sent_mail.from_email)
self.assertEqual([self.studio_request_email], sent_mail.to)
else:
self.assertEquals(base_num_emails, len(mail.outbox))
with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch):
# E-mail message should be sent to admin only when new state is PENDING, regardless of what
# previous state was (unless previous state was already PENDING).
# E-mail message sent to user only on transition into and out of GRANTED state.
check_admin_message_state(CourseCreator.UNREQUESTED, expect_sent_to_admin=False, expect_sent_to_user=False)
check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=False)
check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True)
check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True)
check_admin_message_state(CourseCreator.GRANTED, expect_sent_to_admin=False, expect_sent_to_user=True)
check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=True, expect_sent_to_user=True)
check_admin_message_state(CourseCreator.PENDING, expect_sent_to_admin=False, expect_sent_to_user=False)
check_admin_message_state(CourseCreator.DENIED, expect_sent_to_admin=False, expect_sent_to_user=True)
def _change_state(self, state):
""" Helper method for changing state """
self.table_entry.state = state
self.creator_admin.save_model(self.request, self.table_entry, None, True)
def test_add_permission(self):
"""
Tests that staff cannot add entries
"""
self.assertFalse(self.creator_admin.has_add_permission(self.request))
def test_delete_permission(self):
"""
Tests that staff cannot delete entries
"""
self.assertFalse(self.creator_admin.has_delete_permission(self.request))
def test_change_permission(self):
"""
Tests that only staff can change entries
"""
self.assertTrue(self.creator_admin.has_change_permission(self.request))
self.request.user = self.user
self.assertFalse(self.creator_admin.has_change_permission(self.request))
| Java |
# quium
crowdference's WUI | Java |
<?php
$mod_strings = array_merge($mod_strings,
array(
'LBL_LIST_NONINHERITABLE' => "Não Herdável",
)
);
?>
| Java |
DELETE FROM `weenie` WHERE `class_Id` = 14030;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (14030, 'housecottage2338', 53, '2019-02-10 00:00:00') /* House */;
INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`)
VALUES (14030, 1, 128) /* ItemType - Misc */
, (14030, 5, 10) /* EncumbranceVal */
, (14030, 16, 1) /* ItemUseable - No */
, (14030, 93, 52) /* PhysicsState - Ethereal, IgnoreCollisions, NoDraw */
, (14030, 155, 1) /* HouseType - Cottage */
, (14030, 8041, 101) /* PCAPRecordedPlacement - Resting */;
INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`)
VALUES (14030, 1, True ) /* Stuck */
, (14030, 24, True ) /* UiHidden */;
INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`)
VALUES (14030, 39, 0.1) /* DefaultScale */;
INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`)
VALUES (14030, 1, 'Cottage') /* Name */;
INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`)
VALUES (14030, 1, 0x02000A42) /* Setup */
, (14030, 8, 0x06002181) /* Icon */
, (14030, 30, 152) /* PhysicsScript - RestrictionEffectBlue */
, (14030, 8001, 203423760) /* PCAPRecordedWeenieHeader - Usable, Burden, HouseRestrictions, PScript */
, (14030, 8003, 148) /* PCAPRecordedObjectDesc - Stuck, Attackable, UiHidden */
, (14030, 8005, 163969) /* PCAPRecordedPhysicsDesc - CSetup, ObjScale, Position, AnimationFrame */;
INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (14030, 8040, 0x6B8E0112, 33.9241, 135.967, 17.9995, -0.66963, 0, 0, -0.742695) /* PCAPRecordedLocation */
/* @teleloc 0x6B8E0112 [33.924100 135.967000 17.999500] -0.669630 0.000000 0.000000 -0.742695 */;
INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`)
VALUES (14030, 8000, 0x76B8E1A2) /* PCAPRecordedObjectIID */;
| Java |
<?php
/**
* Validation.
*
* @author Fabio Alessandro Locati <fabiolocati@gmail.com>
* @author Wenzel Pünter <wenzel@phelix.me>
* @author Daniel Mejta <daniel@mejta.net>
*
* @version 2.0.0
*/
namespace Isbn;
/**
* Validation.
*/
class Validation
{
/**
* Check Instance.
*
* @var Check
*/
private $check;
/**
* Hyphens Instance.
*
* @var Hyphens
*/
private $hyphens;
/**
* Constructor.
*
* @param Check $check
* @param Hyphens $hyphens
*/
public function __construct(Check $check, Hyphens $hyphens)
{
$this->check = $check;
$this->hyphens = $hyphens;
}
/**
* Validate the ISBN $isbn.
*
* @param string $isbn
*
* @return bool
*/
public function isbn($isbn)
{
if ($this->check->is13($isbn)) {
return $this->isbn13($isbn);
}
if ($this->check->is10($isbn)) {
return $this->isbn10($isbn);
}
return false;
}
/**
* Validate the ISBN-10 $isbn.
*
* @param string $isbn
*
* @throws Exception
*
* @return bool
*/
public function isbn10($isbn)
{
if (\is_string($isbn) === false) {
throw new Exception('Invalid parameter type.');
}
//Verify ISBN-10 scheme
$isbn = $this->hyphens->removeHyphens($isbn);
if (\strlen($isbn) != 10) {
return false;
}
if (\preg_match('/\d{9}[0-9xX]/i', $isbn) == false) {
return false;
}
//Verify checksum
$check = 0;
for ($i = 0; $i < 10; $i++) {
if (\strtoupper($isbn[$i]) === 'X') {
$check += 10 * \intval(10 - $i);
} else {
$check += \intval($isbn[$i]) * \intval(10 - $i);
}
}
return $check % 11 === 0;
}
/**
* Validate the ISBN-13 $isbn.
*
* @param string $isbn
*
* @throws Exception
*
* @return bool
*/
public function isbn13($isbn)
{
if (\is_string($isbn) === false) {
throw new Exception('Invalid parameter type.');
}
//Verify ISBN-13 scheme
$isbn = $this->hyphens->removeHyphens($isbn);
if (\strlen($isbn) != 13) {
return false;
}
if (\preg_match('/\d{13}/i', $isbn) == false) {
return false;
}
//Verify checksum
$check = 0;
for ($i = 0; $i < 13; $i += 2) {
$check += \substr($isbn, $i, 1);
}
for ($i = 1; $i < 12; $i += 2) {
$check += 3 * \substr($isbn, $i, 1);
}
return $check % 10 === 0;
}
}
| Java |
import unittest
from app import read_config
class ConfigFileReaderTest(unittest.TestCase):
def test_read(self):
config = read_config('config')
self.assertEqual(config['cmus_host'], 'raspberry')
self.assertEqual(config['cmus_passwd'], 'PaSsWd')
self.assertEqual(config['app_host'], 'localhost')
self.assertEqual(config['app_port'], '8080')
if __name__ == '__main__':
unittest.main()
| Java |
/**
* ownCloud - News
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2014
*/
#global-loading {
width: 100%;
height: 100%;
}
#undo-container {
position: fixed;
top: 0px;
width: 100%;
text-align: center;
z-index: 101;
line-height: 1.2;
}
#undo {
z-index:101;
background-color:#fc4;
border:0;
padding:0 .7em .3em;
display:none;
position: relative;
top:0;
border-bottom-left-radius:1em;
border-bottom-right-radius:1em;
}
#undo a {
font-weight: bold;
}
#undo a:hover {
text-decoration: underline;
}
| Java |
/**
* Copyright (C) 2000 - 2011 Silverpeas
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* As a special exception to the terms and conditions of version 3.0 of
* the GPL, you may redistribute this Program in connection with Free/Libre
* Open Source Software ("FLOSS") applications as described in Silverpeas's
* FLOSS exception. You should have received a copy of the text describing
* the FLOSS exception, and it is also available here:
* "http://repository.silverpeas.com/legal/licensing"
*
* This program 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.stratelia.webactiv.beans.admin;
import java.util.ArrayList;
import java.util.List;
import com.silverpeas.scheduler.Scheduler;
import com.silverpeas.scheduler.SchedulerEvent;
import com.silverpeas.scheduler.SchedulerEventListener;
import com.silverpeas.scheduler.SchedulerFactory;
import com.silverpeas.scheduler.trigger.JobTrigger;
import com.stratelia.silverpeas.silvertrace.SilverTrace;
public class SynchroDomainScheduler implements SchedulerEventListener {
public static final String ADMINSYNCHRODOMAIN_JOB_NAME = "AdminSynchroDomainJob";
private List<String> domainIds = null;
public void initialize(String cron, List<String> domainIds) {
try {
this.domainIds = domainIds;
SchedulerFactory schedulerFactory = SchedulerFactory.getFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
scheduler.unscheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME);
JobTrigger trigger = JobTrigger.triggerAt(cron);
scheduler.scheduleJob(ADMINSYNCHRODOMAIN_JOB_NAME, trigger, this);
} catch (Exception e) {
SilverTrace.error("admin", "SynchroDomainScheduler.initialize()",
"admin.CANT_INIT_DOMAINS_SYNCHRO", e);
}
}
public void addDomain(String id) {
if (domainIds == null) {
domainIds = new ArrayList<String>();
}
domainIds.add(id);
}
public void removeDomain(String id) {
if (domainIds != null) {
domainIds.remove(id);
}
}
public void doSynchro() {
SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_ENTER_METHOD");
if (domainIds != null) {
for (String domainId : domainIds) {
try {
AdminReference.getAdminService().synchronizeSilverpeasWithDomain(domainId, true);
} catch (Exception e) {
SilverTrace.error("admin", "SynchroDomainScheduler.doSynchro()",
"admin.MSG_ERR_SYNCHRONIZE_DOMAIN", e);
}
}
}
SilverTrace.info("admin", "SynchroDomainScheduler.doSynchro()", "root.MSG_GEN_EXIT_METHOD");
}
@Override
public void triggerFired(SchedulerEvent anEvent) {
String jobName = anEvent.getJobExecutionContext().getJobName();
SilverTrace.debug("admin", "SynchroDomainScheduler.triggerFired()", "The job '" + jobName +
"' is executed");
doSynchro();
}
@Override
public void jobSucceeded(SchedulerEvent anEvent) {
String jobName = anEvent.getJobExecutionContext().getJobName();
SilverTrace.debug("admin", "SynchroDomainScheduler.jobSucceeded()", "The job '" + jobName +
"' was successfull");
}
@Override
public void jobFailed(SchedulerEvent anEvent) {
String jobName = anEvent.getJobExecutionContext().getJobName();
SilverTrace.error("admin", "SynchroDomainScheduler.jobFailed", "The job '" + jobName +
"' was not successfull");
}
}
| Java |
chunker_bully = Creature:new {
objectName = "@mob/creature_names:chunker_bully",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "chunker",
faction = "thug",
level = 10,
chanceHit = 0.280000,
damageMin = 90,
damageMax = 110,
baseXp = 356,
baseHAM = 810,
baseHAMmax = 990,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + STALKER,
diet = HERBIVORE,
templates = {"object/mobile/dressed_mugger.iff",
"object/mobile/dressed_robber_human_male_01.iff",
"object/mobile/dressed_criminal_thug_zabrak_female_01.iff",
"object/mobile/dressed_criminal_thug_aqualish_female_02.iff",
"object/mobile/dressed_criminal_thug_aqualish_male_02.iff",
"object/mobile/dressed_desperado_bith_female_01.iff",
"object/mobile/dressed_criminal_thug_human_female_01.iff",
"object/mobile/dressed_goon_twk_female_01.iff",
"object/mobile/dressed_criminal_thug_human_male_01.iff",
"object/mobile/dressed_robber_twk_female_01.iff",
"object/mobile/dressed_villain_trandoshan_male_01.iff",
"object/mobile/dressed_desperado_bith_male_01.iff",
"object/mobile/dressed_mugger.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 1200000},
{group = "rifles", chance = 700000},
{group = "melee_knife", chance = 700000},
{group = "pistols", chance = 700000},
{group = "carbines", chance = 700000},
{group = "chunker_common", chance = 6000000},
}
}
},
weapons = {"ranged_weapons"},
reactionStf = "@npc_reaction/slang",
attacks = merge(marksmannovice,brawlernovice)
}
CreatureTemplates:addCreatureTemplate(chunker_bully, "chunker_bully")
| Java |
# frozen_string_literal: true
require 'ffaker'
FactoryBot.define do
sequence(:random_string) { FFaker::Lorem.sentence }
sequence(:random_description) { FFaker::Lorem.paragraphs(Kernel.rand(1..5)).join("\n") }
sequence(:random_email) { FFaker::Internet.email }
factory :classification, class: Spree::Classification do
end
factory :exchange, class: Exchange do
incoming { false }
order_cycle { OrderCycle.first || FactoryBot.create(:simple_order_cycle) }
sender { incoming ? FactoryBot.create(:enterprise) : order_cycle.coordinator }
receiver { incoming ? order_cycle.coordinator : FactoryBot.create(:enterprise) }
end
factory :schedule, class: Schedule do
sequence(:name) { |n| "Schedule #{n}" }
transient do
order_cycles { [OrderCycle.first || create(:simple_order_cycle)] }
end
before(:create) do |schedule, evaluator|
evaluator.order_cycles.each do |order_cycle|
order_cycle.schedules << schedule
end
end
end
factory :proxy_order, class: ProxyOrder do
subscription
order_cycle { subscription.order_cycles.first }
before(:create) do |proxy_order, _proxy|
proxy_order.order&.update_attribute(:order_cycle_id, proxy_order.order_cycle_id)
end
end
factory :variant_override, class: VariantOverride do
price { 77.77 }
on_demand { false }
count_on_hand { 11_111 }
default_stock { 2000 }
resettable { false }
trait :on_demand do
on_demand { true }
count_on_hand { nil }
end
trait :use_producer_stock_settings do
on_demand { nil }
count_on_hand { nil }
end
end
factory :inventory_item, class: InventoryItem do
enterprise
variant
visible { true }
end
factory :enterprise_relationship do
end
factory :enterprise_role do
end
factory :enterprise_group, class: EnterpriseGroup do
name { 'Enterprise group' }
sequence(:permalink) { |n| "group#{n}" }
description { 'this is a group' }
on_front_page { false }
address { FactoryBot.build(:address) }
end
factory :enterprise_fee, class: EnterpriseFee do
transient { amount { nil } }
sequence(:name) { |n| "Enterprise fee #{n}" }
sequence(:fee_type) { |n| EnterpriseFee::FEE_TYPES[n % EnterpriseFee::FEE_TYPES.count] }
enterprise { Enterprise.first || FactoryBot.create(:supplier_enterprise) }
calculator { build(:calculator_per_item, preferred_amount: amount) }
after(:create) { |ef| ef.calculator.save! }
trait :flat_rate do
transient { amount { 1 } }
calculator { build(:calculator_flat_rate, preferred_amount: amount) }
end
trait :per_item do
transient { amount { 1 } }
calculator { build(:calculator_per_item, preferred_amount: amount) }
end
end
factory :adjustment_metadata, class: AdjustmentMetadata do
adjustment { FactoryBot.create(:adjustment) }
enterprise { FactoryBot.create(:distributor_enterprise) }
fee_name { 'fee' }
fee_type { 'packing' }
enterprise_role { 'distributor' }
end
factory :producer_property, class: ProducerProperty do
value { 'abc123' }
producer { create(:supplier_enterprise) }
property
end
factory :stripe_account do
enterprise { FactoryBot.create(:distributor_enterprise) }
stripe_user_id { "abc123" }
stripe_publishable_key { "xyz456" }
end
end
| Java |
module CC::Exporter::Epub
module Exportable
def content_cartridge
self.attachment
end
def convert_to_epub(opts={})
exporter = CC::Exporter::Epub::Exporter.new(content_cartridge.open, opts[:sort_by_content])
epub = CC::Exporter::Epub::Book.new(exporter.templates)
epub.create
end
end
end
| Java |
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>File: scan_rules_reader.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
<div id="fileHeader">
<h1>scan_rules_reader.rb</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>lib/scan_rules_reader.rb
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>Wed Dec 05 10:33:50 -0700 2007</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
<div id="description">
<p>
scan_rules_reader.rb
</p>
<p>
LEGAL NOTICE
</p>
<hr size="10"></hr><p>
OSS Discovery is a tool that finds installed open source software.
</p>
<pre>
Copyright (C) 2007-2009 OpenLogic, Inc.
</pre>
<p>
OSS Discovery is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License version 3 as
published by the Free Software Foundation.
</p>
<p>
This program 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 Affero General Public License
version 3 (discovery2-client/license/OSSDiscoveryLicense.txt) for more
details.
</p>
<p>
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <a
href="http://www.gnu.org/licenses">www.gnu.org/licenses</a>/
</p>
<p>
You can learn more about OSSDiscovery, report bugs and get the latest
versions at <a href="http://www.ossdiscovery.org">www.ossdiscovery.org</a>.
You can contact the OSS Discovery team at info@ossdiscovery.org. You can
contact OpenLogic at info@openlogic.com.
</p>
</div>
<div id="requires-list">
<h3 class="section-bar">Required files</h3>
<div class="name-list">
set
find
rexml/document
eval_rule
expression
project_rule
match_rule_set
matchrules/binary_match_rule
matchrules/filename_match_rule
matchrules/filename_version_match_rule
matchrules/md5_match_rule
</div>
</div>
</div>
</div>
<!-- if includes -->
<div id="includes">
<h3 class="section-bar">Included Modules</h3>
<div id="includes-list">
<span class="include-name">REXML</span>
</div>
</div>
<div id="section">
<!-- if method_list -->
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html> | Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Netto-Lohn</title>
<meta name="viewport" content="user-scalable=no">
<link rel="stylesheet" href="../shared/css/export-email.css">
<script src="../shared/config.js" defer></script>
<script src="../dojotoolkit/dojo/dojo.js" defer></script>
<script src="export-email.js" defer></script>
</head>
<body>
</body>
</html>
| Java |
/*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
#ifndef _BUILD_BASE64_CROSSPLATFORM_DEFINE
#define _BUILD_BASE64_CROSSPLATFORM_DEFINE
#include <stdio.h>
#include <limits.h>
#include "Types.h"
#include "../../Common/kernel_config.h"
namespace NSBase64
{
const int B64_BASE64_FLAG_NONE = 0;
const int B64_BASE64_FLAG_NOPAD = 1;
const int B64_BASE64_FLAG_NOCRLF = 2;
#define _BASE64_INT_MAX 2147483647
KERNEL_DECL int Base64EncodeGetRequiredLength(int nSrcLen, DWORD dwFlags = B64_BASE64_FLAG_NONE);
KERNEL_DECL int Base64DecodeGetRequiredLength(int nSrcLen);
KERNEL_DECL int Base64Encode(const BYTE *pbSrcData, int nSrcLen, BYTE* szDest, int *pnDestLen, DWORD dwFlags = B64_BASE64_FLAG_NONE);
KERNEL_DECL int DecodeBase64Char(unsigned int ch);
KERNEL_DECL int Base64Decode(const char* szSrc, int nSrcLen, BYTE *pbDest, int *pnDestLen);
}
#endif//_BUILD_BASE64_CROSSPLATFORM_DEFINE
| Java |
/*
* AscEmu Framework based on ArcEmu MMORPG Server
* Copyright (c) 2014-2021 AscEmu Team <http://www.ascemu.org>
* Copyright (C) 2005-2011 MaNGOS <http://getmangos.com/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef WDTFILE_H
#define WDTFILE_H
#include "mpq_libmpq04.h"
#include <string>
class ADTFile;
class WDTFile
{
public:
WDTFile(char* file_name, char* file_name1);
~WDTFile(void);
bool init(char* map_id, unsigned int mapID);
ADTFile* GetMap(int x, int z);
std::string* gWmoInstansName;
int gnWMO;
private:
MPQFile WDT;
std::string filename;
};
#endif //WDTFILE_H
| Java |
from django.conf.urls.defaults import *
import frontend.views as frontend_views
import codewiki.views
import codewiki.viewsuml
from django.contrib.syndication.views import feed as feed_view
from django.views.generic import date_based, list_detail
from django.views.generic.simple import direct_to_template
from django.contrib import admin
import django.contrib.auth.views as auth_views
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponsePermanentRedirect
from django.contrib import admin
admin.autodiscover()
# Need to move this somewhere more useful and try to make it less hacky but
# seems to be the easiest way unfortunately.
from django.contrib.auth.models import User
User._meta.ordering = ['username']
from frontend.feeds import LatestCodeObjects, LatestCodeObjectsBySearchTerm, LatestCodeObjectsByTag, LatestViewObjects, LatestScraperObjects
feeds = {
'all_code_objects': LatestCodeObjects,
'all_scrapers': LatestScraperObjects,
'all_views': LatestViewObjects,
'latest_code_objects_by_search_term': LatestCodeObjectsBySearchTerm,
'latest_code_objects_by_tag': LatestCodeObjectsByTag,
}
urlpatterns = patterns('',
url(r'^$', frontend_views.frontpage, name="frontpage"),
# redirects from old version (would clashes if you happen to have a scraper whose name is list!)
(r'^scrapers/list/$', lambda request: HttpResponseRedirect(reverse('scraper_list_wiki_type', args=['scraper']))),
url(r'^', include('codewiki.urls')),
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name="logout"),
url(r'^accounts/', include('registration.urls')),
url(r'^accounts/resend_activation_email/', frontend_views.resend_activation_email, name="resend_activation_email"),
url(r'^captcha/', include('captcha.urls')),
url(r'^attachauth', codewiki.views.attachauth),
# allows direct viewing of the django tables
url(r'^admin/', include(admin.site.urls)),
# favicon
(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/media/images/favicon.ico'}),
# RSS feeds
url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}, name='feeds'),
# API
(r'^api/', include('api.urls', namespace='foo', app_name='api')),
# Status
url(r'^status/$', codewiki.viewsuml.status, name='status'),
# Documentation
(r'^docs/', include('documentation.urls')),
# Robots.txt
(r'^robots.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}),
# pdf cropper technology
(r'^cropper/', include('cropper.urls')),
# froth
(r'^froth/', include('froth.urls')),
# static media server for the dev sites / local dev
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_DIR, 'show_indexes':True}),
url(r'^media-admin/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ADMIN_DIR, 'show_indexes':True}),
#Rest of the site
url(r'^', include('frontend.urls')),
# redirects from old version
(r'^editor/$', lambda request: HttpResponseRedirect('/scrapers/new/python?template=tutorial_python_trivial')),
(r'^scrapers/show/(?P<short_name>[\w_\-]+)/(?:data/|map-only/)?$',
lambda request, short_name: HttpResponseRedirect(reverse('code_overview', args=['scraper', short_name]))),
)
| Java |
function timenow(){
var timenow1 = Date.getHours();
return timenow1;
} | Java |
<!-- | FUNCTION show page to edit account -->
<?php
function $$$showEditAccount () {
global $TSunic;
// activate template
$data = array('User' => $TSunic->Usr);
$TSunic->Tmpl->activate('$$$showEditAccount', '$system$content', $data);
$TSunic->Tmpl->activate('$system$html', false, array('title' => '{SHOWEDITACCOUNT__TITLE}'));
return true;
}
?>
| Java |
package cz.plichtanet.honza;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.sql.DataSource;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/robots.txt", "/index.jsp", "/.well-known/**", "/static/**").permitAll()
.antMatchers("/downloadPdf/**").hasRole("PDF_USER")
.antMatchers("/dir/**", "/setPassword", "/addUser").hasRole("ADMIN")
.antMatchers("/helloagain").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
/*
// pro lokalni testovani bez databaze
auth
.inMemoryAuthentication()
.withUser("jenda").password("604321192").roles("USER","PDF_USER","ADMIN");
*/
PasswordEncoder encoder = passwordEncoder();
auth.jdbcAuthentication().dataSource(dataSource).passwordEncoder(encoder)
/*
.withUser("petra").password(encoder.encode("737438719")).roles("USER")
.and()
.withUser("kuba").password(encoder.encode("737438719")).roles("USER")
.and()
.withUser("jenda").password(encoder.encode("604321192")).roles("USER","ADMIN")
*/
;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | Java |
'use strict';
angular.module('cheeperApp')
.controller('AuthCtrl', function ($scope, $http) {
$scope.signin = function() {
$http
.post('http://127.0.0.1:8000/auth-token/', $scope.credentials)
.success(function(data, status, headers, config) {
$scope.token = data.token;
})
.error(function(data, status, headers, config) {
console.log(data);
});
};
});
| Java |
<?php
//Harvie's PHP HTTP-Auth script (2oo7-2o1o)
//CopyLefted4U ;)
///SETTINGS//////////////////////////////////////////////////////////////////////////////////////////////////////
//Login
/*$realm = 'music'; //This is used by browser to identify protected area and saving passwords (one_site+one_realm==one_user+one_password)
$users = array( //You can specify multiple users in this array
'music' => 'passw'
);*/
//Misc
$require_login = true; //Require login? (if false, no login needed) - WARNING!!!
$location = '401'; //Location after logout - 401 = default logout page (can be overridden by ?logout=[LOCATION])
//CopyLeft
$ver = '2o1o-3.9';
$link = '<a href="https://blog.harvie.cz/">blog.harvie.cz</a>';
$banner = "Harvie's PHP HTTP-Auth script (v$ver)";
$hbanner = "<hr /><i>$banner\n-\n$link</i>\n";
$cbanner = "<!-- $banner -->\n";
//Config file
@include('./_config.php');
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//MANUAL/////////////////////////////////////////////////////////////////////////////////////////////////////////
/* HOWTO
* To each file, you want to lock add this line (at begin of first line - Header-safe):
* <?php require_once('http_auth.php'); ?> //Password Protection 8')
* Protected file have to be php script (if it's html, simply rename it to .php)
* Server needs to have PHP as module (not CGI).
* You need HTTP Basic auth enabled on server and php.
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////CODE/////////////////////////////////////////////////////////////////////////////////////////////////////////
function send_auth_headers($realm='') {
Header('WWW-Authenticate: Basic realm="'.$realm.'"');
Header('HTTP/1.0 401 Unauthorized');
}
function check_auth($PHP_AUTH_USER, $PHP_AUTH_PW) { //Check if login is succesfull (U can modify this to use DB, or anything else)
return (isset($GLOBALS['users'][$PHP_AUTH_USER]) && ($GLOBALS['users'][$PHP_AUTH_USER] == $PHP_AUTH_PW));
}
function unauth() { //Do this when login fails
$cbanner = $GLOBALS['cbanner'];
$hbanner = $GLOBALS['hbanner'];
die("$cbanner<title>401 - Forbidden</title>\n<h1>401 - Forbidden</h1>\n<a href=\"?\">Login...</a>\n$hbanner"); //Show warning and die
die(); //Don't forget!!!
}
//Backward compatibility
if(isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_PW'] != '') $PHP_AUTH_USER = $_SERVER['PHP_AUTH_USER'];
if(isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] != '') $PHP_AUTH_PW = $_SERVER['PHP_AUTH_PW'];
//Logout
if(isset($_GET['logout'])) { //script.php?logout
if(isset($PHP_AUTH_USER) || isset($PHP_AUTH_PW)) {
Header('WWW-Authenticate: Basic realm="'.$realm.'"');
Header('HTTP/1.0 401 Unauthorized');
} else {
if($_GET['logout'] != '') $location = $_GET['logout'];
if(trim($location) != '401') Header('Location: '.$location);
die("$cbanner<title>401 - Log out successfull</title>\n<h1>401 - Log out successfull</h1>\n<a href=\"?\">Continue...</a>\n$hbanner");
}
}
if($require_login) {
if(!isset($PHP_AUTH_USER)) { //Storno or first visit of page
send_auth_headers($realm);
unauth();
} else { //Login sent
if (check_auth($PHP_AUTH_USER, $PHP_AUTH_PW)) { //Login succesfull - probably do nothing
} else { //Bad login
send_auth_headers($realm);
unauth();
}
}
}
//Rest of file will be displayed only if login is correct
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>buffers_iterator::operator++ (1 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../operator_plus__plus_.html" title="buffers_iterator::operator++">
<link rel="prev" href="../operator_plus__plus_.html" title="buffers_iterator::operator++">
<link rel="next" href="overload2.html" title="buffers_iterator::operator++ (2 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.buffers_iterator.operator_plus__plus_.overload1"></a><a class="link" href="overload1.html" title="buffers_iterator::operator++ (1 of 2 overloads)">buffers_iterator::operator++
(1 of 2 overloads)</a>
</h5></div></div></div>
<p>
Increment operator (prefix).
</p>
<pre class="programlisting"><span class="identifier">buffers_iterator</span> <span class="special">&</span> <span class="keyword">operator</span><span class="special">++();</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2017 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../operator_plus__plus_.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
###############################################################################
#
# Package: NaturalDocs::Parser::Native
#
###############################################################################
#
# A package that converts comments from Natural Docs' native format into <NaturalDocs::Parser::ParsedTopic> objects.
# Unlike most second-level packages, these are packages and not object classes.
#
###############################################################################
# This file is part of Natural Docs, which is Copyright © 2003-2010 Greg Valure
# Natural Docs is licensed under version 3 of the GNU Affero General Public License (AGPL)
# Refer to License.txt for the complete details
use strict;
use integer;
package NaturalDocs::Parser::Native;
###############################################################################
# Group: Variables
# Return values of TagType(). Not documented here.
use constant POSSIBLE_OPENING_TAG => 1;
use constant POSSIBLE_CLOSING_TAG => 2;
use constant NOT_A_TAG => 3;
#
# var: package
#
# A <SymbolString> representing the package normal topics will be a part of at the current point in the file. This is a package variable
# because it needs to be reserved between function calls.
#
my $package;
#
# hash: functionListIgnoredHeadings
#
# An existence hash of all the headings that prevent the parser from creating function list symbols. Whenever one of
# these headings are used in a function list topic, symbols are not created from definition lists until the next heading. The keys
# are in all lowercase.
#
my %functionListIgnoredHeadings = ( 'parameters' => 1,
'parameter' => 1,
'params' => 1,
'param' => 1,
'arguments' => 1,
'argument' => 1,
'args' => 1,
'arg' => 1 );
###############################################################################
# Group: Interface Functions
#
# Function: Start
#
# This will be called whenever a file is about to be parsed. It allows the package to reset its internal state.
#
sub Start
{
my ($self) = @_;
$package = undef;
};
#
# Function: IsMine
#
# Examines the comment and returns whether it is *definitely* Natural Docs content, i.e. it is owned by this package. Note
# that a comment can fail this function and still be interpreted as a Natural Docs content, for example a JavaDoc-styled comment
# that doesn't have header lines but no JavaDoc tags either.
#
# Parameters:
#
# commentLines - An arrayref of the comment lines. Must have been run through <NaturalDocs::Parser->CleanComment()>.
# isJavaDoc - Whether the comment was JavaDoc-styled.
#
# Returns:
#
# Whether the comment is *definitely* Natural Docs content.
#
sub IsMine #(string[] commentLines, bool isJavaDoc)
{
my ($self, $commentLines, $isJavaDoc) = @_;
# Skip to the first line with content.
my $line = 0;
while ($line < scalar @$commentLines && !length $commentLines->[$line])
{ $line++; };
return $self->ParseHeaderLine($commentLines->[$line]);
};
#
# Function: ParseComment
#
# This will be called whenever a comment capable of containing Natural Docs content is found.
#
# Parameters:
#
# commentLines - An arrayref of the comment lines. Must have been run through <NaturalDocs::Parser->CleanComment()>.
# *The original memory will be changed.*
# isJavaDoc - Whether the comment is JavaDoc styled.
# lineNumber - The line number of the first of the comment lines.
# parsedTopics - A reference to the array where any new <NaturalDocs::Parser::ParsedTopics> should be placed.
#
# Returns:
#
# The number of parsed topics added to the array, or zero if none.
#
sub ParseComment #(commentLines, isJavaDoc, lineNumber, parsedTopics)
{
my ($self, $commentLines, $isJavaDoc, $lineNumber, $parsedTopics) = @_;
my $topicCount = 0;
my $prevLineBlank = 1;
my $inCodeSection = 0;
my ($type, $scope, $isPlural, $title, $symbol);
#my $package; # package variable.
my ($newKeyword, $newTitle);
my $index = 0;
my $bodyStart = 0;
my $bodyEnd = 0; # Not inclusive.
while ($index < scalar @$commentLines)
{
# Everything but leading whitespace was removed beforehand.
# If we're in a code section...
if ($inCodeSection)
{
if ($commentLines->[$index] =~ /^ *\( *(?:end|finish|done)(?: +(?:table|code|example|diagram))? *\)$/i)
{ $inCodeSection = undef; };
$prevLineBlank = 0;
$bodyEnd++;
}
# If the line is empty...
elsif (!length($commentLines->[$index]))
{
$prevLineBlank = 1;
if ($topicCount)
{ $bodyEnd++; };
}
# If the line has a recognized header and the previous line is blank...
elsif ($prevLineBlank && (($newKeyword, $newTitle) = $self->ParseHeaderLine($commentLines->[$index])) )
{
# Process the previous one, if any.
if ($topicCount)
{
if ($scope == ::SCOPE_START() || $scope == ::SCOPE_END())
{ $package = undef; };
my $body = $self->FormatBody($commentLines, $bodyStart, $bodyEnd, $type, $isPlural);
my $newTopic = $self->MakeParsedTopic($type, $title, $package, $body, $lineNumber + $bodyStart - 1, $isPlural);
push @$parsedTopics, $newTopic;
$package = $newTopic->Package();
};
$title = $newTitle;
my $typeInfo;
($type, $typeInfo, $isPlural) = NaturalDocs::Topics->KeywordInfo($newKeyword);
$scope = $typeInfo->Scope();
$bodyStart = $index + 1;
$bodyEnd = $index + 1;
$topicCount++;
$prevLineBlank = 0;
}
# If we're on a non-empty, non-header line of a JavaDoc-styled comment and we haven't started a topic yet...
elsif ($isJavaDoc && !$topicCount)
{
$type = undef;
$scope = ::SCOPE_NORMAL(); # The scope repair and topic merging processes will handle if this is a class topic.
$isPlural = undef;
$title = undef;
$symbol = undef;
$bodyStart = $index;
$bodyEnd = $index + 1;
$topicCount++;
$prevLineBlank = undef;
}
# If we're on a normal content line within a topic
elsif ($topicCount)
{
$prevLineBlank = 0;
$bodyEnd++;
if ($commentLines->[$index] =~ /^ *\( *(?:(?:start|begin)? +)?(?:table|code|example|diagram) *\)$/i)
{ $inCodeSection = 1; };
};
$index++;
};
# Last one, if any. This is the only one that gets the prototypes.
if ($topicCount)
{
if ($scope == ::SCOPE_START() || $scope == ::SCOPE_END())
{ $package = undef; };
my $body = $self->FormatBody($commentLines, $bodyStart, $bodyEnd, $type, $isPlural);
my $newTopic = $self->MakeParsedTopic($type, $title, $package, $body, $lineNumber + $bodyStart - 1, $isPlural);
push @$parsedTopics, $newTopic;
$topicCount++;
$package = $newTopic->Package();
};
return $topicCount;
};
#
# Function: ParseHeaderLine
#
# If the passed line is a topic header, returns the array ( keyword, title ). Otherwise returns an empty array.
#
sub ParseHeaderLine #(line)
{
my ($self, $line) = @_;
if ($line =~ /^ *([a-z0-9 ]*[a-z0-9]): +(.*)$/i)
{
my ($keyword, $title) = ($1, $2);
# We need to do it this way because if you do "if (ND:T->KeywordInfo($keyword)" and the last element of the array it
# returns is false, the statement is false. That is really retarded, but there it is.
my ($type, undef, undef) = NaturalDocs::Topics->KeywordInfo($keyword);
if ($type)
{ return ($keyword, $title); }
else
{ return ( ); };
}
else
{ return ( ); };
};
###############################################################################
# Group: Support Functions
#
# Function: MakeParsedTopic
#
# Creates a <NaturalDocs::Parser::ParsedTopic> object for the passed parameters. Scope is gotten from
# the package variable <package> instead of from the parameters. The summary is generated from the body.
#
# Parameters:
#
# type - The <TopicType>. May be undef for headerless topics.
# title - The title of the topic. May be undef for headerless topics.
# package - The package <SymbolString> the topic appears in.
# body - The topic's body in <NDMarkup>.
# lineNumber - The topic's line number.
# isList - Whether the topic is a list.
#
# Returns:
#
# The <NaturalDocs::Parser::ParsedTopic> object.
#
sub MakeParsedTopic #(type, title, package, body, lineNumber, isList)
{
my ($self, $type, $title, $package, $body, $lineNumber, $isList) = @_;
my $summary;
if (defined $body)
{ $summary = NaturalDocs::Parser->GetSummaryFromBody($body); };
return NaturalDocs::Parser::ParsedTopic->New($type, $title, $package, undef, undef, $summary,
$body, $lineNumber, $isList);
};
#
# Function: FormatBody
#
# Converts the section body to <NDMarkup>.
#
# Parameters:
#
# commentLines - The arrayref of comment lines.
# startingIndex - The starting index of the body to format.
# endingIndex - The ending index of the body to format, *not* inclusive.
# type - The type of the section. May be undef for headerless comments.
# isList - Whether it's a list topic.
#
# Returns:
#
# The body formatted in <NDMarkup>.
#
sub FormatBody #(commentLines, startingIndex, endingIndex, type, isList)
{
my ($self, $commentLines, $startingIndex, $endingIndex, $type, $isList) = @_;
use constant TAG_NONE => 1;
use constant TAG_PARAGRAPH => 2;
use constant TAG_BULLETLIST => 3;
use constant TAG_DESCRIPTIONLIST => 4;
use constant TAG_HEADING => 5;
use constant TAG_PREFIXCODE => 6;
use constant TAG_TAGCODE => 7;
my %tagEnders = ( TAG_NONE() => '',
TAG_PARAGRAPH() => '</p>',
TAG_BULLETLIST() => '</li></ul>',
TAG_DESCRIPTIONLIST() => '</dd></dl>',
TAG_HEADING() => '</h>',
TAG_PREFIXCODE() => '</code>',
TAG_TAGCODE() => '</code>' );
my $topLevelTag = TAG_NONE;
my $output;
my $textBlock;
my $prevLineBlank = 1;
my $codeBlock;
my $removedCodeSpaces;
my $ignoreListSymbols;
my $index = $startingIndex;
while ($index < $endingIndex)
{
# If we're in a tagged code section...
if ($topLevelTag == TAG_TAGCODE)
{
if ($commentLines->[$index] =~ /^ *\( *(?:end|finish|done)(?: +(?:table|code|example|diagram))? *\)$/i)
{
$codeBlock =~ s/\n+$//;
$output .= NaturalDocs::NDMarkup->ConvertAmpChars($codeBlock) . '</code>';
$codeBlock = undef;
$topLevelTag = TAG_NONE;
$prevLineBlank = undef;
}
else
{
$self->AddToCodeBlock($commentLines->[$index], \$codeBlock, \$removedCodeSpaces);
};
}
# If the line starts with a code designator...
elsif ($commentLines->[$index] =~ /^ *[>:|](.*)$/)
{
my $code = $1;
if ($topLevelTag == TAG_PREFIXCODE)
{
$self->AddToCodeBlock($code, \$codeBlock, \$removedCodeSpaces);
}
else # $topLevelTag != TAG_PREFIXCODE
{
if (defined $textBlock)
{
$output .= $self->RichFormatTextBlock($textBlock) . $tagEnders{$topLevelTag};
$textBlock = undef;
};
$topLevelTag = TAG_PREFIXCODE;
$output .= '<code type="anonymous">';
$self->AddToCodeBlock($code, \$codeBlock, \$removedCodeSpaces);
};
}
# If we're not in either code style...
else
{
# Strip any leading whitespace.
$commentLines->[$index] =~ s/^ +//;
# If we were in a prefixed code section...
if ($topLevelTag == TAG_PREFIXCODE)
{
$codeBlock =~ s/\n+$//;
$output .= NaturalDocs::NDMarkup->ConvertAmpChars($codeBlock) . '</code>';
$codeBlock = undef;
$topLevelTag = TAG_NONE;
$prevLineBlank = undef;
};
# If the line is blank...
if (!length($commentLines->[$index]))
{
# End a paragraph. Everything else ignores it for now.
if ($topLevelTag == TAG_PARAGRAPH)
{
$output .= $self->RichFormatTextBlock($textBlock) . '</p>';
$textBlock = undef;
$topLevelTag = TAG_NONE;
};
$prevLineBlank = 1;
}
# If the line starts with a bullet...
elsif ($commentLines->[$index] =~ /^[-\*o+] +([^ ].*)$/ &&
substr($1, 0, 2) ne '- ') # Make sure "o - Something" is a definition, not a bullet.
{
my $bulletedText = $1;
if (defined $textBlock)
{ $output .= $self->RichFormatTextBlock($textBlock); };
if ($topLevelTag == TAG_BULLETLIST)
{
$output .= '</li><li>';
}
else #($topLevelTag != TAG_BULLETLIST)
{
$output .= $tagEnders{$topLevelTag} . '<ul><li>';
$topLevelTag = TAG_BULLETLIST;
};
$textBlock = $bulletedText;
$prevLineBlank = undef;
}
# If the line looks like a description list entry...
elsif ($commentLines->[$index] =~ /^(.+?) +- +([^ ].*)$/ && $topLevelTag != TAG_PARAGRAPH)
{
my $entry = $1;
my $description = $2;
if (defined $textBlock)
{ $output .= $self->RichFormatTextBlock($textBlock); };
if ($topLevelTag == TAG_DESCRIPTIONLIST)
{
$output .= '</dd>';
}
else #($topLevelTag != TAG_DESCRIPTIONLIST)
{
$output .= $tagEnders{$topLevelTag} . '<dl>';
$topLevelTag = TAG_DESCRIPTIONLIST;
};
if (($isList && !$ignoreListSymbols) || $type eq ::TOPIC_ENUMERATION())
{
$output .= '<ds>' . NaturalDocs::NDMarkup->ConvertAmpChars($entry) . '</ds><dd>';
}
else
{
$output .= '<de>' . NaturalDocs::NDMarkup->ConvertAmpChars($entry) . '</de><dd>';
};
$textBlock = $description;
$prevLineBlank = undef;
}
# If the line could be a header...
elsif ($prevLineBlank && $commentLines->[$index] =~ /^(.*)([^ ]):$/)
{
my $headerText = $1 . $2;
if (defined $textBlock)
{
$output .= $self->RichFormatTextBlock($textBlock);
$textBlock = undef;
}
$output .= $tagEnders{$topLevelTag};
$topLevelTag = TAG_NONE;
$output .= '<h>' . $self->RichFormatTextBlock($headerText) . '</h>';
if ($type eq ::TOPIC_FUNCTION() && $isList)
{
$ignoreListSymbols = exists $functionListIgnoredHeadings{lc($headerText)};
};
$prevLineBlank = undef;
}
# If the line looks like a code tag...
elsif ($commentLines->[$index] =~ /^\( *(?:(?:start|begin)? +)?(table|code|example|diagram) *\)$/i)
{
my $codeType = lc($1);
if (defined $textBlock)
{
$output .= $self->RichFormatTextBlock($textBlock);
$textBlock = undef;
};
if ($codeType eq 'example')
{ $codeType = 'anonymous'; }
elsif ($codeType eq 'table' || $codeType eq 'diagram')
{ $codeType = 'text'; }
# else leave it 'code'
$output .= $tagEnders{$topLevelTag} . '<code type="' . $codeType . '">';
$topLevelTag = TAG_TAGCODE;
}
# If the line looks like an inline image...
elsif ($commentLines->[$index] =~ /^(\( *see +)([^\)]+?)( *\))$/i)
{
if (defined $textBlock)
{
$output .= $self->RichFormatTextBlock($textBlock);
$textBlock = undef;
};
$output .= $tagEnders{$topLevelTag};
$topLevelTag = TAG_NONE;
$output .= '<img mode="inline" target="' . NaturalDocs::NDMarkup->ConvertAmpChars($2) . '" '
. 'original="' . NaturalDocs::NDMarkup->ConvertAmpChars($1 . $2 . $3) . '">';
$prevLineBlank = undef;
}
# If the line isn't any of those, we consider it normal text.
else
{
# A blank line followed by normal text ends lists. We don't handle this when we detect if the line's blank because
# we don't want blank lines between list items to break the list.
if ($prevLineBlank && ($topLevelTag == TAG_BULLETLIST || $topLevelTag == TAG_DESCRIPTIONLIST))
{
$output .= $self->RichFormatTextBlock($textBlock) . $tagEnders{$topLevelTag} . '<p>';
$topLevelTag = TAG_PARAGRAPH;
$textBlock = undef;
}
elsif ($topLevelTag == TAG_NONE)
{
$output .= '<p>';
$topLevelTag = TAG_PARAGRAPH;
# textBlock will already be undef.
};
if (defined $textBlock)
{ $textBlock .= ' '; };
$textBlock .= $commentLines->[$index];
$prevLineBlank = undef;
};
};
$index++;
};
# Clean up anything left dangling.
if (defined $textBlock)
{
$output .= $self->RichFormatTextBlock($textBlock) . $tagEnders{$topLevelTag};
}
elsif (defined $codeBlock)
{
$codeBlock =~ s/\n+$//;
$output .= NaturalDocs::NDMarkup->ConvertAmpChars($codeBlock) . '</code>';
};
return $output;
};
#
# Function: AddToCodeBlock
#
# Adds a line of text to a code block, handling all the indentation processing required.
#
# Parameters:
#
# line - The line of text to add.
# codeBlockRef - A reference to the code block to add it to.
# removedSpacesRef - A reference to a variable to hold the number of spaces removed. It needs to be stored between calls.
# It will reset itself automatically when the code block codeBlockRef points to is undef.
#
sub AddToCodeBlock #(line, codeBlockRef, removedSpacesRef)
{
my ($self, $line, $codeBlockRef, $removedSpacesRef) = @_;
$line =~ /^( *)(.*)$/;
my ($spaces, $code) = ($1, $2);
if (!defined $$codeBlockRef)
{
if (length($code))
{
$$codeBlockRef = $code . "\n";
$$removedSpacesRef = length($spaces);
};
# else ignore leading line breaks.
}
elsif (length $code)
{
# Make sure we have the minimum amount of spaces to the left possible.
if (length($spaces) != $$removedSpacesRef)
{
my $spaceDifference = abs( length($spaces) - $$removedSpacesRef );
my $spacesToAdd = ' ' x $spaceDifference;
if (length($spaces) > $$removedSpacesRef)
{
$$codeBlockRef .= $spacesToAdd;
}
else
{
$$codeBlockRef =~ s/^(.)/$spacesToAdd . $1/gme;
$$removedSpacesRef = length($spaces);
};
};
$$codeBlockRef .= $code . "\n";
}
else # (!length $code)
{
$$codeBlockRef .= "\n";
};
};
#
# Function: RichFormatTextBlock
#
# Applies rich <NDMarkup> formatting to a chunk of text. This includes both amp chars, formatting tags, and link tags.
#
# Parameters:
#
# text - The block of text to format.
#
# Returns:
#
# The formatted text block.
#
sub RichFormatTextBlock #(text)
{
my ($self, $text) = @_;
my $output;
# First find bare urls, e-mail addresses, and images. We have to do this before the split because they may contain underscores,
# asterisks, bacquotes, hyphens or tildas. We have to mark the tags with \x1E and \x1F so they don't get confused with angle
# brackets from the comment. We can't convert the amp chars beforehand because we need lookbehinds in the regexps below
# and they need to be constant length. Sucks, huh?
$text =~ s{
# The previous character can't be an alphanumeric or an opening angle bracket.
(?<! [a-z0-9<] )
# Optional mailto:. Ignored in output.
(?:mailto\:)?
# Begin capture
(
# The user portion. Alphanumeric and - _. Dots can appear between, but not at the edges or more than
# one in a row.
(?: [a-z0-9\-_]+ \. )* [a-z0-9\-_]+
@
# The domain. Alphanumeric and -. Dots same as above, however, there must be at least two sections
# and the last one must be two to four alphanumeric characters (.com, .uk, .info, .203 for IP addresses)
(?: [a-z0-9\-]+ \. )+ [a-z]{2,4}
# End capture.
)
# The next character can't be an alphanumeric, which should prevent .abcde from matching the two to
# four character requirement, or a closing angle bracket.
(?! [a-z0-9>] )
}
{"\x1E" . 'email target="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '" '
. 'name="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '"' . "\x1F"}igxe;
$text =~ s{
# The previous character can't be an alphanumeric or an opening angle bracket.
(?<! [a-z0-9<] )
# Begin capture.
(
# URL must start with one of the acceptable protocols.
(?:http|https|ftp|news|file)\:
# The acceptable URL characters as far as I know.
[a-z0-9\-\=\~\@\#\%\&\_\+\/\;\:\?\*\.\,]*
# The URL characters minus period and comma. If it ends on them, they're probably intended as
# punctuation.
[a-z0-9\-\=\~\@\#\%\&\_\+\/\;\:\?\*]
# End capture.
)
# The next character must not be an acceptable character or a closing angle bracket. It must also not be a
# dot and then an acceptable character. These will prevent the URL from ending early just to get a match.
(?! \.?[a-z0-9\-\=\~\@\#\%\&\_\+\/\;\:\?\*\>] )
}
{"\x1E" . 'url target="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '" '
. 'name="' . NaturalDocs::NDMarkup->ConvertAmpChars($1) . '"' . "\x1F"}igxe;
# Find image links. Inline images should already be pulled out by now.
$text =~ s{(\( *see +)([^\)\<\>]+?)( *\))}
{"\x1E" . 'img mode="link" target="' . NaturalDocs::NDMarkup->ConvertAmpChars($2) . '" '
. 'original="' . NaturalDocs::NDMarkup->ConvertAmpChars($1 . $2 . $3) . '"' . "\x1F"}gie;
# Split the text from the potential tags.
my @tempTextBlocks = split(/([\*_\~\+\`<>\x1E\x1F])/, $text);
# Since the symbols are considered dividers, empty strings could appear between two in a row or at the beginning/end of the
# array. This could seriously screw up TagType(), so we need to get rid of them.
my @textBlocks;
while (scalar @tempTextBlocks)
{
my $tempTextBlock = shift @tempTextBlocks;
if (length $tempTextBlock)
{ push @textBlocks, $tempTextBlock; };
};
my $bold;
my $underline;
my $underlineHasWhitespace;
my $strikethrough;
my $strikethroughHasWhitespace;
my $italic;
my $monotype;
my $index = 0;
while ($index < scalar @textBlocks)
{
if ($textBlocks[$index] eq "\x1E")
{
$output .= '<';
$index++;
while ($textBlocks[$index] ne "\x1F")
{
$output .= $textBlocks[$index];
$index++;
};
$output .= '>';
}
elsif ($textBlocks[$index] eq '<' && $self->TagType(\@textBlocks, $index) == POSSIBLE_OPENING_TAG)
{
my $endingIndex = $self->ClosingTag(\@textBlocks, $index, undef);
if ($endingIndex != -1)
{
my $linkText;
$index++;
while ($index < $endingIndex)
{
$linkText .= $textBlocks[$index];
$index++;
};
# Index will be incremented again at the end of the loop.
$linkText = NaturalDocs::NDMarkup->ConvertAmpChars($linkText);
if ($linkText =~ /^(?:mailto\:)?((?:[a-z0-9\-_]+\.)*[a-z0-9\-_]+@(?:[a-z0-9\-]+\.)+[a-z]{2,4})$/i)
{ $output .= '<email target="' . $1 . '" name="' . $1 . '">'; }
elsif ($linkText =~ /^(.+?) at (?:mailto\:)?((?:[a-z0-9\-_]+\.)*[a-z0-9\-_]+@(?:[a-z0-9\-]+\.)+[a-z]{2,4})$/i)
{ $output .= '<email target="' . $2 . '" name="' . $1 . '">'; }
elsif ($linkText =~ /^(?:http|https|ftp|news|file)\:/i)
{ $output .= '<url target="' . $linkText . '" name="' . $linkText . '">'; }
elsif ($linkText =~ /^(.+?) at ((?:http|https|ftp|news|file)\:.+)/i)
{ $output .= '<url target="' . $2 . '" name="' . $1 . '">'; }
else
{ $output .= '<link target="' . $linkText . '" name="' . $linkText . '" original="<' . $linkText . '>">'; };
}
else # it's not a link.
{
$output .= '<';
};
}
elsif ($textBlocks[$index] eq '*')
{
my $tagType = $self->TagType(\@textBlocks, $index);
if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, undef) != -1)
{
# ClosingTag() makes sure tags aren't opened multiple times in a row.
$bold = 1;
$output .= '<b>';
}
elsif ($bold && $tagType == POSSIBLE_CLOSING_TAG)
{
$bold = undef;
$output .= '</b>';
}
else
{
$output .= '*';
};
}
elsif ($textBlocks[$index] eq '_')
{
my $tagType = $self->TagType(\@textBlocks, $index);
if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, \$underlineHasWhitespace) != -1)
{
# ClosingTag() makes sure tags aren't opened multiple times in a row.
$underline = 1;
#underlineHasWhitespace is set by ClosingTag().
$output .= '<u>';
}
elsif ($underline && $tagType == POSSIBLE_CLOSING_TAG)
{
$underline = undef;
#underlineHasWhitespace will be reset by the next opening underline.
$output .= '</u>';
}
elsif ($underline && !$underlineHasWhitespace)
{
# If there's no whitespace between underline tags, all underscores are replaced by spaces so
# _some_underlined_text_ becomes <u>some underlined text</u>. The standard _some underlined text_
# will work too.
$output .= ' ';
}
else
{
$output .= '_';
};
}
elsif ($textBlocks[$index] eq '~')
{
my $tagType = $self->TagType(\@textBlocks, $index);
if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, \$strikethroughHasWhitespace) != -1)
{
# ClosingTag() makes sure tags aren't opened multiple times in a row.
$strikethrough = 1;
#strikethroughHasWhitespace is set by ClosingTag().
$output .= '<s>';
}
elsif ($strikethrough && $tagType == POSSIBLE_CLOSING_TAG)
{
$strikethrough = undef;
#strikethroughHasWhitespace will be reset by the next opening strikethrough.
$output .= '</s>';
}
elsif ($strikethrough && !$strikethroughHasWhitespace)
{
# If there's no whitespace between strikethrough tags, all hyphens are replaced
# by spaces so -some-struck-through-text- becomes <s>some struck through text</s>.
# The standard -some struck-through text- will work too.
$output .= ' ';
}
else
{
$output .= '~';
};
}
elsif ($textBlocks[$index] eq '+')
{
my $tagType = $self->TagType(\@textBlocks, $index);
if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, undef) != -1)
{
# ClosingTag() makes sure tags aren't opened multiple times in a row.
$italic = 1;
$output .= '<i>';
}
elsif ($italic && $tagType == POSSIBLE_CLOSING_TAG)
{
$italic = undef;
$output .= '</i>';
}
else
{
$output .= '+';
};
}
elsif ($textBlocks[$index] eq '`')
{
my $tagType = $self->TagType(\@textBlocks, $index);
if ($tagType == POSSIBLE_OPENING_TAG && $self->ClosingTag(\@textBlocks, $index, undef) != -1)
{
# ClosingTag() makes sure tags aren't opened multiple times in a row.
$monotype = 1;
$output .= '<tt>';
}
elsif ($monotype && $tagType == POSSIBLE_CLOSING_TAG)
{
$monotype = undef;
$output .= '</tt>';
}
else
{
$output .= '`';
};
}
else # plain text or a > that isn't part of a link
{
$output .= NaturalDocs::NDMarkup->ConvertAmpChars($textBlocks[$index]);
};
$index++;
};
return $output;
};
#
# Function: TagType
#
# Returns whether the tag is a possible opening or closing tag, or neither. "Possible" because it doesn't check if an opening tag is
# closed or a closing tag is opened, just whether the surrounding characters allow it to be a candidate for a tag. For example, in
# "A _B" the underscore is a possible opening underline tag, but in "A_B" it is not. Support function for <RichFormatTextBlock()>.
#
# Parameters:
#
# textBlocks - A reference to an array of text blocks.
# index - The index of the tag.
#
# Returns:
#
# POSSIBLE_OPENING_TAG, POSSIBLE_CLOSING_TAG, or NOT_A_TAG.
#
sub TagType #(textBlocks, index)
{
my ($self, $textBlocks, $index) = @_;
# Possible opening tags
if ( ( $textBlocks->[$index] =~ /^[\*_\~\+\`<]$/ ) &&
# Before it must be whitespace, the beginning of the text, or ({["'-/*_~+`.
( $index == 0 || $textBlocks->[$index-1] =~ /[\ \t\n\(\{\[\"\'\-\/\*\_\~\+\`]$/ ) &&
# Notes for 2.0: Include Spanish upside down ! and ? as well as opening quotes (66) and apostrophes (6). Look into
# Unicode character classes as well.
# After it must be non-whitespace.
( $index + 1 < scalar @$textBlocks && $textBlocks->[$index+1] !~ /^[\ \t\n]/) &&
# Make sure we don't accept <<, <=, <-, or *= as opening tags.
( $textBlocks->[$index] ne '<' || $textBlocks->[$index+1] !~ /^[<=-]/ ) &&
( $textBlocks->[$index] ne '*' || $textBlocks->[$index+1] !~ /^[\=\*]/ ) &&
# Make sure we don't accept *, _, ~, + or ` before it unless it's <.
( $textBlocks->[$index] eq '<' || $index == 0 || $textBlocks->[$index-1] !~ /[\*\_\~\+\`]$/) )
{
return POSSIBLE_OPENING_TAG;
}
# Possible closing tags
elsif ( ( $textBlocks->[$index] =~ /^[\*_\~\+\`>]$/) &&
# After it must be whitespace, the end of the text, or )}].,!?"';:-/*_~+`.
( $index + 1 == scalar @$textBlocks || $textBlocks->[$index+1] =~ /^[ \t\n\)\]\}\.\,\!\?\"\'\;\:\-\/\*\_\~\+\`]/ ||
# Links also get plurals, like <link>s, <linx>es, <link>'s, and <links>'.
( $textBlocks->[$index] eq '>' && $textBlocks->[$index+1] =~ /^(?:es|s|\')/ ) ) &&
# Notes for 2.0: Include closing quotes (99) and apostrophes (9). Look into Unicode character classes as well.
# Before it must be non-whitespace.
( $index != 0 && $textBlocks->[$index-1] !~ /[ \t\n]$/ ) &&
# Make sure we don't accept >>, ->, or => as closing tags. >= is already taken care of.
( $textBlocks->[$index] ne '>' || $textBlocks->[$index-1] !~ /[>=-]$/ ) &&
# Make sure we don't accept *, _, ~, + or ` after it unless it's >.
( $textBlocks->[$index] eq '>' || $textBlocks->[$index+1] !~ /[\*\_\~\+\`]$/) )
{
return POSSIBLE_CLOSING_TAG;
}
else
{
return NOT_A_TAG;
};
};
#
# Function: ClosingTag
#
# Returns whether a tag is closed or not, where it's closed if it is, and optionally whether there is any whitespace between the
# tags. Support function for <RichFormatTextBlock()>.
#
# The results of this function are in full context, meaning that if it says a tag is closed, it can be interpreted as that tag in the
# final output. It takes into account any spoiling factors, like there being two opening tags in a row.
#
# Parameters:
#
# textBlocks - A reference to an array of text blocks.
# index - The index of the opening tag.
# hasWhitespaceRef - A reference to the variable that will hold whether there is whitespace between the tags or not. If
# undef, the function will not check. If the tag is not closed, the variable will not be changed.
#
# Returns:
#
# If the tag is closed, it returns the index of the closing tag and puts whether there was whitespace between the tags in
# hasWhitespaceRef if it was specified. If the tag is not closed, it returns -1 and doesn't touch the variable pointed to by
# hasWhitespaceRef.
#
sub ClosingTag #(textBlocks, index, hasWhitespace)
{
my ($self, $textBlocks, $index, $hasWhitespaceRef) = @_;
my $hasWhitespace;
my $closingTag;
if ($textBlocks->[$index] eq '*' || $textBlocks->[$index] eq '_' ||
$textBlocks->[$index] eq '~' || $textBlocks->[$index] eq '+' ||
$textBlocks->[$index] eq '`')
{ $closingTag = $textBlocks->[$index]; }
elsif ($textBlocks->[$index] eq '<')
{ $closingTag = '>'; }
else
{ return -1; };
my $beginningIndex = $index;
$index++;
while ($index < scalar @$textBlocks)
{
if ($textBlocks->[$index] eq '<' && $self->TagType($textBlocks, $index) == POSSIBLE_OPENING_TAG)
{
# If we hit a < and we're checking whether a link is closed, it's not. The first < becomes literal and the second one
# becomes the new link opening.
if ($closingTag eq '>')
{
return -1;
}
# If we're not searching for the end of a link, we have to skip the link because formatting tags cannot appear within
# them. That's of course provided it's closed.
else
{
my $linkHasWhitespace;
my $endIndex = $self->ClosingTag($textBlocks, $index,
($hasWhitespaceRef && !$hasWhitespace ? \$linkHasWhitespace : undef) );
if ($endIndex != -1)
{
if ($linkHasWhitespace)
{ $hasWhitespace = 1; };
# index will be incremented again at the end of the loop, which will bring us past the link's >.
$index = $endIndex;
};
};
}
elsif ($textBlocks->[$index] eq $closingTag)
{
my $tagType = $self->TagType($textBlocks, $index);
if ($tagType == POSSIBLE_CLOSING_TAG)
{
# There needs to be something between the tags for them to count.
if ($index == $beginningIndex + 1)
{ return -1; }
else
{
# Success!
if ($hasWhitespaceRef)
{ $$hasWhitespaceRef = $hasWhitespace; };
return $index;
};
}
# If there are two opening tags of the same type, the first becomes literal and the next becomes part of a tag.
elsif ($tagType == POSSIBLE_OPENING_TAG)
{ return -1; }
}
elsif ($hasWhitespaceRef && !$hasWhitespace)
{
if ($textBlocks->[$index] =~ /[ \t\n]/)
{ $hasWhitespace = 1; };
};
$index++;
};
# Hit the end of the text blocks if we're here.
return -1;
};
1;
| Java |
/* $OpenBSD: bcrypt_pbkdf.c,v 1.4 2013/07/29 00:55:53 tedu Exp $ */
/*
* Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifndef HAVE_BCRYPT_PBKDF
#include "libssh2_priv.h"
#include <stdlib.h>
#include <sys/types.h>
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#include "blf.h"
#define MINIMUM(a,b) (((a) < (b)) ? (a) : (b))
/*
* pkcs #5 pbkdf2 implementation using the "bcrypt" hash
*
* The bcrypt hash function is derived from the bcrypt password hashing
* function with the following modifications:
* 1. The input password and salt are preprocessed with SHA512.
* 2. The output length is expanded to 256 bits.
* 3. Subsequently the magic string to be encrypted is lengthened and modified
* to "OxychromaticBlowfishSwatDynamite"
* 4. The hash function is defined to perform 64 rounds of initial state
* expansion. (More rounds are performed by iterating the hash.)
*
* Note that this implementation pulls the SHA512 operations into the caller
* as a performance optimization.
*
* One modification from official pbkdf2. Instead of outputting key material
* linearly, we mix it. pbkdf2 has a known weakness where if one uses it to
* generate (i.e.) 512 bits of key material for use as two 256 bit keys, an
* attacker can merely run once through the outer loop below, but the user
* always runs it twice. Shuffling output bytes requires computing the
* entirety of the key material to assemble any subkey. This is something a
* wise caller could do; we just do it for you.
*/
#define BCRYPT_BLOCKS 8
#define BCRYPT_HASHSIZE (BCRYPT_BLOCKS * 4)
static void
bcrypt_hash(uint8_t *sha2pass, uint8_t *sha2salt, uint8_t *out)
{
blf_ctx state;
uint8_t ciphertext[BCRYPT_HASHSIZE] =
"OxychromaticBlowfishSwatDynamite";
uint32_t cdata[BCRYPT_BLOCKS];
int i;
uint16_t j;
size_t shalen = SHA512_DIGEST_LENGTH;
/* key expansion */
Blowfish_initstate(&state);
Blowfish_expandstate(&state, sha2salt, shalen, sha2pass, shalen);
for(i = 0; i < 64; i++) {
Blowfish_expand0state(&state, sha2salt, shalen);
Blowfish_expand0state(&state, sha2pass, shalen);
}
/* encryption */
j = 0;
for(i = 0; i < BCRYPT_BLOCKS; i++)
cdata[i] = Blowfish_stream2word(ciphertext, sizeof(ciphertext),
&j);
for(i = 0; i < 64; i++)
blf_enc(&state, cdata, sizeof(cdata) / sizeof(uint64_t));
/* copy out */
for(i = 0; i < BCRYPT_BLOCKS; i++) {
out[4 * i + 3] = (cdata[i] >> 24) & 0xff;
out[4 * i + 2] = (cdata[i] >> 16) & 0xff;
out[4 * i + 1] = (cdata[i] >> 8) & 0xff;
out[4 * i + 0] = cdata[i] & 0xff;
}
/* zap */
_libssh2_explicit_zero(ciphertext, sizeof(ciphertext));
_libssh2_explicit_zero(cdata, sizeof(cdata));
_libssh2_explicit_zero(&state, sizeof(state));
}
int
bcrypt_pbkdf(const char *pass, size_t passlen, const uint8_t *salt,
size_t saltlen,
uint8_t *key, size_t keylen, unsigned int rounds)
{
uint8_t sha2pass[SHA512_DIGEST_LENGTH];
uint8_t sha2salt[SHA512_DIGEST_LENGTH];
uint8_t out[BCRYPT_HASHSIZE];
uint8_t tmpout[BCRYPT_HASHSIZE];
uint8_t *countsalt;
size_t i, j, amt, stride;
uint32_t count;
size_t origkeylen = keylen;
libssh2_sha512_ctx ctx;
/* nothing crazy */
if(rounds < 1)
return -1;
if(passlen == 0 || saltlen == 0 || keylen == 0 ||
keylen > sizeof(out) * sizeof(out) || saltlen > 1<<20)
return -1;
countsalt = calloc(1, saltlen + 4);
if(countsalt == NULL)
return -1;
stride = (keylen + sizeof(out) - 1) / sizeof(out);
amt = (keylen + stride - 1) / stride;
memcpy(countsalt, salt, saltlen);
/* collapse password */
libssh2_sha512_init(&ctx);
libssh2_sha512_update(ctx, pass, passlen);
libssh2_sha512_final(ctx, sha2pass);
/* generate key, sizeof(out) at a time */
for(count = 1; keylen > 0; count++) {
countsalt[saltlen + 0] = (count >> 24) & 0xff;
countsalt[saltlen + 1] = (count >> 16) & 0xff;
countsalt[saltlen + 2] = (count >> 8) & 0xff;
countsalt[saltlen + 3] = count & 0xff;
/* first round, salt is salt */
libssh2_sha512_init(&ctx);
libssh2_sha512_update(ctx, countsalt, saltlen + 4);
libssh2_sha512_final(ctx, sha2salt);
bcrypt_hash(sha2pass, sha2salt, tmpout);
memcpy(out, tmpout, sizeof(out));
for(i = 1; i < rounds; i++) {
/* subsequent rounds, salt is previous output */
libssh2_sha512_init(&ctx);
libssh2_sha512_update(ctx, tmpout, sizeof(tmpout));
libssh2_sha512_final(ctx, sha2salt);
bcrypt_hash(sha2pass, sha2salt, tmpout);
for(j = 0; j < sizeof(out); j++)
out[j] ^= tmpout[j];
}
/*
* pbkdf2 deviation: output the key material non-linearly.
*/
amt = MINIMUM(amt, keylen);
for(i = 0; i < amt; i++) {
size_t dest = i * stride + (count - 1);
if(dest >= origkeylen) {
break;
}
key[dest] = out[i];
}
keylen -= i;
}
/* zap */
_libssh2_explicit_zero(out, sizeof(out));
free(countsalt);
return 0;
}
#endif /* HAVE_BCRYPT_PBKDF */
| Java |
/*
* Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include "internal/provider_util.h"
void ossl_prov_cipher_reset(PROV_CIPHER *pc)
{
EVP_CIPHER_free(pc->alloc_cipher);
pc->alloc_cipher = NULL;
pc->cipher = NULL;
pc->engine = NULL;
}
int ossl_prov_cipher_copy(PROV_CIPHER *dst, const PROV_CIPHER *src)
{
if (src->alloc_cipher != NULL && !EVP_CIPHER_up_ref(src->alloc_cipher))
return 0;
dst->engine = src->engine;
dst->cipher = src->cipher;
dst->alloc_cipher = src->alloc_cipher;
return 1;
}
static int load_common(const OSSL_PARAM params[], const char **propquery,
ENGINE **engine)
{
const OSSL_PARAM *p;
*propquery = NULL;
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_PROPERTIES);
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
*propquery = p->data;
}
*engine = NULL;
/* TODO legacy stuff, to be removed */
/* Inside the FIPS module, we don't support legacy ciphers */
#if !defined(FIPS_MODE) && !defined(OPENSSL_NO_ENGINE)
p = OSSL_PARAM_locate_const(params, "engine");
if (p != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
ENGINE_finish(*engine);
*engine = ENGINE_by_id(p->data);
if (*engine == NULL)
return 0;
}
#endif
return 1;
}
int ossl_prov_cipher_load_from_params(PROV_CIPHER *pc,
const OSSL_PARAM params[],
OPENSSL_CTX *ctx)
{
const OSSL_PARAM *p;
const char *propquery;
if (!load_common(params, &propquery, &pc->engine))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_CIPHER);
if (p == NULL)
return 1;
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
EVP_CIPHER_free(pc->alloc_cipher);
pc->cipher = pc->alloc_cipher = EVP_CIPHER_fetch(ctx, p->data, propquery);
/* TODO legacy stuff, to be removed */
#ifndef FIPS_MODE /* Inside the FIPS module, we don't support legacy ciphers */
if (pc->cipher == NULL)
pc->cipher = EVP_get_cipherbyname(p->data);
#endif
return pc->cipher != NULL;
}
const EVP_CIPHER *ossl_prov_cipher_cipher(const PROV_CIPHER *pc)
{
return pc->cipher;
}
ENGINE *ossl_prov_cipher_engine(const PROV_CIPHER *pc)
{
return pc->engine;
}
void ossl_prov_digest_reset(PROV_DIGEST *pd)
{
EVP_MD_free(pd->alloc_md);
pd->alloc_md = NULL;
pd->md = NULL;
pd->engine = NULL;
}
int ossl_prov_digest_copy(PROV_DIGEST *dst, const PROV_DIGEST *src)
{
if (src->alloc_md != NULL && !EVP_MD_up_ref(src->alloc_md))
return 0;
dst->engine = src->engine;
dst->md = src->md;
dst->alloc_md = src->alloc_md;
return 1;
}
int ossl_prov_digest_load_from_params(PROV_DIGEST *pd,
const OSSL_PARAM params[],
OPENSSL_CTX *ctx)
{
const OSSL_PARAM *p;
const char *propquery;
if (!load_common(params, &propquery, &pd->engine))
return 0;
p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_DIGEST);
if (p == NULL)
return 1;
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
EVP_MD_free(pd->alloc_md);
pd->md = pd->alloc_md = EVP_MD_fetch(ctx, p->data, propquery);
/* TODO legacy stuff, to be removed */
#ifndef FIPS_MODE /* Inside the FIPS module, we don't support legacy digests */
if (pd->md == NULL)
pd->md = EVP_get_digestbyname(p->data);
#endif
return pd->md != NULL;
}
const EVP_MD *ossl_prov_digest_md(const PROV_DIGEST *pd)
{
return pd->md;
}
ENGINE *ossl_prov_digest_engine(const PROV_DIGEST *pd)
{
return pd->engine;
}
int ossl_prov_macctx_load_from_params(EVP_MAC_CTX **macctx,
const OSSL_PARAM params[],
const char *macname,
const char *ciphername,
const char *mdname,
OPENSSL_CTX *libctx)
{
const OSSL_PARAM *p;
OSSL_PARAM mac_params[5], *mp = mac_params;
const char *properties = NULL;
if (macname == NULL
&& (p = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_MAC)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
macname = p->data;
}
if ((p = OSSL_PARAM_locate_const(params,
OSSL_ALG_PARAM_PROPERTIES)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
properties = p->data;
}
/* If we got a new mac name, we make a new EVP_MAC_CTX */
if (macname != NULL) {
EVP_MAC *mac = EVP_MAC_fetch(libctx, macname, properties);
EVP_MAC_CTX_free(*macctx);
*macctx = mac == NULL ? NULL : EVP_MAC_CTX_new(mac);
/* The context holds on to the MAC */
EVP_MAC_free(mac);
if (*macctx == NULL)
return 0;
}
/*
* If there is no MAC yet (and therefore, no MAC context), we ignore
* all other parameters.
*/
if (*macctx == NULL)
return 1;
if (mdname == NULL) {
if ((p = OSSL_PARAM_locate_const(params,
OSSL_ALG_PARAM_DIGEST)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
mdname = p->data;
}
}
if (ciphername == NULL) {
if ((p = OSSL_PARAM_locate_const(params,
OSSL_ALG_PARAM_CIPHER)) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
ciphername = p->data;
}
}
if (mdname != NULL)
*mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
(char *)mdname, 0);
if (ciphername != NULL)
*mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
(char *)ciphername, 0);
if (properties != NULL)
*mp++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES,
(char *)properties, 0);
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODE)
if ((p = OSSL_PARAM_locate_const(params, "engine")) != NULL) {
if (p->data_type != OSSL_PARAM_UTF8_STRING)
return 0;
*mp++ = OSSL_PARAM_construct_utf8_string("engine",
p->data, p->data_size);
}
#endif
*mp = OSSL_PARAM_construct_end();
if (EVP_MAC_CTX_set_params(*macctx, mac_params))
return 1;
EVP_MAC_CTX_free(*macctx);
*macctx = NULL;
return 0;
}
| Java |
////////////////////////////////////////////////////////////////
//
// Copyright (C) 2008 Affymetrix, Inc.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License
// (version 2.1) as published by the Free Software Foundation.
//
// 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 Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////
#ifndef _FamilialMultiDataData_HEADER_
#define _FamilialMultiDataData_HEADER_
/*! \file FamilialMultiDataData.h This file provides types to store results for a familial file.
*/
//
#include "calvin_files/parameter/src/ParameterNameValueType.h"
#include "calvin_files/portability/src/AffymetrixBaseTypes.h"
//
#include <cstring>
#include <sstream>
#include <string>
#include <vector>
//
namespace affymetrix_calvin_data
{
/*! Stores the segment overlap from a familial file. */
typedef struct _FamilialSegmentOverlap
{
/*! The type of segment; the name of the data set in which the segment appears in the CYCHP file. */
std::string segmentType;
/*! The key identifying the sample from the Samples data set. */
u_int32_t referenceSampleKey;
/*! The ID of the segment of the reference sample. */
std::string referenceSegmentID;
/*! The key identifying the sample from the Samples data set. */
u_int32_t familialSampleKey;
/*! The ID of the segment of the compare sample. */
std::string familialSegmentID;
} FamilialSegmentOverlap;
/*! Stores information about the sample for a familial file. */
typedef struct _FamilialSample
{
/*! Local arbitrary unique sample identifier used within the file. */
u_int32_t sampleKey;
/*! The identifier of the ARR file associated with the sample. If no ARR file was used in generating the associated CYCHP files, this value will be the empty string. */
std::string arrID;
/*! The identifier of the CYCHP file containing the sample data. */
std::string chpID;
/*! The filename (not the complete path) of the CYCHP file containing the sample data. */
std::wstring chpFilename;
/*! The role of the identified sample, such as index, mother, or father. */
std::string role;
/*! The call of whether the assigned role is correct. */
bool roleValidity;
/*! The confidence that the assigned role is correct */
float roleConfidence;
} FamilialSample;
}
#endif
| Java |
/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, development version *
* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH *
* *
* This program is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This program 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 Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#ifndef SOFA_CONTACT_LISTENER_H
#define SOFA_CONTACT_LISTENER_H
#include "config.h"
#include <sofa/core/objectmodel/BaseObject.h>
#include <sofa/core/collision/Contact.h>
//#include <sofa/core/collision/DetectionOutput.h>
#include <sofa/helper/vector.h>
//#include <sofa/core/CollisionModel.h>
namespace sofa
{
namespace core
{
// forward declaration
class CollisionModel;
namespace collision
{
// forward declaration
class NarrowPhaseDetection;
class SOFA_BASE_COLLISION_API ContactListener : public virtual core::objectmodel::BaseObject
{
public:
SOFA_CLASS(ContactListener, core::objectmodel::BaseObject);
protected:
ContactListener( CollisionModel* collModel1 = NULL, CollisionModel* collModel2 = NULL );
virtual ~ContactListener();
// DetectionOutput iterators
typedef helper::vector<const helper::vector<DetectionOutput>* >::const_iterator ContactVectorsIterator;
typedef helper::vector<DetectionOutput>::const_iterator ContactsIterator;
virtual void beginContact(const helper::vector<const helper::vector<DetectionOutput>* >& ) {}
virtual void endContact(void*) {}
protected:
const CollisionModel* mCollisionModel1;
const CollisionModel* mCollisionModel2;
//// are these SingleLinks necessary ? they are used only in canCreate(...) and create functions(...)
//SingleLink<ContactListener, CollisionModel, BaseLink::FLAG_STOREPATH|BaseLink::FLAG_STRONGLINK> mLinkCollisionModel1;
///// Pointer to the next (finer / lower / child level) CollisionModel in the hierarchy.
//SingleLink<ContactListener, CollisionModel, BaseLink::FLAG_STOREPATH|BaseLink::FLAG_STRONGLINK> mLinkCollisionModel2;
private:
helper::vector<const helper::vector<DetectionOutput>* > mContactsVector;
core::collision::NarrowPhaseDetection* mNarrowPhase;
public:
virtual void init(void) override;
virtual void handleEvent( core::objectmodel::Event* event ) override;
template<class T>
static bool canCreate(T*& obj, core::objectmodel::BaseContext* context, core::objectmodel::BaseObjectDescription* arg)
{
core::CollisionModel* collModel1 = NULL;
core::CollisionModel* collModel2 = NULL;
std::string collModelPath1;
std::string collModelPath2;
if (arg->getAttribute("collisionModel1"))
collModelPath1 = arg->getAttribute("collisionModel1");
else
collModelPath1 = "";
context->findLinkDest(collModel1, collModelPath1, NULL);
if (arg->getAttribute("collisionModel2"))
collModelPath2 = arg->getAttribute("collisionModel2");
else
collModelPath2 = "";
context->findLinkDest(collModel2, collModelPath2, NULL);
if (collModel1 == NULL && collModel2 == NULL )
{
context->serr << "Creation of " << className(obj) <<
" CollisonListener failed because no Collision Model links are found: \"" << collModelPath1
<< "\" and \"" << collModelPath2 << "\" " << context->sendl;
return false;
}
return BaseObject::canCreate(obj, context, arg);
}
template<class T>
static typename T::SPtr create(T* , core::objectmodel::BaseContext* context, core::objectmodel::BaseObjectDescription* arg)
{
CollisionModel* collModel1 = NULL;
CollisionModel* collModel2 = NULL;
std::string collModelPath1;
std::string collModelPath2;
if(arg)
{
collModelPath1 = arg->getAttribute(std::string("collisionModel1"), NULL );
collModelPath2 = arg->getAttribute(std::string("collisionModel2"), NULL );
// now 3 cases
if ( strcmp( collModelPath1.c_str(),"" ) != 0 )
{
context->findLinkDest(collModel1, collModelPath1, NULL);
if ( strcmp( collModelPath2.c_str(),"" ) != 0 )
{
context->findLinkDest(collModel2, collModelPath2, NULL);
}
}
else
{
context->findLinkDest(collModel1, collModelPath2, NULL);
}
}
typename T::SPtr obj = sofa::core::objectmodel::New<T>( collModel1, collModel2 );
//if ( obj )
//{
// obj->mLinkCollisionModel1.setPath( collModelPath1 );
// obj->mLinkCollisionModel2.setPath( collModelPath2 );
//}
if (context)
{
context->addObject(obj);
}
if (arg)
{
obj->parse(arg);
}
return obj;
}
};
} // namespace collision
} // namespace core
} // namespace sofa
#endif // SOFA_CONTACT_LISTENER_H
| Java |
/*
Copyright 2009 Will Stephenson <wstephenson@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef KNM_INTERNALS_UNCONFIGUREDINTERFACE_H
#define KNM_INTERNALS_UNCONFIGUREDINTERFACE_H
#include "activatable.h"
namespace Knm
{
class UnconfiguredInterface : public Activatable
{
Q_OBJECT
public:
UnconfiguredInterface(const QString &deviceUni, QObject *parent);
virtual ~UnconfiguredInterface();
};
}
#endif // KNM_INTERNALS_UNCONFIGUREDINTERFACE_H
| Java |
#ifndef HIGHSCORE_HPP
#define HIGHSCORE_HPP
#include <cassert>
#include <sstream>
#include "framework.hpp"
#include "./config.hpp"
#include "./media.hpp"
class Highscore
{
public:
Highscore();
~Highscore();
/* Load/Save */
void load();
void save();
/* Access particular difficulties */
util::Highscore &getHighscore(LEVEL_DIFFICULTY difficulty);
/* Draw */
void draw();
private:
/* Data */
util::Timer timer;
util::Highscore highscore[LEVEL_DIFFICULTY_END];
double offset;
int haltstart;
int difficulty;
bool shifting;
struct
{
font::TtfLabel difficulty[LEVEL_DIFFICULTY_END];
font::TtfLabel place[3/*HIGHSCORE_PLACECOUNT*/];
font::TtfLabel score[LEVEL_DIFFICULTY_END][3/*HIGHSCORE_PLACECOUNT*/];
font::TtfLabel prescore[LEVEL_DIFFICULTY_END][3/*HIGHSCORE_PLACECOUNT*/];
}label;
};
#endif // HIGHSCORE_HPP
| Java |
/* table.h - Iterative table interface.
* Copyright (C) 2006 g10 Code GmbH
*
* This file is part of Scute.
*
* Scute is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Scute 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <https://gnu.org/licenses/>.
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifndef TABLE_H
#define TABLE_H 1
#include <stdbool.h>
#include <gpg-error.h>
/* The indexed list type. */
struct scute_table;
typedef struct scute_table *scute_table_t;
/* TABLE interface. */
/* A table entry allocator function callback. Should return the new
table entry in DATA_R. */
typedef gpg_error_t (*scute_table_alloc_cb_t) (void **data_r, void *hook);
/* A table entry deallocator function callback. */
typedef void (*scute_table_dealloc_cb_t) (void *data);
/* Allocate a new table and return it in TABLE_R. */
gpg_error_t scute_table_create (scute_table_t *table_r,
scute_table_alloc_cb_t alloc,
scute_table_dealloc_cb_t dealloc);
/* Destroy the indexed list TABLE. This also calls the deallocator on
all entries. */
void scute_table_destroy (scute_table_t table);
/* Allocate a new table entry with a free index. Returns the index
pointing to the new list entry in INDEX_R. This calls the
allocator on the new entry before returning. Also returns the
table entry in *DATA_R if this is not NULL. */
gpg_error_t scute_table_alloc (scute_table_t table, int *index_r,
void **data_r, void *hook);
/* Deallocate the list entry index. Afterwards, INDEX points to the
following entry. This calls the deallocator on the entry before
returning. */
void scute_table_dealloc (scute_table_t table, int *index);
/* Return the index for the beginning of the list TABLE. */
int scute_table_first (scute_table_t table);
/* Return the index following INDEX. If INDEX is the last element in
the list, return 0. */
int scute_table_next (scute_table_t table, int index);
/* Return true iff INDEX is the end-of-list marker. */
bool scute_table_last (scute_table_t table, int index);
/* Return the user data associated with INDEX. Return NULL if INDEX is
the end-of-list marker. */
void *scute_table_data (scute_table_t table, int index);
/* Return the number of entries in the table TABLE. */
int scute_table_used (scute_table_t table);
#endif /* !TABLE_H */
| Java |
// CC0 Public Domain: http://creativecommons.org/publicdomain/zero/1.0/
#include "bsefilter.hh"
#include <sfi/sfi.hh>
using namespace Bse;
const gchar*
bse_iir_filter_kind_string (BseIIRFilterKind fkind)
{
switch (fkind)
{
case BSE_IIR_FILTER_BUTTERWORTH: return "Butterworth";
case BSE_IIR_FILTER_BESSEL: return "Bessel";
case BSE_IIR_FILTER_CHEBYSHEV1: return "Chebyshev1";
case BSE_IIR_FILTER_CHEBYSHEV2: return "Chebyshev2";
case BSE_IIR_FILTER_ELLIPTIC: return "Elliptic";
default: return "?unknown?";
}
}
const gchar*
bse_iir_filter_type_string (BseIIRFilterType ftype)
{
switch (ftype)
{
case BSE_IIR_FILTER_LOW_PASS: return "Low-pass";
case BSE_IIR_FILTER_BAND_PASS: return "Band-pass";
case BSE_IIR_FILTER_HIGH_PASS: return "High-pass";
case BSE_IIR_FILTER_BAND_STOP: return "Band-stop";
default: return "?unknown?";
}
}
gchar*
bse_iir_filter_request_string (const BseIIRFilterRequest *ifr)
{
String s;
s += bse_iir_filter_kind_string (ifr->kind);
s += " ";
s += bse_iir_filter_type_string (ifr->type);
s += " order=" + string_from_int (ifr->order);
s += " sample-rate=" + string_from_float (ifr->sampling_frequency);
if (ifr->kind == BSE_IIR_FILTER_CHEBYSHEV1 || ifr->kind == BSE_IIR_FILTER_ELLIPTIC)
s += " passband-ripple-db=" + string_from_float (ifr->passband_ripple_db);
s += " passband-edge=" + string_from_float (ifr->passband_edge);
if (ifr->type == BSE_IIR_FILTER_BAND_PASS || ifr->type == BSE_IIR_FILTER_BAND_STOP)
s += " passband-edge2=" + string_from_float (ifr->passband_edge2);
if (ifr->kind == BSE_IIR_FILTER_ELLIPTIC && ifr->stopband_db < 0)
s += " stopband-db=" + string_from_float (ifr->stopband_db);
if (ifr->kind == BSE_IIR_FILTER_ELLIPTIC && ifr->stopband_edge > 0)
s += " stopband-edge=" + string_from_float (ifr->stopband_edge);
return g_strdup (s.c_str());
}
gchar*
bse_iir_filter_design_string (const BseIIRFilterDesign *fid)
{
String s;
s += "order=" + string_from_int (fid->order);
s += " sampling-frequency=" + string_from_float (fid->sampling_frequency);
s += " center-frequency=" + string_from_float (fid->center_frequency);
s += " gain=" + string_from_double (fid->gain);
s += " n_zeros=" + string_from_int (fid->n_zeros);
s += " n_poles=" + string_from_int (fid->n_poles);
for (uint i = 0; i < fid->n_zeros; i++)
{
String u ("Zero:");
u += " " + string_from_double (fid->zz[i].re);
u += " + " + string_from_double (fid->zz[i].im) + "*i";
s += "\n" + u;
}
for (uint i = 0; i < fid->n_poles; i++)
{
String u ("Pole:");
u += " " + string_from_double (fid->zp[i].re);
u += " + " + string_from_double (fid->zp[i].im) + "*i";
s += "\n" + u;
}
String u;
#if 0
uint o = fid->order;
u = string_from_double (fid->zn[o]);
while (o--)
u = "(" + u + ") * z + " + string_from_double (fid->zn[o]);
s += "\nNominator: " + u;
o = fid->order;
u = string_from_double (fid->zd[o]);
while (o--)
u = "(" + u + ") * z + " + string_from_double (fid->zd[o]);
s += "\nDenominator: " + u;
#endif
return g_strdup (s.c_str());
}
bool
bse_iir_filter_design (const BseIIRFilterRequest *filter_request,
BseIIRFilterDesign *filter_design)
{
if (filter_request->kind == BSE_IIR_FILTER_BUTTERWORTH ||
filter_request->kind == BSE_IIR_FILTER_CHEBYSHEV1 ||
filter_request->kind == BSE_IIR_FILTER_ELLIPTIC)
return _bse_filter_design_ellf (filter_request, filter_design);
return false;
}
| Java |
#include <stdio.h>
#include <QtDebug>
#include "cguitreedomdocument.h"
CGuiTreeDomDocument::CGuiTreeDomDocument()
{
QDomImplementation impl;
impl.setInvalidDataPolicy(QDomImplementation::ReturnNullNode);
}
/**
* Get first "guiObject" located in "guiRoot".
*
* @return Node element of first guiObject or an empty element node if there is none.
**/
CGuiTreeDomElement CGuiTreeDomDocument::getFirstGuiObjectElement()
{
CGuiTreeDomElement domElmGuiTree;
domElmGuiTree = this->firstChildElement("guiRoot");
if(domElmGuiTree.isNull())
return(domElmGuiTree);
return(domElmGuiTree.firstChildElement("guiObject"));
}
| Java |
package mezz.texturedump.dumpers;
import com.google.gson.stream.JsonWriter;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.StartupMessageManager;
import net.minecraftforge.forgespi.language.IModFileInfo;
import net.minecraftforge.forgespi.language.IModInfo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nullable;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ModStatsDumper {
private static final Logger LOGGER = LogManager.getLogger();
public Path saveModStats(String name, TextureAtlas map, Path modStatsDir) throws IOException {
Map<String, Long> modPixelCounts = map.texturesByName.values().stream()
.collect(Collectors.groupingBy(
sprite -> sprite.getName().getNamespace(),
Collectors.summingLong(sprite -> (long) sprite.getWidth() * sprite.getHeight()))
);
final long totalPixels = modPixelCounts.values().stream().mapToLong(longValue -> longValue).sum();
final String filename = name + "_mod_statistics";
Path output = modStatsDir.resolve(filename + ".js");
List<Map.Entry<String, Long>> sortedEntries = modPixelCounts.entrySet().stream()
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.collect(Collectors.toList());
StartupMessageManager.addModMessage("Dumping Mod TextureMap Statistics");
FileWriter fileWriter = new FileWriter(output.toFile());
fileWriter.write("var modStatistics = \n//Start of Data\n");
JsonWriter jsonWriter = new JsonWriter(fileWriter);
jsonWriter.setIndent(" ");
jsonWriter.beginArray();
{
for (Map.Entry<String, Long> modPixels : sortedEntries) {
String resourceDomain = modPixels.getKey();
long pixelCount = modPixels.getValue();
writeModStatisticsObject(jsonWriter, resourceDomain, pixelCount, totalPixels);
}
}
jsonWriter.endArray();
jsonWriter.close();
fileWriter.close();
LOGGER.info("Saved mod statistics to {}.", output.toString());
return output;
}
private static void writeModStatisticsObject(JsonWriter jsonWriter, String resourceDomain, long pixelCount, long totalPixels) throws IOException {
IModInfo modInfo = getModMetadata(resourceDomain);
String modName = modInfo != null ? modInfo.getDisplayName() : "";
jsonWriter.beginObject()
.name("resourceDomain").value(resourceDomain)
.name("pixelCount").value(pixelCount)
.name("percentOfTextureMap").value(pixelCount * 100f / totalPixels)
.name("modName").value(modName)
.name("url").value(getModConfigValue(modInfo, "displayURL"))
.name("issueTrackerUrl").value(getModConfigValue(modInfo, "issueTrackerURL"));
jsonWriter.name("authors").beginArray();
{
String authors = getModConfigValue(modInfo, "authors");
if (!authors.isEmpty()) {
String[] authorList = authors.split(",");
for (String author : authorList) {
jsonWriter.value(author.trim());
}
}
}
jsonWriter.endArray();
jsonWriter.endObject();
}
private static String getModConfigValue(@Nullable IModInfo modInfo, String key) {
if (modInfo == null) {
return "";
}
Map<String, Object> modConfig = modInfo.getModProperties();
Object value = modConfig.getOrDefault(key, "");
if (value instanceof String) {
return (String) value;
}
return "";
}
@Nullable
private static IModInfo getModMetadata(String resourceDomain) {
ModList modList = ModList.get();
IModFileInfo modFileInfo = modList.getModFileById(resourceDomain);
if (modFileInfo == null) {
return null;
}
return modFileInfo.getMods()
.stream()
.findFirst()
.orElse(null);
}
}
| Java |
/*
* Copyright 2005-2006 UniVis Explorer development team.
*
* This file is part of UniVis Explorer
* (http://phobos22.inf.uni-konstanz.de/univis).
*
* UniVis Explorer is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package unikn.dbis.univis.message;
/**
* TODO: document me!!!
* <p/>
* <code>Internationalizable+</code>.
* <p/>
* User: raedler, weiler
* Date: 18.05.2006
* Time: 01:39:22
*
* @author Roman Rädle
* @author Andreas Weiler
* @version $Id: Internationalizable.java 338 2006-10-08 23:11:30Z raedler $
* @since UniVis Explorer 0.1
*/
public interface Internationalizable {
public void internationalize();
} | Java |
package soot.jimple.toolkits.callgraph;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program 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 General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import soot.AnySubType;
import soot.ArrayType;
import soot.FastHierarchy;
import soot.G;
import soot.NullType;
import soot.PhaseOptions;
import soot.RefType;
import soot.Scene;
import soot.Singletons;
import soot.SootClass;
import soot.SootMethod;
import soot.Type;
import soot.jimple.SpecialInvokeExpr;
import soot.options.CGOptions;
import soot.toolkits.scalar.Pair;
import soot.util.Chain;
import soot.util.HashMultiMap;
import soot.util.LargeNumberedMap;
import soot.util.MultiMap;
import soot.util.NumberedString;
import soot.util.SmallNumberedMap;
import soot.util.queue.ChunkedQueue;
/**
* Resolves virtual calls.
*
* @author Ondrej Lhotak
*/
public class VirtualCalls {
private CGOptions options = new CGOptions(PhaseOptions.v().getPhaseOptions("cg"));
public VirtualCalls(Singletons.Global g) {
}
public static VirtualCalls v() {
return G.v().soot_jimple_toolkits_callgraph_VirtualCalls();
}
private final LargeNumberedMap<Type, SmallNumberedMap<SootMethod>> typeToVtbl
= new LargeNumberedMap<Type, SmallNumberedMap<SootMethod>>(Scene.v().getTypeNumberer());
public SootMethod resolveSpecial(SpecialInvokeExpr iie, NumberedString subSig, SootMethod container) {
return resolveSpecial(iie, subSig, container, false);
}
public SootMethod resolveSpecial(SpecialInvokeExpr iie, NumberedString subSig, SootMethod container, boolean appOnly) {
SootMethod target = iie.getMethod();
/* cf. JVM spec, invokespecial instruction */
if (Scene.v().getOrMakeFastHierarchy().canStoreType(container.getDeclaringClass().getType(),
target.getDeclaringClass().getType())
&& container.getDeclaringClass().getType() != target.getDeclaringClass().getType()
&& !target.getName().equals("<init>") && subSig != sigClinit) {
return resolveNonSpecial(container.getDeclaringClass().getSuperclass().getType(), subSig, appOnly);
} else {
return target;
}
}
public SootMethod resolveNonSpecial(RefType t, NumberedString subSig) {
return resolveNonSpecial(t, subSig, false);
}
public SootMethod resolveNonSpecial(RefType t, NumberedString subSig, boolean appOnly) {
SmallNumberedMap<SootMethod> vtbl = typeToVtbl.get(t);
if (vtbl == null) {
typeToVtbl.put(t, vtbl = new SmallNumberedMap<SootMethod>());
}
SootMethod ret = vtbl.get(subSig);
if (ret != null) {
return ret;
}
SootClass cls = t.getSootClass();
if (appOnly && cls.isLibraryClass()) {
return null;
}
SootMethod m = cls.getMethodUnsafe(subSig);
if (m != null) {
if (!m.isAbstract()) {
ret = m;
}
} else {
SootClass c = cls.getSuperclassUnsafe();
if (c != null) {
ret = resolveNonSpecial(c.getType(), subSig);
}
}
vtbl.put(subSig, ret);
return ret;
}
protected MultiMap<Type, Type> baseToSubTypes = new HashMultiMap<Type, Type>();
protected MultiMap<Pair<Type, NumberedString>, Pair<Type, NumberedString>> baseToPossibleSubTypes
= new HashMultiMap<Pair<Type, NumberedString>, Pair<Type, NumberedString>>();
public void resolve(Type t, Type declaredType, NumberedString subSig, SootMethod container,
ChunkedQueue<SootMethod> targets) {
resolve(t, declaredType, null, subSig, container, targets);
}
public void resolve(Type t, Type declaredType, NumberedString subSig, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly) {
resolve(t, declaredType, null, subSig, container, targets, appOnly);
}
public void resolve(Type t, Type declaredType, Type sigType, NumberedString subSig, SootMethod container,
ChunkedQueue<SootMethod> targets) {
resolve(t, declaredType, sigType, subSig, container, targets, false);
}
public void resolve(Type t, Type declaredType, Type sigType, NumberedString subSig, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly) {
if (declaredType instanceof ArrayType) {
declaredType = RefType.v("java.lang.Object");
}
if (sigType instanceof ArrayType) {
sigType = RefType.v("java.lang.Object");
}
if (t instanceof ArrayType) {
t = RefType.v("java.lang.Object");
}
FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy();
if (declaredType != null && !fastHierachy.canStoreType(t, declaredType)) {
return;
}
if (sigType != null && !fastHierachy.canStoreType(t, sigType)) {
return;
}
if (t instanceof RefType) {
SootMethod target = resolveNonSpecial((RefType) t, subSig, appOnly);
if (target != null) {
targets.add(target);
}
} else if (t instanceof AnySubType) {
RefType base = ((AnySubType) t).getBase();
/*
* Whenever any sub type of a specific type is considered as receiver for a method to call and the base type is an
* interface, calls to existing methods with matching signature (possible implementation of method to call) are also
* added. As Javas' subtyping allows contra-variance for return types and co-variance for parameters when overriding a
* method, these cases are also considered here.
*
* Example: Classes A, B (B sub type of A), interface I with method public A foo(B b); and a class C with method public
* B foo(A a) { ... }. The extended class hierarchy will contain C as possible implementation of I.
*
* Since Java has no multiple inheritance call by signature resolution is only activated if the base is an interface.
*/
if (options.library() == CGOptions.library_signature_resolution && base.getSootClass().isInterface()) {
resolveLibrarySignature(declaredType, sigType, subSig, container, targets, appOnly, base);
} else {
resolveAnySubType(declaredType, sigType, subSig, container, targets, appOnly, base);
}
} else if (t instanceof NullType) {
} else {
throw new RuntimeException("oops " + t);
}
}
public void resolveSuperType(Type t, Type declaredType, NumberedString subSig, ChunkedQueue<SootMethod> targets,
boolean appOnly) {
if (declaredType == null) {
return;
}
if (t == null) {
return;
}
if (declaredType instanceof ArrayType) {
declaredType = RefType.v("java.lang.Object");
}
if (t instanceof ArrayType) {
t = RefType.v("java.lang.Object");
}
if (declaredType instanceof RefType) {
RefType parent = (RefType)declaredType;
SootClass parentClass = parent.getSootClass();
RefType child;
SootClass childClass;
if (t instanceof AnySubType) {
child = ((AnySubType) t).getBase();
} else if (t instanceof RefType) {
child = (RefType)t;
} else {
return;
}
childClass = child.getSootClass();
FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy();
if (fastHierachy.canStoreClass(childClass,parentClass)) {
SootMethod target = resolveNonSpecial(child, subSig, appOnly);
if (target != null) {
targets.add(target);
}
}
}
}
protected void resolveAnySubType(Type declaredType, Type sigType, NumberedString subSig, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly, RefType base) {
FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy();
{
Set<Type> subTypes = baseToSubTypes.get(base);
if (subTypes != null && !subTypes.isEmpty()) {
for (final Type st : subTypes) {
resolve(st, declaredType, sigType, subSig, container, targets, appOnly);
}
return;
}
}
Set<Type> newSubTypes = new HashSet<>();
newSubTypes.add(base);
LinkedList<SootClass> worklist = new LinkedList<SootClass>();
HashSet<SootClass> workset = new HashSet<SootClass>();
FastHierarchy fh = fastHierachy;
SootClass cl = base.getSootClass();
if (workset.add(cl)) {
worklist.add(cl);
}
while (!worklist.isEmpty()) {
cl = worklist.removeFirst();
if (cl.isInterface()) {
for (Iterator<SootClass> cIt = fh.getAllImplementersOfInterface(cl).iterator(); cIt.hasNext();) {
final SootClass c = cIt.next();
if (workset.add(c)) {
worklist.add(c);
}
}
} else {
if (cl.isConcrete()) {
resolve(cl.getType(), declaredType, sigType, subSig, container, targets, appOnly);
newSubTypes.add(cl.getType());
}
for (Iterator<SootClass> cIt = fh.getSubclassesOf(cl).iterator(); cIt.hasNext();) {
final SootClass c = cIt.next();
if (workset.add(c)) {
worklist.add(c);
}
}
}
}
baseToSubTypes.putAll(base, newSubTypes);
}
protected void resolveLibrarySignature(Type declaredType, Type sigType, NumberedString subSig, SootMethod container,
ChunkedQueue<SootMethod> targets, boolean appOnly, RefType base) {
FastHierarchy fastHierachy = Scene.v().getOrMakeFastHierarchy();
assert (declaredType instanceof RefType);
Pair<Type, NumberedString> pair = new Pair<Type, NumberedString>(base, subSig);
{
Set<Pair<Type, NumberedString>> types = baseToPossibleSubTypes.get(pair);
// if this type and method has been resolved earlier we can
// just retrieve the previous result.
if (types != null) {
for (Pair<Type, NumberedString> tuple : types) {
Type st = tuple.getO1();
if (!fastHierachy.canStoreType(st, declaredType)) {
resolve(st, st, sigType, subSig, container, targets, appOnly);
} else {
resolve(st, declaredType, sigType, subSig, container, targets, appOnly);
}
}
return;
}
}
Set<Pair<Type, NumberedString>> types = new HashSet<Pair<Type, NumberedString>>();
// get return type; method name; parameter types
String[] split = subSig.getString().replaceAll("(.*) (.*)\\((.*)\\)", "$1;$2;$3").split(";");
Type declaredReturnType = Scene.v().getType(split[0]);
String declaredName = split[1];
List<Type> declaredParamTypes = new ArrayList<Type>();
// separate the parameter types
if (split.length == 3) {
for (String type : split[2].split(",")) {
declaredParamTypes.add(Scene.v().getType(type));
}
}
Chain<SootClass> classes = Scene.v().getClasses();
for (SootClass sc : classes) {
for (SootMethod sm : sc.getMethods()) {
if (!sm.isAbstract()) {
// method name has to match
if (!sm.getName().equals(declaredName)) {
continue;
}
// the return type has to be a the declared return
// type or a sub type of it
if (!fastHierachy.canStoreType(sm.getReturnType(), declaredReturnType)) {
continue;
}
List<Type> paramTypes = sm.getParameterTypes();
// method parameters have to match to the declared
// ones (same type or super type).
if (declaredParamTypes.size() != paramTypes.size()) {
continue;
}
boolean check = true;
for (int i = 0; i < paramTypes.size(); i++) {
if (!fastHierachy.canStoreType(declaredParamTypes.get(i), paramTypes.get(i))) {
check = false;
break;
}
}
if (check) {
Type st = sc.getType();
if (!fastHierachy.canStoreType(st, declaredType)) {
// final classes can not be extended and
// therefore not used in library client
if (!sc.isFinal()) {
NumberedString newSubSig = sm.getNumberedSubSignature();
resolve(st, st, sigType, newSubSig, container, targets, appOnly);
types.add(new Pair<Type, NumberedString>(st, newSubSig));
}
} else {
resolve(st, declaredType, sigType, subSig, container, targets, appOnly);
types.add(new Pair<Type, NumberedString>(st, subSig));
}
}
}
}
}
baseToPossibleSubTypes.putAll(pair, types);
}
public final NumberedString sigClinit = Scene.v().getSubSigNumberer().findOrAdd("void <clinit>()");
public final NumberedString sigStart = Scene.v().getSubSigNumberer().findOrAdd("void start()");
public final NumberedString sigRun = Scene.v().getSubSigNumberer().findOrAdd("void run()");
}
| Java |
// The libMesh Finite Element Library.
// Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 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
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#ifndef LIBMESH_CELL_INF_PRISM_H
#define LIBMESH_CELL_INF_PRISM_H
#include "libmesh/libmesh_config.h"
#ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
// Local includes
#include "libmesh/cell_inf.h"
namespace libMesh
{
/**
* The \p InfPrism is an element in 3D with 4 sides.
* The \f$ 5^{th} \f$ side is theoretically located at infinity,
* and therefore not accounted for.
* However, one could say that the \f$ 5^{th} \f$ side actually
* @e does exist in the mesh, since the outer nodes are located
* at a specific distance from the mesh origin (and therefore
* define a side). Still, this face is not to be used!
*/
class InfPrism : public InfCell
{
public:
/**
* Default infinite prism element, takes number of nodes and
* parent. Derived classes implement 'true' elements.
*/
InfPrism(const unsigned int nn, Elem* p, Node** nodelinkdata);
// /**
// * @returns 4 for the base \p s=0 and 2 for side faces.
// */
// unsigned int n_children_per_side(const unsigned int s) const;
/**
* @returns 4. Infinite elements have one side less
* than their conventional counterparts, since one
* side is supposed to be located at infinity.
*/
unsigned int n_sides() const { return 4; }
/**
* @returns 6. All infinite prisms (in our
* setting) have 6 vertices.
*/
unsigned int n_vertices() const { return 6; }
/**
* @returns 6. All infinite prismahedrals have 6 edges,
* 3 lying in the base, and 3 perpendicular to the base.
*/
unsigned int n_edges() const { return 6; }
/**
* @returns 4. All prisms have 4 faces.
*/
unsigned int n_faces() const { return 4; }
/**
* @returns 4
*/
unsigned int n_children() const { return 4; }
/*
* @returns true iff the specified child is on the
* specified side
*/
virtual bool is_child_on_side(const unsigned int c,
const unsigned int s) const;
/*
* @returns true iff the specified edge is on the specified side
*/
virtual bool is_edge_on_side(const unsigned int e,
const unsigned int s) const;
/**
* @returns an id associated with the \p s side of this element.
* The id is not necessariy unique, but should be close. This is
* particularly useful in the \p MeshBase::find_neighbors() routine.
*/
dof_id_type key (const unsigned int s) const;
/**
* @returns a primitive (3-noded) tri or (4-noded) infquad for
* face i.
*/
AutoPtr<Elem> side (const unsigned int i) const;
protected:
/**
* Data for links to parent/neighbor/interior_parent elements.
*/
Elem* _elemlinks_data[5+(LIBMESH_DIM>3)];
};
// ------------------------------------------------------------
// InfPrism class member functions
inline
InfPrism::InfPrism(const unsigned int nn, Elem* p, Node** nodelinkdata) :
InfCell(nn, InfPrism::n_sides(), p, _elemlinks_data, nodelinkdata)
{
}
// inline
// unsigned int InfPrism::n_children_per_side(const unsigned int s) const
// {
// libmesh_assert_less (s, this->n_sides());
// switch (s)
// {
// case 0:
// // every infinite prism has 4 children in the base side
// return 4;
// default:
// // on infinite faces (sides), only 2 children exist
// //
// // note that the face at infinity is already caught by the libmesh_assertion
// return 2;
// }
// }
} // namespace libMesh
#endif // ifdef LIBMESH_ENABLE_INFINITE_ELEMENTS
#endif // LIBMESH_CELL_INF_PRISM_H
| Java |
/*
Copyright (C) 2000-2001 by Jorrit Tyberghein
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; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csqsqrt.h"
#include "csgeom/box.h"
#include "csgeom/math.h"
#include "csgeom/math3d.h"
#include "csgeom/math2d.h"
#include "csgeom/transfrm.h"
#include "csgfx/renderbuffer.h"
#include "cstool/rbuflock.h"
#include "cstool/rviewclipper.h"
#include "csutil/scfarray.h"
#include "ivaria/reporter.h"
#include "iengine/movable.h"
#include "iengine/rview.h"
#include "ivideo/graph3d.h"
#include "ivideo/graph2d.h"
#include "ivideo/material.h"
#include "ivideo/rendermesh.h"
#include "iengine/material.h"
#include "iengine/camera.h"
#include "igeom/clip2d.h"
#include "iengine/engine.h"
#include "iengine/light.h"
#include "iutil/objreg.h"
#include "spr2d.h"
CS_PLUGIN_NAMESPACE_BEGIN(Spr2D)
{
CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObject);
CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObject::RenderBufferAccessor);
CS_LEAKGUARD_IMPLEMENT (csSprite2DMeshObjectFactory);
csSprite2DMeshObject::csSprite2DMeshObject (csSprite2DMeshObjectFactory* factory) :
scfImplementationType (this), uvani (0), vertices_dirty (true),
texels_dirty (true), colors_dirty (true), indicesSize ((size_t)-1),
logparent (0), factory (factory), initialized (false), current_lod (1),
current_features (0)
{
ifactory = scfQueryInterface<iMeshObjectFactory> (factory);
material = factory->GetMaterialWrapper ();
lighting = factory->HasLighting ();
MixMode = factory->GetMixMode ();
}
csSprite2DMeshObject::~csSprite2DMeshObject ()
{
delete uvani;
}
iColoredVertices* csSprite2DMeshObject::GetVertices ()
{
if (!scfVertices.IsValid())
return factory->GetVertices ();
return scfVertices;
}
csColoredVertices* csSprite2DMeshObject::GetCsVertices ()
{
if (!scfVertices.IsValid())
return factory->GetCsVertices ();
return &vertices;
}
void csSprite2DMeshObject::SetupObject ()
{
if (!initialized)
{
initialized = true;
float max_sq_dist = 0;
size_t i;
csColoredVertices* vertices = GetCsVertices ();
bbox_2d.StartBoundingBox((*vertices)[0].pos);
for (i = 0 ; i < vertices->GetSize () ; i++)
{
csSprite2DVertex& v = (*vertices)[i];
bbox_2d.AddBoundingVertexSmart(v.pos);
if (!lighting)
{
// If there is no lighting then we need to copy the color_init
// array to color.
v.color = (*vertices)[i].color_init;
v.color.Clamp (2, 2, 2);
}
float sqdist = v.pos.x*v.pos.x + v.pos.y*v.pos.y;
if (sqdist > max_sq_dist) max_sq_dist = sqdist;
}
radius = csQsqrt (max_sq_dist);
bufferHolder.AttachNew (new csRenderBufferHolder);
csRef<iRenderBufferAccessor> newAccessor;
newAccessor.AttachNew (new RenderBufferAccessor (this));
bufferHolder->SetAccessor (newAccessor, (uint32)CS_BUFFER_ALL_MASK);
svcontext.AttachNew (new csShaderVariableContext);
}
}
static csVector3 cam;
void csSprite2DMeshObject::UpdateLighting (
const csSafeCopyArray<csLightInfluence>& lights,
const csVector3& pos)
{
if (!lighting) return;
csColor color (0, 0, 0);
// @@@ GET AMBIENT
//csSector* sect = movable.GetSector (0);
//if (sect)
//{
//int r, g, b;
//sect->GetAmbientColor (r, g, b);
//color.Set (r / 128.0, g / 128.0, b / 128.0);
//}
int i;
int num_lights = (int)lights.GetSize ();
for (i = 0; i < num_lights; i++)
{
iLight* li = lights[i].light;
if (!li)
continue;
csColor light_color = li->GetColor ()
* (256. / CS_NORMAL_LIGHT_LEVEL);
float sq_light_radius = csSquare (li->GetCutoffDistance ());
// Compute light position.
csVector3 wor_light_pos = li->GetMovable ()->GetFullPosition ();
float wor_sq_dist =
csSquaredDist::PointPoint (wor_light_pos, pos);
if (wor_sq_dist >= sq_light_radius) continue;
float wor_dist = csQsqrt (wor_sq_dist);
float cosinus = 1.0f;
cosinus /= wor_dist;
light_color *= cosinus * li->GetBrightnessAtDistance (wor_dist);
color += light_color;
}
csColoredVertices* vertices = GetCsVertices ();
for (size_t j = 0 ; j < vertices->GetSize () ; j++)
{
(*vertices)[j].color = (*vertices)[j].color_init + color;
(*vertices)[j].color.Clamp (2, 2, 2);
}
colors_dirty = true;
}
void csSprite2DMeshObject::UpdateLighting (
const csSafeCopyArray<csLightInfluence>& lights,
iMovable* movable, csVector3 offset)
{
if (!lighting) return;
csVector3 pos = movable->GetFullPosition ();
UpdateLighting (lights, pos + offset);
}
csRenderMesh** csSprite2DMeshObject::GetRenderMeshes (int &n,
iRenderView* rview,
iMovable* movable,
uint32 frustum_mask,
csVector3 offset)
{
SetupObject ();
if (!material)
{
csReport (factory->object_reg, CS_REPORTER_SEVERITY_ERROR,
"crystalspace.mesh.sprite2d",
"Error! Trying to draw a sprite with no material!");
return 0;
}
iCamera* camera = rview->GetCamera ();
// Camera transformation for the single 'position' vector.
cam = rview->GetCamera ()->GetTransform ().Other2This (
movable->GetFullPosition () + offset);
if (cam.z < SMALL_Z)
{
n = 0;
return 0;
}
if (factory->light_mgr)
{
csSafeCopyArray<csLightInfluence> lightInfluences;
scfArrayWrap<iLightInfluenceArray, csSafeCopyArray<csLightInfluence> >
relevantLights (lightInfluences); //Yes, know, its on the stack...
factory->light_mgr->GetRelevantLights (logparent, &relevantLights, -1);
UpdateLighting (lightInfluences, movable, offset);
}
csReversibleTransform temp = camera->GetTransform ();
if (!movable->IsFullTransformIdentity ())
temp /= movable->GetFullTransform ();
int clip_portal, clip_plane, clip_z_plane;
CS::RenderViewClipper::CalculateClipSettings (rview->GetRenderContext (),
frustum_mask, clip_portal, clip_plane, clip_z_plane);
csReversibleTransform tr_o2c;
tr_o2c.SetO2TTranslation (-temp.Other2This (offset));
bool meshCreated;
csRenderMesh*& rm = rmHolder.GetUnusedMesh (meshCreated,
rview->GetCurrentFrameNumber ());
if (meshCreated)
{
rm->meshtype = CS_MESHTYPE_TRIANGLEFAN;
rm->buffers = bufferHolder;
rm->variablecontext = svcontext;
rm->geometryInstance = this;
}
rm->material = material;//Moved this statement out of the above 'if'
//to make the change of the material possible at any time
//(thru a call to either iSprite2DState::SetMaterialWrapper () or
//csSprite2DMeshObject::SetMaterialWrapper (). Luca
rm->mixmode = MixMode;
rm->clip_portal = clip_portal;
rm->clip_plane = clip_plane;
rm->clip_z_plane = clip_z_plane;
rm->do_mirror = false/* camera->IsMirrored () */;
/*
Force to false as the front-face culling will let the sprite
disappear.
*/
rm->indexstart = 0;
rm->worldspace_origin = movable->GetFullPosition ();
rm->object2world = tr_o2c.GetInverse () * camera->GetTransform ();
rm->bbox = GetObjectBoundingBox();
rm->indexend = (uint)GetCsVertices ()->GetSize ();
n = 1;
return &rm;
}
void csSprite2DMeshObject::PreGetBuffer (csRenderBufferHolder* holder, csRenderBufferName buffer)
{
if (!holder) return;
csColoredVertices* vertices = GetCsVertices ();
if (buffer == CS_BUFFER_INDEX)
{
size_t indexSize = vertices->GetSize ();
if (!index_buffer.IsValid() ||
(indicesSize != indexSize))
{
index_buffer = csRenderBuffer::CreateIndexRenderBuffer (
indexSize, CS_BUF_DYNAMIC,
CS_BUFCOMP_UNSIGNED_INT, 0, vertices->GetSize () - 1);
holder->SetRenderBuffer (CS_BUFFER_INDEX, index_buffer);
csRenderBufferLock<uint> indexLock (index_buffer);
uint* ptr = indexLock;
for (size_t i = 0; i < vertices->GetSize (); i++)
{
*ptr++ = (uint)i;
}
indicesSize = indexSize;
}
}
else if (buffer == CS_BUFFER_TEXCOORD0)
{
if (texels_dirty)
{
int texels_count;
const csVector2 *uvani_uv = 0;
if (!uvani)
texels_count = (int)vertices->GetSize ();
else
uvani_uv = uvani->GetVertices (texels_count);
size_t texelSize = texels_count;
if (!texel_buffer.IsValid() || (texel_buffer->GetSize()
!= texelSize * sizeof(float) * 2))
{
texel_buffer = csRenderBuffer::CreateRenderBuffer (
texelSize, CS_BUF_STATIC, CS_BUFCOMP_FLOAT, 2);
holder->SetRenderBuffer (CS_BUFFER_TEXCOORD0, texel_buffer);
}
csRenderBufferLock<csVector2> texelLock (texel_buffer);
for (size_t i = 0; i < (size_t)texels_count; i++)
{
csVector2& v = texelLock[i];
if (!uvani)
{
v.x = (*vertices)[i].u;
v.y = (*vertices)[i].v;
}
else
{
v.x = uvani_uv[i].x;
v.y = uvani_uv[i].y;
}
}
texels_dirty = false;
}
}
else if (buffer == CS_BUFFER_COLOR)
{
if (colors_dirty)
{
size_t color_size = vertices->GetSize ();
if (!color_buffer.IsValid() || (color_buffer->GetSize()
!= color_size * sizeof(float) * 2))
{
color_buffer = csRenderBuffer::CreateRenderBuffer (
color_size, CS_BUF_STATIC,
CS_BUFCOMP_FLOAT, 3);
holder->SetRenderBuffer (CS_BUFFER_COLOR, color_buffer);
}
csRenderBufferLock<csColor> colorLock (color_buffer);
for (size_t i = 0; i < vertices->GetSize (); i++)
{
colorLock[i] = (*vertices)[i].color;
}
colors_dirty = false;
}
}
else if (buffer == CS_BUFFER_POSITION)
{
if (vertices_dirty)
{
size_t vertices_size = vertices->GetSize ();
if (!vertex_buffer.IsValid() || (vertex_buffer->GetSize()
!= vertices_size * sizeof(float) * 3))
{
vertex_buffer = csRenderBuffer::CreateRenderBuffer (
vertices_size, CS_BUF_STATIC,
CS_BUFCOMP_FLOAT, 3);
holder->SetRenderBuffer (CS_BUFFER_POSITION, vertex_buffer);
}
csRenderBufferLock<csVector3> vertexLock (vertex_buffer);
for (size_t i = 0; i < vertices->GetSize (); i++)
{
vertexLock[i].Set ((*vertices)[i].pos.x, (*vertices)[i].pos.y, 0.0f);
}
vertices_dirty = false;
}
}
}
const csBox3& csSprite2DMeshObject::GetObjectBoundingBox ()
{
SetupObject ();
obj_bbox.Set (-radius, radius);
return obj_bbox;
}
void csSprite2DMeshObject::SetObjectBoundingBox (const csBox3&)
{
// @@@ TODO
}
void csSprite2DMeshObject::HardTransform (const csReversibleTransform& t)
{
(void)t;
//@@@ TODO
}
void csSprite2DMeshObject::CreateRegularVertices (int n, bool setuv)
{
double angle_inc = TWO_PI / n;
double angle = 0.0;
csColoredVertices* vertices = GetCsVertices ();
vertices->SetSize (n);
size_t i;
for (i = 0; i < vertices->GetSize (); i++, angle += angle_inc)
{
(*vertices) [i].pos.y = cos (angle);
(*vertices) [i].pos.x = sin (angle);
if (setuv)
{
// reuse sin/cos values and scale to [0..1]
(*vertices) [i].u = (*vertices) [i].pos.x / 2.0f + 0.5f;
(*vertices) [i].v = (*vertices) [i].pos.y / 2.0f + 0.5f;
}
(*vertices) [i].color.Set (1, 1, 1);
(*vertices) [i].color_init.Set (1, 1, 1);
}
vertices_dirty = true;
texels_dirty = true;
colors_dirty = true;
ShapeChanged ();
}
void csSprite2DMeshObject::NextFrame (csTicks current_time,
const csVector3& /*pos*/, uint /*currentFrame*/)
{
if (uvani && !uvani->halted)
{
int old_frame_index = uvani->frameindex;
uvani->Advance (current_time);
texels_dirty |= (old_frame_index != uvani->frameindex);
}
}
void csSprite2DMeshObject::UpdateLighting (
const csSafeCopyArray<csLightInfluence>& lights,
const csReversibleTransform& transform)
{
csVector3 new_pos = transform.This2Other (part_pos);
UpdateLighting (lights, new_pos);
}
void csSprite2DMeshObject::AddColor (const csColor& col)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color_init += col;
if (!lighting)
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color = vertices->Get (i).color_init;
colors_dirty = true;
}
bool csSprite2DMeshObject::SetColor (const csColor& col)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color_init = col;
if (!lighting)
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).color = col;
colors_dirty = true;
return true;
}
void csSprite2DMeshObject::ScaleBy (float factor)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).pos *= factor;
vertices_dirty = true;
ShapeChanged ();
}
void csSprite2DMeshObject::Rotate (float angle)
{
iColoredVertices* vertices = GetVertices ();
size_t i;
for (i = 0 ; i < vertices->GetSize(); i++)
vertices->Get (i).pos.Rotate (angle);
vertices_dirty = true;
ShapeChanged ();
}
void csSprite2DMeshObject::SetUVAnimation (const char *name,
int style, bool loop)
{
if (name)
{
iSprite2DUVAnimation *ani = factory->GetUVAnimation (name);
if (ani && ani->GetFrameCount ())
{
uvani = new uvAnimationControl ();
uvani->ani = ani;
uvani->last_time = 0;
uvani->frameindex = 0;
uvani->framecount = ani->GetFrameCount ();
uvani->frame = ani->GetFrame (0);
uvani->style = style;
uvani->counter = 0;
uvani->loop = loop;
uvani->halted = false;
}
}
else
{
// stop animation and show the normal texture
delete uvani;
uvani = 0;
}
}
void csSprite2DMeshObject::StopUVAnimation (int idx)
{
if (uvani)
{
if (idx != -1)
{
uvani->frameindex = csMin (csMax (idx, 0), uvani->framecount-1);
uvani->frame = uvani->ani->GetFrame (uvani->frameindex);
}
uvani->halted = true;
}
}
void csSprite2DMeshObject::PlayUVAnimation (int idx, int style, bool loop)
{
if (uvani)
{
if (idx != -1)
{
uvani->frameindex = csMin (csMax (idx, 0), uvani->framecount-1);
uvani->frame = uvani->ani->GetFrame (uvani->frameindex);
}
uvani->halted = false;
uvani->counter = 0;
uvani->last_time = 0;
uvani->loop = loop;
uvani->style = style;
}
}
int csSprite2DMeshObject::GetUVAnimationCount () const
{
return factory->GetUVAnimationCount ();
}
iSprite2DUVAnimation *csSprite2DMeshObject::CreateUVAnimation ()
{
return factory->CreateUVAnimation ();
}
void csSprite2DMeshObject::RemoveUVAnimation (
iSprite2DUVAnimation *anim)
{
factory->RemoveUVAnimation (anim);
}
iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation (
const char *name) const
{
return factory->GetUVAnimation (name);
}
iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation (
int idx) const
{
return factory->GetUVAnimation (idx);
}
iSprite2DUVAnimation *csSprite2DMeshObject::GetUVAnimation (
int idx, int &style, bool &loop) const
{
style = uvani->style;
loop = uvani->loop;
return factory->GetUVAnimation (idx);
}
void csSprite2DMeshObject::EnsureVertexCopy ()
{
if (!scfVertices.IsValid())
{
scfVertices.AttachNew (new scfArrayWrap<iColoredVertices,
csColoredVertices> (vertices));
vertices = *(factory->GetCsVertices());
}
}
void csSprite2DMeshObject::uvAnimationControl::Advance (csTicks current_time)
{
int oldframeindex = frameindex;
// the goal is to find the next frame to show
if (style < 0)
{ // every (-1*style)-th frame show a new pic
counter--;
if (counter < style)
{
counter = 0;
frameindex++;
if (frameindex == framecount)
{
if (loop)
frameindex = 0;
else
{
frameindex = framecount-1;
halted = true;
}
}
}
}
else if (style > 0)
{ // skip to next frame every <style> millisecond
if (last_time == 0)
last_time = current_time;
counter += (current_time - last_time);
last_time = current_time;
while (counter > style)
{
counter -= style;
frameindex++;
if (frameindex == framecount)
{
if (loop)
frameindex = 0;
else
{
frameindex = framecount-1;
halted = true;
}
}
}
}
else
{ // style == 0 -> use time indices attached to the frames
if (last_time == 0)
last_time = current_time;
while (frame->GetDuration () + last_time < current_time)
{
frameindex++;
if (frameindex == framecount)
{
if (loop)
{
frameindex = 0;
}
else
{
frameindex = framecount-1;
halted = true;
break;
}
}
}
last_time += frame->GetDuration ();
frame = ani->GetFrame (frameindex);
}
if (oldframeindex != frameindex)
frame = ani->GetFrame (frameindex);
}
const csVector2 *csSprite2DMeshObject::uvAnimationControl::GetVertices (
int &num)
{
num = frame->GetUVCount ();
return frame->GetUVCoo ();
}
// The hit beam methods in sprite2d make a couple of small presumptions.
// 1) The sprite is always facing the start of the beam.
// 2) Since it is always facing the beam, only one side
// of its bounding box can be hit (if at all).
void csSprite2DMeshObject::CheckBeam (const csVector3& /*start*/,
const csVector3& pl, float sqr, csMatrix3& o2t)
{
// This method is an optimized version of LookAt() based on
// the presumption that the up vector is always (0,1,0).
// This is used to create a transform to move the intersection
// to the sprites vector space, then it is tested against the 2d
// coords, which are conveniently located at z=0.
// The transformation matrix is stored and used again if the
// start vector for the beam is in the same position. MHV.
csVector3 pl2 = pl * csQisqrt (sqr);
csVector3 v1( pl2.z, 0, -pl2.x);
sqr = v1*v1;
v1 *= csQisqrt(sqr);
csVector3 v2(pl2.y * v1.z, pl2.z * v1.x - pl2.x * v1.z, -pl2.y * v1.x);
o2t.Set (v1.x, v2.x, pl2.x,
v1.y, v2.y, pl2.y,
v1.z, v2.z, pl2.z);
}
bool csSprite2DMeshObject::HitBeamOutline(const csVector3& start,
const csVector3& end, csVector3& isect, float* pr)
{
csVector2 cen = bbox_2d.GetCenter();
csVector3 pl = start - csVector3(cen.x, cen.y, 0);
float sqr = pl * pl;
if (sqr < SMALL_EPSILON) return false; // Too close, Cannot intersect
float dist;
csIntersect3::SegmentPlane(start, end, pl, 0, isect, dist);
if (pr) { *pr = dist; }
csMatrix3 o2t;
CheckBeam (start, pl, sqr, o2t);
csVector3 r = o2t * isect;
csColoredVertices* vertices = GetCsVertices ();
int trail, len = (int)vertices->GetSize ();
trail = len - 1;
csVector2 isec(r.x, r.y);
int i;
for (i = 0; i < len; trail = i++)
{
if (csMath2::WhichSide2D(isec, (*vertices)[trail].pos, (*vertices)[i].pos) > 0)
return false;
}
return true;
}
bool csSprite2DMeshObject::HitBeamObject (const csVector3& start, const csVector3& end,
csVector3& isect, float* pr, int* polygon_idx,
iMaterialWrapper** material, bool bf)
{
if (material) *material = csSprite2DMeshObject::material;
if (polygon_idx) *polygon_idx = -1;
return HitBeamOutline (start, end, isect, pr);
}
//----------------------------------------------------------------------
csSprite2DMeshObjectFactory::csSprite2DMeshObjectFactory (iMeshObjectType* pParent,
iObjectRegistry* object_reg) : scfImplementationType (this, pParent),
material (0), logparent (0), spr2d_type (pParent), MixMode (0),
lighting (true), object_reg (object_reg)
{
light_mgr = csQueryRegistry<iLightManager> (object_reg);
g3d = csQueryRegistry<iGraphics3D> (object_reg);
scfVertices.AttachNew (new scfArrayWrap<iColoredVertices,
csColoredVertices> (vertices));
ax = -10;
}
csSprite2DMeshObjectFactory::~csSprite2DMeshObjectFactory ()
{
}
csPtr<iMeshObject> csSprite2DMeshObjectFactory::NewInstance ()
{
csRef<csSprite2DMeshObject> cm;
cm.AttachNew (new csSprite2DMeshObject (this));
csRef<iMeshObject> im (scfQueryInterface<iMeshObject> (cm));
return csPtr<iMeshObject> (im);
}
//----------------------------------------------------------------------
SCF_IMPLEMENT_FACTORY (csSprite2DMeshObjectType)
csSprite2DMeshObjectType::csSprite2DMeshObjectType (iBase* pParent) :
scfImplementationType (this, pParent)
{
}
csSprite2DMeshObjectType::~csSprite2DMeshObjectType ()
{
}
csPtr<iMeshObjectFactory> csSprite2DMeshObjectType::NewFactory ()
{
csRef<csSprite2DMeshObjectFactory> cm;
cm.AttachNew (new csSprite2DMeshObjectFactory (this,
object_reg));
csRef<iMeshObjectFactory> ifact =
scfQueryInterface<iMeshObjectFactory> (cm);
return csPtr<iMeshObjectFactory> (ifact);
}
bool csSprite2DMeshObjectType::Initialize (iObjectRegistry* object_reg)
{
csSprite2DMeshObjectType::object_reg = object_reg;
return true;
}
}
CS_PLUGIN_NAMESPACE_END(Spr2D)
| Java |
/* Copyright (C) 1991,92,96,97,99,2000,2001,2009 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#ifndef _STRINGS_H
#define _STRINGS_H 1
/* We don't need and should not read this file if <string.h> was already
read. The one exception being that if __USE_BSD isn't defined, then
these aren't defined in string.h, so we need to define them here. */
/* keep this file in sync w/ string.h, the glibc version is out of date */
#if !defined _STRING_H || !defined __USE_BSD
# include <features.h>
# define __need_size_t
# include <stddef.h>
__BEGIN_DECLS
# ifdef __UCLIBC_SUSV3_LEGACY__
/* Copy N bytes of SRC to DEST (like memmove, but args reversed). */
extern void bcopy (__const void *__src, void *__dest, size_t __n)
__THROW __nonnull ((1, 2));
/* Set N bytes of S to 0. */
extern void bzero (void *__s, size_t __n) __THROW __nonnull ((1));
/* Compare N bytes of S1 and S2 (same as memcmp). */
extern int bcmp (__const void *__s1, __const void *__s2, size_t __n)
__THROW __attribute_pure__ __nonnull ((1, 2));
/* Find the first occurrence of C in S (same as strchr). */
extern char *index (__const char *__s, int __c)
__THROW __attribute_pure__ __nonnull ((1));
/* Find the last occurrence of C in S (same as strrchr). */
extern char *rindex (__const char *__s, int __c)
__THROW __attribute_pure__ __nonnull ((1));
# else
# ifdef __UCLIBC_SUSV3_LEGACY_MACROS__
/* bcopy/bzero/bcmp/index/rindex are marked LEGACY in SuSv3.
* They are replaced as proposed by SuSv3. Don't sync this part
* with glibc and keep it in sync with string.h. */
# define bcopy(src,dest,n) (memmove((dest), (src), (n)), (void) 0)
# define bzero(s,n) (memset((s), '\0', (n)), (void) 0)
# define bcmp(s1,s2,n) memcmp((s1), (s2), (size_t)(n))
# define index(s,c) strchr((s), (c))
# define rindex(s,c) strrchr((s), (c))
# endif
# endif
/* Return the position of the first bit set in I, or 0 if none are set.
The least-significant bit is position 1, the most-significant 32. */
extern int ffs (int __i) __THROW __attribute__ ((__const__));
libc_hidden_proto(ffs)
/* The following two functions are non-standard but necessary for non-32 bit
platforms. */
# ifdef __USE_GNU
extern int ffsl (long int __l) __THROW __attribute__ ((__const__));
# ifdef __GNUC__
__extension__ extern int ffsll (long long int __ll)
__THROW __attribute__ ((__const__));
# endif
# endif
/* Compare S1 and S2, ignoring case. */
extern int strcasecmp (__const char *__s1, __const char *__s2)
__THROW __attribute_pure__ __nonnull ((1, 2));
libc_hidden_proto(strcasecmp)
/* Compare no more than N chars of S1 and S2, ignoring case. */
extern int strncasecmp (__const char *__s1, __const char *__s2, size_t __n)
__THROW __attribute_pure__ __nonnull ((1, 2));
libc_hidden_proto(strncasecmp)
#if defined __USE_XOPEN2K8 && defined __UCLIBC_HAS_XLOCALE__
/* The following functions are equivalent to the both above but they
take the locale they use for the collation as an extra argument.
This is not standardsized but something like will come. */
# include <xlocale.h>
/* Again versions of a few functions which use the given locale instead
of the global one. */
extern int strcasecmp_l (__const char *__s1, __const char *__s2,
__locale_t __loc)
__THROW __attribute_pure__ __nonnull ((1, 2, 3));
libc_hidden_proto(strcasecmp_l)
extern int strncasecmp_l (__const char *__s1, __const char *__s2,
size_t __n, __locale_t __loc)
__THROW __attribute_pure__ __nonnull ((1, 2, 4));
libc_hidden_proto(strncasecmp_l)
#endif
__END_DECLS
#ifdef _LIBC
/* comment is wrong and will face this, when HAS_GNU option will be added
* header is SuSv standard */
#error "<strings.h> should not be included from libc."
#endif
#endif /* string.h */
#endif /* strings.h */
| Java |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2021, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.wildfly.clustering.infinispan.spi.persistence.sifs;
import static org.infinispan.configuration.cache.AbstractStoreConfiguration.SEGMENTED;
import static org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration.COMPACTION_THRESHOLD;
import static org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration.OPEN_FILES_LIMIT;
import org.infinispan.commons.configuration.attributes.Attribute;
import org.infinispan.configuration.cache.AbstractStoreConfigurationBuilder;
import org.infinispan.configuration.cache.AsyncStoreConfiguration;
import org.infinispan.configuration.cache.PersistenceConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalStateConfiguration;
import org.infinispan.persistence.PersistenceUtil;
import org.infinispan.persistence.sifs.Log;
import org.infinispan.persistence.sifs.NonBlockingSoftIndexFileStore;
import org.infinispan.persistence.sifs.configuration.DataConfiguration;
import org.infinispan.persistence.sifs.configuration.DataConfigurationBuilder;
import org.infinispan.persistence.sifs.configuration.IndexConfiguration;
import org.infinispan.persistence.sifs.configuration.IndexConfigurationBuilder;
import org.infinispan.util.logging.LogFactory;
/**
* Workaround for ISPN-13605.
* @author Paul Ferraro
*/
public class SoftIndexFileStoreConfigurationBuilder extends AbstractStoreConfigurationBuilder<SoftIndexFileStoreConfiguration, SoftIndexFileStoreConfigurationBuilder> {
private static final Log LOG = LogFactory.getLog(SoftIndexFileStoreConfigurationBuilder.class, Log.class);
protected final IndexConfigurationBuilder index = new IndexConfigurationBuilder();
protected final DataConfigurationBuilder data = new DataConfigurationBuilder();
public SoftIndexFileStoreConfigurationBuilder(PersistenceConfigurationBuilder builder) {
super(builder, org.infinispan.persistence.sifs.configuration.SoftIndexFileStoreConfiguration.attributeDefinitionSet(), AsyncStoreConfiguration.attributeDefinitionSet());
}
/**
* The path where the Soft-Index store will keep its data files. Under this location the store will create
* a directory named after the cache name, under which a <code>data</code> directory will be created.
*
* The default behaviour is to use the {@link GlobalStateConfiguration#persistentLocation()}.
*/
public SoftIndexFileStoreConfigurationBuilder dataLocation(String dataLocation) {
this.data.dataLocation(dataLocation);
return this;
}
/**
* The path where the Soft-Index store will keep its index files. Under this location the store will create
* a directory named after the cache name, under which a <code>index</code> directory will be created.
*
* The default behaviour is to use the {@link GlobalStateConfiguration#persistentLocation()}.
*/
public SoftIndexFileStoreConfigurationBuilder indexLocation(String indexLocation) {
this.index.indexLocation(indexLocation);
return this;
}
/**
* Number of index segment files. Increasing this value improves throughput but requires more threads to be spawned.
* <p>
* Defaults to <code>16</code>.
*/
public SoftIndexFileStoreConfigurationBuilder indexSegments(int indexSegments) {
this.index.indexSegments(indexSegments);
return this;
}
/**
* Sets the maximum size of single data file with entries, in bytes.
*
* Defaults to <code>16777216</code> (16MB).
*/
public SoftIndexFileStoreConfigurationBuilder maxFileSize(int maxFileSize) {
this.data.maxFileSize(maxFileSize);
return this;
}
/**
* If the size of the node (continuous block on filesystem used in index implementation) drops below this threshold,
* the node will try to balance its size with some neighbour node, possibly causing join of multiple nodes.
*
* Defaults to <code>0</code>.
*/
public SoftIndexFileStoreConfigurationBuilder minNodeSize(int minNodeSize) {
this.index.minNodeSize(minNodeSize);
return this;
}
/**
* Max size of node (continuous block on filesystem used in index implementation), in bytes.
*
* Defaults to <code>4096</code>.
*/
public SoftIndexFileStoreConfigurationBuilder maxNodeSize(int maxNodeSize) {
this.index.maxNodeSize(maxNodeSize);
return this;
}
/**
* Sets the maximum number of entry writes that are waiting to be written to the index, per index segment.
*
* Defaults to <code>1000</code>.
*/
public SoftIndexFileStoreConfigurationBuilder indexQueueLength(int indexQueueLength) {
this.index.indexQueueLength(indexQueueLength);
return this;
}
/**
* Sets whether writes shoud wait to be fsynced to disk.
*
* Defaults to <code>false</code>.
*/
public SoftIndexFileStoreConfigurationBuilder syncWrites(boolean syncWrites) {
this.data.syncWrites(syncWrites);
return this;
}
/**
* Sets the maximum number of open files.
*
* Defaults to <code>1000</code>.
*/
public SoftIndexFileStoreConfigurationBuilder openFilesLimit(int openFilesLimit) {
this.attributes.attribute(OPEN_FILES_LIMIT).set(openFilesLimit);
return this;
}
/**
* If the amount of unused space in some data file gets above this threshold, the file is compacted - entries from that file are copied to a new file and the old file is deleted.
*
* Defaults to <code>0.5</code> (50%).
*/
public SoftIndexFileStoreConfigurationBuilder compactionThreshold(double compactionThreshold) {
this.attributes.attribute(COMPACTION_THRESHOLD).set(compactionThreshold);
return this;
}
@Override
public SoftIndexFileStoreConfiguration create() {
return new SoftIndexFileStoreConfiguration(this.attributes.protect(), this.async.create(), this.index.create(), this.data.create());
}
@Override
public SoftIndexFileStoreConfigurationBuilder read(SoftIndexFileStoreConfiguration template) {
super.read(template);
this.index.read(template.index());
this.data.read(template.data());
return this;
}
@Override
public SoftIndexFileStoreConfigurationBuilder self() {
return this;
}
@Override
protected void validate (boolean skipClassChecks) {
Attribute<Boolean> segmentedAttribute = this.attributes.attribute(SEGMENTED);
if (segmentedAttribute.isModified() && !segmentedAttribute.get()) {
throw org.infinispan.util.logging.Log.CONFIG.storeRequiresBeingSegmented(NonBlockingSoftIndexFileStore.class.getSimpleName());
}
super.validate(skipClassChecks);
this.index.validate();
double compactionThreshold = this.attributes.attribute(COMPACTION_THRESHOLD).get();
if (compactionThreshold <= 0 || compactionThreshold > 1) {
throw LOG.invalidCompactionThreshold(compactionThreshold);
}
}
@Override
public void validate(GlobalConfiguration globalConfig) {
PersistenceUtil.validateGlobalStateStoreLocation(globalConfig, NonBlockingSoftIndexFileStore.class.getSimpleName(),
this.data.attributes().attribute(DataConfiguration.DATA_LOCATION),
this.index.attributes().attribute(IndexConfiguration.INDEX_LOCATION));
super.validate(globalConfig);
}
@Override
public String toString () {
return String.format("SoftIndexFileStoreConfigurationBuilder{index=%s, data=%s, attributes=%s, async=%s}", this.index, this.data, this.attributes, this.async);
}
}
| Java |
/*
* qemu_domain.h: QEMU domain private state
*
* Copyright (C) 2006-2011 Red Hat, Inc.
* Copyright (C) 2006 Daniel P. Berrange
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Daniel P. Berrange <berrange@redhat.com>
*/
#include <config.h>
#include "qemu_domain.h"
#include "qemu_command.h"
#include "memory.h"
#include "logging.h"
#include "virterror_internal.h"
#include "c-ctype.h"
#include <sys/time.h>
#include <libxml/xpathInternals.h>
#define VIR_FROM_THIS VIR_FROM_QEMU
#define QEMU_NAMESPACE_HREF "http://libvirt.org/schemas/domain/qemu/1.0"
#define timeval_to_ms(tv) (((tv).tv_sec * 1000ull) + ((tv).tv_usec / 1000))
static void *qemuDomainObjPrivateAlloc(void)
{
qemuDomainObjPrivatePtr priv;
if (VIR_ALLOC(priv) < 0)
return NULL;
return priv;
}
static void qemuDomainObjPrivateFree(void *data)
{
qemuDomainObjPrivatePtr priv = data;
qemuDomainPCIAddressSetFree(priv->pciaddrs);
virDomainChrSourceDefFree(priv->monConfig);
VIR_FREE(priv->vcpupids);
/* This should never be non-NULL if we get here, but just in case... */
if (priv->mon) {
VIR_ERROR0(_("Unexpected QEMU monitor still active during domain deletion"));
qemuMonitorClose(priv->mon);
}
VIR_FREE(priv);
}
static int qemuDomainObjPrivateXMLFormat(virBufferPtr buf, void *data)
{
qemuDomainObjPrivatePtr priv = data;
const char *monitorpath;
/* priv->monitor_chr is set only for qemu */
if (priv->monConfig) {
switch (priv->monConfig->type) {
case VIR_DOMAIN_CHR_TYPE_UNIX:
monitorpath = priv->monConfig->data.nix.path;
break;
default:
case VIR_DOMAIN_CHR_TYPE_PTY:
monitorpath = priv->monConfig->data.file.path;
break;
}
virBufferEscapeString(buf, " <monitor path='%s'", monitorpath);
if (priv->monJSON)
virBufferAddLit(buf, " json='1'");
virBufferVSprintf(buf, " type='%s'/>\n",
virDomainChrTypeToString(priv->monConfig->type));
}
if (priv->nvcpupids) {
int i;
virBufferAddLit(buf, " <vcpus>\n");
for (i = 0 ; i < priv->nvcpupids ; i++) {
virBufferVSprintf(buf, " <vcpu pid='%d'/>\n", priv->vcpupids[i]);
}
virBufferAddLit(buf, " </vcpus>\n");
}
return 0;
}
static int qemuDomainObjPrivateXMLParse(xmlXPathContextPtr ctxt, void *data)
{
qemuDomainObjPrivatePtr priv = data;
char *monitorpath;
char *tmp;
int n, i;
xmlNodePtr *nodes = NULL;
if (VIR_ALLOC(priv->monConfig) < 0) {
virReportOOMError();
goto error;
}
if (!(monitorpath =
virXPathString("string(./monitor[1]/@path)", ctxt))) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("no monitor path"));
goto error;
}
tmp = virXPathString("string(./monitor[1]/@type)", ctxt);
if (tmp)
priv->monConfig->type = virDomainChrTypeFromString(tmp);
else
priv->monConfig->type = VIR_DOMAIN_CHR_TYPE_PTY;
VIR_FREE(tmp);
if (virXPathBoolean("count(./monitor[@json = '1']) > 0", ctxt)) {
priv->monJSON = 1;
} else {
priv->monJSON = 0;
}
switch (priv->monConfig->type) {
case VIR_DOMAIN_CHR_TYPE_PTY:
priv->monConfig->data.file.path = monitorpath;
break;
case VIR_DOMAIN_CHR_TYPE_UNIX:
priv->monConfig->data.nix.path = monitorpath;
break;
default:
VIR_FREE(monitorpath);
qemuReportError(VIR_ERR_INTERNAL_ERROR,
_("unsupported monitor type '%s'"),
virDomainChrTypeToString(priv->monConfig->type));
goto error;
}
n = virXPathNodeSet("./vcpus/vcpu", ctxt, &nodes);
if (n < 0)
goto error;
if (n) {
priv->nvcpupids = n;
if (VIR_REALLOC_N(priv->vcpupids, priv->nvcpupids) < 0) {
virReportOOMError();
goto error;
}
for (i = 0 ; i < n ; i++) {
char *pidstr = virXMLPropString(nodes[i], "pid");
if (!pidstr)
goto error;
if (virStrToLong_i(pidstr, NULL, 10, &(priv->vcpupids[i])) < 0) {
VIR_FREE(pidstr);
goto error;
}
VIR_FREE(pidstr);
}
VIR_FREE(nodes);
}
return 0;
error:
virDomainChrSourceDefFree(priv->monConfig);
priv->monConfig = NULL;
VIR_FREE(nodes);
return -1;
}
static void
qemuDomainDefNamespaceFree(void *nsdata)
{
qemuDomainCmdlineDefPtr cmd = nsdata;
unsigned int i;
if (!cmd)
return;
for (i = 0; i < cmd->num_args; i++)
VIR_FREE(cmd->args[i]);
for (i = 0; i < cmd->num_env; i++) {
VIR_FREE(cmd->env_name[i]);
VIR_FREE(cmd->env_value[i]);
}
VIR_FREE(cmd->args);
VIR_FREE(cmd->env_name);
VIR_FREE(cmd->env_value);
VIR_FREE(cmd);
}
static int
qemuDomainDefNamespaceParse(xmlDocPtr xml,
xmlNodePtr root,
xmlXPathContextPtr ctxt,
void **data)
{
qemuDomainCmdlineDefPtr cmd = NULL;
xmlNsPtr ns;
xmlNodePtr *nodes = NULL;
int n, i;
ns = xmlSearchNs(xml, root, BAD_CAST "qemu");
if (!ns)
/* this is fine; it just means there was no qemu namespace listed */
return 0;
if (STRNEQ((const char *)ns->href, QEMU_NAMESPACE_HREF)) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
_("Found namespace '%s' doesn't match expected '%s'"),
ns->href, QEMU_NAMESPACE_HREF);
return -1;
}
if (xmlXPathRegisterNs(ctxt, ns->prefix, ns->href) < 0) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
_("Failed to register xml namespace '%s'"), ns->href);
return -1;
}
if (VIR_ALLOC(cmd) < 0) {
virReportOOMError();
return -1;
}
/* first handle the extra command-line arguments */
n = virXPathNodeSet("./qemu:commandline/qemu:arg", ctxt, &nodes);
if (n < 0)
/* virXPathNodeSet already set the error */
goto error;
if (n && VIR_ALLOC_N(cmd->args, n) < 0)
goto no_memory;
for (i = 0; i < n; i++) {
cmd->args[cmd->num_args] = virXMLPropString(nodes[i], "value");
if (cmd->args[cmd->num_args] == NULL) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("No qemu command-line argument specified"));
goto error;
}
cmd->num_args++;
}
VIR_FREE(nodes);
/* now handle the extra environment variables */
n = virXPathNodeSet("./qemu:commandline/qemu:env", ctxt, &nodes);
if (n < 0)
/* virXPathNodeSet already set the error */
goto error;
if (n && VIR_ALLOC_N(cmd->env_name, n) < 0)
goto no_memory;
if (n && VIR_ALLOC_N(cmd->env_value, n) < 0)
goto no_memory;
for (i = 0; i < n; i++) {
char *tmp;
tmp = virXMLPropString(nodes[i], "name");
if (tmp == NULL) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("No qemu environment name specified"));
goto error;
}
if (tmp[0] == '\0') {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("Empty qemu environment name specified"));
goto error;
}
if (!c_isalpha(tmp[0]) && tmp[0] != '_') {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("Invalid environment name, it must begin with a letter or underscore"));
goto error;
}
if (strspn(tmp, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_") != strlen(tmp)) {
qemuReportError(VIR_ERR_INTERNAL_ERROR,
"%s", _("Invalid environment name, it must contain only alphanumerics and underscore"));
goto error;
}
cmd->env_name[cmd->num_env] = tmp;
cmd->env_value[cmd->num_env] = virXMLPropString(nodes[i], "value");
/* a NULL value for command is allowed, since it might be empty */
cmd->num_env++;
}
VIR_FREE(nodes);
*data = cmd;
return 0;
no_memory:
virReportOOMError();
error:
VIR_FREE(nodes);
qemuDomainDefNamespaceFree(cmd);
return -1;
}
static int
qemuDomainDefNamespaceFormatXML(virBufferPtr buf,
void *nsdata)
{
qemuDomainCmdlineDefPtr cmd = nsdata;
unsigned int i;
if (!cmd->num_args && !cmd->num_env)
return 0;
virBufferAddLit(buf, " <qemu:commandline>\n");
for (i = 0; i < cmd->num_args; i++)
virBufferEscapeString(buf, " <qemu:arg value='%s'/>\n",
cmd->args[i]);
for (i = 0; i < cmd->num_env; i++) {
virBufferVSprintf(buf, " <qemu:env name='%s'", cmd->env_name[i]);
if (cmd->env_value[i])
virBufferEscapeString(buf, " value='%s'", cmd->env_value[i]);
virBufferAddLit(buf, "/>\n");
}
virBufferAddLit(buf, " </qemu:commandline>\n");
return 0;
}
static const char *
qemuDomainDefNamespaceHref(void)
{
return "xmlns:qemu='" QEMU_NAMESPACE_HREF "'";
}
void qemuDomainSetPrivateDataHooks(virCapsPtr caps)
{
/* Domain XML parser hooks */
caps->privateDataAllocFunc = qemuDomainObjPrivateAlloc;
caps->privateDataFreeFunc = qemuDomainObjPrivateFree;
caps->privateDataXMLFormat = qemuDomainObjPrivateXMLFormat;
caps->privateDataXMLParse = qemuDomainObjPrivateXMLParse;
}
void qemuDomainSetNamespaceHooks(virCapsPtr caps)
{
/* Domain Namespace XML parser hooks */
caps->ns.parse = qemuDomainDefNamespaceParse;
caps->ns.free = qemuDomainDefNamespaceFree;
caps->ns.format = qemuDomainDefNamespaceFormatXML;
caps->ns.href = qemuDomainDefNamespaceHref;
}
/*
* obj must be locked before calling, qemud_driver must NOT be locked
*
* This must be called by anything that will change the VM state
* in any way, or anything that will use the QEMU monitor.
*
* Upon successful return, the object will have its ref count increased,
* successful calls must be followed by EndJob eventually
*/
/* Give up waiting for mutex after 30 seconds */
#define QEMU_JOB_WAIT_TIME (1000ull * 30)
int qemuDomainObjBeginJob(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
struct timeval now;
unsigned long long then;
if (gettimeofday(&now, NULL) < 0) {
virReportSystemError(errno, "%s",
_("cannot get time of day"));
return -1;
}
then = timeval_to_ms(now) + QEMU_JOB_WAIT_TIME;
virDomainObjRef(obj);
while (priv->jobActive) {
if (virCondWaitUntil(&priv->jobCond, &obj->lock, then) < 0) {
virDomainObjUnref(obj);
if (errno == ETIMEDOUT)
qemuReportError(VIR_ERR_OPERATION_TIMEOUT,
"%s", _("cannot acquire state change lock"));
else
virReportSystemError(errno,
"%s", _("cannot acquire job mutex"));
return -1;
}
}
priv->jobActive = QEMU_JOB_UNSPECIFIED;
priv->jobSignals = 0;
memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
priv->jobStart = timeval_to_ms(now);
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
return 0;
}
/*
* obj must be locked before calling, qemud_driver must be locked
*
* This must be called by anything that will change the VM state
* in any way, or anything that will use the QEMU monitor.
*/
int qemuDomainObjBeginJobWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
struct timeval now;
unsigned long long then;
if (gettimeofday(&now, NULL) < 0) {
virReportSystemError(errno, "%s",
_("cannot get time of day"));
return -1;
}
then = timeval_to_ms(now) + QEMU_JOB_WAIT_TIME;
virDomainObjRef(obj);
qemuDriverUnlock(driver);
while (priv->jobActive) {
if (virCondWaitUntil(&priv->jobCond, &obj->lock, then) < 0) {
virDomainObjUnref(obj);
if (errno == ETIMEDOUT)
qemuReportError(VIR_ERR_OPERATION_TIMEOUT,
"%s", _("cannot acquire state change lock"));
else
virReportSystemError(errno,
"%s", _("cannot acquire job mutex"));
qemuDriverLock(driver);
return -1;
}
}
priv->jobActive = QEMU_JOB_UNSPECIFIED;
priv->jobSignals = 0;
memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
priv->jobStart = timeval_to_ms(now);
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
virDomainObjUnlock(obj);
qemuDriverLock(driver);
virDomainObjLock(obj);
return 0;
}
/*
* obj must be locked before calling, qemud_driver does not matter
*
* To be called after completing the work associated with the
* earlier qemuDomainBeginJob() call
*
* Returns remaining refcount on 'obj', maybe 0 to indicated it
* was deleted
*/
int qemuDomainObjEndJob(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
priv->jobActive = QEMU_JOB_NONE;
priv->jobSignals = 0;
memset(&priv->jobSignalsData, 0, sizeof(priv->jobSignalsData));
priv->jobStart = 0;
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
virCondSignal(&priv->jobCond);
return virDomainObjUnref(obj);
}
/*
* obj must be locked before calling, qemud_driver must be unlocked
*
* To be called immediately before any QEMU monitor API call
* Must have already called qemuDomainObjBeginJob(), and checked
* that the VM is still active.
*
* To be followed with qemuDomainObjExitMonitor() once complete
*/
void qemuDomainObjEnterMonitor(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
qemuMonitorLock(priv->mon);
qemuMonitorRef(priv->mon);
virDomainObjUnlock(obj);
}
/* obj must NOT be locked before calling, qemud_driver must be unlocked
*
* Should be paired with an earlier qemuDomainObjEnterMonitor() call
*/
void qemuDomainObjExitMonitor(virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
int refs;
refs = qemuMonitorUnref(priv->mon);
if (refs > 0)
qemuMonitorUnlock(priv->mon);
virDomainObjLock(obj);
if (refs == 0) {
priv->mon = NULL;
}
}
/*
* obj must be locked before calling, qemud_driver must be locked
*
* To be called immediately before any QEMU monitor API call
* Must have already called qemuDomainObjBeginJob().
*
* To be followed with qemuDomainObjExitMonitorWithDriver() once complete
*/
void qemuDomainObjEnterMonitorWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
qemuMonitorLock(priv->mon);
qemuMonitorRef(priv->mon);
virDomainObjUnlock(obj);
qemuDriverUnlock(driver);
}
/* obj must NOT be locked before calling, qemud_driver must be unlocked,
* and will be locked after returning
*
* Should be paired with an earlier qemuDomainObjEnterMonitorWithDriver() call
*/
void qemuDomainObjExitMonitorWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDomainObjPrivatePtr priv = obj->privateData;
int refs;
refs = qemuMonitorUnref(priv->mon);
if (refs > 0)
qemuMonitorUnlock(priv->mon);
qemuDriverLock(driver);
virDomainObjLock(obj);
if (refs == 0) {
priv->mon = NULL;
}
}
void qemuDomainObjEnterRemoteWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
virDomainObjRef(obj);
virDomainObjUnlock(obj);
qemuDriverUnlock(driver);
}
void qemuDomainObjExitRemoteWithDriver(struct qemud_driver *driver,
virDomainObjPtr obj)
{
qemuDriverLock(driver);
virDomainObjLock(obj);
virDomainObjUnref(obj);
}
| Java |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "./";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var _addClass = __webpack_require__(25);
var _addClass2 = _interopRequireDefault(_addClass);
var _removeClass = __webpack_require__(26);
var _removeClass2 = _interopRequireDefault(_removeClass);
var _after = __webpack_require__(96);
var _after2 = _interopRequireDefault(_after);
var _browser = __webpack_require__(97);
var _browser2 = _interopRequireDefault(_browser);
var _fix = __webpack_require__(98);
var _fix2 = _interopRequireDefault(_fix);
var _util = __webpack_require__(27);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// fix hexo 不支持的配置
function isPathMatch(path, href) {
var reg = /\/|index.html/g;
return path.replace(reg, '') === href.replace(reg, '');
}
// 浏览器判断
function tabActive() {
var $tabs = document.querySelectorAll('.js-header-menu li a');
var path = window.location.pathname;
for (var i = 0, len = $tabs.length; i < len; i++) {
var $tab = $tabs[i];
if (isPathMatch(path, $tab.getAttribute('href'))) {
(0, _addClass2.default)($tab, 'active');
}
}
}
function getElementLeft(element) {
var actualLeft = element.offsetLeft;
var current = element.offsetParent;
while (current !== null) {
actualLeft += current.offsetLeft;
current = current.offsetParent;
}
return actualLeft;
}
function getElementTop(element) {
var actualTop = element.offsetTop;
var current = element.offsetParent;
while (current !== null) {
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}
function scrollStop($dom, top, limit, zIndex, diff) {
var nowLeft = getElementLeft($dom);
var nowTop = getElementTop($dom) - top;
if (nowTop - limit <= diff) {
var $newDom = $dom.$newDom;
if (!$newDom) {
$newDom = $dom.cloneNode(true);
(0, _after2.default)($dom, $newDom);
$dom.$newDom = $newDom;
$newDom.style.position = 'fixed';
$newDom.style.top = (limit || nowTop) + 'px';
$newDom.style.left = nowLeft + 'px';
$newDom.style.zIndex = zIndex || 2;
$newDom.style.width = '100%';
$newDom.style.color = '#fff';
}
$newDom.style.visibility = 'visible';
$dom.style.visibility = 'hidden';
} else {
$dom.style.visibility = 'visible';
var _$newDom = $dom.$newDom;
if (_$newDom) {
_$newDom.style.visibility = 'hidden';
}
}
}
function handleScroll() {
var $overlay = document.querySelector('.js-overlay');
var $menu = document.querySelector('.js-header-menu');
scrollStop($overlay, document.body.scrollTop, -63, 2, 0);
scrollStop($menu, document.body.scrollTop, 1, 3, 0);
}
function bindScroll() {
document.querySelector('#container').addEventListener('scroll', function (e) {
handleScroll();
});
window.addEventListener('scroll', function (e) {
handleScroll();
});
handleScroll();
}
function init() {
if (_browser2.default.versions.mobile && window.screen.width < 800) {
tabActive();
bindScroll();
}
}
init();
(0, _util.addLoadEvent)(function () {
_fix2.default.init();
});
module.exports = {};
/***/ },
/* 1 */,
/* 2 */,
/* 3 */,
/* 4 */,
/* 5 */,
/* 6 */,
/* 7 */,
/* 8 */,
/* 9 */,
/* 10 */,
/* 11 */,
/* 12 */,
/* 13 */,
/* 14 */,
/* 15 */,
/* 16 */,
/* 17 */,
/* 18 */,
/* 19 */,
/* 20 */,
/* 21 */,
/* 22 */,
/* 23 */,
/* 24 */,
/* 25 */
/***/ function(module, exports) {
/**
* addClass : addClass(el, className)
* Adds a class name to an element. Compare with `$.fn.addClass`.
*
* var addClass = require('dom101/add-class');
*
* addClass(el, 'active');
*/
function addClass (el, className) {
if (el.classList) {
el.classList.add(className);
} else {
el.className += ' ' + className;
}
}
module.exports = addClass;
/***/ },
/* 26 */
/***/ function(module, exports) {
/**
* removeClass : removeClass(el, className)
* Removes a classname.
*
* var removeClass = require('dom101/remove-class');
*
* el.className = 'selected active';
* removeClass(el, 'active');
*
* el.className
* => "selected"
*/
function removeClass (el, className) {
if (el.classList) {
el.classList.remove(className);
} else {
var expr =
new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi');
el.className = el.className.replace(expr, ' ');
}
}
module.exports = removeClass;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var _typeof2 = __webpack_require__(28);
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var e = function () {
function r(e, r, n) {
return r || n ? String.fromCharCode(r || n) : u[e] || e;
}
function n(e) {
return p[e];
}
var t = /"|<|>|&| |'|&#(\d+);|&#(\d+)/g,
o = /['<> "&]/g,
u = {
""": '"',
"<": "<",
">": ">",
"&": "&",
" ": " "
},
c = /\u00a0/g,
a = /<br\s*\/?>/gi,
i = /\r?\n/g,
f = /\s/g,
p = {};
for (var s in u) {
p[u[s]] = s;
}return u["'"] = "'", p["'"] = "'", {
encode: function encode(e) {
return e ? ("" + e).replace(o, n).replace(i, "<br/>").replace(f, " ") : "";
},
decode: function decode(e) {
return e ? ("" + e).replace(a, "\n").replace(t, r).replace(c, " ") : "";
},
encodeBase16: function encodeBase16(e) {
if (!e) return e;
e += "";
for (var r = [], n = 0, t = e.length; t > n; n++) {
r.push(e.charCodeAt(n).toString(16).toUpperCase());
}return r.join("");
},
encodeBase16forJSON: function encodeBase16forJSON(e) {
if (!e) return e;
e = e.replace(/[\u4E00-\u9FBF]/gi, function (e) {
return escape(e).replace("%u", "\\u");
});
for (var r = [], n = 0, t = e.length; t > n; n++) {
r.push(e.charCodeAt(n).toString(16).toUpperCase());
}return r.join("");
},
decodeBase16: function decodeBase16(e) {
if (!e) return e;
e += "";
for (var r = [], n = 0, t = e.length; t > n; n += 2) {
r.push(String.fromCharCode("0x" + e.slice(n, n + 2)));
}return r.join("");
},
encodeObject: function encodeObject(r) {
if (r instanceof Array) for (var n = 0, t = r.length; t > n; n++) {
r[n] = e.encodeObject(r[n]);
} else if ("object" == (typeof r === "undefined" ? "undefined" : (0, _typeof3.default)(r))) for (var o in r) {
r[o] = e.encodeObject(r[o]);
} else if ("string" == typeof r) return e.encode(r);
return r;
},
loadScript: function loadScript(path) {
var $script = document.createElement('script');
document.getElementsByTagName('body')[0].appendChild($script);
$script.setAttribute('src', path);
},
addLoadEvent: function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
};
}
}
};
}();
module.exports = e;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _iterator = __webpack_require__(29);
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = __webpack_require__(80);
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(30), __esModule: true };
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(31);
__webpack_require__(75);
module.exports = __webpack_require__(79).f('iterator');
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(32)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(35)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(33)
, defined = __webpack_require__(34);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 33 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 34 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(36)
, $export = __webpack_require__(37)
, redefine = __webpack_require__(52)
, hide = __webpack_require__(42)
, has = __webpack_require__(53)
, Iterators = __webpack_require__(54)
, $iterCreate = __webpack_require__(55)
, setToStringTag = __webpack_require__(71)
, getPrototypeOf = __webpack_require__(73)
, ITERATOR = __webpack_require__(72)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ },
/* 36 */
/***/ function(module, exports) {
module.exports = true;
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(38)
, core = __webpack_require__(39)
, ctx = __webpack_require__(40)
, hide = __webpack_require__(42)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 38 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 39 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(41);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 41 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(43)
, createDesc = __webpack_require__(51);
module.exports = __webpack_require__(47) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(44)
, IE8_DOM_DEFINE = __webpack_require__(46)
, toPrimitive = __webpack_require__(50)
, dP = Object.defineProperty;
exports.f = __webpack_require__(47) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(45);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 45 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(47) && !__webpack_require__(48)(function(){
return Object.defineProperty(__webpack_require__(49)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(48)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 48 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(45)
, document = __webpack_require__(38).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(45);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 51 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(42);
/***/ },
/* 53 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 54 */
/***/ function(module, exports) {
module.exports = {};
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var create = __webpack_require__(56)
, descriptor = __webpack_require__(51)
, setToStringTag = __webpack_require__(71)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(42)(IteratorPrototype, __webpack_require__(72)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(44)
, dPs = __webpack_require__(57)
, enumBugKeys = __webpack_require__(69)
, IE_PROTO = __webpack_require__(66)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(49)('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
__webpack_require__(70).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(43)
, anObject = __webpack_require__(44)
, getKeys = __webpack_require__(58);
module.exports = __webpack_require__(47) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(59)
, enumBugKeys = __webpack_require__(69);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(53)
, toIObject = __webpack_require__(60)
, arrayIndexOf = __webpack_require__(63)(false)
, IE_PROTO = __webpack_require__(66)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(61)
, defined = __webpack_require__(34);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(62);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 62 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(60)
, toLength = __webpack_require__(64)
, toIndex = __webpack_require__(65);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(33)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(33)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(67)('keys')
, uid = __webpack_require__(68);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(38)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 68 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 69 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(38).document && document.documentElement;
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
var def = __webpack_require__(43).f
, has = __webpack_require__(53)
, TAG = __webpack_require__(72)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
var store = __webpack_require__(67)('wks')
, uid = __webpack_require__(68)
, Symbol = __webpack_require__(38).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(53)
, toObject = __webpack_require__(74)
, IE_PROTO = __webpack_require__(66)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(34);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(76);
var global = __webpack_require__(38)
, hide = __webpack_require__(42)
, Iterators = __webpack_require__(54)
, TO_STRING_TAG = __webpack_require__(72)('toStringTag');
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype;
if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
/***/ },
/* 76 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(77)
, step = __webpack_require__(78)
, Iterators = __webpack_require__(54)
, toIObject = __webpack_require__(60);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(35)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ },
/* 77 */
/***/ function(module, exports) {
module.exports = function(){ /* empty */ };
/***/ },
/* 78 */
/***/ function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(72);
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
module.exports = { "default": __webpack_require__(81), __esModule: true };
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(82);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
module.exports = __webpack_require__(39).Symbol;
/***/ },
/* 82 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var global = __webpack_require__(38)
, has = __webpack_require__(53)
, DESCRIPTORS = __webpack_require__(47)
, $export = __webpack_require__(37)
, redefine = __webpack_require__(52)
, META = __webpack_require__(83).KEY
, $fails = __webpack_require__(48)
, shared = __webpack_require__(67)
, setToStringTag = __webpack_require__(71)
, uid = __webpack_require__(68)
, wks = __webpack_require__(72)
, wksExt = __webpack_require__(79)
, wksDefine = __webpack_require__(84)
, keyOf = __webpack_require__(85)
, enumKeys = __webpack_require__(86)
, isArray = __webpack_require__(89)
, anObject = __webpack_require__(44)
, toIObject = __webpack_require__(60)
, toPrimitive = __webpack_require__(50)
, createDesc = __webpack_require__(51)
, _create = __webpack_require__(56)
, gOPNExt = __webpack_require__(90)
, $GOPD = __webpack_require__(92)
, $DP = __webpack_require__(43)
, $keys = __webpack_require__(58)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(91).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(88).f = $propertyIsEnumerable;
__webpack_require__(87).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(36)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(42)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
var META = __webpack_require__(68)('meta')
, isObject = __webpack_require__(45)
, has = __webpack_require__(53)
, setDesc = __webpack_require__(43).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(48)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(38)
, core = __webpack_require__(39)
, LIBRARY = __webpack_require__(36)
, wksExt = __webpack_require__(79)
, defineProperty = __webpack_require__(43).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(58)
, toIObject = __webpack_require__(60);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(58)
, gOPS = __webpack_require__(87)
, pIE = __webpack_require__(88);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
/***/ },
/* 87 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 88 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(62);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(60)
, gOPN = __webpack_require__(91).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(59)
, hiddenKeys = __webpack_require__(69).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(88)
, createDesc = __webpack_require__(51)
, toIObject = __webpack_require__(60)
, toPrimitive = __webpack_require__(50)
, has = __webpack_require__(53)
, IE8_DOM_DEFINE = __webpack_require__(46)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(47) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ },
/* 93 */
/***/ function(module, exports) {
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(84)('asyncIterator');
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(84)('observable');
/***/ },
/* 96 */
/***/ function(module, exports) {
/**
* after : after(el, newEl)
* Inserts a new element `newEl` just after `el`.
*
* var after = require('dom101/after');
* var newNode = document.createElement('div');
* var button = document.querySelector('#submit');
*
* after(button, newNode);
*/
function after (el, newEl) {
if (typeof newEl === 'string') {
return el.insertAdjacentHTML('afterend', newEl);
} else {
var next = el.nextSibling;
if (next) {
return el.parentNode.insertBefore(newEl, next);
} else {
return el.parentNode.appendChild(newEl);
}
}
}
module.exports = after;
/***/ },
/* 97 */
/***/ function(module, exports) {
'use strict';
var browser = {
versions: function () {
var u = window.navigator.userAgent;
return {
trident: u.indexOf('Trident') > -1, //IE内核
presto: u.indexOf('Presto') > -1, //opera内核
webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
iPad: u.indexOf('iPad') > -1, //是否为iPad
webApp: u.indexOf('Safari') == -1, //是否为web应用程序,没有头部与底部
weixin: u.indexOf('MicroMessenger') == -1 //是否为微信浏览器
};
}()
};
module.exports = browser;
/***/ },
/* 98 */
/***/ function(module, exports) {
'use strict';
function init() {
// 由于hexo分页不支持,手工美化
var $nav = document.querySelector('#page-nav');
if ($nav && !document.querySelector('#page-nav .extend.prev')) {
$nav.innerHTML = '<a class="extend prev disabled" rel="prev">« Prev</a>' + $nav.innerHTML;
}
if ($nav && !document.querySelector('#page-nav .extend.next')) {
$nav.innerHTML = $nav.innerHTML + '<a class="extend next disabled" rel="next">Next »</a>';
}
// 新窗口打开
if (yiliaConfig && yiliaConfig.open_in_new) {
var $a = document.querySelectorAll('.article-entry a:not(.article-more-a)');
$a.forEach(function ($em) {
$em.setAttribute('target', '_blank');
});
}
// about me 转义
var $aboutme = document.querySelector('#js-aboutme');
if ($aboutme && $aboutme.length !== 0) {
$aboutme.innerHTML = $aboutme.innerText;
}
}
module.exports = {
init: init
};
/***/ }
/******/ ]); | Java |
/*
aim_rxqueue.c
This file contains the management routines for the receive
(incoming packet) queue. The actual packet handlers are in
aim_rxhandlers.c.
*/
#include "aim.h"
/*
This is a modified read() to make SURE we get the number
of bytes we are told to, otherwise block.
*/
int Read(int fd, u_char *buf, int len)
{
int i = 0;
int j = 0;
while ((i < len) && (!(i < 0)))
{
j = read(fd, &(buf[i]), len-i);
if ( (j < 0) && (errno != EAGAIN))
return -errno; /* fail */
else
i += j; /* success, continue */
}
#if 0
printf("\nRead Block: (%d/%04x)\n", len, len);
printf("\t");
for (j = 0; j < len; j++)
{
if (j % 8 == 0)
printf("\n\t");
if (buf[j] >= ' ' && buf[j] < 127)
printf("%c=%02x ",buf[j], buf[j]);
else
printf("0x%02x ", buf[j]);
}
printf("\n\n");
#endif
return i;
}
/*
struct command_struct *
get_generic(
struct connection_info struct *,
struct command_struct *
)
Grab as many command sequences as we can off the socket, and enqueue
each command in the incoming event queue in a seperate struct.
*/
int aim_get_command(void)
{
int i, readgood, j, isav, err;
int s;
fd_set fds;
struct timeval tv;
char generic[6];
struct command_rx_struct *workingStruct = NULL;
struct command_rx_struct *workingPtr = NULL;
struct aim_conn_t *conn = NULL;
#if debug > 0
printf("Reading generic/unknown response...");
#endif
/* dont wait at all (ie, never call this unless something is there) */
tv.tv_sec = 0;
tv.tv_usec = 0;
conn = aim_select(&tv);
if (conn==NULL)
return 0; /* nothing waiting */
s = conn->fd;
FD_ZERO(&fds);
FD_SET(s, &fds);
tv.tv_sec = 0; /* wait, but only for 10us */
tv.tv_usec = 10;
generic[0] = 0x00;
readgood = 0;
i = 0;
j = 0;
/* read first 6 bytes (the FLAP header only) off the socket */
while ( (select(s+1, &fds, NULL, NULL, &tv) == 1) && (i < 6))
{
if ((err = Read(s, &(generic[i]), 1)) < 0)
{
/* error is probably not recoverable...(must be a pessimistic day) */
aim_conn_close(conn);
return err;
}
if (readgood == 0)
{
if (generic[i] == 0x2a)
{
readgood = 1;
#if debug > 1
printf("%x ", generic[i]);
fflush(stdout);
#endif
i++;
}
else
{
#if debug > 1
printf("skipping 0x%d ", generic[i]);
fflush(stdout);
#endif
j++;
}
}
else
{
#if debug > 1
printf("%x ", generic[i]);
#endif
i++;
}
FD_ZERO(&fds);
FD_SET(s, &fds);
tv.tv_sec= 2;
tv.tv_usec= 2;
}
if (generic[0] != 0x2a)
{
/* this really shouldn't happen, since the main loop
select() should protect us from entering this function
without data waiting */
printf("Bad incoming data!");
return -1;
}
isav = i;
/* allocate a new struct */
workingStruct = (struct command_rx_struct *) malloc(sizeof(struct command_rx_struct));
workingStruct->lock = 1; /* lock the struct */
/* store type -- byte 2 */
workingStruct->type = (char) generic[1];
/* store seqnum -- bytes 3 and 4 */
workingStruct->seqnum = ( (( (unsigned int) generic[2]) & 0xFF) << 8);
workingStruct->seqnum += ( (unsigned int) generic[3]) & 0xFF;
/* store commandlen -- bytes 5 and 6 */
workingStruct->commandlen = ( (( (unsigned int) generic[4]) & 0xFF ) << 8);
workingStruct->commandlen += ( (unsigned int) generic[5]) & 0xFF;
/* malloc for data portion */
workingStruct->data = (char *) malloc(workingStruct->commandlen);
/* read the data portion of the packet */
i = Read(s, workingStruct->data, workingStruct->commandlen);
if (i < 0)
{
aim_conn_close(conn);
return i;
}
#if debug > 0
printf(" done. (%db+%db read, %db skipped)\n", isav, i, j);
#endif
workingStruct->conn = conn;
workingStruct->next = NULL; /* this will always be at the bottom */
workingStruct->lock = 0; /* unlock */
/* enqueue this packet */
if (aim_queue_incoming == NULL)
aim_queue_incoming = workingStruct;
else
{
workingPtr = aim_queue_incoming;
while (workingPtr->next != NULL)
workingPtr = workingPtr->next;
workingPtr->next = workingStruct;
}
return 0;
}
/*
purge_rxqueue()
This is just what it sounds. It purges the receive (rx) queue of
all handled commands. This is normally called from inside
aim_rxdispatch() after it's processed all the commands in the queue.
*/
struct command_rx_struct *aim_purge_rxqueue(struct command_rx_struct *queue)
{
int i = 0;
struct command_rx_struct *workingPtr = NULL;
struct command_rx_struct *workingPtr2 = NULL;
workingPtr = queue;
if (queue == NULL)
{
return queue;
}
else if (queue->next == NULL)
{
if (queue->handled == 1)
{
workingPtr2 = queue;
queue = NULL;
free(workingPtr2->data);
free(workingPtr2);
}
return queue;
}
else
{
for (i = 0; workingPtr != NULL; i++)
{
if (workingPtr->next->handled == 1)
{
/* save struct */
workingPtr2 = workingPtr->next;
/* dequeue */
workingPtr->next = workingPtr2->next;
/* free */
free(workingPtr2->data);
free(workingPtr2);
}
workingPtr = workingPtr->next;
}
}
return queue;
}
| Java |
//
// Created by Ulrich Eck on 26/07/2015.
//
#ifndef UBITRACK_GLFW_RENDERMANAGER_H
#define UBITRACK_GLFW_RENDERMANAGER_H
#include <string>
#ifdef HAVE_GLEW
#include "GL/glew.h"
#endif
#include <GLFW/glfw3.h>
#include <utVisualization/utRenderAPI.h>
namespace Ubitrack {
namespace Visualization {
class GLFWWindowImpl : public VirtualWindow {
public:
GLFWWindowImpl(int _width, int _height, const std::string& _title);
~GLFWWindowImpl();
virtual void pre_render();
virtual void post_render();
virtual void reshape(int w, int h);
//custom extensions
virtual void setFullscreen(bool fullscreen);
virtual void onExit();
// Implementation of Public interface
virtual bool is_valid();
virtual bool create();
virtual void initGL(boost::shared_ptr<CameraHandle>& cam);
virtual void destroy();
private:
GLFWwindow* m_pWindow;
boost::shared_ptr<CameraHandle> m_pEventHandler;
};
// callback implementations for GLFW
inline static void WindowResizeCallback(
GLFWwindow *win,
int w,
int h) {
CameraHandle *cam = static_cast<CameraHandle*>(glfwGetWindowUserPointer(win));
cam->on_window_size(w, h);
}
inline static void WindowRefreshCallback(GLFWwindow *win) {
CameraHandle *cam = static_cast<CameraHandle*>(glfwGetWindowUserPointer(win));
cam->on_render(glfwGetTime());
}
inline static void WindowCloseCallback(GLFWwindow *win) {
CameraHandle *cam = static_cast<CameraHandle*>(glfwGetWindowUserPointer(win));
cam->on_window_close();
}
inline static void WindowKeyCallback(GLFWwindow *win,
int key,
int scancode,
int action,
int mods) {
CameraHandle *cam = static_cast<CameraHandle*>(glfwGetWindowUserPointer(win));
if ((action == GLFW_PRESS) && (mods & GLFW_MOD_ALT)) {
switch (key) {
case GLFW_KEY_F:
cam->on_fullscreen();
return;
default:
break;
}
}
if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_ESCAPE:
cam->on_exit();
return;
default:
cam->on_keypress(key, scancode, action, mods);
break;
}
}
}
inline static void WindowCursorPosCallback(GLFWwindow *win,
double xpos,
double ypos) {
CameraHandle *cam = static_cast<CameraHandle*>(glfwGetWindowUserPointer(win));
cam->on_cursorpos(xpos, ypos);
}
}
}
#endif //UBITRACK_GLFW_RENDERMANAGER_H
| Java |
/////////////////////////////////////////////////////////////////////////////
// Name: help.cpp
// Purpose: wxHtml sample: help test
// Author: ?
// Modified by:
// Created: ?
// RCS-ID: $Id$
// Copyright: (c) wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// for all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/image.h"
#include "wx/html/helpfrm.h"
#include "wx/html/helpctrl.h"
#include "wx/filesys.h"
#include "wx/fs_zip.h"
#ifndef wxHAS_IMAGES_IN_RESOURCES
#include "../../sample.xpm"
#endif
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
// Define a new application type, each program should derive a class from wxApp
class MyApp : public wxApp
{
public:
// override base class virtuals
// ----------------------------
// this one is called on application startup and is a good place for the app
// initialization (doing it here and not in the ctor allows to have an error
// return: if OnInit() returns false, the application terminates)
virtual bool OnInit();
};
// Define a new frame type: this is going to be our main frame
class MyFrame : public wxFrame
{
public:
// ctor(s)
MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
// event handlers (these functions should _not_ be virtual)
void OnQuit(wxCommandEvent& event);
void OnHelp(wxCommandEvent& event);
void OnClose(wxCloseEvent& event);
private:
wxHtmlHelpController help;
// any class wishing to process wxWidgets events must use this macro
DECLARE_EVENT_TABLE()
};
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// IDs for the controls and the menu commands
enum
{
// menu items
Minimal_Quit = 1,
Minimal_Help
};
// ----------------------------------------------------------------------------
// event tables and other macros for wxWidgets
// ----------------------------------------------------------------------------
// the event tables connect the wxWidgets events with the functions (event
// handlers) which process them. It can be also done at run-time, but for the
// simple menu events like this the static method is much simpler.
BEGIN_EVENT_TABLE(MyFrame, wxFrame)
EVT_MENU(Minimal_Quit, MyFrame::OnQuit)
EVT_MENU(Minimal_Help, MyFrame::OnHelp)
EVT_CLOSE(MyFrame::OnClose)
END_EVENT_TABLE()
// Create a new application object: this macro will allow wxWidgets to create
// the application object during program execution (it's better than using a
// static object for many reasons) and also declares the accessor function
// wxGetApp() which will return the reference of the right type (i.e. MyApp and
// not wxApp)
IMPLEMENT_APP(MyApp)
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// the application class
// ----------------------------------------------------------------------------
// `Main program' equivalent: the program execution "starts" here
bool MyApp::OnInit()
{
if ( !wxApp::OnInit() )
return false;
wxInitAllImageHandlers();
#if wxUSE_STREAMS && wxUSE_ZIPSTREAM && wxUSE_ZLIB
wxFileSystem::AddHandler(new wxZipFSHandler);
#endif
SetVendorName(wxT("wxWidgets"));
SetAppName(wxT("wxHTMLHelp"));
// Create the main application window
MyFrame *frame = new MyFrame(_("HTML Help Sample"),
wxDefaultPosition, wxDefaultSize);
// Show it
frame->Show(true);
// success: wxApp::OnRun() will be called which will enter the main message
// loop and the application will run. If we returned false here, the
// application would exit immediately.
return true;
}
// ----------------------------------------------------------------------------
// main frame
// ----------------------------------------------------------------------------
// frame constructor
MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
: wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size),
help(wxHF_DEFAULT_STYLE | wxHF_OPEN_FILES)
{
SetIcon(wxICON(sample));
// create a menu bar
wxMenu *menuFile = new wxMenu;
menuFile->Append(Minimal_Help, _("&Help"));
menuFile->Append(Minimal_Quit, _("E&xit"));
// now append the freshly created menu to the menu bar...
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(menuFile, _("&File"));
// ... and attach this menu bar to the frame
SetMenuBar(menuBar);
help.UseConfig(wxConfig::Get());
bool ret;
help.SetTempDir(wxT("."));
ret = help.AddBook(wxFileName(wxT("helpfiles/testing.hhp"), wxPATH_UNIX));
if (! ret)
wxMessageBox(wxT("Failed adding book helpfiles/testing.hhp"));
ret = help.AddBook(wxFileName(wxT("helpfiles/another.hhp"), wxPATH_UNIX));
if (! ret)
wxMessageBox(_("Failed adding book helpfiles/another.hhp"));
}
// event handlers
void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
{
// true is to force the frame to close
Close(true);
}
void MyFrame::OnHelp(wxCommandEvent& WXUNUSED(event))
{
help.Display(wxT("Test HELPFILE"));
}
void MyFrame::OnClose(wxCloseEvent& event)
{
// Close the help frame; this will cause the config data to
// get written.
if ( help.GetFrame() ) // returns NULL if no help frame active
help.GetFrame()->Close(true);
// now we can safely delete the config pointer
event.Skip();
delete wxConfig::Set(NULL);
}
| Java |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Qt 4.7: imageprovider-example.qml Example File (declarative/cppextensions/imageprovider/imageprovider-example.qml)</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
<script src="scripts/jquery.js" type="text/javascript"></script>
<script src="scripts/functions.js" type="text/javascript"></script>
</head>
<body class="offline narrow creator">
<div class="header" id="qtdocheader">
<div class="content">
<div id="nav-logo">
<a href="index.html">Home</a></div>
<a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a>
<div id="nav-topright">
<ul>
<li class="nav-topright-home"><a href="http://qt.nokia.com/">Qt HOME</a></li>
<li class="nav-topright-dev"><a href="http://developer.qt.nokia.com/">DEV</a></li>
<li class="nav-topright-labs"><a href="http://labs.qt.nokia.com/blogs/">LABS</a></li>
<li class="nav-topright-doc nav-topright-doc-active"><a href="http://doc.qt.nokia.com/">
DOC</a></li>
<li class="nav-topright-blog"><a href="http://blog.qt.nokia.com/">BLOG</a></li>
</ul>
</div>
<div id="shortCut">
<ul>
<li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.7</a></span></li>
<li class="shortCut-topleft-active"><a href="http://doc.qt.nokia.com">ALL VERSIONS </a></li>
</ul>
</div>
<ul class="sf-menu sf-js-enabled sf-shadow" id="narrowmenu">
<li><a href="#">API Lookup</a>
<ul id="topmenuLook">
<li><a href="classes.html">Class index</a></li>
<li><a href="functions.html">Function index</a></li>
<li><a href="modules.html">Modules</a></li>
<li><a href="namespaces.html">Namespaces</a></li>
<li><a href="qtglobal.html">Global Declarations</a></li>
<li><a href="licensing.html">Licenses and Credits</a></li>
</ul>
</li>
<li><a href="#">Qt Topics</a>
<ul id="topmenuTopic">
<li><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li><a href="qtquick.html">Device UI's & Qt Quick</a></li>
<li><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li>
<li><a href="platform-specific.html">Platform-specific info</a></li>
<li><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</li>
<li><a href="#">Examples</a>
<ul id="topmenuexample">
<li><a href="all-examples.html">Examples</a></li>
<li><a href="tutorials.html">Tutorials</a></li>
<li><a href="demos.html">Demos</a></li>
<li><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="wrapper">
<div class="hd">
<span></span>
</div>
<div class="bd group">
<div class="sidebar">
<div class="searchlabel">
Search index:</div>
<div class="search">
<form id="qtdocsearch" action="" onsubmit="return false;">
<fieldset>
<input type="text" name="searchstring" id="pageType" value="" />
</fieldset>
</form>
</div>
<div class="box first bottombar" id="lookup">
<h2 title="API Lookup"><span></span>
API Lookup</h2>
<div id="list001" class="list">
<ul id="ul001" >
<li class="defaultLink"><a href="classes.html">Class index</a></li>
<li class="defaultLink"><a href="functions.html">Function index</a></li>
<li class="defaultLink"><a href="modules.html">Modules</a></li>
<li class="defaultLink"><a href="namespaces.html">Namespaces</a></li>
<li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li>
<li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li>
</ul>
</div>
</div>
<div class="box bottombar" id="topics">
<h2 title="Qt Topics"><span></span>
Qt Topics</h2>
<div id="list002" class="list">
<ul id="ul002" >
<li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li>
<li class="defaultLink"><a href="qtquick.html">Device UI's & Qt Quick</a></li>
<li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li>
<li class="defaultLink"><a href="developing-with-qt.html">Cross-platform and Platform-specific</a></li>
<li class="defaultLink"><a href="platform-specific.html">Platform-specific info</a></li>
<li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li>
<li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li>
</ul>
</div>
</div>
<div class="box" id="examples">
<h2 title="Examples"><span></span>
Examples</h2>
<div id="list003" class="list">
<ul id="ul003">
<li class="defaultLink"><a href="all-examples.html">Examples</a></li>
<li class="defaultLink"><a href="tutorials.html">Tutorials</a></li>
<li class="defaultLink"><a href="demos.html">Demos</a></li>
<li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li>
</ul>
</div>
</div>
</div>
<div class="wrap">
<div class="toolbar">
<div class="breadcrumb toolblock">
<ul>
<li class="first"><a href="index.html">Home</a></li>
<!-- Bread crumbs goes here -->
</ul>
</div>
<div class="toolbuttons toolblock">
<ul>
<li id="smallA" class="t_button">A</li>
<li id="medA" class="t_button active">A</li>
<li id="bigA" class="t_button">A</li>
<li id="print" class="t_button"><a href="javascript:this.print();">
<span>Print</span></a></li>
</ul>
</div>
</div>
<div class="content">
<h1 class="title">imageprovider-example.qml Example File</h1>
<span class="small-subtitle">declarative/cppextensions/imageprovider/imageprovider-example.qml</span>
<!-- $$$declarative/cppextensions/imageprovider/imageprovider-example.qml-description -->
<div class="descr"> <a name="details"></a>
<pre class="highlightedCode brush: cpp"> /****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
import QtQuick 1.0
import "ImageProviderCore" // import the plugin that registers the color image provider
Column {
Image { source: "image://colors/yellow" }
Image { source: "image://colors/red" }
}</pre>
</div>
<!-- @@@declarative/cppextensions/imageprovider/imageprovider-example.qml -->
<div class="feedback t_button">
[+] Documentation Feedback</div>
</div>
</div>
</div>
<div class="ft">
<span></span>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2008-2010 Nokia Corporation and/or its
subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation
in Finland and/or other countries worldwide.</p>
<p>
All other trademarks are property of their respective owners. <a title="Privacy Policy"
href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p>
<br />
<p>
Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p>
<p>
Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU
Free Documentation License version 1.3</a>
as published by the Free Software Foundation.</p>
</div>
<div id="feedbackBox">
<div id="feedcloseX" class="feedclose t_button">X</div>
<form id="feedform" action="http://doc.qt.nokia.com/docFeedbck/feedback.php" method="get">
<p id="noteHead">Thank you for giving your feedback.</p> <p class="note">Make sure it is related to this specific page. For more general bugs and
requests, please use the <a href="http://bugreports.qt.nokia.com/secure/Dashboard.jspa">Qt Bug Tracker</a>.</p>
<p><textarea id="feedbox" name="feedText" rows="5" cols="40"></textarea></p>
<p><input id="feedsubmit" class="feedclose" type="submit" name="feedback" /></p>
</form>
</div>
<div id="blurpage">
</div>
</body>
</html>
| Java |
<?php
// (c) Copyright 2002-2016 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
/**
* @group unit
*/
abstract class Search_Index_StemmingTest extends PHPUnit_Framework_TestCase
{
protected $index;
protected function populate($index)
{
$typeFactory = $index->getTypeFactory();
$index->addDocument(
[
'object_type' => $typeFactory->identifier('wikipage?!'),
'object_id' => $typeFactory->identifier('Comité Wiki'),
'description' => $typeFactory->plaintext('a descriptions for the pages éducation Case'),
'contents' => $typeFactory->plaintext('a descriptions for the pages éducation Case'),
'hebrew' => $typeFactory->plaintext('מחשב הוא מכונה המעבדת נתונים על פי תוכנית, כלומר על פי רצף פקודות נתון מראש. מחשבים הם חלק בלתי נפרד מחיי היומיום '),
]
);
}
function testSearchWithAdditionalS()
{
$query = new Search_Query('description');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testSearchWithMissingS()
{
$query = new Search_Query('page');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testSearchAccents()
{
$query = new Search_Query('education');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testSearchAccentExactMatch()
{
$query = new Search_Query('éducation');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testSearchExtraAccents()
{
$query = new Search_Query('pagé');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testCaseSensitivity()
{
$query = new Search_Query('casE');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testFilterIdentifierExactly()
{
$query = new Search_Query;
$query->filterType('wikipage?!');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testSearchObject()
{
$query = new Search_Query;
$query->addObject('wikipage?!', 'Comité Wiki');
$this->assertGreaterThan(0, count($query->search($this->index)));
}
function testStopWords()
{
$query = new Search_Query('a for the');
$this->assertEquals(0, count($query->search($this->index)));
}
function testHebrewString()
{
$query = new Search_Query;
$query->filterContent('מחשב', 'hebrew');
$this->assertEquals(1, count($query->search($this->index)));
}
}
| Java |
/*
Copyright (C) 2009-2010 Red Hat, Inc.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _H_MESSAGES
#define _H_MESSAGES
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <spice/protocol.h>
#include <spice/macros.h>
#ifdef USE_SMARTCARD_012
#include <vscard_common.h>
#else
#ifdef USE_SMARTCARD
#include <libcacard.h>
#endif
#endif
#include "draw.h"
SPICE_BEGIN_DECLS
typedef struct SpiceMsgData {
uint32_t data_size;
uint8_t data[0];
} SpiceMsgData;
typedef struct SpiceMsgCompressedData {
uint8_t type;
uint32_t uncompressed_size;
uint32_t compressed_size;
uint8_t *compressed_data;
} SpiceMsgCompressedData;
typedef struct SpiceMsgEmpty {
uint8_t padding;
} SpiceMsgEmpty;
typedef struct SpiceMsgInputsInit {
uint32_t keyboard_modifiers;
} SpiceMsgInputsInit;
typedef struct SpiceMsgInputsKeyModifiers {
uint32_t modifiers;
} SpiceMsgInputsKeyModifiers;
typedef struct SpiceMsgMainMultiMediaTime {
uint32_t time;
} SpiceMsgMainMultiMediaTime;
typedef struct SpiceMigrationDstInfo {
uint16_t port;
uint16_t sport;
uint32_t host_size;
uint8_t *host_data;
uint16_t pub_key_type;
uint32_t pub_key_size;
uint8_t *pub_key_data;
uint32_t cert_subject_size;
uint8_t *cert_subject_data;
} SpiceMigrationDstInfo;
typedef struct SpiceMsgMainMigrationBegin {
SpiceMigrationDstInfo dst_info;
} SpiceMsgMainMigrationBegin;
typedef struct SpiceMsgMainMigrateBeginSeamless {
SpiceMigrationDstInfo dst_info;
uint32_t src_mig_version;
} SpiceMsgMainMigrateBeginSeamless;
typedef struct SpiceMsgcMainMigrateDstDoSeamless {
uint32_t src_version;
} SpiceMsgcMainMigrateDstDoSeamless;
typedef struct SpiceMsgMainMigrationSwitchHost {
uint16_t port;
uint16_t sport;
uint32_t host_size;
uint8_t *host_data;
uint32_t cert_subject_size;
uint8_t *cert_subject_data;
} SpiceMsgMainMigrationSwitchHost;
typedef struct SpiceMsgMigrate {
uint32_t flags;
} SpiceMsgMigrate;
typedef struct SpiceResourceID {
uint8_t type;
uint64_t id;
} SpiceResourceID;
typedef struct SpiceResourceList {
uint16_t count;
SpiceResourceID resources[0];
} SpiceResourceList;
typedef struct SpiceMsgSetAck {
uint32_t generation;
uint32_t window;
} SpiceMsgSetAck;
typedef struct SpiceMsgcAckSync {
uint32_t generation;
} SpiceMsgcAckSync;
typedef struct SpiceWaitForChannel {
uint8_t channel_type;
uint8_t channel_id;
uint64_t message_serial;
} SpiceWaitForChannel;
typedef struct SpiceMsgWaitForChannels {
uint8_t wait_count;
SpiceWaitForChannel wait_list[0];
} SpiceMsgWaitForChannels;
typedef struct SpiceChannelId {
uint8_t type;
uint8_t id;
} SpiceChannelId;
typedef struct SpiceMsgMainInit {
uint32_t session_id;
uint32_t display_channels_hint;
uint32_t supported_mouse_modes;
uint32_t current_mouse_mode;
uint32_t agent_connected;
uint32_t agent_tokens;
uint32_t multi_media_time;
uint32_t ram_hint;
} SpiceMsgMainInit;
typedef struct SpiceMsgDisconnect {
uint64_t time_stamp;
uint32_t reason; // SPICE_ERR_?
} SpiceMsgDisconnect;
typedef struct SpiceMsgNotify {
uint64_t time_stamp;
uint32_t severity;
uint32_t visibilty;
uint32_t what;
uint32_t message_len;
uint8_t message[0];
} SpiceMsgNotify;
typedef struct SpiceMsgChannels {
uint32_t num_of_channels;
SpiceChannelId channels[0];
} SpiceMsgChannels;
typedef struct SpiceMsgMainName {
uint32_t name_len;
uint8_t name[0];
} SpiceMsgMainName;
typedef struct SpiceMsgMainUuid {
uint8_t uuid[16];
} SpiceMsgMainUuid;
typedef struct SpiceMsgMainMouseMode {
uint32_t supported_modes;
uint32_t current_mode;
} SpiceMsgMainMouseMode;
typedef struct SpiceMsgPing {
uint32_t id;
uint64_t timestamp;
void *data;
uint32_t data_len;
} SpiceMsgPing;
typedef struct SpiceMsgMainAgentDisconnect {
uint32_t error_code; // SPICE_ERR_?
} SpiceMsgMainAgentDisconnect;
#define SPICE_AGENT_MAX_DATA_SIZE 2048
typedef struct SpiceMsgMainAgentTokens {
uint32_t num_tokens;
} SpiceMsgMainAgentTokens, SpiceMsgcMainAgentTokens, SpiceMsgcMainAgentStart;
typedef struct SpiceMsgMainAgentTokens SpiceMsgMainAgentConnectedTokens;
typedef struct SpiceMsgcClientInfo {
uint64_t cache_size;
} SpiceMsgcClientInfo;
typedef struct SpiceMsgcMainMouseModeRequest {
uint32_t mode;
} SpiceMsgcMainMouseModeRequest;
typedef struct SpiceCursor {
uint32_t flags;
SpiceCursorHeader header;
uint32_t data_size;
uint8_t *data;
} SpiceCursor;
typedef struct SpiceMsgDisplayMode {
uint32_t x_res;
uint32_t y_res;
uint32_t bits;
} SpiceMsgDisplayMode;
typedef struct SpiceMsgSurfaceCreate {
uint32_t surface_id;
uint32_t width;
uint32_t height;
uint32_t format;
uint32_t flags;
} SpiceMsgSurfaceCreate;
typedef struct SpiceMsgSurfaceDestroy {
uint32_t surface_id;
} SpiceMsgSurfaceDestroy;
typedef struct SpiceMsgDisplayBase {
uint32_t surface_id;
SpiceRect box;
SpiceClip clip;
} SpiceMsgDisplayBase;
typedef struct SpiceMsgDisplayDrawFill {
SpiceMsgDisplayBase base;
SpiceFill data;
} SpiceMsgDisplayDrawFill;
typedef struct SpiceMsgDisplayDrawOpaque {
SpiceMsgDisplayBase base;
SpiceOpaque data;
} SpiceMsgDisplayDrawOpaque;
typedef struct SpiceMsgDisplayDrawCopy {
SpiceMsgDisplayBase base;
SpiceCopy data;
} SpiceMsgDisplayDrawCopy;
typedef struct SpiceMsgDisplayDrawTransparent {
SpiceMsgDisplayBase base;
SpiceTransparent data;
} SpiceMsgDisplayDrawTransparent;
typedef struct SpiceMsgDisplayDrawAlphaBlend {
SpiceMsgDisplayBase base;
SpiceAlphaBlend data;
} SpiceMsgDisplayDrawAlphaBlend;
typedef struct SpiceMsgDisplayDrawComposite {
SpiceMsgDisplayBase base;
SpiceComposite data;
} SpiceMsgDisplayDrawComposite;
typedef struct SpiceMsgDisplayCopyBits {
SpiceMsgDisplayBase base;
SpicePoint src_pos;
} SpiceMsgDisplayCopyBits;
typedef SpiceMsgDisplayDrawCopy SpiceMsgDisplayDrawBlend;
typedef struct SpiceMsgDisplayDrawRop3 {
SpiceMsgDisplayBase base;
SpiceRop3 data;
} SpiceMsgDisplayDrawRop3;
typedef struct SpiceMsgDisplayDrawBlackness {
SpiceMsgDisplayBase base;
SpiceBlackness data;
} SpiceMsgDisplayDrawBlackness;
typedef struct SpiceMsgDisplayDrawWhiteness {
SpiceMsgDisplayBase base;
SpiceWhiteness data;
} SpiceMsgDisplayDrawWhiteness;
typedef struct SpiceMsgDisplayDrawInvers {
SpiceMsgDisplayBase base;
SpiceInvers data;
} SpiceMsgDisplayDrawInvers;
typedef struct SpiceMsgDisplayDrawStroke {
SpiceMsgDisplayBase base;
SpiceStroke data;
} SpiceMsgDisplayDrawStroke;
typedef struct SpiceMsgDisplayDrawText {
SpiceMsgDisplayBase base;
SpiceText data;
} SpiceMsgDisplayDrawText;
typedef struct SpiceMsgDisplayInvalOne {
uint64_t id;
} SpiceMsgDisplayInvalOne;
typedef struct SpiceMsgDisplayStreamCreate {
uint32_t surface_id;
uint32_t id;
uint32_t flags;
uint32_t codec_type;
uint64_t stamp;
uint32_t stream_width;
uint32_t stream_height;
uint32_t src_width;
uint32_t src_height;
SpiceRect dest;
SpiceClip clip;
} SpiceMsgDisplayStreamCreate;
typedef struct SpiceStreamDataHeader {
uint32_t id;
uint32_t multi_media_time;
} SpiceStreamDataHeader;
typedef struct SpiceMsgDisplayStreamData {
SpiceStreamDataHeader base;
uint32_t data_size;
uint8_t data[0];
} SpiceMsgDisplayStreamData;
typedef struct SpiceMsgDisplayStreamDataSized {
SpiceStreamDataHeader base;
uint32_t width;
uint32_t height;
SpiceRect dest;
uint32_t data_size;
uint8_t data[0];
} SpiceMsgDisplayStreamDataSized;
typedef struct SpiceMsgDisplayStreamClip {
uint32_t id;
SpiceClip clip;
} SpiceMsgDisplayStreamClip;
typedef struct SpiceMsgDisplayStreamDestroy {
uint32_t id;
} SpiceMsgDisplayStreamDestroy;
typedef struct SpiceMsgDisplayStreamActivateReport {
uint32_t stream_id;
uint32_t unique_id;
uint32_t max_window_size;
uint32_t timeout_ms;
} SpiceMsgDisplayStreamActivateReport;
typedef struct SpiceMsgcDisplayStreamReport {
uint32_t stream_id;
uint32_t unique_id;
uint32_t start_frame_mm_time;
uint32_t end_frame_mm_time;
uint32_t num_frames;
uint32_t num_drops;
int32_t last_frame_delay;
uint32_t audio_delay;
} SpiceMsgcDisplayStreamReport;
typedef struct SpiceMsgcDisplayGlDrawDone {
} SpiceMsgcDisplayGlDrawDone;
typedef struct SpiceMsgCursorInit {
SpicePoint16 position;
uint16_t trail_length;
uint16_t trail_frequency;
uint8_t visible;
SpiceCursor cursor;
} SpiceMsgCursorInit;
typedef struct SpiceMsgCursorSet {
SpicePoint16 position;
uint8_t visible;
SpiceCursor cursor;
} SpiceMsgCursorSet;
typedef struct SpiceMsgCursorMove {
SpicePoint16 position;
} SpiceMsgCursorMove;
typedef struct SpiceMsgCursorTrail {
uint16_t length;
uint16_t frequency;
} SpiceMsgCursorTrail;
typedef struct SpiceMsgcDisplayInit {
uint8_t pixmap_cache_id;
int64_t pixmap_cache_size; //in pixels
uint8_t glz_dictionary_id;
int32_t glz_dictionary_window_size; // in pixels
} SpiceMsgcDisplayInit;
typedef struct SpiceMsgcKeyDown {
uint32_t code;
} SpiceMsgcKeyDown;
typedef struct SpiceMsgcKeyUp {
uint32_t code;
} SpiceMsgcKeyUp;
typedef struct SpiceMsgcKeyModifiers {
uint32_t modifiers;
} SpiceMsgcKeyModifiers;
typedef struct SpiceMsgcMouseMotion {
int32_t dx;
int32_t dy;
uint32_t buttons_state;
} SpiceMsgcMouseMotion;
typedef struct SpiceMsgcMousePosition {
uint32_t x;
uint32_t y;
uint32_t buttons_state;
uint8_t display_id;
} SpiceMsgcMousePosition;
typedef struct SpiceMsgcMousePress {
int32_t button;
int32_t buttons_state;
} SpiceMsgcMousePress;
typedef struct SpiceMsgcMouseRelease {
int32_t button;
int32_t buttons_state;
} SpiceMsgcMouseRelease;
typedef struct SpiceMsgAudioVolume {
uint8_t nchannels;
uint16_t volume[0];
} SpiceMsgAudioVolume;
typedef struct SpiceMsgAudioMute {
uint8_t mute;
} SpiceMsgAudioMute;
typedef struct SpiceMsgPlaybackMode {
uint32_t time;
uint32_t mode; //SPICE_AUDIO_DATA_MODE_?
uint8_t *data;
uint32_t data_size;
} SpiceMsgPlaybackMode, SpiceMsgcRecordMode;
typedef struct SpiceMsgPlaybackStart {
uint32_t channels;
uint32_t format; //SPICE_AUDIO_FMT_?
uint32_t frequency;
uint32_t time;
} SpiceMsgPlaybackStart;
typedef struct SpiceMsgPlaybackPacket {
uint32_t time;
uint8_t *data;
uint32_t data_size;
} SpiceMsgPlaybackPacket, SpiceMsgcRecordPacket;
typedef struct SpiceMsgPlaybackLatency {
uint32_t latency_ms;
} SpiceMsgPlaybackLatency;
typedef struct SpiceMsgRecordStart {
uint32_t channels;
uint32_t format; //SPICE_AUDIO_FMT_?
uint32_t frequency;
} SpiceMsgRecordStart;
typedef struct SpiceMsgcRecordStartMark {
uint32_t time;
} SpiceMsgcRecordStartMark;
typedef struct SpiceMsgTunnelInit {
uint16_t max_num_of_sockets;
uint32_t max_socket_data_size;
} SpiceMsgTunnelInit;
typedef uint8_t SpiceTunnelIPv4[4];
typedef struct SpiceMsgTunnelIpInfo {
uint16_t type;
union {
SpiceTunnelIPv4 ipv4;
} u;
uint8_t data[0];
} SpiceMsgTunnelIpInfo;
typedef struct SpiceMsgTunnelServiceIpMap {
uint32_t service_id;
SpiceMsgTunnelIpInfo virtual_ip;
} SpiceMsgTunnelServiceIpMap;
typedef struct SpiceMsgTunnelSocketOpen {
uint16_t connection_id;
uint32_t service_id;
uint32_t tokens;
} SpiceMsgTunnelSocketOpen;
/* connection id must be the first field in msgs directed to a specific connection */
typedef struct SpiceMsgTunnelSocketFin {
uint16_t connection_id;
} SpiceMsgTunnelSocketFin;
typedef struct SpiceMsgTunnelSocketClose {
uint16_t connection_id;
} SpiceMsgTunnelSocketClose;
typedef struct SpiceMsgTunnelSocketData {
uint16_t connection_id;
uint8_t data[0];
} SpiceMsgTunnelSocketData;
typedef struct SpiceMsgTunnelSocketTokens {
uint16_t connection_id;
uint32_t num_tokens;
} SpiceMsgTunnelSocketTokens;
typedef struct SpiceMsgTunnelSocketClosedAck {
uint16_t connection_id;
} SpiceMsgTunnelSocketClosedAck;
typedef struct SpiceMsgcTunnelAddGenericService {
uint32_t type;
uint32_t id;
uint32_t group;
uint32_t port;
uint64_t name;
uint64_t description;
union {
SpiceMsgTunnelIpInfo ip;
} u;
} SpiceMsgcTunnelAddGenericService;
typedef struct SpiceMsgcTunnelRemoveService {
uint32_t id;
} SpiceMsgcTunnelRemoveService;
/* connection id must be the first field in msgs directed to a specific connection */
typedef struct SpiceMsgcTunnelSocketOpenAck {
uint16_t connection_id;
uint32_t tokens;
} SpiceMsgcTunnelSocketOpenAck;
typedef struct SpiceMsgcTunnelSocketOpenNack {
uint16_t connection_id;
} SpiceMsgcTunnelSocketOpenNack;
typedef struct SpiceMsgcTunnelSocketData {
uint16_t connection_id;
uint8_t data[0];
} SpiceMsgcTunnelSocketData;
typedef struct SpiceMsgcTunnelSocketFin {
uint16_t connection_id;
} SpiceMsgcTunnelSocketFin;
typedef struct SpiceMsgcTunnelSocketClosed {
uint16_t connection_id;
} SpiceMsgcTunnelSocketClosed;
typedef struct SpiceMsgcTunnelSocketClosedAck {
uint16_t connection_id;
} SpiceMsgcTunnelSocketClosedAck;
typedef struct SpiceMsgcTunnelSocketTokens {
uint16_t connection_id;
uint32_t num_tokens;
} SpiceMsgcTunnelSocketTokens;
#ifdef USE_SMARTCARD
typedef struct SpiceMsgSmartcard {
VSCMsgType type;
uint32_t length;
uint32_t reader_id;
uint8_t data[0];
} SpiceMsgSmartcard;
typedef struct SpiceMsgcSmartcard {
VSCMsgHeader header;
union {
VSCMsgError error;
VSCMsgATR atr_data;
VSCMsgReaderAdd add;
};
} SpiceMsgcSmartcard;
#endif
typedef struct SpiceMsgDisplayHead {
uint32_t id;
uint32_t surface_id;
uint32_t width;
uint32_t height;
uint32_t x;
uint32_t y;
uint32_t flags;
} SpiceHead;
typedef struct SpiceMsgDisplayMonitorsConfig {
uint16_t count;
uint16_t max_allowed;
SpiceHead heads[0];
} SpiceMsgDisplayMonitorsConfig;
typedef struct SpiceMsgPortInit {
uint32_t name_size;
uint8_t *name;
uint8_t opened;
} SpiceMsgPortInit;
typedef struct SpiceMsgPortEvent {
uint8_t event;
} SpiceMsgPortEvent;
typedef struct SpiceMsgcPortEvent {
uint8_t event;
} SpiceMsgcPortEvent;
typedef struct SpiceMsgcDisplayPreferredVideoCodecType {
uint8_t num_of_codecs;
uint8_t codecs[0];
} SpiceMsgcDisplayPreferredVideoCodecType;
typedef struct SpiceMsgcDisplayPreferredCompression {
uint8_t image_compression;
} SpiceMsgcDisplayPreferredCompression;
typedef struct SpiceMsgDisplayGlScanoutUnix {
int drm_dma_buf_fd;
uint32_t width;
uint32_t height;
uint32_t stride;
uint32_t drm_fourcc_format;
uint32_t flags;
} SpiceMsgDisplayGlScanoutUnix;
typedef struct SpiceMsgDisplayGlDraw {
uint32_t x;
uint32_t y;
uint32_t w;
uint32_t h;
} SpiceMsgDisplayGlDraw;
SPICE_END_DECLS
#endif /* _H_SPICE_PROTOCOL */
| Java |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller.interfaces;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.jboss.as.controller.logging.ControllerLogger;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Overall interface criteria. Encapsulates a set of individual criteria and selects interfaces and addresses
* that meet them all.
*/
public final class OverallInterfaceCriteria implements InterfaceCriteria {
// java.net properties
static final String PREFER_IPV4_STACK = "java.net.preferIPv4Stack";
static final String PREFER_IPV6_ADDRESSES = "java.net.preferIPv6Addresses";
private static final long serialVersionUID = -5417786897309925997L;
private final String interfaceName;
private final Set<InterfaceCriteria> interfaceCriteria;
public OverallInterfaceCriteria(final String interfaceName, Set<InterfaceCriteria> criteria) {
this.interfaceName = interfaceName;
this.interfaceCriteria = criteria;
}
@Override
public Map<NetworkInterface, Set<InetAddress>> getAcceptableAddresses(Map<NetworkInterface, Set<InetAddress>> candidates) throws SocketException {
Map<NetworkInterface, Set<InetAddress>> result = AbstractInterfaceCriteria.cloneCandidates(candidates);
Set<InterfaceCriteria> sorted = new TreeSet<>(interfaceCriteria);
for (InterfaceCriteria criteria : sorted) {
result = criteria.getAcceptableAddresses(result);
if (result.size() == 0) {
break;
}
}
if (result.size() > 0) {
if (hasMultipleMatches(result)) {
// Multiple options matched the criteria. Eliminate the same address showing up in both
// a subinterface (an alias) and in the parent
result = pruneAliasDuplicates(result);
}
if (hasMultipleMatches(result)) {
// Multiple options matched the criteria. Try and narrow the selection based on
// preferences indirectly expressed via -Djava.net.preferIPv4Stack and -Djava.net.preferIPv6Addresses
result = pruneIPTypes(result);
}
if (hasMultipleMatches(result)) {
// Multiple options matched the criteria; Pick one
Map<NetworkInterface, Set<InetAddress>> selected = selectInterfaceAndAddress(result);
// Warn user their criteria was insufficiently exact
if (interfaceName != null) { // will be null if the resolution is being performed for the "resolved-address"
// user query operation in which case we don't want to log a WARN
Map.Entry<NetworkInterface, Set<InetAddress>> entry = selected.entrySet().iterator().next();
warnMultipleValidInterfaces(interfaceName, result, entry.getKey(), entry.getValue().iterator().next());
}
result = selected;
}
}
return result;
}
public String toString() {
StringBuilder sb = new StringBuilder("OverallInterfaceCriteria(");
for (InterfaceCriteria criteria : interfaceCriteria) {
sb.append(criteria.toString());
sb.append(",");
}
sb.setLength(sb.length() - 1);
sb.append(")");
return sb.toString();
}
@Override
public int compareTo(InterfaceCriteria o) {
if (this.equals(o)) {
return 0;
}
return 1;
}
private Map<NetworkInterface, Set<InetAddress>> pruneIPTypes(Map<NetworkInterface, Set<InetAddress>> candidates) {
Boolean preferIPv4Stack = getBoolean(PREFER_IPV4_STACK);
Boolean preferIPv6Stack = (preferIPv4Stack != null && !preferIPv4Stack) ? Boolean.TRUE : getBoolean(PREFER_IPV6_ADDRESSES);
if (preferIPv4Stack == null && preferIPv6Stack == null) {
// No meaningful user input
return candidates;
}
final Map<NetworkInterface, Set<InetAddress>> result = new HashMap<NetworkInterface, Set<InetAddress>>();
for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : candidates.entrySet()) {
Set<InetAddress> good = null;
for (InetAddress address : entry.getValue()) {
if ((preferIPv4Stack != null && preferIPv4Stack && address instanceof Inet4Address)
|| (preferIPv6Stack != null && preferIPv6Stack && address instanceof Inet6Address)) {
if (good == null) {
good = new HashSet<InetAddress>();
result.put(entry.getKey(), good);
}
good.add(address);
}
}
}
return result.size() == 0 ? candidates : result;
}
static Map<NetworkInterface, Set<InetAddress>> pruneAliasDuplicates(Map<NetworkInterface, Set<InetAddress>> result) {
final Map<NetworkInterface, Set<InetAddress>> pruned = new HashMap<NetworkInterface, Set<InetAddress>>();
for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : result.entrySet()) {
NetworkInterface ni = entry.getKey();
if (ni.getParent() != null) {
pruned.put(ni, entry.getValue());
} else {
Set<InetAddress> retained = new HashSet<InetAddress>(entry.getValue());
Enumeration<NetworkInterface> subInterfaces = ni.getSubInterfaces();
while (subInterfaces.hasMoreElements()) {
NetworkInterface sub = subInterfaces.nextElement();
Set<InetAddress> subAddresses = result.get(sub);
if (subAddresses != null) {
retained.removeAll(subAddresses);
}
}
if (retained.size() > 0) {
pruned.put(ni, retained);
}
}
}
return pruned;
}
private static Boolean getBoolean(final String property) {
final String value = WildFlySecurityManager.getPropertyPrivileged(property, null);
return value == null ? null : value.equalsIgnoreCase("true");
}
private static Map<NetworkInterface, Set<InetAddress>> selectInterfaceAndAddress(Map<NetworkInterface, Set<InetAddress>> acceptable) throws SocketException {
// Give preference to NetworkInterfaces that are 1) up, 2) not loopback 3) not point-to-point.
// If any of these criteria eliminate all interfaces, discard it.
if (acceptable.size() > 1) {
Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>();
for (NetworkInterface ni : acceptable.keySet()) {
if (ni.isUp()) {
preferred.put(ni, acceptable.get(ni));
}
}
if (preferred.size() > 0) {
acceptable = preferred;
} // else this preference eliminates all interfaces, so ignore it
}
if (acceptable.size() > 1) {
Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>();
for (NetworkInterface ni : acceptable.keySet()) {
if (!ni.isLoopback()) {
preferred.put(ni, acceptable.get(ni));
}
}
if (preferred.size() > 0) {
acceptable = preferred;
} // else this preference eliminates all interfaces, so ignore it
}
if (acceptable.size() > 1) {
Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>();
for (NetworkInterface ni : acceptable.keySet()) {
if (!ni.isPointToPoint()) {
preferred.put(ni, acceptable.get(ni));
}
}
if (preferred.size() > 0) {
acceptable = preferred;
} // else this preference eliminates all interfaces, so ignore it
}
if (hasMultipleMatches(acceptable)) {
// Give preference to non-link-local addresses
Map<NetworkInterface, Set<InetAddress>> preferred = new HashMap<NetworkInterface, Set<InetAddress>>();
for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : acceptable.entrySet()) {
Set<InetAddress> acceptableAddresses = entry.getValue();
if (acceptableAddresses.size() > 1) {
Set<InetAddress> preferredAddresses = null;
for (InetAddress addr : acceptableAddresses) {
if (!addr.isLinkLocalAddress()) {
if (preferredAddresses == null) {
preferredAddresses = new HashSet<InetAddress>();
preferred.put(entry.getKey(), preferredAddresses);
}
preferredAddresses.add(addr);
}
}
} else {
acceptable.put(entry.getKey(), acceptableAddresses);
}
}
if (preferred.size() > 0) {
acceptable = preferred;
} // else this preference eliminates all interfaces, so ignore it
}
Map.Entry<NetworkInterface, Set<InetAddress>> entry = acceptable.entrySet().iterator().next();
return Collections.singletonMap(entry.getKey(), Collections.singleton(entry.getValue().iterator().next()));
}
private static boolean hasMultipleMatches(Map<NetworkInterface, Set<InetAddress>> map) {
return map.size() > 1 || (map.size() == 1 && map.values().iterator().next().size() > 1);
}
private static void warnMultipleValidInterfaces(String interfaceName, Map<NetworkInterface, Set<InetAddress>> acceptable,
NetworkInterface selectedInterface, InetAddress selectedAddress) {
Set<String> nis = new HashSet<String>();
Set<InetAddress> addresses = new HashSet<InetAddress>();
for (Map.Entry<NetworkInterface, Set<InetAddress>> entry : acceptable.entrySet()) {
nis.add(entry.getKey().getName());
addresses.addAll(entry.getValue());
}
ControllerLogger.ROOT_LOGGER.multipleMatchingAddresses(interfaceName, addresses, nis, selectedAddress, selectedInterface.getName());
}
}
| Java |
/*
* CLiC, Framework for Command Line Interpretation in Eclipse
*
* Copyright (C) 2013 Worldline or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.worldline.clic.internal.assist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
/**
* This class allows to deal with autocompletion for all commands.
*
* @author mvanbesien
* @since 1.0
* @version 1.0
*/
public class ContentAssistProvider {
private final StyledText text;
private final IProcessor[] processors;
private final Map<String, Object> properties = new HashMap<String, Object>();
private IStructuredContentProvider assistContentProvider;
private Listener textKeyListener;
private Listener assistTablePopulationListener;
private Listener onSelectionListener;
private Listener onEscapeListener;
private IDoubleClickListener tableDoubleClickListener;
private Listener focusOutListener;
private Listener vanishListener;
private Table table;
private TableViewer viewer;
private Shell popupShell;
public ContentAssistProvider(final StyledText text,
final IProcessor... processors) {
this.text = text;
this.processors = processors;
build();
}
public void setProperty(final String key, final Object value) {
properties.put(key, value);
}
private void build() {
// Creation of graphical elements
final Display display = text.getDisplay();
popupShell = new Shell(display, SWT.ON_TOP);
popupShell.setLayout(new FillLayout());
table = new Table(popupShell, SWT.SINGLE);
viewer = new TableViewer(table);
assistContentProvider = newAssistContentProvider();
textKeyListener = newTextKeyListener();
assistTablePopulationListener = newAssistTablePopulationListener();
onSelectionListener = newOnSelectionListener();
onEscapeListener = newOnEscapeListener();
tableDoubleClickListener = newDoubleClickListener();
focusOutListener = newFocusOutListener();
vanishListener = newVanishListener();
viewer.setContentProvider(assistContentProvider);
text.addListener(SWT.KeyDown, textKeyListener);
text.addListener(SWT.Modify, assistTablePopulationListener);
table.addListener(SWT.DefaultSelection, onSelectionListener);
table.addListener(SWT.KeyDown, onEscapeListener);
viewer.addDoubleClickListener(tableDoubleClickListener);
table.addListener(SWT.FocusOut, focusOutListener);
text.addListener(SWT.FocusOut, focusOutListener);
text.getShell().addListener(SWT.Move, vanishListener);
text.addDisposeListener(newDisposeListener());
}
private DisposeListener newDisposeListener() {
return new DisposeListener() {
@Override
public void widgetDisposed(final DisposeEvent e) {
text.removeListener(SWT.KeyDown, textKeyListener);
text.removeListener(SWT.Modify, assistTablePopulationListener);
table.removeListener(SWT.DefaultSelection, onSelectionListener);
table.removeListener(SWT.KeyDown, onEscapeListener);
viewer.removeDoubleClickListener(tableDoubleClickListener);
table.removeListener(SWT.FocusOut, focusOutListener);
text.removeListener(SWT.FocusOut, focusOutListener);
text.getShell().removeListener(SWT.Move, vanishListener);
table.dispose();
popupShell.dispose();
}
};
}
private IStructuredContentProvider newAssistContentProvider() {
return new IStructuredContentProvider() {
@Override
public void inputChanged(final Viewer viewer,
final Object oldInput, final Object newInput) {
}
@Override
public void dispose() {
}
@Override
public Object[] getElements(final Object inputElement) {
final Collection<String> results = new ArrayList<String>();
if (inputElement instanceof String) {
final String input = (String) inputElement;
final ProcessorContext pc = new ProcessorContext(input,
text.getCaretOffset(), properties);
for (final IProcessor processor : processors)
results.addAll(processor.getProposals(pc));
}
return results.toArray();
}
};
}
private Listener newAssistTablePopulationListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.widget instanceof Text) {
final Text text = (Text) event.widget;
final String string = text.getText();
if (string.length() == 0)
// if (popupShell.isVisible())
popupShell.setVisible(false);
else {
viewer.setInput(string);
final Rectangle textBounds = text.getDisplay().map(
text.getParent(), null, text.getBounds());
popupShell.setBounds(textBounds.x, textBounds.y
+ textBounds.height, textBounds.width, 80);
// if (!popupShell.isVisible())
popupShell.setVisible(true);
}
}
}
};
}
private Listener newVanishListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
popupShell.setVisible(false);
}
};
}
private Listener newTextKeyListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
switch (event.keyCode) {
case SWT.ARROW_DOWN:
int index = (table.getSelectionIndex() + 1)
% table.getItemCount();
table.setSelection(index);
event.doit = false;
break;
case SWT.ARROW_UP:
index = table.getSelectionIndex() - 1;
if (index < 0)
index = table.getItemCount() - 1;
table.setSelection(index);
event.doit = false;
break;
case SWT.ARROW_RIGHT:
if (popupShell.isVisible()
&& table.getSelectionIndex() != -1) {
text.setText(table.getSelection()[0].getText());
text.setSelection(text.getText().length());
popupShell.setVisible(false);
}
break;
case SWT.ESC:
popupShell.setVisible(false);
break;
}
}
};
}
private IDoubleClickListener newDoubleClickListener() {
return new IDoubleClickListener() {
@Override
public void doubleClick(final DoubleClickEvent event) {
if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
text.setText(table.getSelection()[0].getText());
text.setSelection(text.getText().length());
popupShell.setVisible(false);
}
}
};
}
private Listener newOnSelectionListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.widget instanceof Text) {
final Text text = (Text) event.widget;
final ISelection selection = viewer.getSelection();
if (selection instanceof IStructuredSelection) {
text.setText(((IStructuredSelection) selection)
.getFirstElement().toString());
text.setSelection(text.getText().length() - 1);
}
popupShell.setVisible(false);
}
}
};
}
private Listener newOnEscapeListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
if (event.keyCode == SWT.ESC)
popupShell.setVisible(false);
}
};
}
private Listener newFocusOutListener() {
return new Listener() {
@Override
public void handleEvent(final Event event) {
popupShell.setVisible(false);
}
};
}
}
| Java |
// LICENSE: (Please see the file COPYING for details)
//
// NUS - Nemesis Utilities System: A C++ application development framework
// Copyright (C) 2006, 2007 Otavio Rodolfo Piske
//
// This file is part of NUS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation version 2.1
// of the License.
//
// 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "nthread.h"
void *nthread_start_routine(void *data) {
NThread *thread = static_cast<NThread *>(data);
thread->threadStart();
return NULL;
}
NThread::NThread(void)
: NObject()
{
}
void NThread::threadCreate() {
int ret = 0;
pthread_t a_thread;
ret = pthread_create(&a_thread, NULL, nthread_start_routine, (void *) this);
}
| Java |
package com.stek101.projectzulu.common.core;
/**
* For usage see: {@link Pair}
*/
public class PairDirectoryFile<K, V> {
private final K directory;
private final V file;
public static <K, V> PairDirectoryFile<K, V> createPair(K directory, V file) {
return new PairDirectoryFile<K, V>(directory, file);
}
public PairDirectoryFile(K directory, V file) {
this.file = file;
this.directory = directory;
}
public K getDirectory() {
return directory;
}
public V getFile() {
return file;
}
@Override
public boolean equals(Object object){
if (! (object instanceof PairDirectoryFile)) { return false; }
PairDirectoryFile pair = (PairDirectoryFile)object;
return directory.equals(pair.directory) && file.equals(pair.file);
}
@Override
public int hashCode(){
return 7 * directory.hashCode() + 13 * file.hashCode();
}
} | Java |
using System;
namespace InSimDotNet.Packets {
/// <summary>
/// Message to connection packet.
/// </summary>
/// <remarks>
/// Used to send a message to a specific connection or player (can only be used on hosts).
/// </remarks>
public class IS_MTC : IPacket, ISendable {
/// <summary>
/// Gets the size of the packet.
/// </summary>
public int Size { get; private set; }
/// <summary>
/// Gets the type of the packet.
/// </summary>
public PacketType Type { get; private set; }
/// <summary>
/// Gets or sets the request ID.
/// </summary>
public byte ReqI { get; set; }
/// <summary>
/// Gets or sets the sound effect.
/// </summary>
public MessageSound Sound { get; set; }
/// <summary>
/// Gets or sets the unique ID of the connection to send the message to (0 = host / 255 = all).
/// </summary>
public byte UCID { get; set; }
/// <summary>
/// Gets or sets the unique ID of the player to send the message to (if 0 use UCID).
/// </summary>
public byte PLID { get; set; }
/// <summary>
/// Gets or sets the message to send.
/// </summary>
public string Msg { get; set; }
/// <summary>
/// Creates a new message to connection packet.
/// </summary>
public IS_MTC() {
Size = 8;
Type = PacketType.ISP_MTC;
Msg = String.Empty;
}
/// <summary>
/// Returns the packet data.
/// </summary>
/// <returns>The packet data.</returns>
public byte[] GetBuffer() {
// Encode string first so we can figure out the packet size.
byte[] buffer = new byte[128];
int length = LfsEncoding.Current.GetBytes(Msg, buffer, 0, 128);
// Get the packet size (MTC needs trailing zero).
Size = (byte)(8 + Math.Min(length + (4 - (length % 4)), 128));
PacketWriter writer = new PacketWriter(Size);
writer.WriteSize(Size);
writer.Write((byte)Type);
writer.Write(ReqI);
writer.Write((byte)Sound);
writer.Write(UCID);
writer.Write(PLID);
writer.Skip(2);
writer.Write(buffer, length);
return writer.GetBuffer();
}
}
}
| Java |
// BESWWW.h
// This file is part of bes, A C++ back-end server implementation framework
// for the OPeNDAP Data Access Protocol.
// Copyright (c) 2004,2005 University Corporation for Atmospheric Research
// Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
// You can contact University Corporation for Atmospheric Research at
// 3080 Center Green Drive, Boulder, CO 80301
// (c) COPYRIGHT University Corporation for Atmospheric Research 2004-2005
// Please read the full copyright statement in the file COPYRIGHT_UCAR.
//
// Authors:
// pwest Patrick West <pwest@ucar.edu>
// jgarcia Jose Garcia <jgarcia@ucar.edu>
#ifndef I_BESWWW_h
#define I_BESWWW_h 1
#include "BESResponseObject.h"
#include "BESDASResponse.h"
#include "BESDDSResponse.h"
/** @brief container for a DAS and DDS needed to write out the usage
* information for a dataset.
*
* This is a container for the usage response information, which needs a DAS
* and a DDS. An instances of BESWWW takes ownership of the das and dds
* passed to it and deletes it in the destructor.
*
* @see BESResponseObject
* @see DAS
* @see DDS
*/
class BESWWW : public BESResponseObject
{
private:
#if 0
BESDASResponse *_das ;
#endif
BESDDSResponse *_dds ;
BESWWW() {}
public:
BESWWW( /* BESDASResponse *das,*/ BESDDSResponse *dds )
: /*_das( das ),*/ _dds( dds ) {}
virtual ~ BESWWW() {
#if 0
if (_das)
delete _das;
#endif
if (_dds)
delete _dds;
}
#if 0
BESDASResponse *get_das() { return _das ; }
#endif
BESDDSResponse *get_dds() { return _dds ; }
/** @brief dumps information about this object
*
* Displays the pointer value of this instance along with the das object
* created
*
* @param strm C++ i/o stream to dump the information to
*/
virtual void dump(ostream & strm) const {
strm << BESIndent::LMarg << "dump - (" << (void *) this << ")" << endl;
BESIndent::Indent();
#if 0
strm << BESIndent::LMarg << "das: " << *_das << endl;
#endif
strm << BESIndent::LMarg << "dds: " << *_dds << endl;
BESIndent::UnIndent();
}
} ;
#endif // I_BESWWW_h
| Java |
package fastSim.data;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.*;
//import fanweizhu.fastSim.util.Config;
//import fanweizhu.fastSim.util.IndexManager;
//import fanweizhu.fastSim.util.KeyValuePair;
//import fanweizhu.fastSim.util.MapCapacity;
import fastSim.util.*;
import fastSim.util.io.DataReader;
import fastSim.util.io.DataWriter;
public class PrimeSim implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7028575305146090045L;
private List<Integer> hubs;
protected Map<Integer, Map<Integer,Double>> map;
protected boolean outG;
protected List<Integer> meetingNodes;
/*public PrimeSim(int capacity) {
super(capacity);
hubs = new ArrayList<Integer>();
}*/
public PrimeSim() {
map = new HashMap<Integer, Map<Integer,Double>>();
hubs = new ArrayList<Integer>();
meetingNodes = new ArrayList<Integer>();
}
public PrimeSim(int numNodes) {
//need to change MapCapacity when double->Map?
map = new HashMap<Integer, Map<Integer,Double>>(MapCapacity.compute(numNodes));
hubs = new ArrayList<Integer>();
}
public Set<Integer> getLengths(){
return map.keySet();
}
public int numHubs() {
return hubs.size();
}
public int numLength(){
return map.size();
}
public Map<Integer,Map<Integer,Double>> getMap(){
return map;
}
public int getHubId(int index) {
return hubs.get(index);
}
public List<Integer> getMeetingNodes(){
return meetingNodes;
}
public void addNewNode(Node h, String simType){
h.isVisited = true;
if(h.isHub)
hubs.add(h.id);
if(simType=="in" && h.out.size()>1) //store meeting nodes for ingraphs //meetingnodes refer to >1 nodes (descendants)
meetingNodes.add(h.id);
}
public void set(int l, Node n, double value) {
// if (n.isVisited == false){
// if (n.isHub)
// hubs.add(n.id);
// if (graphType=="in" && n.in.size()>1)
// meetingNodes.add(n.id);
// }
//
Map<Integer, Double> nodesVal;
if (map.get(l)!= null)
{
nodesVal = map.get(l);
nodesVal.put(n.id, value);
map.put(l, nodesVal);
}
else
{
nodesVal = new HashMap<Integer,Double>();
nodesVal.put(n.id, value);
map.put(l, nodesVal);
}
}
public void set(int l, Map<Integer,Double> nodeValuePairs){
//System.out.println(l);
Map<Integer, Double> nodesVal = map.get(l);
// for(Integer i:nodeValuePairs.keySet()) {
// System.out.println("PS node: "+ i + " rea: " +nodeValuePairs.get(i));
// }
if(nodesVal == null)
{
map.put(l, nodeValuePairs);
}
else{
System.out.println("####PrimeSim line108: should not go to here.");
nodesVal.putAll(nodeValuePairs);
map.put(l, nodesVal);
}
//System.out.println("length_Test:" + l + " Map_Size:" + map.get(l).size());
// for(Integer i: map.get(l).keySet())
// System.out.println(map.get(l).get(i));
}
public long computeStorageInBytes() {
long nodeIdSize = (1 + hubs.size()) * 4;
long mapSize = (1 + map.size()) * 4 + map.size() * 8;
return nodeIdSize + mapSize;
}
public String getCountInfo() {
//int graphSize = map.size();
int hubSize = hubs.size();
int meetingNodesSize = meetingNodes.size();
return "hub size: " + hubSize + " meetingNodesSize: " + meetingNodesSize ;
}
public void trim(double clip) {
Map<Integer, Map<Integer,Double>> newMap = new HashMap<Integer, Map<Integer,Double>>();
List<Integer> newHublist = new ArrayList<Integer>();
List<Integer> newXlist = new ArrayList<Integer>();
for (int l: map.keySet()){
Map<Integer, Double> pairMap =map.get(l);
Map<Integer, Double> newPairs = new HashMap<Integer, Double>();
for (int nid: pairMap.keySet()){
double score = pairMap.get(nid);
if (score > clip){
newPairs.put(nid, score);
if(hubs.contains(nid) && !newHublist.contains(nid))
newHublist.add(nid);
if(meetingNodes.contains(nid) && !newXlist.contains(nid))
newXlist.add(nid);
}
}
newMap.put(l, newPairs);
}
this.map = newMap;
this.hubs = newHublist;
this.meetingNodes = newXlist;
}
public void saveToDisk(int id,String type,boolean doTrim) throws Exception {
String path = "";
if(type == "out")
//path = "./outSim/" + Integer.toString(id);
path = IndexManager.getIndexDeepDir() + "out/" +Integer.toString(id);
else if(type == "in")
//path = "./inSim/" + Integer.toString(id);
path = IndexManager.getIndexDeepDir() + "in/" +Integer.toString(id);
else{
System.out.println("Type of prime graph should be either out or in.");
System.exit(0);
}
// System.out.println(path+"/"+id);
DataWriter out = new DataWriter(path);
if (doTrim)
trim(Config.clip);
out.writeInteger(hubs.size());
for (int i : hubs) {
out.writeInteger(i);
}
out.writeInteger(meetingNodes.size());
for(int i: meetingNodes){
out.writeInteger(i);
}
out.writeInteger(map.size());
for(int i=0; i<map.size();i++){
int pairNum = map.get(i).size();
Map<Integer,Double> pairMap = map.get(i);
out.writeInteger(pairNum);
for(int j: pairMap.keySet()){
out.writeInteger(j);
out.writeDouble(pairMap.get(j));
}
}
out.close();
/*//test: read all the content
DataReader in = new DataReader(path);
while(true){
double oneNum =in.readDouble();
if (oneNum == -1.11)
break;
System.out.print(oneNum+"\t");
}
System.out.println();
in.close();*/
}
public void loadFromDisk(int id,String type) throws Exception {
String path = "";
if(type == "out")
path = IndexManager.getIndexDeepDir() + "out/" + Integer.toString(id);
else if(type == "in")
path = IndexManager.getIndexDeepDir() + "in/" + Integer.toString(id);
else
{
System.out.println("Type of prime graph should be either out or in.");
System.exit(0);
}
//==============
DataReader in = new DataReader(path);
int n = in.readInteger();
this.hubs = new ArrayList<Integer>(n);
for (int i = 0; i < n; i++)
this.hubs.add(in.readInteger());
int numM = in.readInteger();
this.meetingNodes=new ArrayList<Integer>(numM);
for(int i =0; i<numM; i++)
this.meetingNodes.add(in.readInteger());
int numL = in.readInteger();
for(int i=0; i<numL; i++){
int numPair = in.readInteger();
Map<Integer,Double> pairMap = new HashMap<Integer, Double>();
for(int j=0; j<numPair; j++){
int nodeId = in.readInteger();
double nodeScore = in.readDouble();
pairMap.put(nodeId, nodeScore);
}
this.map.put(i, pairMap);
}
in.close();
}
public PrimeSim duplicate() {
// TODO Auto-generated method stub
PrimeSim sim = new PrimeSim();
sim.map.putAll(this.map);
return sim;
}
public void addFrom(PrimeSim nextOut, Map<Integer, Double> oneHubValue) {
// TODO Auto-generated method stub
for (int lenToHub : oneHubValue.keySet()){
double hubScoreoflen = oneHubValue.get(lenToHub);
for (int lenFromHub : nextOut.getMap().keySet()){
if(lenFromHub == 0){
// the new score of hub (over length==0) is just the score on prime graph
continue;
}
int newLen = lenToHub + lenFromHub;
if (!this.getMap().containsKey(newLen))
this.getMap().put(newLen, new HashMap<Integer,Double>());
for(int toNode: nextOut.getMap().get(lenFromHub).keySet()){
double oldValue = this.getMap().get(newLen).keySet()
.contains(toNode) ? this.getMap().get(newLen).get(toNode): 0.0;
//System.out.println(oldValue);
double newValue = hubScoreoflen *nextOut.getMap().get(lenFromHub).get(toNode);
// //added aug-29
// if (newValue<Config.epsilon)
// continue;
this.getMap().get(newLen).put(toNode, oldValue + newValue) ;
// PrintInfor.printDoubleMap(this.getMap(), "assemble simout of the hub at length: " + lenFromHub +" node: "+ toNode );
// System.out.println(this.getMap());
}
}
}
}
public void addMeetingNodes(List<Integer> nodes){
for (int nid: nodes){
if (!this.meetingNodes.contains(nid))
this.meetingNodes.add(nid);
}
//System.out.println("====PrimeSim: line 195: meetingnodes Size " + this.meetingNodes.size());
}
}
| Java |
/* Copyright (c) 2013-2014 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.geotools.data;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;
import org.eclipse.jdt.annotation.Nullable;
import org.geotools.data.DataStore;
import org.geotools.data.Transaction;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.store.ContentDataStore;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentState;
import org.geotools.feature.NameImpl;
import org.locationtech.geogig.data.FindFeatureTypeTrees;
import org.locationtech.geogig.model.ObjectId;
import org.locationtech.geogig.model.Ref;
import org.locationtech.geogig.model.RevObject.TYPE;
import org.locationtech.geogig.model.RevTree;
import org.locationtech.geogig.model.SymRef;
import org.locationtech.geogig.plumbing.ForEachRef;
import org.locationtech.geogig.plumbing.RefParse;
import org.locationtech.geogig.plumbing.RevParse;
import org.locationtech.geogig.plumbing.TransactionBegin;
import org.locationtech.geogig.porcelain.AddOp;
import org.locationtech.geogig.porcelain.CheckoutOp;
import org.locationtech.geogig.porcelain.CommitOp;
import org.locationtech.geogig.repository.Context;
import org.locationtech.geogig.repository.GeogigTransaction;
import org.locationtech.geogig.repository.NodeRef;
import org.locationtech.geogig.repository.Repository;
import org.locationtech.geogig.repository.WorkingTree;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.Name;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Throwables;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
/**
* A GeoTools {@link DataStore} that serves and edits {@link SimpleFeature}s in a geogig repository.
* <p>
* Multiple instances of this kind of data store may be created against the same repository,
* possibly working against different {@link #setHead(String) heads}.
* <p>
* A head is any commit in GeoGig. If a head has a branch pointing at it then the store allows
* transactions, otherwise no data modifications may be made.
*
* A branch in Geogig is a separate line of history that may or may not share a common ancestor with
* another branch. In the later case the branch is called "orphan" and by convention the default
* branch is called "master", which is created when the geogig repo is first initialized, but does
* not necessarily exist.
* <p>
* Every read operation (like in {@link #getFeatureSource(Name)}) reads committed features out of
* the configured "head" branch. Write operations are only supported if a {@link Transaction} is
* set, in which case a {@link GeogigTransaction} is tied to the geotools transaction by means of a
* {@link GeogigTransactionState}. During the transaction, read operations will read from the
* transaction's {@link WorkingTree} in order to "see" features that haven't been committed yet.
* <p>
* When the transaction is committed, the changes made inside that transaction are merged onto the
* actual repository. If any other change was made to the repository meanwhile, a rebase will be
* attempted, and the transaction commit will fail if the rebase operation finds any conflict. This
* provides for optimistic locking and reduces thread contention.
*
*/
public class GeoGigDataStore extends ContentDataStore implements DataStore {
private final Repository geogig;
/** @see #setHead(String) */
private String refspec;
/** When the configured head is not a branch, we disallow transactions */
private boolean allowTransactions = true;
public GeoGigDataStore(Repository geogig) {
super();
Preconditions.checkNotNull(geogig);
this.geogig = geogig;
}
@Override
public void dispose() {
super.dispose();
geogig.close();
}
/**
* Instructs the datastore to operate against the specified refspec, or against the checked out
* branch, whatever it is, if the argument is {@code null}.
*
* Editing capabilities are disabled if the refspec is not a local branch.
*
* @param refspec the name of the branch to work against, or {@code null} to default to the
* currently checked out branch
* @see #getConfiguredBranch()
* @see #getOrFigureOutHead()
* @throws IllegalArgumentException if {@code refspec} is not null and no such commit exists in
* the repository
*/
public void setHead(@Nullable final String refspec) throws IllegalArgumentException {
if (refspec == null) {
allowTransactions = true; // when no branch name is set we assume we should make
// transactions against the current HEAD
} else {
final Context context = getCommandLocator(null);
Optional<ObjectId> rev = context.command(RevParse.class).setRefSpec(refspec).call();
if (!rev.isPresent()) {
throw new IllegalArgumentException("Bad ref spec: " + refspec);
}
Optional<Ref> branchRef = context.command(RefParse.class).setName(refspec).call();
if (branchRef.isPresent()) {
Ref ref = branchRef.get();
if (ref instanceof SymRef) {
ref = context.command(RefParse.class).setName(((SymRef) ref).getTarget()).call()
.orNull();
}
Preconditions.checkArgument(ref != null, "refSpec is a dead symref: " + refspec);
if (ref.getName().startsWith(Ref.HEADS_PREFIX)) {
allowTransactions = true;
} else {
allowTransactions = false;
}
} else {
allowTransactions = false;
}
}
this.refspec = refspec;
}
public String getOrFigureOutHead() {
String branch = getConfiguredHead();
if (branch != null) {
return branch;
}
return getCheckedOutBranch();
}
public Repository getGeogig() {
return geogig;
}
/**
* @return the configured refspec of the commit this datastore works against, or {@code null} if
* no head in particular has been set, meaning the data store works against whatever the
* currently checked out branch is.
*/
@Nullable
public String getConfiguredHead() {
return this.refspec;
}
/**
* @return whether or not we can support transactions against the configured head
*/
public boolean isAllowTransactions() {
return this.allowTransactions;
}
/**
* @return the name of the currently checked out branch in the repository, not necessarily equal
* to {@link #getConfiguredBranch()}, or {@code null} in the (improbable) case HEAD is
* on a dettached state (i.e. no local branch is currently checked out)
*/
@Nullable
public String getCheckedOutBranch() {
Optional<Ref> head = getCommandLocator(null).command(RefParse.class).setName(Ref.HEAD)
.call();
if (!head.isPresent()) {
return null;
}
Ref headRef = head.get();
if (!(headRef instanceof SymRef)) {
return null;
}
String refName = ((SymRef) headRef).getTarget();
Preconditions.checkState(refName.startsWith(Ref.HEADS_PREFIX));
String branchName = refName.substring(Ref.HEADS_PREFIX.length());
return branchName;
}
public ImmutableList<String> getAvailableBranches() {
ImmutableSet<Ref> heads = getCommandLocator(null).command(ForEachRef.class)
.setPrefixFilter(Ref.HEADS_PREFIX).call();
List<String> list = Lists.newArrayList(Collections2.transform(heads, (ref) -> {
String branchName = ref.getName().substring(Ref.HEADS_PREFIX.length());
return branchName;
}));
Collections.sort(list);
return ImmutableList.copyOf(list);
}
public Context getCommandLocator(@Nullable Transaction transaction) {
Context commandLocator = null;
if (transaction != null && !Transaction.AUTO_COMMIT.equals(transaction)) {
GeogigTransactionState state;
state = (GeogigTransactionState) transaction.getState(GeogigTransactionState.class);
Optional<GeogigTransaction> geogigTransaction = state.getGeogigTransaction();
if (geogigTransaction.isPresent()) {
commandLocator = geogigTransaction.get();
}
}
if (commandLocator == null) {
commandLocator = geogig.context();
}
return commandLocator;
}
public Name getDescriptorName(NodeRef treeRef) {
Preconditions.checkNotNull(treeRef);
Preconditions.checkArgument(TYPE.TREE.equals(treeRef.getType()));
Preconditions.checkArgument(!treeRef.getMetadataId().isNull(),
"NodeRef '%s' is not a feature type reference", treeRef.path());
return new NameImpl(getNamespaceURI(), NodeRef.nodeFromPath(treeRef.path()));
}
public NodeRef findTypeRef(Name typeName, @Nullable Transaction tx) {
Preconditions.checkNotNull(typeName);
final String localName = typeName.getLocalPart();
final List<NodeRef> typeRefs = findTypeRefs(tx);
Collection<NodeRef> matches = Collections2.filter(typeRefs, new Predicate<NodeRef>() {
@Override
public boolean apply(NodeRef input) {
return NodeRef.nodeFromPath(input.path()).equals(localName);
}
});
switch (matches.size()) {
case 0:
throw new NoSuchElementException(
String.format("No tree ref matched the name: %s", localName));
case 1:
return matches.iterator().next();
default:
throw new IllegalArgumentException(String
.format("More than one tree ref matches the name %s: %s", localName, matches));
}
}
@Override
protected ContentState createContentState(ContentEntry entry) {
return new ContentState(entry);
}
@Override
protected ImmutableList<Name> createTypeNames() throws IOException {
List<NodeRef> typeTrees = findTypeRefs(Transaction.AUTO_COMMIT);
return ImmutableList
.copyOf(Collections2.transform(typeTrees, (ref) -> getDescriptorName(ref)));
}
private List<NodeRef> findTypeRefs(@Nullable Transaction tx) {
final String rootRef = getRootRef(tx);
Context commandLocator = getCommandLocator(tx);
List<NodeRef> typeTrees = commandLocator.command(FindFeatureTypeTrees.class)
.setRootTreeRef(rootRef).call();
return typeTrees;
}
String getRootRef(@Nullable Transaction tx) {
final String rootRef;
if (null == tx || Transaction.AUTO_COMMIT.equals(tx)) {
rootRef = getOrFigureOutHead();
} else {
rootRef = Ref.WORK_HEAD;
}
return rootRef;
}
@Override
protected GeogigFeatureStore createFeatureSource(ContentEntry entry) throws IOException {
return new GeogigFeatureStore(entry);
}
/**
* Creates a new feature type tree on the {@link #getOrFigureOutHead() current branch}.
* <p>
* Implementation detail: the operation is the homologous to starting a transaction, checking
* out the current/configured branch, creating the type tree inside the transaction, issueing a
* geogig commit, and committing the transaction for the created tree to be merged onto the
* configured branch.
*/
@Override
public void createSchema(SimpleFeatureType featureType) throws IOException {
if (!allowTransactions) {
throw new IllegalStateException("Configured head " + refspec
+ " is not a branch; transactions are not supported.");
}
GeogigTransaction tx = getCommandLocator(null).command(TransactionBegin.class).call();
boolean abort = false;
try {
String treePath = featureType.getName().getLocalPart();
// check out the datastore branch on the transaction space
final String branch = getOrFigureOutHead();
tx.command(CheckoutOp.class).setForce(true).setSource(branch).call();
// now we can use the transaction working tree with the correct branch checked out
WorkingTree workingTree = tx.workingTree();
workingTree.createTypeTree(treePath, featureType);
tx.command(AddOp.class).addPattern(treePath).call();
tx.command(CommitOp.class).setMessage("Created feature type tree " + treePath).call();
tx.commit();
} catch (IllegalArgumentException alreadyExists) {
abort = true;
throw new IOException(alreadyExists.getMessage(), alreadyExists);
} catch (Exception e) {
abort = true;
throw Throwables.propagate(e);
} finally {
if (abort) {
tx.abort();
}
}
}
// Deliberately leaving the @Override annotation commented out so that the class builds
// both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x)
// @Override
public void removeSchema(Name name) throws IOException {
throw new UnsupportedOperationException(
"removeSchema not yet supported by geogig DataStore");
}
// Deliberately leaving the @Override annotation commented out so that the class builds
// both against GeoTools 10.x and 11.x (as the method was added to DataStore in 11.x)
// @Override
public void removeSchema(String name) throws IOException {
throw new UnsupportedOperationException(
"removeSchema not yet supported by geogig DataStore");
}
public static enum ChangeType {
ADDED, REMOVED, CHANGED_NEW, CHANGED_OLD;
}
/**
* Builds a FeatureSource (read-only) that fetches features out of the differences between two
* root trees: a provided tree-ish as the left side of the comparison, and the datastore's
* configured HEAD as the right side of the comparison.
* <p>
* E.g., to get all features of a given feature type that were removed between a given commit
* and its parent:
*
* <pre>
* <code>
* String commitId = ...
* GeoGigDataStore store = new GeoGigDataStore(geogig);
* store.setHead(commitId);
* FeatureSource removed = store.getDiffFeatureSource("roads", commitId + "~1", ChangeType.REMOVED);
* </code>
* </pre>
*
* @param typeName the feature type name to look up a type tree for in the datastore's current
* {@link #getOrFigureOutHead() HEAD}
* @param oldRoot a tree-ish string that resolves to the ROOT tree to be used as the left side
* of the diff
* @param changeType the type of change between {@code oldRoot} and {@link #getOrFigureOutHead()
* head} to pick as the features to return.
* @return a feature source whose features are computed out of the diff between the feature type
* diffs between the given {@code oldRoot} and the datastore's
* {@link #getOrFigureOutHead() HEAD}.
*/
public SimpleFeatureSource getDiffFeatureSource(final String typeName, final String oldRoot,
final ChangeType changeType) throws IOException {
Preconditions.checkNotNull(typeName, "typeName");
Preconditions.checkNotNull(oldRoot, "oldRoot");
Preconditions.checkNotNull(changeType, "changeType");
final Name name = name(typeName);
final ContentEntry entry = ensureEntry(name);
GeogigFeatureSource featureSource = new GeogigFeatureSource(entry);
featureSource.setTransaction(Transaction.AUTO_COMMIT);
featureSource.setChangeType(changeType);
if (ObjectId.NULL.toString().equals(oldRoot)
|| RevTree.EMPTY_TREE_ID.toString().equals(oldRoot)) {
featureSource.setOldRoot(null);
} else {
featureSource.setOldRoot(oldRoot);
}
return featureSource;
}
}
| Java |
/* Copyright (C) 2008-2011 D. V. Wiebe
*
***************************************************************************
*
* This file is part of the GetData project.
*
* GetData is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* GetData 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with GetData; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Attempt to read INT32 as INT64 */
#include "test.h"
#include <inttypes.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
int main(void)
{
const char *filedir = "dirfile";
const char *format = "dirfile/format";
const char *data = "dirfile/data";
const char *format_data = "data RAW INT32 8\n";
int32_t data_data[256];
int64_t c[8];
int fd, i, n, error, r = 0;
DIRFILE *D;
memset(c, 0, 8);
rmdirfile();
mkdir(filedir, 0777);
for (fd = 0; fd < 256; ++fd)
data_data[fd] = fd;
fd = open(format, O_CREAT | O_EXCL | O_WRONLY, 0666);
write(fd, format_data, strlen(format_data));
close(fd);
fd = open(data, O_CREAT | O_EXCL | O_WRONLY | O_BINARY, 0666);
write(fd, data_data, 256 * sizeof(int32_t));
close(fd);
D = gd_open(filedir, GD_RDONLY | GD_VERBOSE);
n = gd_getdata(D, "data", 5, 0, 1, 0, GD_INT64, c);
error = gd_error(D);
gd_close(D);
unlink(data);
unlink(format);
rmdir(filedir);
CHECKI(error, 0);
CHECKI(n, 8);
for (i = 0; i < 8; ++i)
CHECKIi(i,c[i], 40 + i);
return r;
}
| Java |
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2003-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* 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
* Lesser General Public License for more details.
*/
package org.geotools.data.vpf.exc;
/**
* Class VPFHeaderFormatException.java is responsible for
*
* <p>Created: Tue Jan 21 15:12:10 2003
*
* @author <a href="mailto:kobit@users.sourceforge.net">Artur Hefczyc</a>
* @source $URL$
* @version 1.0.0
*/
public class VPFHeaderFormatException extends VPFDataException {
/** serialVersionUID */
private static final long serialVersionUID = 4680952037855445222L;
/** Creates a new VPFHeaderFormatException object. */
public VPFHeaderFormatException() {
super();
}
/**
* Creates a new VPFHeaderFormatException object.
*
* @param message DOCUMENT ME!
*/
public VPFHeaderFormatException(String message) {
super(message);
}
}
// VPFHeaderFormatException
| Java |
#!/usr/bin/env python
import sys
import gobject
import dbus.mainloop.glib
dbus.mainloop.glib.DBusGMainLoop(set_as_default = True)
import telepathy
DBUS_PROPERTIES = 'org.freedesktop.DBus.Properties'
def get_registry():
reg = telepathy.client.ManagerRegistry()
reg.LoadManagers()
return reg
def get_connection_manager(reg):
cm = reg.GetManager('bluewire')
return cm
class Action(object):
def __init__(self):
self._action = None
def queue_action(self):
pass
def append_action(self, action):
assert self._action is None
self._action = action
def get_next_action(self):
assert self._action is not None
return self._action
def _on_done(self):
if self._action is None:
return
self._action.queue_action()
def _on_error(self, error):
print error
def _on_generic_message(self, *args):
pass
class DummyAction(Action):
def queue_action(self):
gobject.idle_add(self._on_done)
class QuitLoop(Action):
def __init__(self, loop):
super(QuitLoop, self).__init__()
self._loop = loop
def queue_action(self):
self._loop.quit()
class DisplayParams(Action):
def __init__(self, cm):
super(DisplayParams, self).__init__()
self._cm = cm
def queue_action(self):
self._cm[telepathy.interfaces.CONN_MGR_INTERFACE].GetParameters(
'bluetooth,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, params):
print "Connection Parameters:"
for name, flags, signature, default in params:
print "\t%s (%s)" % (name, signature),
if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_REQUIRED:
print "required",
if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_REGISTER:
print "register",
if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_SECRET:
print "secret",
if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_DBUS_PROPERTY:
print "dbus-property",
if flags & telepathy.constants.CONN_MGR_PARAM_FLAG_HAS_DEFAULT:
print "has-default(%s)" % default,
print ""
super(DisplayParams, self)._on_done()
class RequestConnection(Action):
def __init__(self, cm, username, password, forward):
super(RequestConnection, self).__init__()
self._cm = cm
self._conn = None
self._serviceName = None
self._username = username
self._password = password
self._forward = forward
@property
def conn(self):
return self._conn
@property
def serviceName(self):
return self._serviceName
def queue_action(self):
self._cm[telepathy.server.CONNECTION_MANAGER].RequestConnection(
'bluetooth",
{
'account': self._username,
'password': self._password,
'forward': self._forward,
},
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, busName, objectPath):
self._serviceName = busName
self._conn = telepathy.client.Connection(busName, objectPath)
super(RequestConnection, self)._on_done()
class Connect(Action):
def __init__(self, connAction):
super(Connect, self).__init__()
self._connAction = connAction
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION].connect_to_signal(
'StatusChanged',
self._on_change,
)
self._connAction.conn[telepathy.server.CONNECTION].Connect(
reply_handler = self._on_generic_message,
error_handler = self._on_error,
)
def _on_done(self):
super(Connect, self)._on_done()
def _on_change(self, status, reason):
if status == telepathy.constants.CONNECTION_STATUS_DISCONNECTED:
print "Disconnected!"
self._conn = None
elif status == telepathy.constants.CONNECTION_STATUS_CONNECTED:
print "Connected"
self._on_done()
elif status == telepathy.constants.CONNECTION_STATUS_CONNECTING:
print "Connecting"
else:
print "Status: %r" % status
class SimplePresenceOptions(Action):
def __init__(self, connAction):
super(SimplePresenceOptions, self).__init__()
self._connAction = connAction
def queue_action(self):
self._connAction.conn[DBUS_PROPERTIES].Get(
telepathy.server.CONNECTION_INTERFACE_SIMPLE_PRESENCE,
'Statuses',
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, statuses):
print "\tAvailable Statuses"
for (key, value) in statuses.iteritems():
print "\t\t - %s" % key
super(SimplePresenceOptions, self)._on_done()
class NullHandle(object):
@property
def handle(self):
return 0
@property
def handles(self):
return []
class UserHandle(Action):
def __init__(self, connAction):
super(UserHandle, self).__init__()
self._connAction = connAction
self._handle = None
@property
def handle(self):
return self._handle
@property
def handles(self):
return [self._handle]
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION].GetSelfHandle(
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, handle):
self._handle = handle
super(UserHandle, self)._on_done()
class RequestHandle(Action):
def __init__(self, connAction, handleType, handleNames):
super(RequestHandle, self).__init__()
self._connAction = connAction
self._handle = None
self._handleType = handleType
self._handleNames = handleNames
@property
def handle(self):
return self._handle
@property
def handles(self):
return [self._handle]
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION].RequestHandles(
self._handleType,
self._handleNames,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, handles):
self._handle = handles[0]
super(RequestHandle, self)._on_done()
class RequestChannel(Action):
def __init__(self, connAction, handleAction, channelType, handleType):
super(RequestChannel, self).__init__()
self._connAction = connAction
self._handleAction = handleAction
self._channel = None
self._channelType = channelType
self._handleType = handleType
@property
def channel(self):
return self._channel
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION].RequestChannel(
self._channelType,
self._handleType,
self._handleAction.handle,
True,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, channelObjectPath):
self._channel = telepathy.client.Channel(self._connAction.serviceName, channelObjectPath)
super(RequestChannel, self)._on_done()
class EnsureChannel(Action):
def __init__(self, connAction, channelType, handleType, handleId):
super(EnsureChannel, self).__init__()
self._connAction = connAction
self._channel = None
self._channelType = channelType
self._handleType = handleType
self._handleId = handleId
self._handle = None
@property
def channel(self):
return self._channel
@property
def handle(self):
return self._handle
@property
def handles(self):
return [self._handle]
def queue_action(self):
properties = {
telepathy.server.CHANNEL_INTERFACE+".ChannelType": self._channelType,
telepathy.server.CHANNEL_INTERFACE+".TargetHandleType": self._handleType,
telepathy.server.CHANNEL_INTERFACE+".TargetID": self._handleId,
}
self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_REQUESTS].EnsureChannel(
properties,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, yours, channelObjectPath, properties):
print "Create?", not not yours
print "Path:", channelObjectPath
print "Properties:", properties
self._channel = telepathy.client.Channel(self._connAction.serviceName, channelObjectPath)
self._handle = properties[telepathy.server.CHANNEL_INTERFACE+".TargetHandle"]
super(EnsureChannel, self)._on_done()
class CloseChannel(Action):
def __init__(self, connAction, chanAction):
super(CloseChannel, self).__init__()
self._connAction = connAction
self._chanAction = chanAction
self._handles = []
def queue_action(self):
self._chanAction.channel[telepathy.server.CHANNEL].Close(
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self):
super(CloseChannel, self)._on_done()
class ContactHandles(Action):
def __init__(self, connAction, chanAction):
super(ContactHandles, self).__init__()
self._connAction = connAction
self._chanAction = chanAction
self._handles = []
@property
def handles(self):
return self._handles
def queue_action(self):
self._chanAction.channel[DBUS_PROPERTIES].Get(
telepathy.server.CHANNEL_INTERFACE_GROUP,
'Members',
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, handles):
self._handles = list(handles)
super(ContactHandles, self)._on_done()
class SimplePresenceStatus(Action):
def __init__(self, connAction, handleAction):
super(SimplePresenceStatus, self).__init__()
self._connAction = connAction
self._handleAction = handleAction
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_SIMPLE_PRESENCE].GetPresences(
self._handleAction.handles,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, aliases):
print "\tPresences:"
for hid, (presenceType, presence, presenceMessage) in aliases.iteritems():
print "\t\t%s:" % hid, presenceType, presence, presenceMessage
super(SimplePresenceStatus, self)._on_done()
class SetSimplePresence(Action):
def __init__(self, connAction, status, message):
super(SetSimplePresence, self).__init__()
self._connAction = connAction
self._status = status
self._message = message
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_SIMPLE_PRESENCE].SetPresence(
self._status,
self._message,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self):
super(SetSimplePresence, self)._on_done()
class Aliases(Action):
def __init__(self, connAction, handleAction):
super(Aliases, self).__init__()
self._connAction = connAction
self._handleAction = handleAction
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION_INTERFACE_ALIASING].RequestAliases(
self._handleAction.handles,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, aliases):
print "\tAliases:"
for h, alias in zip(self._handleAction.handles, aliases):
print "\t\t", h, alias
super(Aliases, self)._on_done()
class Call(Action):
def __init__(self, connAction, chanAction, handleAction):
super(Call, self).__init__()
self._connAction = connAction
self._chanAction = chanAction
self._handleAction = handleAction
def queue_action(self):
self._chanAction.channel[telepathy.server.CHANNEL_TYPE_STREAMED_MEDIA].RequestStreams(
self._handleAction.handle,
[telepathy.constants.MEDIA_STREAM_TYPE_AUDIO],
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self, handle):
print "Call started"
super(Call, self)._on_done()
class SendText(Action):
def __init__(self, connAction, chanAction, handleAction, messageType, message):
super(SendText, self).__init__()
self._connAction = connAction
self._chanAction = chanAction
self._handleAction = handleAction
self._messageType = messageType
self._message = message
def queue_action(self):
self._chanAction.channel[telepathy.server.CHANNEL_TYPE_TEXT].Send(
self._messageType,
self._message,
reply_handler = self._on_done,
error_handler = self._on_error,
)
def _on_done(self,):
print "Message sent"
super(SendText, self)._on_done()
class Sleep(Action):
def __init__(self, length):
super(Sleep, self).__init__()
self._length = length
def queue_action(self):
gobject.timeout_add(self._length, self._on_done)
class Block(Action):
def __init__(self):
super(Block, self).__init__()
def queue_action(self):
print "Blocking"
def _on_done(self):
#super(SendText, self)._on_done()
pass
class Disconnect(Action):
def __init__(self, connAction):
super(Disconnect, self).__init__()
self._connAction = connAction
def queue_action(self):
self._connAction.conn[telepathy.server.CONNECTION].Disconnect(
reply_handler = self._on_done,
error_handler = self._on_error,
)
if __name__ == '__main__':
loop = gobject.MainLoop()
reg = get_registry()
cm = get_connection_manager(reg)
nullHandle = NullHandle()
dummy = DummyAction()
firstAction = dummy
lastAction = dummy
if True:
dp = DisplayParams(cm)
lastAction.append_action(dp)
lastAction = lastAction.get_next_action()
if True:
username = sys.argv[1]
password = sys.argv[2]
forward = sys.argv[3]
reqcon = RequestConnection(cm, username, password, forward)
lastAction.append_action(reqcon)
lastAction = lastAction.get_next_action()
if False:
reqcon = RequestConnection(cm, username, password, forward)
lastAction.append_action(reqcon)
lastAction = lastAction.get_next_action()
con = Connect(reqcon)
lastAction.append_action(con)
lastAction = lastAction.get_next_action()
if True:
spo = SimplePresenceOptions(reqcon)
lastAction.append_action(spo)
lastAction = lastAction.get_next_action()
if True:
uh = UserHandle(reqcon)
lastAction.append_action(uh)
lastAction = lastAction.get_next_action()
ua = Aliases(reqcon, uh)
lastAction.append_action(ua)
lastAction = lastAction.get_next_action()
sps = SimplePresenceStatus(reqcon, uh)
lastAction.append_action(sps)
lastAction = lastAction.get_next_action()
if False:
setdnd = SetSimplePresence(reqcon, "dnd", "")
lastAction.append_action(setdnd)
lastAction = lastAction.get_next_action()
sps = SimplePresenceStatus(reqcon, uh)
lastAction.append_action(sps)
lastAction = lastAction.get_next_action()
setdnd = SetSimplePresence(reqcon, "available", "")
lastAction.append_action(setdnd)
lastAction = lastAction.get_next_action()
sps = SimplePresenceStatus(reqcon, uh)
lastAction.append_action(sps)
lastAction = lastAction.get_next_action()
if False:
sl = Sleep(10 * 1000)
lastAction.append_action(sl)
lastAction = lastAction.get_next_action()
if False:
rclh = RequestHandle(reqcon, telepathy.HANDLE_TYPE_LIST, ["subscribe"])
lastAction.append_action(rclh)
lastAction = lastAction.get_next_action()
rclc = RequestChannel(
reqcon,
rclh,
telepathy.CHANNEL_TYPE_CONTACT_LIST,
telepathy.HANDLE_TYPE_LIST,
)
lastAction.append_action(rclc)
lastAction = lastAction.get_next_action()
ch = ContactHandles(reqcon, rclc)
lastAction.append_action(ch)
lastAction = lastAction.get_next_action()
ca = Aliases(reqcon, ch)
lastAction.append_action(ca)
lastAction = lastAction.get_next_action()
if True:
accountNumber = sys.argv[4]
enChan = EnsureChannel(reqcon, telepathy.CHANNEL_TYPE_TEXT, telepathy.HANDLE_TYPE_CONTACT, accountNumber)
lastAction.append_action(enChan)
lastAction = lastAction.get_next_action()
sendDebugtext = SendText(reqcon, enChan, enChan, telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, "Boo!")
lastAction.append_action(sendDebugtext)
lastAction = lastAction.get_next_action()
if False:
rch = RequestHandle(reqcon, telepathy.HANDLE_TYPE_CONTACT, ["18005558355"]) #(1-800-555-TELL)
lastAction.append_action(rch)
lastAction = lastAction.get_next_action()
# making a phone call
if True:
smHandle = rch
smHandleType = telepathy.HANDLE_TYPE_CONTACT
else:
smHandle = nullHandle
smHandleType = telepathy.HANDLE_TYPE_NONE
rsmc = RequestChannel(
reqcon,
smHandle,
telepathy.CHANNEL_TYPE_STREAMED_MEDIA,
smHandleType,
)
lastAction.append_action(rsmc)
lastAction = lastAction.get_next_action()
if False:
call = Call(reqcon, rsmc, rch)
lastAction.append_action(call)
lastAction = lastAction.get_next_action()
# sending a text
rtc = RequestChannel(
reqcon,
rch,
telepathy.CHANNEL_TYPE_TEXT,
smHandleType,
)
lastAction.append_action(rtc)
lastAction = lastAction.get_next_action()
if True:
closechan = CloseChannel(reqcon, rtc)
lastAction.append_action(closechan)
lastAction = lastAction.get_next_action()
rtc = RequestChannel(
reqcon,
rch,
telepathy.CHANNEL_TYPE_TEXT,
smHandleType,
)
lastAction.append_action(rtc)
lastAction = lastAction.get_next_action()
if False:
sendtext = SendText(reqcon, rtc, rch, telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL, "Boo!")
lastAction.append_action(sendtext)
lastAction = lastAction.get_next_action()
if False:
bl = Block()
lastAction.append_action(bl)
lastAction = lastAction.get_next_action()
if False:
sl = Sleep(30 * 1000)
lastAction.append_action(sl)
lastAction = lastAction.get_next_action()
dis = Disconnect(reqcon)
lastAction.append_action(dis)
lastAction = lastAction.get_next_action()
quitter = QuitLoop(loop)
lastAction.append_action(quitter)
lastAction = lastAction.get_next_action()
firstAction.queue_action()
loop.run()
| Java |
// This file was generated by the Gtk# code generator.
// Any changes made will be lost if regenerated.
namespace Pango {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#region Autogenerated code
public partial class FontFace : GLib.Object {
public FontFace (IntPtr raw) : base(raw) {}
protected FontFace() : base(IntPtr.Zero)
{
CreateNativeObject (new string [0], new GLib.Value [0]);
}
[DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr pango_font_face_describe(IntPtr raw);
public Pango.FontDescription Describe() {
IntPtr raw_ret = pango_font_face_describe(Handle);
Pango.FontDescription ret = raw_ret == IntPtr.Zero ? null : (Pango.FontDescription) GLib.Opaque.GetOpaque (raw_ret, typeof (Pango.FontDescription), true);
return ret;
}
[DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr pango_font_face_get_face_name(IntPtr raw);
public string FaceName {
get {
IntPtr raw_ret = pango_font_face_get_face_name(Handle);
string ret = GLib.Marshaller.Utf8PtrToString (raw_ret);
return ret;
}
}
[DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern IntPtr pango_font_face_get_type();
public static new GLib.GType GType {
get {
IntPtr raw_ret = pango_font_face_get_type();
GLib.GType ret = new GLib.GType(raw_ret);
return ret;
}
}
[DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern bool pango_font_face_is_synthesized(IntPtr raw);
public bool IsSynthesized {
get {
bool raw_ret = pango_font_face_is_synthesized(Handle);
bool ret = raw_ret;
return ret;
}
}
[DllImport("libpango-1.0-0.dll", CallingConvention = CallingConvention.Cdecl)]
static extern void pango_font_face_list_sizes(IntPtr raw, out int sizes, out int n_sizes);
public void ListSizes(out int sizes, out int n_sizes) {
pango_font_face_list_sizes(Handle, out sizes, out n_sizes);
}
#endregion
}
}
| Java |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ia">
<context>
<name>LxQtTaskButton</name>
<message>
<location filename="../lxqttaskbutton.cpp" line="367"/>
<source>Application</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="400"/>
<source>To &Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="402"/>
<source>&All Desktops</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="410"/>
<source>Desktop &%1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="417"/>
<source>&To Current Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="426"/>
<source>Ma&ximize</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="433"/>
<source>Maximize vertically</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="438"/>
<source>Maximize horizontally</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="444"/>
<source>&Restore</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="448"/>
<source>Mi&nimize</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="454"/>
<source>Roll down</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="460"/>
<source>Roll up</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="468"/>
<source>&Layer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="470"/>
<source>Always on &top</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="476"/>
<source>&Normal</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="482"/>
<source>Always on &bottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbutton.cpp" line="490"/>
<source>&Close</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>LxQtTaskbarConfiguration</name>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="14"/>
<source>Task Manager Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="20"/>
<source>Taskbar Contents</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="26"/>
<source>Show windows from current desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="49"/>
<source>Taskbar Appearance</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="65"/>
<source>Minimum button width</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="88"/>
<source>Auto&rotate buttons when the panel is vertical</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="98"/>
<source>Close on middle-click</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="36"/>
<source>Show windows from all desktops</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.ui" line="55"/>
<source>Button style</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.cpp" line="46"/>
<source>Icon and text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.cpp" line="47"/>
<source>Only icon</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../lxqttaskbarconfiguration.cpp" line="48"/>
<source>Only text</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| Java |
//
// Copyright (c) 2013, Ford Motor Company
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#ifndef NSSMARTDEVICELINKRPCV2_SCROLLABLEMESSAGE_RESPONSEMARSHALLER_INCLUDE
#define NSSMARTDEVICELINKRPCV2_SCROLLABLEMESSAGE_RESPONSEMARSHALLER_INCLUDE
#include <string>
#include <json/json.h>
#include "../include/JSONHandler/SDLRPCObjects/V2/ScrollableMessage_response.h"
/*
interface Ford Sync RAPI
version 2.0O
date 2012-11-02
generated at Thu Jan 24 06:36:23 2013
source stamp Thu Jan 24 06:35:41 2013
author RC
*/
namespace NsSmartDeviceLinkRPCV2
{
struct ScrollableMessage_responseMarshaller
{
static bool checkIntegrity(ScrollableMessage_response& e);
static bool checkIntegrityConst(const ScrollableMessage_response& e);
static bool fromString(const std::string& s,ScrollableMessage_response& e);
static const std::string toString(const ScrollableMessage_response& e);
static bool fromJSON(const Json::Value& s,ScrollableMessage_response& e);
static Json::Value toJSON(const ScrollableMessage_response& e);
};
}
#endif
| Java |
/*
* Copyright (C) 2007-2010 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors:
* Mark McLoughlin <markmc@redhat.com>
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#include "internal.h"
#include "iptables.h"
#include "util.h"
#include "memory.h"
#include "virterror_internal.h"
#include "logging.h"
enum {
ADD = 0,
REMOVE
};
typedef struct
{
char *table;
char *chain;
} iptRules;
struct _iptablesContext
{
iptRules *input_filter;
iptRules *forward_filter;
iptRules *nat_postrouting;
};
static void
iptRulesFree(iptRules *rules)
{
VIR_FREE(rules->table);
VIR_FREE(rules->chain);
VIR_FREE(rules);
}
static iptRules *
iptRulesNew(const char *table,
const char *chain)
{
iptRules *rules;
if (VIR_ALLOC(rules) < 0)
return NULL;
if (!(rules->table = strdup(table)))
goto error;
if (!(rules->chain = strdup(chain)))
goto error;
return rules;
error:
iptRulesFree(rules);
return NULL;
}
static int ATTRIBUTE_SENTINEL
iptablesAddRemoveRule(iptRules *rules, int action, const char *arg, ...)
{
va_list args;
int retval = ENOMEM;
const char **argv;
const char *s;
int n;
n = 1 + /* /sbin/iptables */
2 + /* --table foo */
2 + /* --insert bar */
1; /* arg */
va_start(args, arg);
while (va_arg(args, const char *))
n++;
va_end(args);
if (VIR_ALLOC_N(argv, n + 1) < 0)
goto error;
n = 0;
if (!(argv[n++] = strdup(IPTABLES_PATH)))
goto error;
if (!(argv[n++] = strdup("--table")))
goto error;
if (!(argv[n++] = strdup(rules->table)))
goto error;
if (!(argv[n++] = strdup(action == ADD ? "--insert" : "--delete")))
goto error;
if (!(argv[n++] = strdup(rules->chain)))
goto error;
if (!(argv[n++] = strdup(arg)))
goto error;
va_start(args, arg);
while ((s = va_arg(args, const char *))) {
if (!(argv[n++] = strdup(s))) {
va_end(args);
goto error;
}
}
va_end(args);
if (virRun(argv, NULL) < 0) {
retval = errno;
goto error;
}
retval = 0;
error:
if (argv) {
n = 0;
while (argv[n])
VIR_FREE(argv[n++]);
VIR_FREE(argv);
}
return retval;
}
/**
* iptablesContextNew:
*
* Create a new IPtable context
*
* Returns a pointer to the new structure or NULL in case of error
*/
iptablesContext *
iptablesContextNew(void)
{
iptablesContext *ctx;
if (VIR_ALLOC(ctx) < 0)
return NULL;
if (!(ctx->input_filter = iptRulesNew("filter", "INPUT")))
goto error;
if (!(ctx->forward_filter = iptRulesNew("filter", "FORWARD")))
goto error;
if (!(ctx->nat_postrouting = iptRulesNew("nat", "POSTROUTING")))
goto error;
return ctx;
error:
iptablesContextFree(ctx);
return NULL;
}
/**
* iptablesContextFree:
* @ctx: pointer to the IP table context
*
* Free the resources associated with an IP table context
*/
void
iptablesContextFree(iptablesContext *ctx)
{
if (ctx->input_filter)
iptRulesFree(ctx->input_filter);
if (ctx->forward_filter)
iptRulesFree(ctx->forward_filter);
if (ctx->nat_postrouting)
iptRulesFree(ctx->nat_postrouting);
VIR_FREE(ctx);
}
static int
iptablesInput(iptablesContext *ctx,
const char *iface,
int port,
int action,
int tcp)
{
char portstr[32];
snprintf(portstr, sizeof(portstr), "%d", port);
portstr[sizeof(portstr) - 1] = '\0';
return iptablesAddRemoveRule(ctx->input_filter,
action,
"--in-interface", iface,
"--protocol", tcp ? "tcp" : "udp",
"--destination-port", portstr,
"--jump", "ACCEPT",
NULL);
}
/**
* iptablesAddTcpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the TCP port to add
*
* Add an input to the IP table allowing access to the given @port on
* the given @iface interface for TCP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesAddTcpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, ADD, 1);
}
/**
* iptablesRemoveTcpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the TCP port to remove
*
* Removes an input from the IP table, hence forbidding access to the given
* @port on the given @iface interface for TCP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesRemoveTcpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, REMOVE, 1);
}
/**
* iptablesAddUdpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the UDP port to add
*
* Add an input to the IP table allowing access to the given @port on
* the given @iface interface for UDP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesAddUdpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, ADD, 0);
}
/**
* iptablesRemoveUdpInput:
* @ctx: pointer to the IP table context
* @iface: the interface name
* @port: the UDP port to remove
*
* Removes an input from the IP table, hence forbidding access to the given
* @port on the given @iface interface for UDP packets
*
* Returns 0 in case of success or an error code in case of error
*/
int
iptablesRemoveUdpInput(iptablesContext *ctx,
const char *iface,
int port)
{
return iptablesInput(ctx, iface, port, REMOVE, 0);
}
/* Allow all traffic coming from the bridge, with a valid network address
* to proceed to WAN
*/
static int
iptablesForwardAllowOut(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--source", network,
"--in-interface", iface,
"--out-interface", physdev,
"--jump", "ACCEPT",
NULL);
} else {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--source", network,
"--in-interface", iface,
"--jump", "ACCEPT",
NULL);
}
}
/**
* iptablesAddForwardAllowOut:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the source interface name
* @physdev: the physical output device
*
* Add a rule to the IP table context to allow the traffic for the
* network @network via interface @iface to be forwarded to
* @physdev device. This allow the outbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowOut(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowOut(ctx, network, iface, physdev, ADD);
}
/**
* iptablesRemoveForwardAllowOut:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the source interface name
* @physdev: the physical output device
*
* Remove a rule from the IP table context hence forbidding forwarding
* of the traffic for the network @network via interface @iface
* to the @physdev device output. This stops the outbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowOut(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowOut(ctx, network, iface, physdev, REMOVE);
}
/* Allow all traffic destined to the bridge, with a valid network address
* and associated with an existing connection
*/
static int
iptablesForwardAllowRelatedIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--in-interface", physdev,
"--out-interface", iface,
"--match", "state",
"--state", "ESTABLISHED,RELATED",
"--jump", "ACCEPT",
NULL);
} else {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--out-interface", iface,
"--match", "state",
"--state", "ESTABLISHED,RELATED",
"--jump", "ACCEPT",
NULL);
}
}
/**
* iptablesAddForwardAllowRelatedIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Add rules to the IP table context to allow the traffic for the
* network @network on @physdev device to be forwarded to
* interface @iface, if it is part of an existing connection.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowRelatedIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowRelatedIn(ctx, network, iface, physdev, ADD);
}
/**
* iptablesRemoveForwardAllowRelatedIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Remove rules from the IP table context hence forbidding the traffic for
* network @network on @physdev device to be forwarded to
* interface @iface, if it is part of an existing connection.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowRelatedIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowRelatedIn(ctx, network, iface, physdev, REMOVE);
}
/* Allow all traffic destined to the bridge, with a valid network address
*/
static int
iptablesForwardAllowIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--in-interface", physdev,
"--out-interface", iface,
"--jump", "ACCEPT",
NULL);
} else {
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--destination", network,
"--out-interface", iface,
"--jump", "ACCEPT",
NULL);
}
}
/**
* iptablesAddForwardAllowIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Add rules to the IP table context to allow the traffic for the
* network @network on @physdev device to be forwarded to
* interface @iface. This allow the inbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowIn(ctx, network, iface, physdev, ADD);
}
/**
* iptablesRemoveForwardAllowIn:
* @ctx: pointer to the IP table context
* @network: the source network name
* @iface: the output interface name
* @physdev: the physical input device or NULL
*
* Remove rules from the IP table context hence forbidding the traffic for
* network @network on @physdev device to be forwarded to
* interface @iface. This stops the inbound traffic on a bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowIn(iptablesContext *ctx,
const char *network,
const char *iface,
const char *physdev)
{
return iptablesForwardAllowIn(ctx, network, iface, physdev, REMOVE);
}
/* Allow all traffic between guests on the same bridge,
* with a valid network address
*/
static int
iptablesForwardAllowCross(iptablesContext *ctx,
const char *iface,
int action)
{
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--in-interface", iface,
"--out-interface", iface,
"--jump", "ACCEPT",
NULL);
}
/**
* iptablesAddForwardAllowCross:
* @ctx: pointer to the IP table context
* @iface: the input/output interface name
*
* Add rules to the IP table context to allow traffic to cross that
* interface. It allows all traffic between guests on the same bridge
* represented by that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardAllowCross(iptablesContext *ctx,
const char *iface) {
return iptablesForwardAllowCross(ctx, iface, ADD);
}
/**
* iptablesRemoveForwardAllowCross:
* @ctx: pointer to the IP table context
* @iface: the input/output interface name
*
* Remove rules to the IP table context to block traffic to cross that
* interface. It forbids traffic between guests on the same bridge
* represented by that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardAllowCross(iptablesContext *ctx,
const char *iface) {
return iptablesForwardAllowCross(ctx, iface, REMOVE);
}
/* Drop all traffic trying to forward from the bridge.
* ie the bridge is the in interface
*/
static int
iptablesForwardRejectOut(iptablesContext *ctx,
const char *iface,
int action)
{
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--in-interface", iface,
"--jump", "REJECT",
NULL);
}
/**
* iptablesAddForwardRejectOut:
* @ctx: pointer to the IP table context
* @iface: the output interface name
*
* Add rules to the IP table context to forbid all traffic to that
* interface. It forbids forwarding from the bridge to that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardRejectOut(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectOut(ctx, iface, ADD);
}
/**
* iptablesRemoveForwardRejectOut:
* @ctx: pointer to the IP table context
* @iface: the output interface name
*
* Remove rules from the IP table context forbidding all traffic to that
* interface. It reallow forwarding from the bridge to that interface.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardRejectOut(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectOut(ctx, iface, REMOVE);
}
/* Drop all traffic trying to forward to the bridge.
* ie the bridge is the out interface
*/
static int
iptablesForwardRejectIn(iptablesContext *ctx,
const char *iface,
int action)
{
return iptablesAddRemoveRule(ctx->forward_filter,
action,
"--out-interface", iface,
"--jump", "REJECT",
NULL);
}
/**
* iptablesAddForwardRejectIn:
* @ctx: pointer to the IP table context
* @iface: the input interface name
*
* Add rules to the IP table context to forbid all traffic from that
* interface. It forbids forwarding from that interface to the bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardRejectIn(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectIn(ctx, iface, ADD);
}
/**
* iptablesRemoveForwardRejectIn:
* @ctx: pointer to the IP table context
* @iface: the input interface name
*
* Remove rules from the IP table context forbidding all traffic from that
* interface. It allows forwarding from that interface to the bridge.
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardRejectIn(iptablesContext *ctx,
const char *iface)
{
return iptablesForwardRejectIn(ctx, iface, REMOVE);
}
/* Masquerade all traffic coming from the network associated
* with the bridge
*/
static int
iptablesForwardMasquerade(iptablesContext *ctx,
const char *network,
const char *physdev,
int action)
{
if (physdev && physdev[0]) {
return iptablesAddRemoveRule(ctx->nat_postrouting,
action,
"--source", network,
"!", "--destination", network,
"--out-interface", physdev,
"--jump", "MASQUERADE",
NULL);
} else {
return iptablesAddRemoveRule(ctx->nat_postrouting,
action,
"--source", network,
"!", "--destination", network,
"--jump", "MASQUERADE",
NULL);
}
}
/**
* iptablesAddForwardMasquerade:
* @ctx: pointer to the IP table context
* @network: the source network name
* @physdev: the physical input device or NULL
*
* Add rules to the IP table context to allow masquerading
* network @network on @physdev. This allow the bridge to
* masquerade for that network (on @physdev).
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesAddForwardMasquerade(iptablesContext *ctx,
const char *network,
const char *physdev)
{
return iptablesForwardMasquerade(ctx, network, physdev, ADD);
}
/**
* iptablesRemoveForwardMasquerade:
* @ctx: pointer to the IP table context
* @network: the source network name
* @physdev: the physical input device or NULL
*
* Remove rules from the IP table context to stop masquerading
* network @network on @physdev. This stops the bridge from
* masquerading for that network (on @physdev).
*
* Returns 0 in case of success or an error code otherwise
*/
int
iptablesRemoveForwardMasquerade(iptablesContext *ctx,
const char *network,
const char *physdev)
{
return iptablesForwardMasquerade(ctx, network, physdev, REMOVE);
}
| Java |
package compiler.ASTNodes.Operators;
import compiler.ASTNodes.GeneralNodes.Node;
import compiler.ASTNodes.GeneralNodes.UnaryNode;
import compiler.ASTNodes.SyntaxNodes.ExprNode;
import compiler.Visitors.AbstractVisitor;
public class UnaryMinusNode extends ExprNode {
public UnaryMinusNode(Node child) {
super(child, null);
}
@Override
public Object Accept(AbstractVisitor v) {
return v.visit(this);
}
}
| Java |
#include <QtGui>
#include "btglobal.h"
#include "btqlistdelegate.h"
//#include <QMetaType>
btQListDeletgate::btQListDeletgate(QObject *parent)
: QItemDelegate(parent)
{
}
QWidget *btQListDeletgate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
//qRegisterMetaType<btChildWeights>("btChildWeights");
//qRegisterMetaType<btParallelConditions>("btParallelConditions");
QComboBox *comboBox = new QComboBox(parent);
comboBox->addItem("int", QVariant("int"));
comboBox->addItem("QString", QVariant("QString"));
comboBox->addItem("double", QVariant("double"));
comboBox->addItem("QVariantList", QVariant("QVariantList"));
//comboBox->addItem("btChildWeights", QVariant("btChildWeights"));
comboBox->setCurrentIndex(comboBox->findData(index.data()));
return comboBox;
}
void btQListDeletgate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::EditRole).toString();
QComboBox *comboBox = static_cast<QComboBox*>(editor);
comboBox->setCurrentIndex(comboBox->findText(value));//comboBox->findData(value));
}
void btQListDeletgate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
QComboBox *comboBox = static_cast<QComboBox*>(editor);
QString value = comboBox->currentText();
model->setData(index, value, Qt::EditRole);
}
void btQListDeletgate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &/* index */) const
{
editor->setGeometry(option.rect);
}
#include "btqlistdelegate.moc"
| Java |
/**
* NativeFmod Project
*
* Want to use FMOD API (www.fmod.org) in the Java language ? NativeFmod is made for you.
* Copyright © 2004-2007 Jérôme JOUVIE (Jouvieje)
*
* Created on 28 avr. 2004
* @version NativeFmod v3.4 (for FMOD v3.75)
* @author Jérôme JOUVIE (Jouvieje)
*
*
* WANT TO CONTACT ME ?
* E-mail :
* jerome.jouvie@gmail.com
* My web sites :
* http://jerome.jouvie.free.fr/
*
*
* INTRODUCTION
* Fmod is an API (Application Programming Interface) that allow you to use music
* and creating sound effects with a lot of sort of musics.
* Fmod is at :
* http://www.fmod.org/
* The reason of this project is that Fmod can't be used in Java direcly, so I've created
* NativeFmod project.
*
*
* GNU LESSER GENERAL PUBLIC LICENSE
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.jouvieje.Fmod.Structures;
import org.jouvieje.Fmod.Misc.Pointer;
/**
* Structure defining the properties for a reverb source, related to a FSOUND channel.
* For more indepth descriptions of the reverb properties under win32, please see the EAX3
* documentation at http://developer.creative.com/ under the 'downloads' section.
* If they do not have the EAX3 documentation, then most information can be attained from
* the EAX2 documentation, as EAX3 only adds some more parameters and functionality on top of
* EAX2.
* Note the default reverb properties are the same as the FSOUND_PRESET_GENERIC preset.
* Note that integer values that typically range from -10,000 to 1000 are represented in
* decibels, and are of a logarithmic scale, not linear, wheras float values are typically linear.
* PORTABILITY: Each member has the platform it supports in braces ie (win32/xbox).
* Some reverb parameters are only supported in win32 and some only on xbox. If all parameters are set then
* the reverb should product a similar effect on either platform.
* Linux and FMODCE do not support the reverb api.
* The numerical values listed below are the maximum, minimum and default values for each variable respectively.
*/
public class FSOUND_REVERB_CHANNELPROPERTIES extends Pointer
{
/**
* Create a view of the <code>Pointer</code> object as a <code>FSOUND_REVERB_CHANNELPROPERTIES</code> object.<br>
* This view is valid only if the memory holded by the <code>Pointer</code> holds a FSOUND_REVERB_CHANNELPROPERTIES object.
*/
public static FSOUND_REVERB_CHANNELPROPERTIES createView(Pointer pointer)
{
return new FSOUND_REVERB_CHANNELPROPERTIES(Pointer.getPointer(pointer));
}
/**
* Create a new <code>FSOUND_REVERB_CHANNELPROPERTIES</code>.<br>
* The call <code>isNull()</code> on the object created will return false.<br>
* <pre><code> FSOUND_REVERB_CHANNELPROPERTIES obj = FSOUND_REVERB_CHANNELPROPERTIES.create();
* (obj == null) <=> obj.isNull() <=> false
* </code></pre>
*/
public static FSOUND_REVERB_CHANNELPROPERTIES create()
{
return new FSOUND_REVERB_CHANNELPROPERTIES(StructureJNI.new_FSOUND_REVERB_CHANNELPROPERTIES());
}
protected FSOUND_REVERB_CHANNELPROPERTIES(long pointer)
{
super(pointer);
}
/**
* Create an object that holds a null <code>FSOUND_REVERB_CHANNELPROPERTIES</code>.<br>
* The call <code>isNull()</code> on the object created will returns true.<br>
* <pre><code> FSOUND_REVERB_CHANNELPROPERTIES obj = new FSOUND_REVERB_CHANNELPROPERTIES();
* (obj == null) <=> false
* obj.isNull() <=> true
* </code></pre>
* To creates a new <code>FSOUND_REVERB_CHANNELPROPERTIES</code>, use the static "constructor" :
* <pre><code> FSOUND_REVERB_CHANNELPROPERTIES obj = FSOUND_REVERB_CHANNELPROPERTIES.create();</code></pre>
* @see FSOUND_REVERB_CHANNELPROPERTIES#create()
*/
public FSOUND_REVERB_CHANNELPROPERTIES()
{
super();
}
public void release()
{
if(pointer != 0)
{
StructureJNI.delete_FSOUND_REVERB_CHANNELPROPERTIES(pointer);
}
pointer = 0;
}
/**
* -10000, 1000, 0, direct path level (at low and mid frequencies) (WIN32/XBOX)
*/
public void setDirect(int Direct)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Direct(pointer, Direct);
}
/**
* @return value of Direct
*/
public int getDirect()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Direct(pointer);
}
/**
* -10000, 0, 0, relative direct path level at high frequencies (WIN32/XBOX)
*/
public void setDirectHF(int DirectHF)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_DirectHF(pointer, DirectHF);
}
/**
* @return value of DirectHF
*/
public int getDirectHF()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_DirectHF(pointer);
}
/**
* -10000, 1000, 0, room effect level (at low and mid frequencies) (WIN32/XBOX/PS2)
*/
public void setRoom(int Room)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Room(pointer, Room);
}
/**
* @return value of Room
*/
public int getRoom()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Room(pointer);
}
/**
* -10000, 0, 0, relative room effect level at high frequencies (WIN32/XBOX)
*/
public void setRoomHF(int RoomHF)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_RoomHF(pointer, RoomHF);
}
/**
* @return value of RoomHF
*/
public int getRoomHF()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_RoomHF(pointer);
}
/**
* -10000, 0, 0, main obstruction control (attenuation at high frequencies) (WIN32/XBOX)
*/
public void setObstruction(int Obstruction)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Obstruction(pointer, Obstruction);
}
/**
* @return value of Obstruction
*/
public int getObstruction()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Obstruction(pointer);
}
/**
* 0.0, 1.0, 0.0, obstruction low-frequency level re. main control (WIN32/XBOX)
*/
public void setObstructionLFRatio(float ObstructionLFRatio)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_ObstructionLFRatio(pointer,
ObstructionLFRatio);
}
/**
* @return value of ObstructionLFRatio
*/
public float getObstructionLFRatio()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_ObstructionLFRatio(pointer);
}
/**
* -10000, 0, 0, main occlusion control (attenuation at high frequencies) (WIN32/XBOX)
*/
public void setOcclusion(int Occlusion)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Occlusion(pointer, Occlusion);
}
/**
* @return value of Occlusion
*/
public int getOcclusion()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Occlusion(pointer);
}
/**
* 0.0, 1.0, 0.25, occlusion low-frequency level re. main control (WIN32/XBOX)
*/
public void setOcclusionLFRatio(float OcclusionLFRatio)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionLFRatio(pointer,
OcclusionLFRatio);
}
/**
* @return value of OcclusionLFRatio
*/
public float getOcclusionLFRatio()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionLFRatio(pointer);
}
/**
* 0.0, 10.0, 1.5, relative occlusion control for room effect (WIN32)
*/
public void setOcclusionRoomRatio(float OcclusionRoomRatio)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionRoomRatio(pointer,
OcclusionRoomRatio);
}
/**
* @return value of OcclusionRoomRatio
*/
public float getOcclusionRoomRatio()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionRoomRatio(pointer);
}
/**
* 0.0, 10.0, 1.0, relative occlusion control for direct path (WIN32)
*/
public void setOcclusionDirectRatio(float OcclusionDirectRatio)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionDirectRatio(pointer,
OcclusionDirectRatio);
}
/**
* @return value of OcclusionDirectRatio
*/
public float getOcclusionDirectRatio()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OcclusionDirectRatio(pointer);
}
/**
* -10000, 0, 0, main exlusion control (attenuation at high frequencies) (WIN32)
*/
public void setExclusion(int Exclusion)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Exclusion(pointer, Exclusion);
}
/**
* @return value of Exclusion
*/
public int getExclusion()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Exclusion(pointer);
}
/**
* 0.0, 1.0, 1.0, exclusion low-frequency level re. main control (WIN32)
*/
public void setExclusionLFRatio(float ExclusionLFRatio)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_ExclusionLFRatio(pointer,
ExclusionLFRatio);
}
/**
* @return value of ExclusionLFRatio
*/
public float getExclusionLFRatio()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_ExclusionLFRatio(pointer);
}
/**
* -10000, 0, 0, outside sound cone level at high frequencies (WIN32)
*/
public void setOutsideVolumeHF(int OutsideVolumeHF)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI
.set_FSOUND_REVERB_CHANNELPROPERTIES_OutsideVolumeHF(pointer, OutsideVolumeHF);
}
/**
* @return value of OutsideVolumeHF
*/
public int getOutsideVolumeHF()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_OutsideVolumeHF(pointer);
}
/**
* 0.0, 10.0, 0.0, like DS3D flDopplerFactor but per source (WIN32)
*/
public void setDopplerFactor(float DopplerFactor)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_DopplerFactor(pointer, DopplerFactor);
}
/**
* @return value of DopplerFactor
*/
public float getDopplerFactor()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_DopplerFactor(pointer);
}
/**
* 0.0, 10.0, 0.0, like DS3D flRolloffFactor but per source (WIN32)
*/
public void setRolloffFactor(float RolloffFactor)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_RolloffFactor(pointer, RolloffFactor);
}
/**
* @return value of RolloffFactor
*/
public float getRolloffFactor()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_RolloffFactor(pointer);
}
/**
* 0.0, 10.0, 0.0, like DS3D flRolloffFactor but for room effect (WIN32/XBOX)
*/
public void setRoomRolloffFactor(float RoomRolloffFactor)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_RoomRolloffFactor(pointer,
RoomRolloffFactor);
}
/**
* @return value of RoomRolloverFactor
*/
public float getRoomRolloffFactor()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_RoomRolloffFactor(pointer);
}
/**
* 0.0, 10.0, 1.0, multiplies AirAbsorptionHF member of FSOUND_REVERB_PROPERTIES (WIN32)
* */
public void setAirAbsorptionFactor(float AirAbsorptionFactor)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_AirAbsorptionFactor(pointer,
AirAbsorptionFactor);
}
/**
* @return value of AirAbsorptionFactor
*/
public float getAirAbsorptionFactor()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_AirAbsorptionFactor(pointer);
}
/**
* FSOUND_REVERB_CHANNELFLAGS - modifies the behavior of properties (WIN32)
*/
public void setFlags(int Flags)
{
if(pointer == 0) throw new NullPointerException();
StructureJNI.set_FSOUND_REVERB_CHANNELPROPERTIES_Flags(pointer, Flags);
}
/**
* @return value of EchoTime
*/
public int getFlags()
{
if(pointer == 0) throw new NullPointerException();
return StructureJNI.get_FSOUND_REVERB_CHANNELPROPERTIES_Flags(pointer);
}
} | Java |
/*
* Multisim: a microprocessor architecture exploration framework
* Copyright (C) 2014 Tommy Thorn
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
int SZ(loadelf,)(memory_t *m, char *name, FILE *f, elf_info_t *elf_info)
{
memset(elf_info, 0, sizeof *elf_info);
SZ(Elf,_Ehdr) ehdr;
SZ(Elf,_Phdr) *ph;
if (fread(&ehdr, sizeof ehdr, 1, f) != 1) {
fprintf(stderr, "%s: short header read, file corrupted?\n", name);
return 10;
}
if (ehdr.e_ident[EI_DATA] != ELFDATA2MSB && ehdr.e_ident[EI_DATA] != ELFDATA2LSB) {
fprintf(stderr, "%s: Unsupported endian (%d)\n",
name, ehdr.e_ident[EI_DATA]);
return 11;
}
elf_info->endian_is_big = ehdr.e_ident[EI_DATA] == ELFDATA2MSB;
memory_set_endian(m, elf_info->endian_is_big);
if (NATIVE(ehdr.e_type) != ET_EXEC) {
fprintf(stderr, "%s: Need a fully linked ELF executable, not type %d\n",
name, NATIVE(ehdr.e_type));
return 12;
}
elf_info->machine = NATIVE(ehdr.e_machine);
if (elf_info->machine != EM_ALPHA &&
elf_info->machine != EM_RISCV &&
elf_info->machine != EM_LM32 &&
elf_info->machine != EM_LM32_ALT) {
fprintf(stderr, "%s: Unsupported machine architecture %d\n",
name, NATIVE(ehdr.e_machine));
return 13;
}
if (enable_verb_prog_sec) {
printf("%s:\n", name);
printf("%sendian\n", elf_info->endian_is_big ? "big" : "little");
printf("Entry: %016"PRIx64"\n",
(uint64_t) NATIVE(ehdr.e_entry)); /* Entry point virtual address */
printf("Proc Flags: %08x\n",
NATIVE(ehdr.e_flags)); /* Processor-specific flags */
printf("Phdr.tbl entry cnt % 8d\n",
NATIVE(ehdr.e_phnum)); /*Program header table entry count */
printf("Shdr.tbl entry cnt % 8d\n",
NATIVE(ehdr.e_shnum)); /*Section header table entry count */
printf("Shdr.str tbl idx % 8d\n",
NATIVE(ehdr.e_shstrndx)); /*Section header string table index */
}
elf_info->program_entry = NATIVE(ehdr.e_entry);
if (NATIVE(ehdr.e_ehsize) != sizeof ehdr) {
return 14;
}
if (NATIVE(ehdr.e_shentsize) != sizeof(SZ(Elf,_Shdr))) {
return 15;
}
// Allocate program headers
ph = alloca(sizeof *ph * NATIVE(ehdr.e_phnum));
int phnum = NATIVE(ehdr.e_phnum);
for (int i = 0; i < phnum; ++i) {
fseek(f, NATIVE(ehdr.e_phoff) + i * NATIVE(ehdr.e_phentsize), SEEK_SET);
if (fread(ph + i, sizeof *ph, 1, f) != 1)
return 16;
if (enable_verb_prog_sec) {
printf("\nProgram header #%d (%lx)\n", i, ftell(f));
printf(" type %08x\n", NATIVE(ph[i].p_type));
printf(" filesz %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_filesz));
printf(" offset %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_offset));
printf(" vaddr %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_vaddr));
printf(" paddr %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_paddr));
printf(" memsz %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_memsz));
printf(" flags %08x\n", NATIVE(ph[i].p_flags));
printf(" align %016"PRIx64"\n", (uint64_t)NATIVE(ph[i].p_align));
}
if (NATIVE(ph[i].p_type) == PT_LOAD && NATIVE(ph[i].p_filesz)) {
if (enable_verb_prog_sec)
fprintf(stderr, "Loading section [%016"PRIx64"; %016"PRIx64"]\n",
(uint64_t)NATIVE(ph[i].p_vaddr),
(uint64_t)NATIVE(ph[i].p_vaddr) + NATIVE(ph[i].p_memsz) - 1);
loadsection(f,
(unsigned)NATIVE(ph[i].p_offset),
(unsigned)NATIVE(ph[i].p_filesz),
m,
NATIVE(ph[i].p_vaddr),
NATIVE(ph[i].p_memsz),
elf_info);
}
if (ph[i].p_flags & 1) {
elf_info->text_segments++;
elf_info->text_start = NATIVE(ph[i].p_vaddr);
elf_info->text_size = NATIVE(ph[i].p_memsz);
}
}
if (enable_verb_elf) {
printf("\n");
fseek(f, NATIVE(ehdr.e_shoff), SEEK_SET);
int shnum = NATIVE(ehdr.e_shnum);
for (int i = 0; i < shnum; ++i) {
SZ(Elf,_Shdr) sh;
if (fread(&sh, sizeof sh, 1, f) != 1)
return 17;
printf("\nSection header #%d (%lx)\n", i, ftell(f));
printf(" name %08x\n", NATIVE(sh.sh_name));
printf(" type %08x\n", NATIVE(sh.sh_type));
printf(" flags %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_flags));
printf(" addr %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_addr));
printf(" offset %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_offset));
printf(" size %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_size));
printf(" link %08x\n", NATIVE(sh.sh_link));
printf(" info %08x\n", NATIVE(sh.sh_info));
printf(" addralign %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_addralign));
printf(" entsize %016"PRIx64"\n", (uint64_t)NATIVE(sh.sh_entsize));
}
printf(" (now at %lx)\n", ftell(f));
}
return 0;
}
// Local Variables:
// mode: C
// c-style-variables-are-local-p: t
// c-file-style: "stroustrup"
// End:
| Java |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>getBytes</title>
<!-- <script src="http://use.edgefonts.net/source-sans-pro;source-code-pro.js"></script> -->
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../assets/css/bootstrap.css">
<link rel="stylesheet" href="../assets/css/jquery.bonsai.css">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/icons.css">
<script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="../assets/js/bootstrap.js"></script>
<script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script>
<!-- <script type="text/javascript" src="../assets/js/main.js"></script> -->
</head>
<body>
<div>
<!-- Name Title -->
<h1>getBytes</h1>
<!-- Type and Stereotype -->
<section style="margin-top: .5em;">
<span class="alert alert-info">
<span class="node-icon _icon-UMLOperation"></span>
UMLOperation
</span>
</section>
<!-- Path -->
<section style="margin-top: 10px">
<span class="label label-info"><a href='cf9c8b720f3815adeccaf3ef6e48c6c4.html'><span class='node-icon _icon-Project'></span>Untitled</a></span>
<span>::</span>
<span class="label label-info"><a href='6550300e57d7fc770bd2e9afbcdb3ecb.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span>
<span>::</span>
<span class="label label-info"><a href='7ff2d96ca3eb7f62f48c1a30b3c7c990.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span>
<span>::</span>
<span class="label label-info"><a href='7adc4be4f2e4859086f068fc27512d85.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span>
<span>::</span>
<span class="label label-info"><a href='bb15307bdbbaf31bfef4f71be74150ae.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span>
<span>::</span>
<span class="label label-info"><a href='13ebeea6c90c35d72f303d2d478d584e.html'><span class='node-icon _icon-UMLPackage'></span>buffer</a></span>
<span>::</span>
<span class="label label-info"><a href='cb2e81bf6fa08af090f5bd728f5884e7.html'><span class='node-icon _icon-UMLClass'></span>DynamicChannelBuffer</a></span>
<span>::</span>
<span class="label label-info"><a href='5dbf13610803e568d209258ff152c232.html'><span class='node-icon _icon-UMLOperation'></span>getBytes</a></span>
</section>
<!-- Diagram -->
<!-- Description -->
<section>
<h3>Description</h3>
<div>
<span class="label label-info">none</span>
</div>
</section>
<!-- Specification -->
<!-- Directed Relationship -->
<!-- Undirected Relationship -->
<!-- Classifier -->
<!-- Interface -->
<!-- Component -->
<!-- Node -->
<!-- Actor -->
<!-- Use Case -->
<!-- Template Parameters -->
<!-- Literals -->
<!-- Attributes -->
<!-- Operations -->
<!-- Receptions -->
<!-- Extension Points -->
<!-- Parameters -->
<section>
<h3>Parameters</h3>
<table class="table table-striped table-bordered">
<tr>
<th>Direction</th>
<th>Name</th>
<th>Type</th>
<th>Description</th>
</tr>
<tr>
<td>in</td>
<td><a href="8a1ae1290c4853091cbbd9134dfc989f.html">index</a></td>
<td>int</td>
<td></td>
</tr>
<tr>
<td>in</td>
<td><a href="718af3560069519895f7ba3fde3cab13.html">dst</a></td>
<td><a href='6a3cd6770cde0833c191b1edd40d225c.html'><span class='node-icon _icon-UMLClass'></span>ByteBuffer</a></td>
<td></td>
</tr>
<tr>
<td>return</td>
<td><a href="977ac87f8fef3f04dc8885021a167d8c.html">(unnamed)</a></td>
<td>void</td>
<td></td>
</tr>
</table>
</section>
<!-- Diagrams -->
<!-- Behavior -->
<!-- Action -->
<!-- Interaction -->
<!-- CombinedFragment -->
<!-- Activity -->
<!-- State Machine -->
<!-- State Machine -->
<!-- State -->
<!-- Vertex -->
<!-- Transition -->
<!-- Properties -->
<section>
<h3>Properties</h3>
<table class="table table-striped table-bordered">
<tr>
<th width="50%">Name</th>
<th width="50%">Value</th>
</tr>
<tr>
<td>name</td>
<td>getBytes</td>
</tr>
<tr>
<td>stereotype</td>
<td><span class='label label-info'>null</span></td>
</tr>
<tr>
<td>visibility</td>
<td>public</td>
</tr>
<tr>
<td>isStatic</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isLeaf</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>parameters</td>
<td>
<a href='8a1ae1290c4853091cbbd9134dfc989f.html'><span class='node-icon _icon-UMLParameter'></span>index</a>
<span>, </span>
<a href='718af3560069519895f7ba3fde3cab13.html'><span class='node-icon _icon-UMLParameter'></span>dst</a>
<span>, </span>
<a href='977ac87f8fef3f04dc8885021a167d8c.html'><span class='node-icon _icon-UMLParameter'></span>(Parameter)</a>
</td>
</tr>
<tr>
<td>raisedExceptions</td>
<td>
</td>
</tr>
<tr>
<td>concurrency</td>
<td>sequential</td>
</tr>
<tr>
<td>isQuery</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>isAbstract</td>
<td><span class='label label-info'>false</span></td>
</tr>
<tr>
<td>specification</td>
<td></td>
</tr>
</table>
</section>
<!-- Tags -->
<!-- Constraints, Dependencies, Dependants -->
<!-- Relationships -->
<!-- Owned Elements -->
</div>
</body>
</html>
| Java |
//Copyright (c) Microsoft Corporation. All rights reserved.
// AddIn.cpp : Implementation of DLL Exports.
#include "stdafx.h"
#include "resource.h"
#include "AddIn.h"
CAddInModule _AtlModule;
// DLL Entry Point
extern "C" BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
_AtlModule.SetResourceInstance(hInstance);
return _AtlModule.DllMain(dwReason, lpReserved);
}
// Used to determine whether the DLL can be unloaded by OLE
STDAPI DllCanUnloadNow(void)
{
return _AtlModule.DllCanUnloadNow();
}
// Returns a class factory to create an object of the requested type
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
return _AtlModule.DllGetClassObject(rclsid, riid, ppv);
}
void CreateRegistrationKey(const CString& version, const CString& modulePath, const CString& moduleShortName)
{
CString path = "Software\\Microsoft\\VisualStudio\\" + version;
CRegKey devKey;
if (devKey.Open(HKEY_LOCAL_MACHINE, path) == ERROR_SUCCESS)
{
// Auto create the addins key if it isn't already there.
if (devKey.Create(HKEY_LOCAL_MACHINE, path + "\\AddIns") == ERROR_SUCCESS)
{
// Create the WorkspaceWhiz.DSAddin.1 key.
if (devKey.Create(HKEY_LOCAL_MACHINE, path + "\\AddIns\\LuaPlusDebugger.Connect") == ERROR_SUCCESS)
{
// Remove all old entries.
devKey.SetStringValue("SatelliteDLLPath", modulePath);
devKey.SetStringValue("SatelliteDLLName", moduleShortName);
devKey.SetDWORDValue("LoadBehavior", 3);
devKey.SetStringValue("FriendlyName", "LuaPlus Debugger Window");
devKey.SetStringValue("Description", "The LuaPlus Debugger Window add-in provides support for viewing Lua tables while debugging.");
devKey.SetDWORDValue("CommandPreload", 1);
}
}
}
if (devKey.Open(HKEY_CURRENT_USER, path + "\\PreloadAddinState") == ERROR_SUCCESS)
{
devKey.SetDWORDValue("LuaPlusDebugger.Connect", 1);
}
}
void DestroyRegistrationKey(const CString& version)
{
CString path = "Software\\Microsoft\\VisualStudio\\" + version;
CRegKey key;
if (key.Open(HKEY_LOCAL_MACHINE, path + "\\AddIns") == ERROR_SUCCESS)
{
// Remove all old entries.
key.RecurseDeleteKey("LuaPlusDebugger.Connect");
}
}
// DllRegisterServer - Adds entries to the system registry
STDAPI DllRegisterServer(void)
{
// registers object, typelib and all interfaces in typelib
HRESULT hr = _AtlModule.DllRegisterServer();
// Get the module name.
TCHAR moduleName[_MAX_PATH];
moduleName[0] = 0;
::GetModuleFileName(_AtlModule.GetResourceInstance(), (TCHAR*)&moduleName, _MAX_PATH);
// Get the module path.
TCHAR modulePath[_MAX_PATH];
_tcscpy(modulePath, moduleName);
TCHAR* ptr = _tcsrchr(modulePath, '\\');
ptr++;
*ptr++ = 0;
// Get the short module name.
TCHAR moduleShortName[_MAX_PATH];
ptr = _tcsrchr(moduleName, '\\');
_tcscpy(moduleShortName, ptr + 1);
// Register the add-in?
CreateRegistrationKey("7.0", modulePath, moduleShortName);
CreateRegistrationKey("7.1", modulePath, moduleShortName);
return hr;
}
// DllUnregisterServer - Removes entries from the system registry
STDAPI DllUnregisterServer(void)
{
HRESULT hr = _AtlModule.DllUnregisterServer();
// Remove entries.
DestroyRegistrationKey("7.0");
DestroyRegistrationKey("7.1");
return hr;
}
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime: <..>
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
#if !BUILD_LAND_XML
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using XmlSchemaProcessor.Common;
namespace XmlSchemaProcessor.LandXml20
{
public enum CurveType
{
[StringValue("arc")]
Arc,
[StringValue("chord")]
Chord,
}
}
#endif
| Java |
import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
def start(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))
| Java |
## State Machine Sequences and Wave-forms
This section provides additional explanation to particular functions of [API Functions](readme.md#functions) by presenting screenshots of state machine sequence diagrams and wave-forms. All wave-forms were taken during operation of application with DimSwitch library controlling OSRAM QUICKTRONIC - INTELLIGENT QTi DALI 2x28/54 DIM electronic ballast.
### Table of Contents
* [Toggle Relay](#toggle-relay)
* [Sequence](#toggle-relay-sequence)
* [Wave-forms](#toggle-relay-wave-forms)
* [Power On](#power-on)
* [Sequence](#power-on-sequence)
* [Wave-forms](#power-on-wave-forms)
* [Power Off](#power-off)
* [Sequence](#power-off-sequence)
* [Wave-forms](#power-off-wave-forms)
* [Calibrate](#calibrate)
* [Sequence](#calibrate-sequence)
* [Wave-forms](#calibrate-wave-forms)
* [Set Intensity](#set-intensity)
* [Sequence](#set-intensity-sequence)
* [Wave-forms](#set-intensity-wave-forms)
### Toggle Relay
#### Toggle Relay Sequence

#### Toggle Relay Wave-forms

### Power On
#### Power On Sequence

#### Power On Wave-forms

### Power Off
#### Power Off Sequence

#### Power Off Wave-forms


### Calibrate
#### Calibrate Sequence

#### Calibrate Wave-forms


### Set Intensity
#### Set Intensity Sequence

#### Set Intensity Wave-forms
Sequence of setting light intensity depends on initial lamp state (if it is off or already on) and initial direction of intensity change. In later case if initial direction is opposite from desired, the relay is momentary toggled off to change it. See the following wave-forms that illustrate particular cases.
Set the light intensity when the lamp is initially off (below).

Set the light intensity when the lamp is already on (below).

Set the light intensity with altering direction change (below).

Set the light intensity with altering direction change - another example (below).

| Java |
/**
* @file common/js/xml_handler.js
* @brief XE에서 ajax기능을 이용함에 있어 module, act를 잘 사용하기 위한 자바스크립트
**/
// xml handler을 이용하는 user function
var show_waiting_message = true;
/* This work is licensed under Creative Commons GNU LGPL License.
License: http://creativecommons.org/licenses/LGPL/2.1/
Version: 0.9
Author: Stefan Goessner/2006
Web: http://goessner.net/
*/
function xml2json(xml, tab, ignoreAttrib) {
var X = {
toObj: function(xml) {
var o = {};
if (xml.nodeType==1) { // element node ..
if (ignoreAttrib && xml.attributes.length) // element with attributes ..
for (var i=0; i<xml.attributes.length; i++)
o["@"+xml.attributes[i].nodeName] = (xml.attributes[i].nodeValue||"").toString();
if (xml.firstChild) { // element has child nodes ..
var textChild=0, cdataChild=0, hasElementChild=false;
for (var n=xml.firstChild; n; n=n.nextSibling) {
if (n.nodeType==1) hasElementChild = true;
else if (n.nodeType==3 && n.nodeValue.match(/[^ \f\n\r\t\v]/)) textChild++; // non-whitespace text
else if (n.nodeType==4) cdataChild++; // cdata section node
}
if (hasElementChild) {
if (textChild < 2 && cdataChild < 2) { // structured element with evtl. a single text or/and cdata node ..
X.removeWhite(xml);
for (var n=xml.firstChild; n; n=n.nextSibling) {
if (n.nodeType == 3) // text node
o = X.escape(n.nodeValue);
else if (n.nodeType == 4) // cdata node
// o["#cdata"] = X.escape(n.nodeValue);
o = X.escape(n.nodeValue);
else if (o[n.nodeName]) { // multiple occurence of element ..
if (o[n.nodeName] instanceof Array)
o[n.nodeName][o[n.nodeName].length] = X.toObj(n);
else
o[n.nodeName] = [o[n.nodeName], X.toObj(n)];
}
else // first occurence of element..
o[n.nodeName] = X.toObj(n);
}
}
else { // mixed content
if (!xml.attributes.length)
o = X.escape(X.innerXml(xml));
else
o["#text"] = X.escape(X.innerXml(xml));
}
}
else if (textChild) { // pure text
if (!xml.attributes.length)
o = X.escape(X.innerXml(xml));
else
o["#text"] = X.escape(X.innerXml(xml));
}
else if (cdataChild) { // cdata
if (cdataChild > 1)
o = X.escape(X.innerXml(xml));
else
for (var n=xml.firstChild; n; n=n.nextSibling){
//o["#cdata"] = X.escape(n.nodeValue);
o = X.escape(n.nodeValue);
}
}
}
if (!xml.attributes.length && !xml.firstChild) o = null;
}
else if (xml.nodeType==9) { // document.node
o = X.toObj(xml.documentElement);
}
else
alert("unhandled node type: " + xml.nodeType);
return o;
},
toJson: function(o, name, ind) {
var json = name ? ("\""+name+"\"") : "";
if (o instanceof Array) {
for (var i=0,n=o.length; i<n; i++)
o[i] = X.toJson(o[i], "", ind+"\t");
json += (name?":[":"[") + (o.length > 1 ? ("\n"+ind+"\t"+o.join(",\n"+ind+"\t")+"\n"+ind) : o.join("")) + "]";
}
else if (o == null)
json += (name&&":") + "null";
else if (typeof(o) == "object") {
var arr = [];
for (var m in o)
arr[arr.length] = X.toJson(o[m], m, ind+"\t");
json += (name?":{":"{") + (arr.length > 1 ? ("\n"+ind+"\t"+arr.join(",\n"+ind+"\t")+"\n"+ind) : arr.join("")) + "}";
}
else if (typeof(o) == "string")
json += (name&&":") + "\"" + o.toString() + "\"";
else
json += (name&&":") + o.toString();
return json;
},
innerXml: function(node) {
var s = ""
if ("innerHTML" in node)
s = node.innerHTML;
else {
var asXml = function(n) {
var s = "";
if (n.nodeType == 1) {
s += "<" + n.nodeName;
for (var i=0; i<n.attributes.length;i++)
s += " " + n.attributes[i].nodeName + "=\"" + (n.attributes[i].nodeValue||"").toString() + "\"";
if (n.firstChild) {
s += ">";
for (var c=n.firstChild; c; c=c.nextSibling)
s += asXml(c);
s += "</"+n.nodeName+">";
}
else
s += "/>";
}
else if (n.nodeType == 3)
s += n.nodeValue;
else if (n.nodeType == 4)
s += "<![CDATA[" + n.nodeValue + "]]>";
return s;
};
for (var c=node.firstChild; c; c=c.nextSibling)
s += asXml(c);
}
return s;
},
escape: function(txt) {
return txt.replace(/[\\]/g, "\\\\")
.replace(/[\"]/g, '\\"')
.replace(/[\n]/g, '\\n')
.replace(/[\r]/g, '\\r');
},
removeWhite: function(e) {
e.normalize();
for (var n = e.firstChild; n; ) {
if (n.nodeType == 3) { // text node
if (!n.nodeValue.match(/[^ \f\n\r\t\v]/)) { // pure whitespace text node
var nxt = n.nextSibling;
e.removeChild(n);
n = nxt;
}
else
n = n.nextSibling;
}
else if (n.nodeType == 1) { // element node
X.removeWhite(n);
n = n.nextSibling;
}
else // any other node
n = n.nextSibling;
}
return e;
}
};
if (xml.nodeType == 9) // document node
xml = xml.documentElement;
var json_obj = X.toObj(X.removeWhite(xml)), json_str;
if (typeof(JSON)=='object' && jQuery.isFunction(JSON.stringify) && false) {
var obj = {}; obj[xml.nodeName] = json_obj;
json_str = JSON.stringify(obj);
return json_str;
} else {
json_str = X.toJson(json_obj, xml.nodeName, "");
return "{" + (tab ? json_str.replace(/\t/g, tab) : json_str.replace(/\t|\n/g, "")) + "}";
}
}
(function($){
/**
* @brief exec_xml
* @author NHN (developers@xpressengine.com)
**/
$.exec_xml = window.exec_xml = function(module, act, params, callback_func, response_tags, callback_func_arg, fo_obj) {
var xml_path = request_uri+"index.php"
if(!params) params = {};
// {{{ set parameters
if($.isArray(params)) params = arr2obj(params);
params['module'] = module;
params['act'] = act;
if(typeof(xeVid)!='undefined') params['vid'] = xeVid;
if(typeof(response_tags)=="undefined" || response_tags.length<1) response_tags = ['error','message'];
else {
response_tags.push('error', 'message');
}
// }}} set parameters
// use ssl?
if ($.isArray(ssl_actions) && params['act'] && $.inArray(params['act'], ssl_actions) >= 0)
{
var url = default_url || request_uri;
var port = window.https_port || 443;
var _ul = $('<a>').attr('href', url)[0];
var target = 'https://' + _ul.hostname.replace(/:\d+$/, '');
if(port != 443) target += ':'+port;
if(_ul.pathname[0] != '/') target += '/';
target += _ul.pathname;
xml_path = target.replace(/\/$/, '')+'/index.php';
}
var _u1 = $('<a>').attr('href', location.href)[0];
var _u2 = $('<a>').attr('href', xml_path)[0];
// 현 url과 ajax call 대상 url의 schema 또는 port가 다르면 직접 form 전송
if(_u1.protocol != _u2.protocol || _u1.port != _u2.port) return send_by_form(xml_path, params);
var xml = [], i = 0;
xml[i++] = '<?xml version="1.0" encoding="utf-8" ?>';
xml[i++] = '<methodCall>';
xml[i++] = '<params>';
$.each(params, function(key, val) {
xml[i++] = '<'+key+'><![CDATA['+val+']]></'+key+'>';
});
xml[i++] = '</params>';
xml[i++] = '</methodCall>';
var _xhr = null;
if (_xhr && _xhr.readyState != 0) _xhr.abort();
// 전송 성공시
function onsuccess(data, textStatus, xhr) {
var resp_xml = $(data).find('response')[0], resp_obj, txt='', ret=[], tags={}, json_str='';
waiting_obj.css('visibility', 'hidden');
if(!resp_xml) {
alert(_xhr.responseText);
return null;
}
json_str = xml2json(resp_xml, false, false);
resp_obj = (typeof(JSON)=='object' && $.isFunction(JSON.parse))?JSON.parse(json_str):eval('('+json_str+')');
resp_obj = resp_obj.response;
if (typeof(resp_obj)=='undefined') {
ret['error'] = -1;
ret['message'] = 'Unexpected error occured.';
try {
if(typeof(txt=resp_xml.childNodes[0].firstChild.data)!='undefined') ret['message'] += '\r\n'+txt;
} catch(e){};
return ret;
}
$.each(response_tags, function(key, val){ tags[val] = true; });
tags["redirect_url"] = true;
tags["act"] = true;
$.each(resp_obj, function(key, val){ if(tags[key]) ret[key] = val; });
if(ret['error'] != 0) {
if ($.isFunction($.exec_xml.onerror)) {
return $.exec_xml.onerror(module, act, ret, callback_func, response_tags, callback_func_arg, fo_obj);
}
alert(ret['message'] || 'error!');
return null;
}
if(ret['redirect_url']) {
location.href = ret['redirect_url'].replace(/&/g, '&');
return null;
}
if($.isFunction(callback_func)) callback_func(ret, response_tags, callback_func_arg, fo_obj);
}
// 모든 xml데이터는 POST방식으로 전송. try-catch문으로 오류 발생시 대처
try {
$.ajax({
url : xml_path,
type : 'POST',
dataType : 'xml',
data : xml.join('\n'),
contentType : 'text/plain',
beforeSend : function(xhr){ _xhr = xhr; },
success : onsuccess,
error : function(xhr, textStatus) {
waiting_obj.css('visibility', 'hidden');
var msg = '';
if (textStatus == 'parsererror') {
msg = 'The result is not valid XML :\n-------------------------------------\n';
if(xhr.responseText == "") return;
msg += xhr.responseText.replace(/<[^>]+>/g, '');
} else {
msg = textStatus;
}
alert(msg);
}
});
} catch(e) {
alert(e);
return;
}
// ajax 통신중 대기 메세지 출력 (show_waiting_message값을 false로 세팅시 보이지 않음)
var waiting_obj = $('#waitingforserverresponse');
if(show_waiting_message && waiting_obj.length) {
var d = $(document);
waiting_obj.html(waiting_message).css({
'top' : (d.scrollTop()+20)+'px',
'left' : (d.scrollLeft()+20)+'px',
'visibility' : 'visible'
});
}
}
function send_by_form(url, params) {
var frame_id = 'xeTmpIframe';
var form_id = 'xeVirtualForm';
if (!$('#'+frame_id).length) {
$('<iframe name="%id%" id="%id%" style="position:absolute;left:-1px;top:1px;width:1px;height:1px"></iframe>'.replace(/%id%/g, frame_id)).appendTo(document.body);
}
$('#'+form_id).remove();
var form = $('<form id="%id%"></form>'.replace(/%id%/g, form_id)).attr({
'id' : form_id,
'method' : 'post',
'action' : url,
'target' : frame_id
});
params['xeVirtualRequestMethod'] = 'xml';
params['xeRequestURI'] = location.href.replace(/#(.*)$/i,'');
params['xeVirtualRequestUrl'] = request_uri;
$.each(params, function(key, value){
$('<input type="hidden">').attr('name', key).attr('value', value).appendTo(form);
});
form.appendTo(document.body).submit();
}
function arr2obj(arr) {
var ret = {};
for(var key in arr) {
if(arr.hasOwnProperty(key)) ret[key] = arr[key];
}
return ret;
}
/**
* @brief exec_json (exec_xml와 같은 용도)
**/
$.exec_json = function(action,data,func){
if(typeof(data) == 'undefined') data = {};
action = action.split(".");
if(action.length == 2){
if(show_waiting_message) {
$("#waitingforserverresponse").html(waiting_message).css('top',$(document).scrollTop()+20).css('left',$(document).scrollLeft()+20).css('visibility','visible');
}
$.extend(data,{module:action[0],act:action[1]});
if(typeof(xeVid)!='undefined') $.extend(data,{vid:xeVid});
$.ajax({
type:"POST"
,dataType:"json"
,url:request_uri
,contentType:"application/json"
,data:$.param(data)
,success : function(data){
$("#waitingforserverresponse").css('visibility','hidden');
if(data.error > 0) alert(data.message);
if($.isFunction(func)) func(data);
}
});
}
};
$.fn.exec_html = function(action,data,type,func,args){
if(typeof(data) == 'undefined') data = {};
if(!$.inArray(type, ['html','append','prepend'])) type = 'html';
var self = $(this);
action = action.split(".");
if(action.length == 2){
if(show_waiting_message) {
$("#waitingforserverresponse").html(waiting_message).css('top',$(document).scrollTop()+20).css('left',$(document).scrollLeft()+20).css('visibility','visible');
}
$.extend(data,{module:action[0],act:action[1]});
$.ajax({
type:"POST"
,dataType:"html"
,url:request_uri
,data:$.param(data)
,success : function(html){
$("#waitingforserverresponse").css('visibility','hidden');
self[type](html);
if($.isFunction(func)) func(args);
}
});
}
};
})(jQuery);
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.kore.runtime.jsf.converter;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import org.kore.runtime.person.Titel;
/**
*
* @author Konrad Renner
*/
@FacesConverter(value = "CurrencyConverter")
public class TitelConverter implements Converter {
@Override
public Titel getAsObject(FacesContext fc, UIComponent uic, String string) {
if (string == null || string.trim().length() == 0) {
return null;
}
return new Titel(string.trim());
}
@Override
public String getAsString(FacesContext fc, UIComponent uic, Object o) {
if (o == null) {
return null;
}
if (o instanceof Titel) {
return ((Titel) o).getValue();
}
throw new IllegalArgumentException("Given object is not a org.kore.runtime.person.Titel");
}
}
| Java |
#!/bin/bash
# Copyright 2021 Collabora Ltd.
# SPDX-License-Identifier: LGPL-2.0-or-later
set -euo pipefail
. $(dirname $0)/libtest.sh
skip_without_bwrap
echo "1..16"
setup_repo
install_repo
cp -a "$G_TEST_BUILDDIR/try-syscall" "$test_tmpdir/try-syscall"
# How this works:
# try-syscall tries to make various syscalls, some benign, some not.
#
# The parameters are chosen to make them fail with EBADF or EFAULT if
# not blocked. If they are blocked, we get ENOSYS or EPERM. If the syscall
# is impossible for a particular architecture, we get ENOENT.
#
# The exit status is an errno value, which we can compare with the expected
# errno value.
eval "$("$test_tmpdir/try-syscall" print-errno-values)"
try_syscall () {
${FLATPAK} run \
--filesystem="$test_tmpdir" \
--command="$test_tmpdir/try-syscall" \
$extra_argv \
org.test.Hello "$@"
}
for extra_argv in "" "--allow=multiarch"; do
echo "# testing with extra argv: '$extra_argv'"
echo "# chmod (benign)"
e=0
try_syscall chmod || e="$?"
assert_streq "$e" "$EFAULT"
ok "chmod not blocked"
echo "# chroot (harmful)"
e=0
try_syscall chroot || e="$?"
assert_streq "$e" "$EPERM"
ok "chroot blocked with EPERM"
echo "# clone3 (harmful)"
e=0
try_syscall clone3 || e="$?"
# This is either ENOSYS because the kernel genuinely doesn't implement it,
# or because we successfully blocked it. We can't tell which.
assert_streq "$e" "$ENOSYS"
ok "clone3 blocked with ENOSYS (CVE-2021-41133)"
echo "# ioctl TIOCNOTTY (benign)"
e=0
try_syscall "ioctl TIOCNOTTY" || e="$?"
assert_streq "$e" "$EBADF"
ok "ioctl TIOCNOTTY not blocked"
echo "# ioctl TIOCSTI (CVE-2017-5226)"
e=0
try_syscall "ioctl TIOCSTI" || e="$?"
assert_streq "$e" "$EPERM"
ok "ioctl TIOCSTI blocked (CVE-2017-5226)"
echo "# ioctl TIOCSTI (trying to repeat CVE-2019-10063)"
e=0
try_syscall "ioctl TIOCSTI CVE-2019-10063" || e="$?"
if test "$e" = "$ENOENT"; then
echo "ok # SKIP Cannot replicate CVE-2019-10063 on 32-bit architecture"
else
assert_streq "$e" "$EPERM"
ok "ioctl TIOCSTI with high bits blocked (CVE-2019-10063)"
fi
echo "# listen (benign)"
e=0
try_syscall "listen" || e="$?"
assert_streq "$e" "$EBADF"
ok "listen not blocked"
echo "# prctl (benign)"
e=0
try_syscall "prctl" || e="$?"
assert_streq "$e" "$EFAULT"
ok "prctl not blocked"
done
| Java |
/*
* The implementation of rb tree.
* Copyright (C) 2008 - 2014 Wangbo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Author e-mail: activesys.wb@gmail.com
* activesys@sina.com.cn
*/
/** include section **/
#include <cstl/cstl_def.h>
#include <cstl/cstl_alloc.h>
#include <cstl/cstl_types.h>
#include <cstl/citerator.h>
#include <cstl/cstring.h>
#include <cstl/cstl_rb_tree_iterator.h>
#include <cstl/cstl_rb_tree_private.h>
#include <cstl/cstl_rb_tree.h>
#include "cstl_rb_tree_aux.h"
/** local constant declaration and local macro section **/
/** local data type declaration and local struct, union, enum section **/
/** local function prototype section **/
/** exported global variable definition section **/
/** local global variable definition section **/
/** exported function implementation section **/
/**
* Create rb tree container.
*/
_rb_tree_t* _create_rb_tree(const char* s_typename)
{
_rb_tree_t* pt_rb_tree = NULL;
if ((pt_rb_tree = (_rb_tree_t*)malloc(sizeof(_rb_tree_t))) == NULL) {
return NULL;
}
if (!_create_rb_tree_auxiliary(pt_rb_tree, s_typename)) {
free(pt_rb_tree);
return NULL;
}
return pt_rb_tree;
}
/**
* Initialize rb tree container.
*/
void _rb_tree_init(_rb_tree_t* pt_rb_tree, bfun_t t_compare)
{
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_created(pt_rb_tree));
pt_rb_tree->_t_rbroot._pt_left = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_rbroot._pt_right = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_compare = t_compare != NULL ? t_compare : _GET_RB_TREE_TYPE_LESS_FUNCTION(pt_rb_tree);
}
/**
* Destroy rb tree.
*/
void _rb_tree_destroy(_rb_tree_t* pt_rb_tree)
{
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree) || _rb_tree_is_created(pt_rb_tree));
_rb_tree_destroy_auxiliary(pt_rb_tree);
free(pt_rb_tree);
}
/**
* Initialize rb tree container with rb tree.
*/
void _rb_tree_init_copy(_rb_tree_t* pt_dest, const _rb_tree_t* cpt_src)
{
_rb_tree_iterator_t it_iter;
_rb_tree_iterator_t it_begin;
_rb_tree_iterator_t it_end;
assert(pt_dest != NULL);
assert(cpt_src != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_is_inited(cpt_src));
assert(_rb_tree_same_type(pt_dest, cpt_src));
_rb_tree_init(pt_dest, cpt_src->_t_compare);
it_begin = _rb_tree_begin(cpt_src);
it_end = _rb_tree_end(cpt_src);
for (it_iter = it_begin;
!_rb_tree_iterator_equal(it_iter, it_end);
it_iter = _rb_tree_iterator_next(it_iter)) {
_rb_tree_insert_equal(pt_dest, _rb_tree_iterator_get_pointer_ignore_cstr(it_iter));
}
}
/**
* Initialize rb tree container with specific range.
*/
void _rb_tree_init_copy_equal_range(_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_equal_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific range.
*/
void _rb_tree_init_copy_unique_range(_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_unique_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific array.
*/
void _rb_tree_init_copy_equal_array(_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_equal_array(pt_dest, cpv_array, t_count);
}
/**
* Initialize rb tree container with specific array.
*/
void _rb_tree_init_copy_unique_array(_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, NULL);
_rb_tree_insert_unique_array(pt_dest, cpv_array, t_count);
}
/**
* Initialize rb tree container with specific range and compare function.
*/
void _rb_tree_init_copy_equal_range_ex(
_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_equal_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific range and compare function.
*/
void _rb_tree_init_copy_unique_range_ex(
_rb_tree_t* pt_dest, iterator_t it_begin, iterator_t it_end, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(_rb_tree_same_iterator_type(pt_dest, it_begin));
assert(_rb_tree_same_iterator_type(pt_dest, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_unique_range(pt_dest, it_begin, it_end);
}
/**
* Initialize rb tree container with specific array and compare function.
*/
void _rb_tree_init_copy_equal_array_ex(
_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_equal_array(pt_dest, cpv_array, t_count);
}
/**
* Initialize rb tree container with specific array and compare function.
*/
void _rb_tree_init_copy_unique_array_ex(
_rb_tree_t* pt_dest, const void* cpv_array, size_t t_count, bfun_t t_compare)
{
assert(pt_dest != NULL);
assert(_rb_tree_is_created(pt_dest));
assert(cpv_array != NULL);
_rb_tree_init(pt_dest, t_compare);
_rb_tree_insert_unique_array(pt_dest, cpv_array, t_count);
}
/**
* Assign rb tree container.
*/
void _rb_tree_assign(_rb_tree_t* pt_dest, const _rb_tree_t* cpt_src)
{
assert(pt_dest != NULL);
assert(cpt_src != NULL);
assert(_rb_tree_is_inited(pt_dest));
assert(_rb_tree_is_inited(cpt_src));
assert(_rb_tree_same_type_ex(pt_dest, cpt_src));
if (!_rb_tree_equal(pt_dest, cpt_src)) {
_rb_tree_iterator_t it_iter;
_rb_tree_iterator_t it_begin;
_rb_tree_iterator_t it_end;
/* clear dest rb tree */
_rb_tree_clear(pt_dest);
it_begin = _rb_tree_begin(cpt_src);
it_end = _rb_tree_end(cpt_src);
/* insert all elements of src into dest */
for (it_iter = it_begin;
!_rb_tree_iterator_equal(it_iter, it_end);
it_iter = _rb_tree_iterator_next(it_iter)) {
_rb_tree_insert_equal(pt_dest, _rb_tree_iterator_get_pointer_ignore_cstr(it_iter));
}
}
}
/**
* Test if an rb tree is empty.
*/
bool_t _rb_tree_empty(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return cpt_rb_tree->_t_nodecount == 0 ? true : false;
}
/**
* Get the number of elements int the rb tree.
*/
size_t _rb_tree_size(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return cpt_rb_tree->_t_nodecount;
}
/**
* Get the maximum number of elements int the rb tree.
*/
size_t _rb_tree_max_size(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return (size_t)(-1) / _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
}
/**
* Return an iterator that addresses the first element in the rb tree.
*/
_rb_tree_iterator_t _rb_tree_begin(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_begin = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_begin) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_begin) = (_byte_t*)cpt_rb_tree->_t_rbroot._pt_left;
return it_begin;
}
/**
* Return an iterator that addresses the location succeeding the last element in the rb tree.
*/
_rb_tree_iterator_t _rb_tree_end(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_end = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_end) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_end) = (_byte_t*)&cpt_rb_tree->_t_rbroot;
return it_end;
}
_rb_tree_iterator_t _rb_tree_rend(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_newiterator = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
_RB_TREE_ITERATOR_TREE_POINTER(it_newiterator) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_newiterator) = (_byte_t*)&cpt_rb_tree->_t_rbroot;
return it_newiterator;
}
_rb_tree_iterator_t _rb_tree_rbegin(const _rb_tree_t* cpt_rb_tree)
{
_rb_tree_iterator_t it_newiterator = _create_rb_tree_iterator();
assert(cpt_rb_tree != NULL);
_RB_TREE_ITERATOR_TREE_POINTER(it_newiterator) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_newiterator) = (_byte_t*)cpt_rb_tree->_t_rbroot._pt_right;
return it_newiterator;
}
/**
* Return the compare function of key.
*/
bfun_t _rb_tree_key_comp(const _rb_tree_t* cpt_rb_tree)
{
assert(cpt_rb_tree != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
return cpt_rb_tree->_t_compare;
}
/**
* Find specific element.
*/
_rb_tree_iterator_t _rb_tree_find(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
_rb_tree_iterator_t it_iter;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = (void*)cpt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)_rb_tree_find_value(
cpt_rb_tree, cpt_rb_tree->_t_rbroot._pt_parent, cpv_value);
if (_RB_TREE_ITERATOR_COREPOS(it_iter) == NULL) {
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)&cpt_rb_tree->_t_rbroot;
}
return it_iter;
}
/**
* Erases all the elements of an rb tree.
*/
void _rb_tree_clear(_rb_tree_t* pt_rb_tree)
{
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
pt_rb_tree->_t_rbroot._pt_parent = _rb_tree_destroy_subtree(pt_rb_tree, pt_rb_tree->_t_rbroot._pt_parent);
assert(pt_rb_tree->_t_rbroot._pt_parent == NULL);
pt_rb_tree->_t_rbroot._pt_left = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_rbroot._pt_right = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_nodecount = 0;
}
/**
* Tests if the two rb tree are equal.
*/
bool_t _rb_tree_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
_rb_tree_iterator_t it_first;
_rb_tree_iterator_t it_first_begin;
_rb_tree_iterator_t it_first_end;
_rb_tree_iterator_t it_second;
_rb_tree_iterator_t it_second_begin;
_rb_tree_iterator_t it_second_end;
bool_t b_less = false;
bool_t b_greater = false;
assert(cpt_first != NULL);
assert(cpt_second != NULL);
assert(_rb_tree_is_inited(cpt_first));
assert(_rb_tree_is_inited(cpt_second));
assert(_rb_tree_same_type_ex(cpt_first, cpt_second));
if (cpt_first == cpt_second) {
return true;
}
/* test rb tree size */
if (_rb_tree_size(cpt_first) != _rb_tree_size(cpt_second)) {
return false;
}
it_first_begin = _rb_tree_begin(cpt_first);
it_first_end = _rb_tree_end(cpt_first);
it_second_begin = _rb_tree_begin(cpt_second);
it_second_end = _rb_tree_end(cpt_second);
/* test each element */
for (it_first = it_first_begin, it_second = it_second_begin;
!_rb_tree_iterator_equal(it_first, it_first_end) && !_rb_tree_iterator_equal(it_second, it_second_end);
it_first = _rb_tree_iterator_next(it_first), it_second = _rb_tree_iterator_next(it_second)) {
b_less = b_greater = _GET_RB_TREE_TYPE_SIZE(cpt_first);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data, &b_less);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data, &b_greater);
if (b_less || b_greater) {
return false;
}
}
assert(_rb_tree_iterator_equal(it_first, it_first_end) && _rb_tree_iterator_equal(it_second, it_second_end));
return true;
}
/**
* Tests if the two rb tree are not equal.
*/
bool_t _rb_tree_not_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return !_rb_tree_equal(cpt_first, cpt_second);
}
/**
* Tests if the first rb tree is less than the second rb tree.
*/
bool_t _rb_tree_less(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
_rb_tree_iterator_t it_first;
_rb_tree_iterator_t it_first_begin;
_rb_tree_iterator_t it_first_end;
_rb_tree_iterator_t it_second;
_rb_tree_iterator_t it_second_begin;
_rb_tree_iterator_t it_second_end;
bool_t b_result = false;
assert(cpt_first != NULL);
assert(cpt_second != NULL);
assert(_rb_tree_is_inited(cpt_first));
assert(_rb_tree_is_inited(cpt_second));
assert(_rb_tree_same_type_ex(cpt_first, cpt_second));
it_first_begin = _rb_tree_begin(cpt_first);
it_first_end = _rb_tree_end(cpt_first);
it_second_begin = _rb_tree_begin(cpt_second);
it_second_end = _rb_tree_end(cpt_second);
/* test each element */
for (it_first = it_first_begin, it_second = it_second_begin;
!_rb_tree_iterator_equal(it_first, it_first_end) && !_rb_tree_iterator_equal(it_second, it_second_end);
it_first = _rb_tree_iterator_next(it_first), it_second = _rb_tree_iterator_next(it_second)) {
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_first);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data, &b_result);
if (b_result) {
return true;
}
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_first);
_GET_RB_TREE_TYPE_LESS_FUNCTION(cpt_first)(
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_second))->_pby_data,
((_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_first))->_pby_data, &b_result);
if (b_result) {
return false;
}
}
return _rb_tree_size(cpt_first) < _rb_tree_size(cpt_second) ? true : false;
}
/**
* Tests if the first rb tree is less than or equal to the second rb tree.
*/
bool_t _rb_tree_less_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return (_rb_tree_less(cpt_first, cpt_second) || _rb_tree_equal(cpt_first, cpt_second)) ? true : false;
}
/**
* Tests if the first rb tree is greater than the second rb tree.
*/
bool_t _rb_tree_greater(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return _rb_tree_less(cpt_second, cpt_first);
}
/**
* Tests if the first rb tree is greater than or equal to the second rb tree.
*/
bool_t _rb_tree_greater_equal(const _rb_tree_t* cpt_first, const _rb_tree_t* cpt_second)
{
return (_rb_tree_greater(cpt_first, cpt_second) || _rb_tree_equal(cpt_first, cpt_second)) ? true : false;
}
/**
* Swap the datas of first rb_tree and second rb_tree.
*/
void _rb_tree_swap(_rb_tree_t* pt_first, _rb_tree_t* pt_second)
{
_rb_tree_t t_temp;
assert(pt_first != NULL);
assert(pt_second != NULL);
assert(_rb_tree_is_inited(pt_first));
assert(_rb_tree_is_inited(pt_second));
assert(_rb_tree_same_type_ex(pt_first, pt_second));
if (_rb_tree_equal(pt_first, pt_second)) {
return;
}
t_temp = *pt_first;
*pt_first = *pt_second;
*pt_second = t_temp;
if (_rb_tree_empty(pt_first)) {
pt_first->_t_rbroot._pt_left = &pt_first->_t_rbroot;
pt_first->_t_rbroot._pt_right = &pt_first->_t_rbroot;
} else {
pt_first->_t_rbroot._pt_parent->_pt_parent = &pt_first->_t_rbroot;
}
if (_rb_tree_empty(pt_second)) {
pt_second->_t_rbroot._pt_left = &pt_second->_t_rbroot;
pt_second->_t_rbroot._pt_right = &pt_second->_t_rbroot;
} else {
pt_second->_t_rbroot._pt_parent->_pt_parent = &pt_second->_t_rbroot;
}
}
/**
* Return the number of specific elements in an rb tree
*/
size_t _rb_tree_count(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
range_t r_range;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
r_range = _rb_tree_equal_range(cpt_rb_tree, cpv_value);
return abs(_rb_tree_iterator_distance(r_range.it_begin, r_range.it_end));
}
/**
* Return an iterator to the first element that is equal to or greater than a specific element.
*/
_rb_tree_iterator_t _rb_tree_lower_bound(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
_rbnode_t* pt_cur = NULL;
_rbnode_t* pt_prev = NULL;
_rb_tree_iterator_t it_iter;
bool_t b_less = false;
bool_t b_greater = false;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
it_iter = _create_rb_tree_iterator();
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = (void*)cpt_rb_tree;
if (!_rb_tree_empty(cpt_rb_tree)) {
pt_prev = cpt_rb_tree->_t_rbroot._pt_parent;
b_less = b_greater = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_less);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, pt_prev->_pby_data, cpv_value, &b_greater);
pt_cur = (b_less || !b_greater) ? pt_prev->_pt_left : pt_prev->_pt_right;
while (pt_cur != NULL) {
pt_prev = pt_cur;
b_less = b_greater = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_less);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, pt_prev->_pby_data, cpv_value, &b_greater);
pt_cur = (b_less || !b_greater) ? pt_prev->_pt_left : pt_prev->_pt_right;
}
if (b_less || !b_greater) {
assert(pt_prev->_pt_left == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
assert(_rb_tree_iterator_belong_to_rb_tree(cpt_rb_tree, it_iter));
} else {
assert(pt_prev->_pt_right == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
it_iter = _rb_tree_iterator_next(it_iter);
}
} else {
it_iter = _rb_tree_end(cpt_rb_tree);
}
return it_iter;
}
/**
* Return an iterator to the first element that is greater than a specific element.
*/
_rb_tree_iterator_t _rb_tree_upper_bound(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
_rbnode_t* pt_cur = NULL;
_rbnode_t* pt_prev = NULL;
_rb_tree_iterator_t it_iter;
bool_t b_result = false;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
it_iter = _create_rb_tree_iterator();
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = (void*)cpt_rb_tree;
if (!_rb_tree_empty(cpt_rb_tree)) {
pt_prev = cpt_rb_tree->_t_rbroot._pt_parent;
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_result);
pt_cur = b_result ? pt_prev->_pt_left : pt_prev->_pt_right;
while (pt_cur != NULL) {
pt_prev = pt_cur;
b_result = _GET_RB_TREE_TYPE_SIZE(cpt_rb_tree);
_rb_tree_elem_compare_auxiliary(cpt_rb_tree, cpv_value, pt_prev->_pby_data, &b_result);
pt_cur = b_result ? pt_prev->_pt_left : pt_prev->_pt_right;
}
if (b_result) {
assert(pt_prev->_pt_left == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
assert(_rb_tree_iterator_belong_to_rb_tree(cpt_rb_tree, it_iter));
} else {
assert(pt_prev->_pt_right == NULL);
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)pt_prev;
it_iter = _rb_tree_iterator_next(it_iter);
}
} else {
it_iter = _rb_tree_end(cpt_rb_tree);
}
return it_iter;
}
/**
* Return an iterator range that is equal to a specific element.
*/
range_t _rb_tree_equal_range(const _rb_tree_t* cpt_rb_tree, const void* cpv_value)
{
range_t r_range;
assert(cpt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(cpt_rb_tree));
r_range.it_begin = _rb_tree_lower_bound(cpt_rb_tree, cpv_value);
r_range.it_end = _rb_tree_upper_bound(cpt_rb_tree, cpv_value);
return r_range;
}
/**
* Inserts an element into a rb tree.
*/
_rb_tree_iterator_t _rb_tree_insert_equal(_rb_tree_t* pt_rb_tree, const void* cpv_value)
{
_rb_tree_iterator_t it_iter = _create_rb_tree_iterator();
assert(pt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
_RB_TREE_ITERATOR_TREE_POINTER(it_iter) = pt_rb_tree;
_RB_TREE_ITERATOR_COREPOS(it_iter) = (_byte_t*)_rb_tree_insert_rbnode(pt_rb_tree, cpv_value);
pt_rb_tree->_t_rbroot._pt_left = _rb_tree_get_min_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
pt_rb_tree->_t_rbroot._pt_right = _rb_tree_get_max_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
pt_rb_tree->_t_nodecount++;
return it_iter;
}
/**
* Inserts an unique element into a rb tree.
*/
_rb_tree_iterator_t _rb_tree_insert_unique(_rb_tree_t* pt_rb_tree, const void* cpv_value)
{
assert(pt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
/* if the rb tree is empty */
if (_rb_tree_empty(pt_rb_tree)) {
return _rb_tree_insert_equal(pt_rb_tree, cpv_value);
} else {
/* find value in rb tree */
_rb_tree_iterator_t it_iter = _rb_tree_find(pt_rb_tree, cpv_value);
/* if the value is exist */
if (!_rb_tree_iterator_equal(it_iter, _rb_tree_end(pt_rb_tree))) {
return _rb_tree_end(pt_rb_tree);
} else {
/* insert value into rb tree */
return _rb_tree_insert_equal(pt_rb_tree, cpv_value);
}
}
}
/**
* Inserts an range into a rb tree.
*/
void _rb_tree_insert_equal_range(_rb_tree_t* pt_rb_tree, iterator_t it_begin, iterator_t it_end)
{
iterator_t it_iter;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_begin));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
for (it_iter = it_begin; !iterator_equal(it_iter, it_end); it_iter = iterator_next(it_iter)) {
_rb_tree_insert_equal(pt_rb_tree, _iterator_get_pointer_ignore_cstr(it_iter));
}
}
/**
* Inserts an array into a rb tree.
*/
void _rb_tree_insert_equal_array(_rb_tree_t* pt_rb_tree, const void* cpv_array, size_t t_count)
{
size_t i = 0;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(cpv_array != NULL);
/*
* Copy the elements from src array to dest rb tree.
* The array of c builtin and user define or cstl builtin are different,
* the elements of c builtin array are element itself, but the elements of
* c string, user define or cstl are pointer of element.
*/
if (strncmp(_GET_RB_TREE_TYPE_BASENAME(pt_rb_tree), _C_STRING_TYPE, _TYPE_NAME_SIZE) == 0) {
/*
* We need built a string_t for c string element.
*/
string_t* pstr_elem = create_string();
assert(pstr_elem != NULL);
string_init(pstr_elem);
for (i = 0; i < t_count; ++i) {
string_assign_cstr(pstr_elem, *((const char**)cpv_array + i));
_rb_tree_insert_equal(pt_rb_tree, pstr_elem);
}
string_destroy(pstr_elem);
} else if (_GET_RB_TREE_TYPE_STYLE(pt_rb_tree) == _TYPE_C_BUILTIN) {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_equal(pt_rb_tree, (unsigned char*)cpv_array + i * _GET_RB_TREE_TYPE_SIZE(pt_rb_tree));
}
} else {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_equal(pt_rb_tree, *((void**)cpv_array + i));
}
}
}
/**
* Inserts an range of unique element into a rb tree.
*/
void _rb_tree_insert_unique_range(_rb_tree_t* pt_rb_tree, iterator_t it_begin, iterator_t it_end)
{
iterator_t it_iter;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_begin));
assert(_rb_tree_same_iterator_type(pt_rb_tree, it_end));
assert(iterator_equal(it_begin, it_end) || _iterator_before(it_begin, it_end));
for (it_iter = it_begin; !iterator_equal(it_iter, it_end); it_iter = iterator_next(it_iter)) {
_rb_tree_insert_unique(pt_rb_tree, _iterator_get_pointer_ignore_cstr(it_iter));
}
}
/**
* Inserts an array of unique element into a rb tree.
*/
void _rb_tree_insert_unique_array(_rb_tree_t* pt_rb_tree, const void* cpv_array, size_t t_count)
{
size_t i = 0;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(cpv_array != NULL);
/*
* Copy the elements from src array to dest rb tree.
* The array of c builtin and user define or cstl builtin are different,
* the elements of c builtin array are element itself, but the elements of
* c string, user define or cstl are pointer of element.
*/
if (strncmp(_GET_RB_TREE_TYPE_BASENAME(pt_rb_tree), _C_STRING_TYPE, _TYPE_NAME_SIZE) == 0) {
/*
* We need built a string_t for c string element.
*/
string_t* pstr_elem = create_string();
assert(pstr_elem != NULL);
string_init(pstr_elem);
for (i = 0; i < t_count; ++i) {
string_assign_cstr(pstr_elem, *((const char**)cpv_array + i));
_rb_tree_insert_unique(pt_rb_tree, pstr_elem);
}
string_destroy(pstr_elem);
} else if (_GET_RB_TREE_TYPE_STYLE(pt_rb_tree) == _TYPE_C_BUILTIN) {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_unique(pt_rb_tree, (unsigned char*)cpv_array + i * _GET_RB_TREE_TYPE_SIZE(pt_rb_tree));
}
} else {
for (i = 0; i < t_count; ++i) {
_rb_tree_insert_unique(pt_rb_tree, *((void**)cpv_array + i));
}
}
}
/*
* Erase an element in an rb tree from specificed position.
*/
void _rb_tree_erase_pos(_rb_tree_t* pt_rb_tree, _rb_tree_iterator_t it_pos)
{
_rbnode_t* pt_parent = NULL;
_rbnode_t* pt_cur = NULL;
_rbnode_t* pt_parenttmp = NULL;
_rbnode_t* pt_curtmp = NULL;
_color_t t_colortmp; /* temporary color for deletion */
bool_t b_result = false;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_iterator_belong_to_rb_tree(pt_rb_tree, it_pos));
assert(!_rb_tree_iterator_equal(it_pos, _rb_tree_end(pt_rb_tree)));
pt_cur = (_rbnode_t*)_RB_TREE_ITERATOR_COREPOS(it_pos);
pt_parent = pt_cur->_pt_parent;
/* delete the current node pointted by it_pos */
if (pt_cur == pt_parent->_pt_parent) {
assert(pt_cur == pt_rb_tree->_t_rbroot._pt_parent);
if (pt_cur->_pt_left == NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* | =>
* c
*/
pt_parent->_pt_parent = NULL;
} else if (pt_cur->_pt_left != NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* | |
* c => l
* /
* l
*/
pt_parent->_pt_parent = pt_cur->_pt_left;
pt_parent->_pt_parent->_pt_parent = pt_parent;
pt_parent->_pt_parent->_t_color = _COLOR_BLACK;
} else if (pt_cur->_pt_left == NULL && pt_cur->_pt_right != NULL) {
/*
* p p
* | |
* c => r
* \
* r
*/
pt_parent->_pt_parent = pt_cur->_pt_right;
pt_parent->_pt_parent->_pt_parent = pt_parent;
pt_parent->_pt_parent->_t_color = _COLOR_BLACK;
} else {
/*
* here the real deleted node is pt_curtmp, so the
* color of pt_curtmp is used.
*/
pt_curtmp = _rb_tree_get_min_rbnode(pt_cur->_pt_right);
t_colortmp = pt_curtmp->_t_color;
if (pt_cur == pt_curtmp->_pt_parent) {
/*
* p p
* | |
* c => r
* / \ / \
* l r l rr
* \
* rr
*/
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_parent = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_curtmp->_pt_right, pt_curtmp);
}
} else {
/*
* p p
* | |
* c => rll
* / \ / \
* l r l r
* / \ / \
* rl rr rl rr
* / \ \ \ \
* rll rlr rrr rlr rrr
*/
pt_parenttmp = pt_curtmp->_pt_parent;
pt_parenttmp->_pt_left = pt_curtmp->_pt_right;
if (pt_parenttmp->_pt_left != NULL) {
pt_parenttmp->_pt_left->_pt_parent = pt_parenttmp;
}
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_right = pt_cur->_pt_right;
pt_curtmp->_pt_right->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_parent = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parenttmp->_pt_left, pt_parenttmp);
}
}
}
} else if (pt_cur == pt_parent->_pt_left) {
if (pt_cur->_pt_left == NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* / =>
* c
*/
pt_parent->_pt_left = NULL;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_left, pt_parent);
}
} else if (pt_cur->_pt_left != NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* / /
* c => l
* /
* l
*/
pt_parent->_pt_left = pt_cur->_pt_left;
pt_parent->_pt_left->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_left, pt_parent);
}
} else if (pt_cur->_pt_left == NULL && pt_cur->_pt_right != NULL) {
/*
* p p
* / /
* c => r
* \
* r
*/
pt_parent->_pt_left = pt_cur->_pt_right;
pt_parent->_pt_left->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_left, pt_parent);
}
} else {
/*
* here the real deleted node is pt_curtmp, so the
* color of pt_curtmp is used.
*/
pt_curtmp = _rb_tree_get_min_rbnode(pt_cur->_pt_right);
t_colortmp = pt_curtmp->_t_color;
if (pt_cur == pt_curtmp->_pt_parent) {
/*
* p p
* / /
* c => r
* / \ / \
* l r l rr
* \
* rr
*/
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_left = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_curtmp->_pt_right, pt_curtmp);
}
} else {
/*
* p p
* / /
* c => rll
* / \ / \
* l r l r
* / \ / \
* rl rr rl rr
* / \ \ \ \
* rll rlr rrr rlr rrr
*/
pt_parenttmp = pt_curtmp->_pt_parent;
pt_parenttmp->_pt_left = pt_curtmp->_pt_right;
if (pt_parenttmp->_pt_left != NULL) {
pt_parenttmp->_pt_left->_pt_parent = pt_parenttmp;
}
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_right = pt_cur->_pt_right;
pt_curtmp->_pt_right->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_left = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parenttmp->_pt_left, pt_parenttmp);
}
}
}
} else {
if (pt_cur->_pt_left == NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* \ =>
* c
*/
pt_parent->_pt_right = NULL;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_right, pt_parent);
}
} else if (pt_cur->_pt_left != NULL && pt_cur->_pt_right == NULL) {
/*
* p p
* \ \
* c => l
* /
* l
*/
pt_parent->_pt_right = pt_cur->_pt_left;
pt_parent->_pt_right->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_right, pt_parent);
}
} else if (pt_cur->_pt_left == NULL && pt_cur->_pt_right != NULL) {
/*
* p p
* \ \
* c => r
* \
* r
*/
pt_parent->_pt_right = pt_cur->_pt_right;
pt_parent->_pt_right->_pt_parent = pt_parent;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parent->_pt_right, pt_parent);
}
} else {
/*
* here the real deleted node is pt_curtmp, so the
* color of pt_curtmp is used.
*/
pt_curtmp = _rb_tree_get_min_rbnode(pt_cur->_pt_right);
t_colortmp = pt_curtmp->_t_color;
if (pt_cur == pt_curtmp->_pt_parent) {
/*
* p p
* \ \
* c => r
* / \ / \
* l r l rr
* \
* rr
*/
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_right = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_curtmp->_pt_right, pt_curtmp);
}
} else {
/*
* p p
* \ \
* c => rll
* / \ / \
* l r l r
* / \ / \
* rl rr rl rr
* / \ \ \ \
* rll rlr rrr rlr rrr
*/
pt_parenttmp = pt_curtmp->_pt_parent;
pt_parenttmp->_pt_left = pt_curtmp->_pt_right;
if (pt_parenttmp->_pt_left != NULL) {
pt_parenttmp->_pt_left->_pt_parent = pt_parenttmp;
}
pt_curtmp->_pt_left = pt_cur->_pt_left;
pt_curtmp->_pt_left->_pt_parent = pt_curtmp;
pt_curtmp->_pt_right = pt_cur->_pt_right;
pt_curtmp->_pt_right->_pt_parent = pt_curtmp;
pt_curtmp->_pt_parent = pt_cur->_pt_parent;
pt_curtmp->_pt_parent->_pt_right = pt_curtmp;
pt_curtmp->_t_color = pt_cur->_t_color;
pt_cur->_t_color = t_colortmp;
if (_rb_tree_get_color(pt_cur) == _COLOR_BLACK) {
_rb_tree_fixup_deletion(pt_rb_tree, pt_parenttmp->_pt_left, pt_parenttmp);
}
}
}
}
/* destroy the node */
b_result = _GET_RB_TREE_TYPE_SIZE(pt_rb_tree);
_GET_RB_TREE_TYPE_DESTROY_FUNCTION(pt_rb_tree)(pt_cur->_pby_data, &b_result);
assert(b_result);
_alloc_deallocate(&pt_rb_tree->_t_allocator, pt_cur, _RB_TREE_NODE_SIZE(_GET_RB_TREE_TYPE_SIZE(pt_rb_tree)), 1);
pt_rb_tree->_t_nodecount--;
/* update the left and right pointer */
if (pt_rb_tree->_t_nodecount == 0) {
pt_rb_tree->_t_rbroot._pt_parent = NULL;
pt_rb_tree->_t_rbroot._pt_left = &pt_rb_tree->_t_rbroot;
pt_rb_tree->_t_rbroot._pt_right = &pt_rb_tree->_t_rbroot;
} else {
pt_rb_tree->_t_rbroot._pt_left = _rb_tree_get_min_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
pt_rb_tree->_t_rbroot._pt_right = _rb_tree_get_max_rbnode(pt_rb_tree->_t_rbroot._pt_parent);
}
}
/*
* Erase a range of element in an rb tree.
*/
void _rb_tree_erase_range(_rb_tree_t* pt_rb_tree, _rb_tree_iterator_t it_begin, _rb_tree_iterator_t it_end)
{
_rb_tree_iterator_t it_iter;
_rb_tree_iterator_t it_next;
assert(pt_rb_tree != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
assert(_rb_tree_same_rb_tree_iterator_type(pt_rb_tree, it_begin));
assert(_rb_tree_same_rb_tree_iterator_type(pt_rb_tree, it_end));
assert(_rb_tree_iterator_equal(it_begin, it_end) || _rb_tree_iterator_before(it_begin, it_end));
it_iter = it_next = it_begin;
if (!_rb_tree_iterator_equal(it_next, _rb_tree_end(pt_rb_tree))) {
it_next = _rb_tree_iterator_next(it_next);
}
while (!_rb_tree_iterator_equal(it_iter, it_end)) {
_rb_tree_erase_pos(pt_rb_tree, it_iter);
it_iter = it_next;
if (!_rb_tree_iterator_equal(it_next, _rb_tree_end(pt_rb_tree))) {
it_next = _rb_tree_iterator_next(it_next);
}
}
}
/**
* Erase an element from a rb tree that match a specified element.
*/
size_t _rb_tree_erase(_rb_tree_t* pt_rb_tree, const void* cpv_value)
{
size_t t_count = 0;
range_t r_range;
assert(pt_rb_tree != NULL);
assert(cpv_value != NULL);
assert(_rb_tree_is_inited(pt_rb_tree));
t_count = _rb_tree_count(pt_rb_tree, cpv_value);
r_range = _rb_tree_equal_range(pt_rb_tree, cpv_value);
if (!_rb_tree_iterator_equal(r_range.it_begin, _rb_tree_end(pt_rb_tree))) {
_rb_tree_erase_range(pt_rb_tree, r_range.it_begin, r_range.it_end);
}
return t_count;
}
/** local function implementation section **/
/** eof **/
| Java |
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qvariant.h>
class tst_QGuiVariant : public QObject
{
Q_OBJECT
public:
tst_QGuiVariant();
private slots:
void variantWithoutApplication();
};
tst_QGuiVariant::tst_QGuiVariant()
{}
void tst_QGuiVariant::variantWithoutApplication()
{
QVariant v = QString("red");
QVERIFY(qvariant_cast<QColor>(v) == QColor(Qt::red));
}
QTEST_APPLESS_MAIN(tst_QGuiVariant)
#include "tst_qguivariant.moc"
| Java |
/*
* crypt.c - blowfish-cbc code
*
* This file is part of the SSH Library
*
* Copyright (c) 2003 by Aris Adamantiadis
*
* The SSH Library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* The SSH 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the SSH Library; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
#include "config.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#ifdef OPENSSL_CRYPTO
#include <openssl/blowfish.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#endif
#include "libssh/priv.h"
#include "libssh/session.h"
#include "libssh/wrapper.h"
#include "libssh/crypto.h"
#include "libssh/buffer.h"
uint32_t packet_decrypt_len(ssh_session session, char *crypted){
uint32_t decrypted;
if (session->current_crypto) {
if (packet_decrypt(session, crypted,
session->current_crypto->in_cipher->blocksize) < 0) {
return 0;
}
}
memcpy(&decrypted,crypted,sizeof(decrypted));
return ntohl(decrypted);
}
int packet_decrypt(ssh_session session, void *data,uint32_t len) {
struct ssh_cipher_struct *crypto = session->current_crypto->in_cipher;
char *out = NULL;
assert(len);
if(len % session->current_crypto->in_cipher->blocksize != 0){
ssh_set_error(session, SSH_FATAL, "Cryptographic functions must be set on at least one blocksize (received %d)",len);
return SSH_ERROR;
}
out = malloc(len);
if (out == NULL) {
return -1;
}
if (crypto->set_decrypt_key(crypto, session->current_crypto->decryptkey,
session->current_crypto->decryptIV) < 0) {
SAFE_FREE(out);
return -1;
}
crypto->cbc_decrypt(crypto,data,out,len);
memcpy(data,out,len);
memset(out,0,len);
SAFE_FREE(out);
return 0;
}
unsigned char *packet_encrypt(ssh_session session, void *data, uint32_t len) {
struct ssh_cipher_struct *crypto = NULL;
HMACCTX ctx = NULL;
char *out = NULL;
unsigned int finallen;
uint32_t seq;
assert(len);
if (!session->current_crypto) {
return NULL; /* nothing to do here */
}
if(len % session->current_crypto->in_cipher->blocksize != 0){
ssh_set_error(session, SSH_FATAL, "Cryptographic functions must be set on at least one blocksize (received %d)",len);
return NULL;
}
out = malloc(len);
if (out == NULL) {
return NULL;
}
seq = ntohl(session->send_seq);
crypto = session->current_crypto->out_cipher;
if (crypto->set_encrypt_key(crypto, session->current_crypto->encryptkey,
session->current_crypto->encryptIV) < 0) {
SAFE_FREE(out);
return NULL;
}
if (session->version == 2) {
ctx = hmac_init(session->current_crypto->encryptMAC,20,SSH_HMAC_SHA1);
if (ctx == NULL) {
SAFE_FREE(out);
return NULL;
}
hmac_update(ctx,(unsigned char *)&seq,sizeof(uint32_t));
hmac_update(ctx,data,len);
hmac_final(ctx,session->current_crypto->hmacbuf,&finallen);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("mac: ",data,len);
if (finallen != 20) {
printf("Final len is %d\n",finallen);
}
ssh_print_hexa("Packet hmac", session->current_crypto->hmacbuf, 20);
#endif
}
crypto->cbc_encrypt(crypto, data, out, len);
memcpy(data, out, len);
memset(out, 0, len);
SAFE_FREE(out);
if (session->version == 2) {
return session->current_crypto->hmacbuf;
}
return NULL;
}
/**
* @internal
*
* @brief Verify the hmac of a packet
*
* @param session The session to use.
* @param buffer The buffer to verify the hmac from.
* @param mac The mac to compare with the hmac.
*
* @return 0 if hmac and mac are equal, < 0 if not or an error
* occurred.
*/
int packet_hmac_verify(ssh_session session, ssh_buffer buffer,
unsigned char *mac) {
unsigned char hmacbuf[EVP_MAX_MD_SIZE] = {0};
HMACCTX ctx;
unsigned int len;
uint32_t seq;
ctx = hmac_init(session->current_crypto->decryptMAC, 20, SSH_HMAC_SHA1);
if (ctx == NULL) {
return -1;
}
seq = htonl(session->recv_seq);
hmac_update(ctx, (unsigned char *) &seq, sizeof(uint32_t));
hmac_update(ctx, buffer_get_rest(buffer), buffer_get_rest_len(buffer));
hmac_final(ctx, hmacbuf, &len);
#ifdef DEBUG_CRYPTO
ssh_print_hexa("received mac",mac,len);
ssh_print_hexa("Computed mac",hmacbuf,len);
ssh_print_hexa("seq",(unsigned char *)&seq,sizeof(uint32_t));
#endif
if (memcmp(mac, hmacbuf, len) == 0) {
return 0;
}
return -1;
}
/* vim: set ts=2 sw=2 et cindent: */
| Java |
/*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2012, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* 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
* Lesser General Public License for more details.
*/
package org.geotools.referencing.factory.gridshift;
import java.net.URL;
import org.geotools.metadata.iso.citation.Citations;
import org.geotools.util.factory.AbstractFactory;
import org.opengis.metadata.citation.Citation;
/**
* Default grid shift file locator, looks up grids in the classpath
*
* @author Andrea Aime - GeoSolutions
*/
public class ClasspathGridShiftLocator extends AbstractFactory implements GridShiftLocator {
public ClasspathGridShiftLocator() {
super(NORMAL_PRIORITY);
}
@Override
public Citation getVendor() {
return Citations.GEOTOOLS;
}
@Override
public URL locateGrid(String grid) {
return getClass().getResource(grid);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.