code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
FILE(REMOVE_RECURSE
"CMakeFiles/testRot3Optimization.dir/testRot3Optimization.cpp.o"
"testRot3Optimization.pdb"
"testRot3Optimization"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
INCLUDE(CMakeFiles/testRot3Optimization.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
| devbharat/gtsam | build/tests/CMakeFiles/testRot3Optimization.dir/cmake_clean.cmake | CMake | bsd-3-clause | 314 |
# Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 3. 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 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.
=head1 NAME
Brocade::BSC::Node
=head1 DESCRIPTION
A I<Brocade::BSC::Node> object is used to model, query, and configure
network devices via Brocade's OpenDaylight-based Software-Defined
Networking controller.
=cut
package Brocade::BSC::Node;
use strict;
use warnings;
use YAML;
use JSON -convert_blessed_universally;
=head1 METHODS
=cut
# Constructor ==========================================================
#
=over 4
=item B<new>
Creates a new I<Brocade::BSC::Node> object and populates fields with
values from argument hash, if present, or YAML configuration file.
### parameters:
# + cfgfile - path to YAML configuration file specifying node attributes
# + ctrl - reference to Brocade::BSC controller object (required)
# + name - name of controlled node
#
### YAML configuration file labels and default values
#
# parameter hash | YAML label | default value
# -------------- | ----------- | -------------
# name | nodeName |
Returns new I<Brocade::BSC::Node> object.
=cut
sub new {
my $class = shift;
my %params = @_;
my $yamlcfg;
if ($params{cfgfile} && ( -e $params{cfgfile})) {
$yamlcfg = YAML::LoadFile($params{cfgfile});
}
my $self = {
ctrl => $params{ctrl},
name => ''
};
if ($yamlcfg) {
$yamlcfg->{nodeName}
&& ($self->{name} = $yamlcfg->{nodeName});
}
$params{name} && ($self->{name} = $params{name});
bless ($self, $class);
}
# Method ===============================================================
#
=item B<as_json>
# Returns : Returns pretty-printed JSON string representing netconf node.
=cut
sub as_json {
my $self = shift;
my $json = new JSON->canonical->allow_blessed->convert_blessed;
return $json->pretty->encode($self);
}
# Method ===============================================================
#
=item B<ctrl_req>
# Parameters: $method (string, req) HTTP verb
# : $urlpath (string, req) path for REST request
# : $data (string, opt)
# : $headerref (hash ref, opt)
# Returns : HTTP::Response
=cut
sub ctrl_req {
my $self = shift;
return $self->{ctrl}->_http_req(@_);
}
# Module ===============================================================
1;
=back
=head1 COPYRIGHT
Copyright (c) 2015, BROCADE COMMUNICATIONS SYSTEMS, INC
All rights reserved.
| BRCDcomm/perlbsc | Brocade-BSC/lib/Brocade/BSC/Node.pm | Perl | bsd-3-clause | 4,002 |
<?php
/**
* Created by PhpStorm.
* User: sergey
* Date: 21.01.17
* Time: 17:26
*/
namespace app\models;
use yii\db\ActiveRecord;
class Category extends ActiveRecord
{
public static function tableName()
{
return 'category';
}
public function getProducts()
{
return $this->hasMany(Product::className(), ['category_id' => 'id']);
}
} | sergeygusevrepositories/yii2_shop | models/Category.php | PHP | bsd-3-clause | 378 |
/*
* 2007 2013 Copyright Northwestern University
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details.
*/
#ifndef _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CNPPD_ST_NT
#define _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CNPPD_ST_NT
#include "type_iso.CANY.h"
namespace AIMXML
{
namespace iso
{
class CNPPD_ST_NT : public ::AIMXML::iso::CANY
{
public:
AIMXML_EXPORT CNPPD_ST_NT(xercesc::DOMNode* const& init);
AIMXML_EXPORT CNPPD_ST_NT(CNPPD_ST_NT const& init);
void operator=(CNPPD_ST_NT const& other) { m_node = other.m_node; }
static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_iso_altova_CNPPD_ST_NT); }
MemberElement<iso::CUVP_ST_NT, _altova_mi_iso_altova_CNPPD_ST_NT_altova_item> item;
struct item { typedef Iterator<iso::CUVP_ST_NT> iterator; };
AIMXML_EXPORT void SetXsiType();
};
} // namespace iso
} // namespace AIMXML
#endif // _ALTOVA_INCLUDED_AIMXML_ALTOVA_iso_ALTOVA_CNPPD_ST_NT
| NCIP/annotation-and-image-markup | AIMToolkit_v4.0.0_rv44/source/AIMLib/AIMXML/type_iso.CNPPD_ST_NT.h | C | bsd-3-clause | 1,091 |
# -*-coding:Utf-8 -*
# Copyright (c) 2012 NOEL-BARON Léo
# 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 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 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.
"""Package contenant la commande 'chercherbois'."""
from random import random, randint, choice
from math import sqrt
from primaires.interpreteur.commande.commande import Commande
from primaires.perso.exceptions.stat import DepassementStat
class CmdChercherBois(Commande):
"""Commande 'chercherbois'"""
def __init__(self):
"""Constructeur de la commande"""
Commande.__init__(self, "chercherbois", "gatherwood")
self.nom_categorie = "objets"
self.aide_courte = "permet de chercher du bois"
self.aide_longue = \
"Cette commande permet de chercher du combustible dans la salle " \
"où vous vous trouvez."
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande"""
salle = personnage.salle
if salle.interieur:
personnage << "|err|Vous ne pouvez chercher du combustible " \
"ici.|ff|"
return
personnage.agir("chercherbois")
prototypes = importeur.objet.prototypes.values()
prototypes = [p for p in prototypes if p.est_de_type("combustible")]
combustibles = []
choix = None
for proto in prototypes:
if personnage.salle.terrain.nom in proto.terrains:
combustibles.append((proto.rarete, proto))
combustibles = sorted(combustibles, key=lambda combu: combu[0])
if not combustibles:
personnage << "|err|Il n'y a rien qui puisse brûler par ici.|ff|"
else:
niveau = sqrt(personnage.get_talent("collecte_bois") / 100)
if not niveau:
niveau = 0.1
proba_trouver = round(random(), 1)
if proba_trouver <= niveau: # on trouve du bois
possibles = []
for proba, combustible in combustibles:
if 2 * proba_trouver >= (proba - 1) / 10:
for i in range(int(10 / proba)):
possibles.append(combustible)
nb_obj = randint(int(proba_trouver * 10), int(niveau * 10)) + 1
if possibles:
choix = choice(possibles)
somme_qualites = 0
end = int(choix.poids_unitaire * nb_obj / 2)
try:
personnage.stats.endurance -= end
except DepassementStat:
personnage << "|err|Vous êtes trop fatigué pour " \
"cela.|ff|"
return
try:
personnage.stats.endurance -= 3
except DepassementStat:
personnage << "|err|Vous êtes trop fatigué pour cela.|ff|"
return
# On cherche le bois
personnage.etats.ajouter("collecte_bois")
personnage << "Vous vous penchez et commencez à chercher du bois."
personnage.salle.envoyer(
"{} se met à chercher quelque chose par terre.",
personnage)
yield 5
if "collecte_bois" not in personnage.etats:
return
if choix:
for i in range(nb_obj):
objet = importeur.objet.creer_objet(choix)
personnage.salle.objets_sol.ajouter(objet)
somme_qualites += objet.qualite
personnage << "Vous trouvez {} " \
"et vous relevez.".format(choix.get_nom(nb_obj))
personnage.salle.envoyer("{} se relève, l'air satisfait.",
personnage)
personnage.pratiquer_talent("collecte_bois")
personnage.gagner_xp("survie", somme_qualites * 2)
else:
personnage << "Vous vous redressez sans avoir rien trouvé."
personnage.salle.envoyer("{} se relève, l'air dépité.",
personnage)
personnage.pratiquer_talent("collecte_bois", 4)
personnage.etats.retirer("collecte_bois")
| stormi/tsunami | src/primaires/salle/commandes/chercherbois/__init__.py | Python | bsd-3-clause | 5,680 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview User pod row implementation.
*/
cr.define('login', function() {
/**
* Pod width. 170px Pod + 10px padding + 10px margin on both sides.
* @type {number}
* @const
*/
var POD_WIDTH = 170 + 2 * (10 + 10);
/**
* Number of displayed columns depending on user pod count.
* @type {Array.<number>}
* @const
*/
var COLUMNS = [0, 1, 2, 3, 4, 5, 4, 4, 4, 5, 5, 6, 6, 5, 5, 6, 6, 6, 6];
/**
* Whether to preselect the first pod automatically on login screen.
* @type {boolean}
* @const
*/
var PRESELECT_FIRST_POD = true;
/**
* Wallpaper load delay in milliseconds.
* @type {number}
* @const
*/
var WALLPAPER_LOAD_DELAY_MS = 500;
/**
* Wallpaper load delay in milliseconds. TODO(nkostylev): Tune this constant.
* @type {number}
* @const
*/
var WALLPAPER_BOOT_LOAD_DELAY_MS = 100;
/**
* Maximum time for which the pod row remains hidden until all user images
* have been loaded.
* @type {number}
* @const
*/
var POD_ROW_IMAGES_LOAD_TIMEOUT_MS = 3000;
/**
* Oauth token status. These must match UserManager::OAuthTokenStatus.
* @enum {number}
* @const
*/
var OAuthTokenStatus = {
UNKNOWN: 0,
INVALID_OLD: 1,
VALID_OLD: 2,
INVALID_NEW: 3,
VALID_NEW: 4
};
/**
* Tab order for user pods. Update these when adding new controls.
* @enum {number}
* @const
*/
var UserPodTabOrder = {
POD_INPUT: 1, // Password input fields (and whole pods themselves).
HEADER_BAR: 2, // Buttons on the header bar (Shutdown, Add User).
ACTION_BOX: 3, // Action box buttons.
PAD_MENU_ITEM: 4 // User pad menu items (Remove this user).
};
// Focus and tab order are organized as follows:
//
// (1) all user pods have tab index 1 so they are traversed first;
// (2) when a user pod is activated, its tab index is set to -1 and its
// main input field gets focus and tab index 1;
// (3) buttons on the header bar have tab index 2 so they follow user pods;
// (4) Action box buttons have tab index 3 and follow header bar buttons;
// (5) lastly, focus jumps to the Status Area and back to user pods.
//
// 'Focus' event is handled by a capture handler for the whole document
// and in some cases 'mousedown' event handlers are used instead of 'click'
// handlers where it's necessary to prevent 'focus' event from being fired.
/**
* Helper function to remove a class from given element.
* @param {!HTMLElement} el Element whose class list to change.
* @param {string} cl Class to remove.
*/
function removeClass(el, cl) {
el.classList.remove(cl);
}
/**
* Creates a user pod.
* @constructor
* @extends {HTMLDivElement}
*/
var UserPod = cr.ui.define(function() {
var node = $('user-pod-template').cloneNode(true);
node.removeAttribute('id');
return node;
});
/**
* Stops event propagation from the any user pod child element.
* @param {Event} e Event to handle.
*/
function stopEventPropagation(e) {
// Prevent default so that we don't trigger a 'focus' event.
e.preventDefault();
e.stopPropagation();
}
/**
* Unique salt added to user image URLs to prevent caching. Dictionary with
* user names as keys.
* @type {Object}
*/
UserPod.userImageSalt_ = {};
UserPod.prototype = {
__proto__: HTMLDivElement.prototype,
/** @override */
decorate: function() {
this.tabIndex = UserPodTabOrder.POD_INPUT;
this.actionBoxAreaElement.tabIndex = UserPodTabOrder.ACTION_BOX;
// Mousedown has to be used instead of click to be able to prevent 'focus'
// event later.
this.addEventListener('mousedown',
this.handleMouseDown_.bind(this));
this.signinButtonElement.addEventListener('click',
this.activate.bind(this));
this.actionBoxAreaElement.addEventListener('mousedown',
stopEventPropagation);
this.actionBoxAreaElement.addEventListener('click',
this.handleActionAreaButtonClick_.bind(this));
this.actionBoxAreaElement.addEventListener('keydown',
this.handleActionAreaButtonKeyDown_.bind(this));
this.actionBoxMenuRemoveElement.addEventListener('click',
this.handleRemoveCommandClick_.bind(this));
this.actionBoxMenuRemoveElement.addEventListener('keydown',
this.handleRemoveCommandKeyDown_.bind(this));
this.actionBoxMenuRemoveElement.addEventListener('blur',
this.handleRemoveCommandBlur_.bind(this));
},
/**
* Initializes the pod after its properties set and added to a pod row.
*/
initialize: function() {
this.passwordElement.addEventListener('keydown',
this.parentNode.handleKeyDown.bind(this.parentNode));
this.passwordElement.addEventListener('keypress',
this.handlePasswordKeyPress_.bind(this));
this.imageElement.addEventListener('load',
this.parentNode.handlePodImageLoad.bind(this.parentNode, this));
},
/**
* Resets tab order for pod elements to its initial state.
*/
resetTabOrder: function() {
this.tabIndex = UserPodTabOrder.POD_INPUT;
this.mainInput.tabIndex = -1;
},
/**
* Handles keypress event (i.e. any textual input) on password input.
* @param {Event} e Keypress Event object.
* @private
*/
handlePasswordKeyPress_: function(e) {
// When tabbing from the system tray a tab key press is received. Suppress
// this so as not to type a tab character into the password field.
if (e.keyCode == 9) {
e.preventDefault();
return;
}
},
/**
* Gets signed in indicator element.
* @type {!HTMLDivElement}
*/
get signedInIndicatorElement() {
return this.querySelector('.signed-in-indicator');
},
/**
* Gets image element.
* @type {!HTMLImageElement}
*/
get imageElement() {
return this.querySelector('.user-image');
},
/**
* Gets name element.
* @type {!HTMLDivElement}
*/
get nameElement() {
return this.querySelector('.name');
},
/**
* Gets password field.
* @type {!HTMLInputElement}
*/
get passwordElement() {
return this.querySelector('.password');
},
/**
* Gets Caps Lock hint image.
* @type {!HTMLImageElement}
*/
get capslockHintElement() {
return this.querySelector('.capslock-hint');
},
/**
* Gets user signin button.
* @type {!HTMLInputElement}
*/
get signinButtonElement() {
return this.querySelector('.signin-button');
},
/**
* Gets action box area.
* @type {!HTMLInputElement}
*/
get actionBoxAreaElement() {
return this.querySelector('.action-box-area');
},
/**
* Gets action box menu.
* @type {!HTMLInputElement}
*/
get actionBoxMenuElement() {
return this.querySelector('.action-box-menu');
},
/**
* Gets action box menu title, user name item.
* @type {!HTMLInputElement}
*/
get actionBoxMenuTitleNameElement() {
return this.querySelector('.action-box-menu-title-name');
},
/**
* Gets action box menu title, user email item.
* @type {!HTMLInputElement}
*/
get actionBoxMenuTitleEmailElement() {
return this.querySelector('.action-box-menu-title-email');
},
/**
* Gets action box menu, remove user command item.
* @type {!HTMLInputElement}
*/
get actionBoxMenuCommandElement() {
return this.querySelector('.action-box-menu-remove-command');
},
/**
* Gets action box menu, remove user command item div.
* @type {!HTMLInputElement}
*/
get actionBoxMenuRemoveElement() {
return this.querySelector('.action-box-menu-remove');
},
/**
* Updates the user pod element.
*/
update: function() {
this.imageElement.src = 'chrome://userimage/' + this.user.username +
'?id=' + UserPod.userImageSalt_[this.user.username];
this.nameElement.textContent = this.user_.displayName;
this.actionBoxMenuRemoveElement.hidden = !this.user_.canRemove;
this.signedInIndicatorElement.hidden = !this.user_.signedIn;
var needSignin = this.needGaiaSignin;
this.passwordElement.hidden = needSignin;
this.actionBoxAreaElement.setAttribute(
'aria-label', loadTimeData.getStringF(
'podMenuButtonAccessibleName', this.user_.emailAddress));
this.actionBoxMenuRemoveElement.setAttribute(
'aria-label', loadTimeData.getString(
'podMenuRemoveItemAccessibleName'));
this.actionBoxMenuTitleNameElement.textContent = !this.user_.canRemove ?
loadTimeData.getStringF('ownerUserPattern', this.user_.displayName) :
this.user_.displayName;
this.actionBoxMenuTitleEmailElement.textContent = this.user_.emailAddress;
this.actionBoxMenuCommandElement.textContent =
loadTimeData.getString('removeUser');
this.passwordElement.setAttribute('aria-label', loadTimeData.getStringF(
'passwordFieldAccessibleName', this.user_.emailAddress));
this.signinButtonElement.hidden = !needSignin;
},
/**
* The user that this pod represents.
* @type {!Object}
*/
user_: undefined,
get user() {
return this.user_;
},
set user(userDict) {
this.user_ = userDict;
this.update();
},
/**
* Whether Gaia signin is required for this user.
*/
get needGaiaSignin() {
// Gaia signin is performed if the user has an invalid oauth token and is
// not currently signed in (i.e. not the lock screen).
// Locally managed users never require GAIA signin.
return this.user.oauthTokenStatus != OAuthTokenStatus.VALID_OLD &&
this.user.oauthTokenStatus != OAuthTokenStatus.VALID_NEW &&
!this.user.signedIn && !this.user.locallyManagedUser;
},
/**
* Gets main input element.
* @type {(HTMLButtonElement|HTMLInputElement)}
*/
get mainInput() {
if (!this.signinButtonElement.hidden)
return this.signinButtonElement;
else
return this.passwordElement;
},
/**
* Whether action box button is in active state.
* @type {boolean}
*/
get activeActionBoxMenu() {
return this.actionBoxAreaElement.classList.contains('active');
},
set activeActionBoxMenu(active) {
if (active == this.activeActionBoxMenu)
return;
if (active) {
// Clear focus first if another pod is focused.
if (!this.parentNode.isFocused(this)) {
this.parentNode.focusPod(undefined, true);
this.actionBoxAreaElement.focus();
}
this.actionBoxAreaElement.classList.add('active');
} else {
this.actionBoxAreaElement.classList.remove('active');
}
},
/**
* Updates the image element of the user.
*/
updateUserImage: function() {
UserPod.userImageSalt_[this.user.username] = new Date().getTime();
this.update();
},
/**
* Focuses on input element.
*/
focusInput: function() {
var needSignin = this.needGaiaSignin;
this.signinButtonElement.hidden = !needSignin;
this.passwordElement.hidden = needSignin;
// Move tabIndex from the whole pod to the main input.
this.tabIndex = -1;
this.mainInput.tabIndex = UserPodTabOrder.POD_INPUT;
this.mainInput.focus();
},
/**
* Activates the pod.
* @return {boolean} True if activated successfully.
*/
activate: function() {
if (!this.signinButtonElement.hidden) {
// Switch to Gaia signin.
this.showSigninUI();
} else if (!this.passwordElement.value) {
return false;
} else {
Oobe.disableSigninUI();
chrome.send('authenticateUser',
[this.user.username, this.passwordElement.value]);
}
return true;
},
/**
* Shows signin UI for this user.
*/
showSigninUI: function() {
this.parentNode.showSigninUI(this.user.emailAddress);
},
/**
* Resets the input field and updates the tab order of pod controls.
* @param {boolean} takeFocus If true, input field takes focus.
*/
reset: function(takeFocus) {
this.passwordElement.value = '';
if (takeFocus)
this.focusInput(); // This will set a custom tab order.
else
this.resetTabOrder();
},
/**
* Handles a click event on action area button.
* @param {Event} e Click event.
*/
handleActionAreaButtonClick_: function(e) {
if (this.parentNode.disabled)
return;
this.activeActionBoxMenu = !this.activeActionBoxMenu;
},
/**
* Handles a keydown event on action area button.
* @param {Event} e KeyDown event.
*/
handleActionAreaButtonKeyDown_: function(e) {
if (this.disabled)
return;
switch (e.keyIdentifier) {
case 'Enter':
case 'U+0020': // Space
if (this.parentNode.focusedPod_ && !this.activeActionBoxMenu)
this.activeActionBoxMenu = true;
e.stopPropagation();
break;
case 'Up':
case 'Down':
if (this.activeActionBoxMenu) {
this.actionBoxMenuRemoveElement.tabIndex =
UserPodTabOrder.PAD_MENU_ITEM;
this.actionBoxMenuRemoveElement.focus();
}
e.stopPropagation();
break;
case 'U+001B': // Esc
this.activeActionBoxMenu = false;
e.stopPropagation();
break;
default:
this.activeActionBoxMenu = false;
break;
}
},
/**
* Handles a click event on remove user command.
* @param {Event} e Click event.
*/
handleRemoveCommandClick_: function(e) {
if (this.activeActionBoxMenu)
chrome.send('removeUser', [this.user.username]);
},
/**
* Handles a keydown event on remove command.
* @param {Event} e KeyDown event.
*/
handleRemoveCommandKeyDown_: function(e) {
if (this.disabled)
return;
switch (e.keyIdentifier) {
case 'Enter':
chrome.send('removeUser', [this.user.username]);
e.stopPropagation();
break;
case 'Up':
case 'Down':
e.stopPropagation();
break;
case 'U+001B': // Esc
this.actionBoxAreaElement.focus();
this.activeActionBoxMenu = false;
e.stopPropagation();
break;
default:
this.actionBoxAreaElement.focus();
this.activeActionBoxMenu = false;
break;
}
},
/**
* Handles a blur event on remove command.
* @param {Event} e Blur event.
*/
handleRemoveCommandBlur_: function(e) {
if (this.disabled)
return;
this.actionBoxMenuRemoveElement.tabIndex = -1;
},
/**
* Handles mousedown event on a user pod.
* @param {Event} e Mousedown event.
*/
handleMouseDown_: function(e) {
if (this.parentNode.disabled)
return;
if (!this.signinButtonElement.hidden) {
this.showSigninUI();
// Prevent default so that we don't trigger 'focus' event.
e.preventDefault();
}
}
};
/**
* Creates a public account user pod.
* @constructor
* @extends {UserPod}
*/
var PublicAccountUserPod = cr.ui.define(function() {
var node = UserPod();
var extras = $('public-account-user-pod-extras-template').children;
for (var i = 0; i < extras.length; ++i) {
var el = extras[i].cloneNode(true);
node.appendChild(el);
}
return node;
});
PublicAccountUserPod.prototype = {
__proto__: UserPod.prototype,
/**
* "Enter" button in expanded side pane.
* @type {!HTMLButtonElement}
*/
get enterButtonElement() {
return this.querySelector('.enter-button');
},
/**
* Boolean flag of whether the pod is showing the side pane. The flag
* controls whether 'expanded' class is added to the pod's class list and
* resets tab order because main input element changes when the 'expanded'
* state changes.
* @type {boolean}
*/
get expanded() {
return this.classList.contains('expanded');
},
set expanded(expanded) {
if (this.expanded == expanded)
return;
this.resetTabOrder();
this.classList.toggle('expanded', expanded);
var self = this;
this.classList.add('animating');
this.addEventListener('webkitTransitionEnd', function f(e) {
self.removeEventListener('webkitTransitionEnd', f);
self.classList.remove('animating');
// Accessibility focus indicator does not move with the focused
// element. Sends a 'focus' event on the currently focused element
// so that accessibility focus indicator updates its location.
if (document.activeElement)
document.activeElement.dispatchEvent(new Event('focus'));
});
},
/** @override */
get needGaiaSignin() {
return false;
},
/** @override */
get mainInput() {
if (this.expanded)
return this.enterButtonElement;
else
return this.nameElement;
},
/** @override */
decorate: function() {
UserPod.prototype.decorate.call(this);
this.classList.remove('need-password');
this.classList.add('public-account');
this.nameElement.addEventListener('keydown', (function(e) {
if (e.keyIdentifier == 'Enter') {
this.parentNode.activatedPod = this;
// Stop this keydown event from bubbling up to PodRow handler.
e.stopPropagation();
// Prevent default so that we don't trigger a 'click' event on the
// newly focused "Enter" button.
e.preventDefault();
}
}).bind(this));
this.enterButtonElement.addEventListener('click', (function(e) {
chrome.send('launchPublicAccount', [this.user.username]);
}).bind(this));
},
/**
* Updates the user pod element.
*/
update: function() {
UserPod.prototype.update.call(this);
this.querySelector('.side-pane-name').textContent =
this.user_.displayName;
this.querySelector('.info').textContent =
loadTimeData.getStringF('publicAccountInfoFormat',
this.user_.enterpriseDomain);
},
/** @override */
focusInput: function() {
// Move tabIndex from the whole pod to the main input.
this.tabIndex = -1;
this.mainInput.tabIndex = UserPodTabOrder.POD_INPUT;
this.mainInput.focus();
},
/** @override */
reset: function(takeFocus) {
if (!takeFocus)
this.expanded = false;
UserPod.prototype.reset.call(this, takeFocus);
},
/** @override */
activate: function() {
this.expanded = true;
this.focusInput();
return true;
},
/** @override */
handleMouseDown_: function(e) {
if (this.parentNode.disabled)
return;
this.parentNode.focusPod(this);
this.parentNode.activatedPod = this;
// Prevent default so that we don't trigger 'focus' event.
e.preventDefault();
}
};
/**
* Creates a new pod row element.
* @constructor
* @extends {HTMLDivElement}
*/
var PodRow = cr.ui.define('podrow');
PodRow.prototype = {
__proto__: HTMLDivElement.prototype,
// Whether this user pod row is shown for the first time.
firstShown_: true,
// Whether the initial wallpaper load after boot has been requested. Used
// only if |Oobe.getInstance().shouldLoadWallpaperOnBoot()| is true.
bootWallpaperLoaded_: false,
// True if inside focusPod().
insideFocusPod_: false,
// True if user pod has been activated with keyboard.
// In case of activation with keyboard we delay wallpaper change.
keyboardActivated_: false,
// Focused pod.
focusedPod_: undefined,
// Activated pod, i.e. the pod of current login attempt.
activatedPod_: undefined,
// Pod that was most recently focused, if any.
lastFocusedPod_: undefined,
// When moving through users quickly at login screen, set a timeout to
// prevent loading intermediate wallpapers.
loadWallpaperTimeout_: null,
// Pods whose initial images haven't been loaded yet.
podsWithPendingImages_: [],
/** @override */
decorate: function() {
this.style.left = 0;
// Event listeners that are installed for the time period during which
// the element is visible.
this.listeners_ = {
focus: [this.handleFocus_.bind(this), true],
click: [this.handleClick_.bind(this), false],
keydown: [this.handleKeyDown.bind(this), false]
};
},
/**
* Returns all the pods in this pod row.
* @type {NodeList}
*/
get pods() {
return this.children;
},
/**
* Return true if user pod row has only single user pod in it.
* @type {boolean}
*/
get isSinglePod() {
return this.children.length == 1;
},
hideTitles: function() {
for (var i = 0, pod; pod = this.pods[i]; ++i)
pod.imageElement.title = '';
},
updateTitles: function() {
for (var i = 0, pod; pod = this.pods[i]; ++i) {
pod.imageElement.title = pod.user.nameTooltip || '';
}
},
/**
* Returns pod with the given username (null if there is no such pod).
* @param {string} username Username to be matched.
* @return {Object} Pod with the given username. null if pod hasn't been
* found.
*/
getPodWithUsername_: function(username) {
for (var i = 0, pod; pod = this.pods[i]; ++i) {
if (pod.user.username == username)
return pod;
}
return null;
},
/**
* True if the the pod row is disabled (handles no user interaction).
* @type {boolean}
*/
disabled_: false,
get disabled() {
return this.disabled_;
},
set disabled(value) {
this.disabled_ = value;
var controls = this.querySelectorAll('button,input');
for (var i = 0, control; control = controls[i]; ++i) {
control.disabled = value;
}
},
/**
* Creates a user pod from given email.
* @param {string} email User's email.
*/
createUserPod: function(user) {
var userPod;
if (user.publicAccount)
userPod = new PublicAccountUserPod({user: user});
else
userPod = new UserPod({user: user});
userPod.hidden = false;
return userPod;
},
/**
* Add an existing user pod to this pod row.
* @param {!Object} user User info dictionary.
* @param {boolean} animated Whether to use init animation.
*/
addUserPod: function(user, animated) {
var userPod = this.createUserPod(user);
if (animated) {
userPod.classList.add('init');
userPod.nameElement.classList.add('init');
}
this.appendChild(userPod);
userPod.initialize();
},
/**
* Returns index of given pod or -1 if not found.
* @param {UserPod} pod Pod to look up.
* @private
*/
indexOf_: function(pod) {
for (var i = 0; i < this.pods.length; ++i) {
if (pod == this.pods[i])
return i;
}
return -1;
},
/**
* Start first time show animation.
*/
startInitAnimation: function() {
// Schedule init animation.
for (var i = 0, pod; pod = this.pods[i]; ++i) {
window.setTimeout(removeClass, 500 + i * 70, pod, 'init');
window.setTimeout(removeClass, 700 + i * 70, pod.nameElement, 'init');
}
},
/**
* Start login success animation.
*/
startAuthenticatedAnimation: function() {
var activated = this.indexOf_(this.activatedPod_);
if (activated == -1)
return;
for (var i = 0, pod; pod = this.pods[i]; ++i) {
if (i < activated)
pod.classList.add('left');
else if (i > activated)
pod.classList.add('right');
else
pod.classList.add('zoom');
}
},
/**
* Populates pod row with given existing users and start init animation.
* @param {array} users Array of existing user emails.
* @param {boolean} animated Whether to use init animation.
*/
loadPods: function(users, animated) {
// Clear existing pods.
this.innerHTML = '';
this.focusedPod_ = undefined;
this.activatedPod_ = undefined;
this.lastFocusedPod_ = undefined;
// Populate the pod row.
for (var i = 0; i < users.length; ++i) {
this.addUserPod(users[i], animated);
}
for (var i = 0, pod; pod = this.pods[i]; ++i) {
this.podsWithPendingImages_.push(pod);
}
// Make sure we eventually show the pod row, even if some image is stuck.
setTimeout(function() {
$('pod-row').classList.remove('images-loading');
}, POD_ROW_IMAGES_LOAD_TIMEOUT_MS);
// loadPods is called after user list update (for ex. after deleting user)
// so make sure that tooltips are updated.
$('pod-row').updateTitles();
var columns = users.length < COLUMNS.length ?
COLUMNS[users.length] : COLUMNS[COLUMNS.length - 1];
var rows = Math.floor((users.length - 1) / columns) + 1;
// Cancel any pending resize operation.
this.removeEventListener('mouseout', this.deferredResizeListener_);
if (!this.columns || !this.rows) {
// Set initial dimensions.
this.resize_(columns, rows);
} else if (columns != this.columns || rows != this.rows) {
// Defer the resize until mouse cursor leaves the pod row.
this.deferredResizeListener_ = function(e) {
if (!findAncestorByClass(e.toElement, 'podrow')) {
this.resize_(columns, rows);
}
}.bind(this);
this.addEventListener('mouseout', this.deferredResizeListener_);
}
this.focusPod(this.preselectedPod);
},
/**
* Resizes the pod row and cancel any pending resize operations.
* @param {number} columns Number of columns.
* @param {number} rows Number of rows.
* @private
*/
resize_: function(columns, rows) {
this.removeEventListener('mouseout', this.deferredResizeListener_);
this.columns = columns;
this.rows = rows;
},
/**
* Number of columns.
* @type {?number}
*/
set columns(columns) {
// Cannot use 'columns' here.
this.setAttribute('ncolumns', columns);
},
get columns() {
return this.getAttribute('ncolumns');
},
/**
* Number of rows.
* @type {?number}
*/
set rows(rows) {
// Cannot use 'rows' here.
this.setAttribute('nrows', rows);
},
get rows() {
return this.getAttribute('nrows');
},
/**
* Whether the pod is currently focused.
* @param {UserPod} pod Pod to check for focus.
* @return {boolean} Pod focus status.
*/
isFocused: function(pod) {
return this.focusedPod_ == pod;
},
/**
* Focuses a given user pod or clear focus when given null.
* @param {UserPod=} podToFocus User pod to focus (undefined clears focus).
* @param {boolean=} opt_force If true, forces focus update even when
* podToFocus is already focused.
*/
focusPod: function(podToFocus, opt_force) {
if (this.isFocused(podToFocus) && !opt_force) {
this.keyboardActivated_ = false;
return;
}
// Make sure there's only one focusPod operation happening at a time.
if (this.insideFocusPod_) {
this.keyboardActivated_ = false;
return;
}
this.insideFocusPod_ = true;
clearTimeout(this.loadWallpaperTimeout_);
for (var i = 0, pod; pod = this.pods[i]; ++i) {
if (!this.isSinglePod)
pod.activeActionBoxMenu = false;
if (pod != podToFocus) {
pod.classList.remove('focused');
pod.classList.remove('faded');
pod.reset(false);
}
}
// Clear any error messages for previous pod.
if (!this.isFocused(podToFocus))
Oobe.clearErrors();
var hadFocus = !!this.focusedPod_;
this.focusedPod_ = podToFocus;
if (podToFocus) {
podToFocus.classList.remove('faded');
podToFocus.classList.add('focused');
podToFocus.reset(true); // Reset and give focus.
if (hadFocus && this.keyboardActivated_) {
// Delay wallpaper loading to let user tab through pods without lag.
this.loadWallpaperTimeout_ = window.setTimeout(
this.loadWallpaper_.bind(this), WALLPAPER_LOAD_DELAY_MS);
} else if (!this.firstShown_) {
// Load wallpaper immediately if there no pod was focused
// previously, and it is not a boot into user pod list case.
this.loadWallpaper_();
}
this.firstShown_ = false;
this.lastFocusedPod_ = podToFocus;
}
this.insideFocusPod_ = false;
this.keyboardActivated_ = false;
},
/**
* Loads wallpaper for the active user pod, if any.
* @private
*/
loadWallpaper_: function() {
if (this.focusedPod_)
chrome.send('loadWallpaper', [this.focusedPod_.user.username]);
},
/**
* Resets wallpaper to the last active user's wallpaper, if any.
*/
loadLastWallpaper: function() {
if (this.lastFocusedPod_)
chrome.send('loadWallpaper', [this.lastFocusedPod_.user.username]);
},
/**
* Returns the currently activated pod.
* @type {UserPod}
*/
get activatedPod() {
return this.activatedPod_;
},
set activatedPod(pod) {
if (pod && pod.activate())
this.activatedPod_ = pod;
},
/**
* The pod of the signed-in user, if any; null otherwise.
* @type {?UserPod}
*/
get lockedPod() {
for (var i = 0, pod; pod = this.pods[i]; ++i) {
if (pod.user.signedIn)
return pod;
}
return null;
},
/**
* The pod that is preselected on user pod row show.
* @type {?UserPod}
*/
get preselectedPod() {
var lockedPod = this.lockedPod;
var preselectedPod = PRESELECT_FIRST_POD ?
lockedPod || this.pods[0] : lockedPod;
return preselectedPod;
},
/**
* Resets input UI.
* @param {boolean} takeFocus True to take focus.
*/
reset: function(takeFocus) {
this.disabled = false;
if (this.activatedPod_)
this.activatedPod_.reset(takeFocus);
},
/**
* Shows signin UI.
* @param {string} email Email for signin UI.
*/
showSigninUI: function(email) {
// Clear any error messages that might still be around.
Oobe.clearErrors();
this.disabled = true;
this.lastFocusedPod_ = this.getPodWithUsername_(email);
Oobe.showSigninUI(email);
},
/**
* Updates current image of a user.
* @param {string} username User for which to update the image.
*/
updateUserImage: function(username) {
var pod = this.getPodWithUsername_(username);
if (pod)
pod.updateUserImage();
},
/**
* Resets OAuth token status (invalidates it).
* @param {string} username User for which to reset the status.
*/
resetUserOAuthTokenStatus: function(username) {
var pod = this.getPodWithUsername_(username);
if (pod) {
pod.user.oauthTokenStatus = OAuthTokenStatus.INVALID_OLD;
pod.update();
} else {
console.log('Failed to update Gaia state for: ' + username);
}
},
/**
* Handler of click event.
* @param {Event} e Click Event object.
* @private
*/
handleClick_: function(e) {
if (this.disabled)
return;
// Clear all menus if the click is outside pod menu and its
// button area.
if (!findAncestorByClass(e.target, 'action-box-menu') &&
!findAncestorByClass(e.target, 'action-box-area')) {
for (var i = 0, pod; pod = this.pods[i]; ++i)
pod.activeActionBoxMenu = false;
}
// Clears focus if not clicked on a pod and if there's more than one pod.
var pod = findAncestorByClass(e.target, 'pod');
if ((!pod || pod.parentNode != this) && !this.isSinglePod) {
this.focusPod();
}
// Return focus back to single pod.
if (this.isSinglePod) {
this.focusPod(this.focusedPod_, true /* force */);
}
},
/**
* Handles focus event.
* @param {Event} e Focus Event object.
* @private
*/
handleFocus_: function(e) {
if (this.disabled)
return;
if (e.target.parentNode == this) {
// Focus on a pod
if (e.target.classList.contains('focused'))
e.target.focusInput();
else
this.focusPod(e.target);
return;
}
var pod = findAncestorByClass(e.target, 'pod');
if (pod && pod.parentNode == this) {
// Focus on a control of a pod but not on the action area button.
if (!pod.classList.contains('focused') &&
!e.target.classList.contains('action-box-button')) {
this.focusPod(pod);
e.target.focus();
}
return;
}
// Clears pod focus when we reach here. It means new focus is neither
// on a pod nor on a button/input for a pod.
// Do not "defocus" user pod when it is a single pod.
// That means that 'focused' class will not be removed and
// input field/button will always be visible.
if (!this.isSinglePod)
this.focusPod();
},
/**
* Handler of keydown event.
* @param {Event} e KeyDown Event object.
*/
handleKeyDown: function(e) {
if (this.disabled)
return;
var editing = e.target.tagName == 'INPUT' && e.target.value;
switch (e.keyIdentifier) {
case 'Left':
if (!editing) {
this.keyboardActivated_ = true;
if (this.focusedPod_ && this.focusedPod_.previousElementSibling)
this.focusPod(this.focusedPod_.previousElementSibling);
else
this.focusPod(this.lastElementChild);
e.stopPropagation();
}
break;
case 'Right':
if (!editing) {
this.keyboardActivated_ = true;
if (this.focusedPod_ && this.focusedPod_.nextElementSibling)
this.focusPod(this.focusedPod_.nextElementSibling);
else
this.focusPod(this.firstElementChild);
e.stopPropagation();
}
break;
case 'Enter':
if (this.focusedPod_) {
this.activatedPod = this.focusedPod_;
e.stopPropagation();
}
break;
case 'U+001B': // Esc
if (!this.isSinglePod)
this.focusPod();
break;
}
},
/**
* Called right after the pod row is shown.
*/
handleAfterShow: function() {
// Force input focus for user pod on show and once transition ends.
if (this.focusedPod_) {
var focusedPod = this.focusedPod_;
var screen = this.parentNode;
var self = this;
focusedPod.addEventListener('webkitTransitionEnd', function f(e) {
if (e.target == focusedPod) {
focusedPod.removeEventListener('webkitTransitionEnd', f);
focusedPod.reset(true);
// Notify screen that it is ready.
screen.onShow();
// Boot transition: load wallpaper.
if (!self.bootWallpaperLoaded_ &&
Oobe.getInstance().shouldLoadWallpaperOnBoot()) {
self.loadWallpaperTimeout_ = window.setTimeout(
self.loadWallpaper_.bind(self), WALLPAPER_BOOT_LOAD_DELAY_MS);
self.bootWallpaperLoaded_ = true;
}
}
});
}
},
/**
* Called right before the pod row is shown.
*/
handleBeforeShow: function() {
for (var event in this.listeners_) {
this.ownerDocument.addEventListener(
event, this.listeners_[event][0], this.listeners_[event][1]);
}
$('login-header-bar').buttonsTabIndex = UserPodTabOrder.HEADER_BAR;
this.updateTitles();
},
/**
* Called when the element is hidden.
*/
handleHide: function() {
for (var event in this.listeners_) {
this.ownerDocument.removeEventListener(
event, this.listeners_[event][0], this.listeners_[event][1]);
}
$('login-header-bar').buttonsTabIndex = 0;
this.hideTitles();
},
/**
* Called when a pod's user image finishes loading.
*/
handlePodImageLoad: function(pod) {
var index = this.podsWithPendingImages_.indexOf(pod);
if (index == -1) {
return;
}
this.podsWithPendingImages_.splice(index, 1);
if (this.podsWithPendingImages_.length == 0) {
this.classList.remove('images-loading');
chrome.send('userImagesLoaded');
}
}
};
return {
PodRow: PodRow
};
});
| zcbenz/cefode-chromium | chrome/browser/resources/chromeos/login/user_pod_row.js | JavaScript | bsd-3-clause | 37,808 |
/*
* 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 COSE;
import com.upokecenter.cbor.CBORObject;
import com.upokecenter.cbor.CBORType;
import java.util.ArrayList;
import java.util.List;
/**
* The Signer class is used to implement the COSE_Signer object.
* This provides the information dealing with a single signature for the SignMessage class.
* <p>
* Create a Signer object for adding a new signature to a message, existing signers will have a Signer object created for them when a SignMessage object is created by Message.DecodeFromBytes.
* <p>
* Examples of using this class can be found in
* <br><a href="https://github.com/cose-wg/COSE-JAVA/wiki/Sign-Message-Example">Single Signer Example</a> an example of signing and verify a message with a single signature.
* <br><a href="https://github.com/cose-wg/COSE-JAVA/wiki/Multi-Sign-Example">Multiple Signer Example</a> an example of signing and verifying a message which has multiple signatures.
* @author jimsch
*/
public class Signer extends Attribute {
protected byte[] rgbSignature;
protected String contextString;
OneKey cnKey;
/**
* Create a new signer object to add to a SignMessage
*/
public Signer() {
contextString = "Signature";
}
/**
* Create a new signer object for a SignMessage and set the key to be used.
*
* @param key key to use for signing.
*/
public Signer(OneKey key) {
contextString = "Signature";
cnKey = key;
}
/**
* Remove the key object from the signer
*
* @since COSE 0.9.1
*/
public void clearKey() {
cnKey = null;
}
/**
* Set a key object on a signer
*
* @since COSE 0.9.1
* @param keyIn key to be used for signing or verification
* @throws CoseException - Invalid key passed in
*/
public void setKey(OneKey keyIn) throws CoseException {
setupKey(keyIn);
}
/**
* Set the key on the object, if there is not a signature on this object then set
* the algorithm and the key id from the key if they exist on the key and do not exist in the message.
*
* @param key key to be used]
*/
private void setupKey(OneKey key) throws CoseException {
CBORObject cn2;
CBORObject cn;
cnKey = key;
if (rgbSignature != null) return;
cn = key.get(KeyKeys.Algorithm);
if (cn != null) {
cn2 = findAttribute(HeaderKeys.Algorithm);
if (cn2 == null) addAttribute(HeaderKeys.Algorithm, cn, Attribute.PROTECTED);
}
cn = key.get(KeyKeys.KeyId);
if (cn != null) {
cn2 = findAttribute(HeaderKeys.KID);
if (cn2 == null) addAttribute(HeaderKeys.KID, cn, Attribute.UNPROTECTED);
}
}
/**
* Internal function used in creating a Sign1Message object from a byte string.
*
* @param obj COSE_Sign1 encoded object.
* @throws CoseException Errors generated by the COSE module
*/
protected void DecodeFromCBORObject(CBORObject obj) throws CoseException {
if (obj.getType() != CBORType.Array) throw new CoseException("Invalid Signer structure");
if (obj.size() != 3) throw new CoseException("Invalid Signer structure");
if (obj.get(0).getType() == CBORType.ByteString) {
rgbProtected = obj.get(0).GetByteString();
if (rgbProtected.length == 0) {
objProtected = CBORObject.NewMap();
}
else {
objProtected = CBORObject.DecodeFromBytes(rgbProtected);
if (objProtected.size() == 0) rgbProtected = new byte[0];
}
}
else throw new CoseException("Invalid Signer structure");
if (obj.get(1).getType() == CBORType.Map) {
objUnprotected = obj.get(1);
}
else throw new CoseException("Invalid Signer structure");
if (obj.get(2).getType() == CBORType.ByteString) rgbSignature = obj.get(2).GetByteString();
else if (!obj.get(2).isNull()) throw new CoseException("Invalid Signer structure");
CBORObject countersignature = this.findAttribute(HeaderKeys.CounterSignature, UNPROTECTED);
if (countersignature != null) {
if ((countersignature.getType() != CBORType.Array) ||
(countersignature.getValues().isEmpty())) {
throw new CoseException("Invalid countersignature attribute");
}
if (countersignature.get(0).getType() == CBORType.Array) {
for (CBORObject csObj : countersignature.getValues()) {
if (csObj.getType() != CBORType.Array) {
throw new CoseException("Invalid countersignature attribute");
}
CounterSign cs = new CounterSign(csObj);
cs.setObject(this);
this.addCountersignature(cs);
}
}
else {
CounterSign cs = new CounterSign(countersignature);
cs.setObject(this);
this.addCountersignature(cs);
}
}
countersignature = this.findAttribute(HeaderKeys.CounterSignature0, UNPROTECTED);
if (countersignature != null) {
if (countersignature.getType() != CBORType.ByteString) {
throw new CoseException("Invalid Countersignature0 attribute");
}
CounterSign1 cs = new CounterSign1(countersignature.GetByteString());
cs.setObject(this);
this.counterSign1 = cs;
}
}
/**
* Internal function used to create a serialization of a COSE_Sign1 message
*
* @return CBOR object which can be encoded.
* @throws CoseException Errors generated by the COSE module
*/
protected CBORObject EncodeToCBORObject() throws CoseException {
if (rgbSignature == null) throw new CoseException("Message not yet signed");
if (rgbProtected == null) throw new CoseException("Internal Error");
CBORObject obj = CBORObject.NewArray();
obj.Add(rgbProtected);
obj.Add(objUnprotected);
obj.Add(rgbSignature);
return obj;
}
public void sign(byte[] rgbBodyProtected, byte[] rgbContent) throws CoseException
{
if (rgbProtected == null) {
if(objProtected.size() == 0) rgbProtected = new byte[0];
else rgbProtected = objProtected.EncodeToBytes();
}
CBORObject obj = CBORObject.NewArray();
obj.Add(contextString);
obj.Add(rgbBodyProtected);
obj.Add(rgbProtected);
obj.Add(externalData);
obj.Add(rgbContent);
AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm));
rgbSignature = SignCommon.computeSignature(alg, obj.EncodeToBytes(), cnKey);
ProcessCounterSignatures();
}
public boolean validate(byte[] rgbBodyProtected, byte[] rgbContent) throws CoseException
{
CBORObject obj = CBORObject.NewArray();
obj.Add(contextString);
obj.Add(rgbBodyProtected);
obj.Add(rgbProtected);
obj.Add(externalData);
obj.Add(rgbContent);
AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm));
return SignCommon.validateSignature(alg, obj.EncodeToBytes(), rgbSignature, cnKey);
}
List<CounterSign> counterSignList = new ArrayList<CounterSign>();
CounterSign1 counterSign1;
public void addCountersignature(CounterSign countersignature)
{
counterSignList.add(countersignature);
}
public List<CounterSign> getCountersignerList() {
return counterSignList;
}
public CounterSign1 getCountersign1() {
return counterSign1;
}
public void setCountersign1(CounterSign1 value) {
counterSign1 = value;
}
protected void ProcessCounterSignatures() throws CoseException {
if (!counterSignList.isEmpty()) {
if (counterSignList.size() == 1) {
counterSignList.get(0).sign(rgbProtected, rgbSignature);
addAttribute(HeaderKeys.CounterSignature, counterSignList.get(0).EncodeToCBORObject(), Attribute.UNPROTECTED);
}
else {
CBORObject list = CBORObject.NewArray();
for (CounterSign sig : counterSignList) {
sig.sign(rgbProtected, rgbSignature);
list.Add(sig.EncodeToCBORObject());
}
addAttribute(HeaderKeys.CounterSignature, list, Attribute.UNPROTECTED);
}
}
if (counterSign1 != null) {
counterSign1.sign(rgbProtected, rgbSignature);
addAttribute(HeaderKeys.CounterSignature0, counterSign1.EncodeToCBORObject(), Attribute.UNPROTECTED);
}
}
public boolean validate(CounterSign1 countersignature) throws CoseException {
return countersignature.validate(rgbProtected, rgbSignature);
}
public boolean validate(CounterSign countersignature) throws CoseException {
return countersignature.validate(rgbProtected, rgbSignature);
}
}
| cose-wg/COSE-JAVA | src/main/java/COSE/Signer.java | Java | bsd-3-clause | 9,626 |
#include "wag.h"
#include "jsonutil.h"
RateModel wagModel() {
RateModel m;
ParsedJson pj (wagModelText);
m.read (pj.value);
return m;
}
const char* wagModelText =
"{\n"
" \"insrate\": 0.01,\n"
" \"delrate\": 0.01,\n"
" \"insextprob\": 0.66,\n"
" \"delextprob\": 0.66,\n"
" \"alphabet\": \"arndcqeghilkmfpstwyv\",\n"
" \"wildcard\": \"x\",\n"
" \"rootprob\": {\n"
" \"a\": 0.0866279,\n"
" \"r\": 0.043972,\n"
" \"n\": 0.0390894,\n"
" \"d\": 0.0570451,\n"
" \"c\": 0.0193078,\n"
" \"q\": 0.0367281,\n"
" \"e\": 0.0580589,\n"
" \"g\": 0.0832518,\n"
" \"h\": 0.0244313,\n"
" \"i\": 0.048466,\n"
" \"l\": 0.086209,\n"
" \"k\": 0.0620286,\n"
" \"m\": 0.0195027,\n"
" \"f\": 0.0384319,\n"
" \"p\": 0.0457631,\n"
" \"s\": 0.0695179,\n"
" \"t\": 0.0610127,\n"
" \"w\": 0.0143859,\n"
" \"y\": 0.0352742,\n"
" \"v\": 0.0708956\n"
" },\n"
" \"subrate\": {\n"
" \"a\": {\n"
" \"r\": 0.025454598385999616,\n"
" \"n\": 0.02091646702061985,\n"
" \"d\": 0.04424357528121363,\n"
" \"c\": 0.02081175744532852,\n"
" \"q\": 0.035023443574964015,\n"
" \"e\": 0.09644887575081307,\n"
" \"g\": 0.12378449891932998,\n"
" \"h\": 0.008127021700558104,\n"
" \"i\": 0.00983413727974195,\n"
" \"l\": 0.03600240591167065,\n"
" \"k\": 0.058997796671425476,\n"
" \"m\": 0.018288410390575757,\n"
" \"f\": 0.008490244215136958,\n"
" \"p\": 0.0690921970791226,\n"
" \"s\": 0.2459330790396344,\n"
" \"t\": 0.1358226005680265,\n"
" \"w\": 0.0017081065048031225,\n"
" \"y\": 0.008912201865156585,\n"
" \"v\": 0.14925915610414991\n"
" },\n"
" \"r\": {\n"
" \"a\": 0.05014733019927536,\n"
" \"n\": 0.02606501085751585,\n"
" \"d\": 0.008819043641828382,\n"
" \"c\": 0.010703169279488157,\n"
" \"q\": 0.11700847126210188,\n"
" \"e\": 0.0267594522084214,\n"
" \"g\": 0.05108452203729041,\n"
" \"h\": 0.054798691379025835,\n"
" \"i\": 0.009510834326060312,\n"
" \"l\": 0.045028092312345704,\n"
" \"k\": 0.3483771182417943,\n"
" \"m\": 0.01398321539127933,\n"
" \"f\": 0.004142832924363317,\n"
" \"p\": 0.03263521455708591,\n"
" \"s\": 0.08931698979453778,\n"
" \"t\": 0.03550113640910716,\n"
" \"w\": 0.01757311591728718,\n"
" \"y\": 0.014124656216249351,\n"
" \"v\": 0.01873907368640937\n"
" },\n"
" \"n\": {\n"
" \"a\": 0.04635398889252723,\n"
" \"r\": 0.029320753386511092,\n"
" \"d\": 0.32505764901031786,\n"
" \"c\": 0.005375100807094234,\n"
" \"q\": 0.0595022093819901,\n"
" \"e\": 0.05771626004575205,\n"
" \"g\": 0.09834468392035196,\n"
" \"h\": 0.10144328414754514,\n"
" \"i\": 0.028191651327359554,\n"
" \"l\": 0.011900341642688054,\n"
" \"k\": 0.19608166877491712,\n"
" \"m\": 0.004057261583745554,\n"
" \"f\": 0.0038786840158884423,\n"
" \"p\": 0.00936955607965821,\n"
" \"s\": 0.28996010451902554,\n"
" \"t\": 0.12999232878498895,\n"
" \"w\": 0.0010858138922681688,\n"
" \"y\": 0.040204586892475344,\n"
" \"v\": 0.014601877532422574\n"
" },\n"
" \"d\": {\n"
" \"a\": 0.06718768159059141,\n"
" \"r\": 0.006797971903256855,\n"
" \"n\": 0.22274145308227913,\n"
" \"c\": 0.000613890511207434,\n"
" \"q\": 0.023774941831807932,\n"
" \"e\": 0.3762142911240105,\n"
" \"g\": 0.07562953986150356,\n"
" \"h\": 0.023863475609042995,\n"
" \"i\": 0.0020059941133327296,\n"
" \"l\": 0.0076729282198898146,\n"
" \"k\": 0.03123853146901499,\n"
" \"m\": 0.002123675687035865,\n"
" \"f\": 0.0018848637408716454,\n"
" \"p\": 0.020363550857735023,\n"
" \"s\": 0.0781956861126082,\n"
" \"t\": 0.02400407097441143,\n"
" \"w\": 0.001959250234757204,\n"
" \"y\": 0.012058081216698928,\n"
" \"v\": 0.011334636190809457\n"
" },\n"
" \"c\": {\n"
" \"a\": 0.09337567422483009,\n"
" \"r\": 0.024375628479560242,\n"
" \"n\": 0.010882102854226238,\n"
" \"d\": 0.0018137460301473598,\n"
" \"q\": 0.003809102754844756,\n"
" \"e\": 0.0013010559402542,\n"
" \"g\": 0.026795335296732312,\n"
" \"h\": 0.006383894340602587,\n"
" \"i\": 0.008654050979330679,\n"
" \"l\": 0.03476937677790025,\n"
" \"k\": 0.004819602410986463,\n"
" \"m\": 0.007992531657816939,\n"
" \"f\": 0.01605407756282275,\n"
" \"p\": 0.005254570733894776,\n"
" \"s\": 0.10270297409240318,\n"
" \"t\": 0.03284828270565342,\n"
" \"w\": 0.01082647796309808,\n"
" \"y\": 0.020133131771174533,\n"
" \"v\": 0.07456521687240483\n"
" },\n"
" \"q\": {\n"
" \"a\": 0.08260725078802401,\n"
" \"r\": 0.1400861056884822,\n"
" \"n\": 0.06332768815746974,\n"
" \"d\": 0.03692660209184975,\n"
" \"c\": 0.0020024284994320856,\n"
" \"e\": 0.33327493600328495,\n"
" \"g\": 0.028837964761789698,\n"
" \"h\": 0.11010533122971648,\n"
" \"i\": 0.005794478063963399,\n"
" \"l\": 0.07866930352897629,\n"
" \"k\": 0.25355775436051825,\n"
" \"m\": 0.03162895977166221,\n"
" \"f\": 0.004030290621926787,\n"
" \"p\": 0.0448289751292168,\n"
" \"s\": 0.07506642865070463,\n"
" \"t\": 0.054936336191958854,\n"
" \"w\": 0.0032572438901709603,\n"
" \"y\": 0.008430005968034586,\n"
" \"v\": 0.022417110488090485\n"
" },\n"
" \"e\": {\n"
" \"a\": 0.14390840273677005,\n"
" \"r\": 0.020266774474003227,\n"
" \"n\": 0.03885871029992681,\n"
" \"d\": 0.3696449960057509,\n"
" \"c\": 0.0004326731626544775,\n"
" \"q\": 0.21082995332364635,\n"
" \"g\": 0.049603707417827984,\n"
" \"h\": 0.014616018554303254,\n"
" \"i\": 0.006480047165555776,\n"
" \"l\": 0.013957350547609538,\n"
" \"k\": 0.16824623664329103,\n"
" \"m\": 0.006450075921906529,\n"
" \"f\": 0.0032725238017544465,\n"
" \"p\": 0.032772865828733594,\n"
" \"s\": 0.051432399765372755,\n"
" \"t\": 0.05268471788655578,\n"
" \"w\": 0.002363731449466225,\n"
" \"y\": 0.007267293757599988,\n"
" \"v\": 0.04380511175535132\n"
" },\n"
" \"g\": {\n"
" \"a\": 0.12880431647044058,\n"
" \"r\": 0.026981862290349684,\n"
" \"n\": 0.04617599484499082,\n"
" \"d\": 0.05182223885073304,\n"
" \"c\": 0.00621438785518449,\n"
" \"q\": 0.012722411450172708,\n"
" \"e\": 0.03459308613868929,\n"
" \"h\": 0.006395125104388008,\n"
" \"i\": 0.0015488683558686756,\n"
" \"l\": 0.005546613450830665,\n"
" \"k\": 0.02431860319992978,\n"
" \"m\": 0.003563543931924977,\n"
" \"f\": 0.0020139594663315984,\n"
" \"p\": 0.011698436927852277,\n"
" \"s\": 0.09789928299210637,\n"
" \"t\": 0.014460931000315464,\n"
" \"w\": 0.00508784222382568,\n"
" \"y\": 0.00383550278122285,\n"
" \"v\": 0.013932298045888985\n"
" },\n"
" \"h\": {\n"
" \"a\": 0.028816592779499144,\n"
" \"r\": 0.0986279099891747,\n"
" \"n\": 0.16230643115008417,\n"
" \"d\": 0.05571927619346571,\n"
" \"c\": 0.005045124702716869,\n"
" \"q\": 0.16552371817865405,\n"
" \"e\": 0.03473372107265832,\n"
" \"g\": 0.02179195033278989,\n"
" \"i\": 0.007029143355768693,\n"
" \"l\": 0.04519013774664148,\n"
" \"k\": 0.05796706932931398,\n"
" \"m\": 0.008272109179736312,\n"
" \"f\": 0.02740232834513958,\n"
" \"p\": 0.03343773203718397,\n"
" \"s\": 0.05400278308043134,\n"
" \"t\": 0.030307616109985305,\n"
" \"w\": 0.003964323555988536,\n"
" \"y\": 0.14339784074842513,\n"
" \"v\": 0.008806543934564124\n"
" },\n"
" \"i\": {\n"
" \"a\": 0.01757749062963227,\n"
" \"r\": 0.008628944146113234,\n"
" \"n\": 0.022737480613124427,\n"
" \"d\": 0.0023610806502388664,\n"
" \"c\": 0.0034475856373276294,\n"
" \"q\": 0.0043911230508202476,\n"
" \"e\": 0.007762646192800854,\n"
" \"g\": 0.0026605471586082573,\n"
" \"h\": 0.003543331615313656,\n"
" \"l\": 0.2869018485699968,\n"
" \"k\": 0.02108144360832765,\n"
" \"m\": 0.08714328402305177,\n"
" \"f\": 0.04273356503563595,\n"
" \"p\": 0.004799485831900335,\n"
" \"s\": 0.023306365204720795,\n"
" \"t\": 0.09337143441135705,\n"
" \"w\": 0.003208114294326871,\n"
" \"y\": 0.01555502879798468,\n"
" \"v\": 0.5819515543977287\n"
" },\n"
" \"l\": {\n"
" \"a\": 0.03617734597403535,\n"
" \"r\": 0.02296715279331004,\n"
" \"n\": 0.005395924028902904,\n"
" \"d\": 0.005077230423696326,\n"
" \"c\": 0.007787124000421562,\n"
" \"q\": 0.033515921156057886,\n"
" \"e\": 0.009399812313199404,\n"
" \"g\": 0.005356349727822667,\n"
" \"h\": 0.012806711739256018,\n"
" \"i\": 0.16129389034547978,\n"
" \"k\": 0.016766814918052653,\n"
" \"m\": 0.0993538972799683,\n"
" \"f\": 0.08531506768141249,\n"
" \"p\": 0.01997259434998482,\n"
" \"s\": 0.025152182050808426,\n"
" \"t\": 0.020914827351118027,\n"
" \"w\": 0.010044979189131912,\n"
" \"y\": 0.014757156554240088,\n"
" \"v\": 0.13395607654026914\n"
" },\n"
" \"k\": {\n"
" \"a\": 0.08239514079428809,\n"
" \"r\": 0.24696412047552546,\n"
" \"n\": 0.12356743153013684,\n"
" \"d\": 0.028728766270770374,\n"
" \"c\": 0.0015002098939980012,\n"
" \"q\": 0.15013549488346584,\n"
" \"e\": 0.15747883119479028,\n"
" \"g\": 0.032639258178967664,\n"
" \"h\": 0.022831578673471083,\n"
" \"i\": 0.016471970122188925,\n"
" \"l\": 0.023302965845922705,\n"
" \"m\": 0.019123110686634925,\n"
" \"f\": 0.003583186860888704,\n"
" \"p\": 0.02674718861671479,\n"
" \"s\": 0.07056187384310551,\n"
" \"t\": 0.08881351298887914,\n"
" \"w\": 0.002076080232495853,\n"
" \"y\": 0.0049335396571259975,\n"
" \"v\": 0.022726118556495197\n"
" },\n"
" \"m\": {\n"
" \"a\": 0.08123421815819129,\n"
" \"r\": 0.031527426827328245,\n"
" \"n\": 0.008131998182388257,\n"
" \"d\": 0.0062117189893978585,\n"
" \"c\": 0.00791265838795643,\n"
" \"q\": 0.0595646550164637,\n"
" \"e\": 0.01920166504855117,\n"
" \"g\": 0.015211814093014394,\n"
" \"h\": 0.010362584719187178,\n"
" \"i\": 0.2165590612305592,\n"
" \"l\": 0.4391802227696055,\n"
" \"k\": 0.06082131107677413,\n"
" \"f\": 0.04802388414809219,\n"
" \"p\": 0.008228769965151712,\n"
" \"s\": 0.036035344059722085,\n"
" \"t\": 0.09708282982645708,\n"
" \"w\": 0.007786240735824199,\n"
" \"y\": 0.01586107973706396,\n"
" \"v\": 0.15316100611790942\n"
" },\n"
" \"f\": {\n"
" \"a\": 0.019137540086346574,\n"
" \"r\": 0.004740037556043385,\n"
" \"n\": 0.003945041254027766,\n"
" \"d\": 0.0027977341891604916,\n"
" \"c\": 0.008065407090658259,\n"
" \"q\": 0.0038516158969811335,\n"
" \"e\": 0.0049437871183491125,\n"
" \"g\": 0.004362671392753026,\n"
" \"h\": 0.017419760784624455,\n"
" \"i\": 0.05389077727141078,\n"
" \"l\": 0.19137556742567735,\n"
" \"k\": 0.005783218225466892,\n"
" \"m\": 0.024370260262308076,\n"
" \"p\": 0.007754002756415745,\n"
" \"s\": 0.03983116473384182,\n"
" \"t\": 0.01100759154661732,\n"
" \"w\": 0.02309483558296031,\n"
" \"y\": 0.23894259768726128,\n"
" \"v\": 0.04835585639096426\n"
" },\n"
" \"p\": {\n"
" \"a\": 0.13078904050098275,\n"
" \"r\": 0.031357920562728084,\n"
" \"n\": 0.008003179972951824,\n"
" \"d\": 0.025383787266041423,\n"
" \"c\": 0.002216943363012854,\n"
" \"q\": 0.035978399222154685,\n"
" \"e\": 0.041578401372806044,\n"
" \"g\": 0.02128168614954346,\n"
" \"h\": 0.017851222113887663,\n"
" \"i\": 0.005082957236919737,\n"
" \"l\": 0.0376245793295874,\n"
" \"k\": 0.03625389590807342,\n"
" \"m\": 0.0035068260672761315,\n"
" \"f\": 0.006511819752907784,\n"
" \"s\": 0.11770502397155011,\n"
" \"t\": 0.050931410124981355,\n"
" \"w\": 0.002104766843468124,\n"
" \"y\": 0.007998195377322033,\n"
" \"v\": 0.0234294783616071\n"
" },\n"
" \"s\": {\n"
" \"a\": 0.30646302862626096,\n"
" \"r\": 0.056495473471514755,\n"
" \"n\": 0.1630424179899853,\n"
" \"d\": 0.06416593041306407,\n"
" \"c\": 0.02852457400441185,\n"
" \"q\": 0.03965953082768531,\n"
" \"e\": 0.04295452760710264,\n"
" \"g\": 0.11724018602118652,\n"
" \"h\": 0.018978683105688496,\n"
" \"i\": 0.016248567577731753,\n"
" \"l\": 0.031191167489497573,\n"
" \"k\": 0.06296010448912374,\n"
" \"m\": 0.010109432313023583,\n"
" \"f\": 0.02202004577144211,\n"
" \"p\": 0.07748431386035029,\n"
" \"t\": 0.28034098266418594,\n"
" \"w\": 0.007907570002020605,\n"
" \"y\": 0.029135109072071685,\n"
" \"v\": 0.017317175254621738\n"
" },\n"
" \"t\": {\n"
" \"a\": 0.19284553313895209,\n"
" \"r\": 0.02558575460815961,\n"
" \"n\": 0.08328302364602694,\n"
" \"d\": 0.02244310822406478,\n"
" \"c\": 0.01039501731318586,\n"
" \"q\": 0.033070282896706486,\n"
" \"e\": 0.050134099413790136,\n"
" \"g\": 0.019731933440940375,\n"
" \"h\": 0.012136071038781825,\n"
" \"i\": 0.07417045861240087,\n"
" \"l\": 0.029551984277249393,\n"
" \"k\": 0.09029231408841092,\n"
" \"m\": 0.03103251135020159,\n"
" \"f\": 0.006933681963926234,\n"
" \"p\": 0.03820154188702572,\n"
" \"s\": 0.3194206517454663,\n"
" \"w\": 0.0016738486520157104,\n"
" \"y\": 0.010778531367007745,\n"
" \"v\": 0.10329262480170291\n"
" },\n"
" \"w\": {\n"
" \"a\": 0.01028574364394542,\n"
" \"r\": 0.05371405703605279,\n"
" \"n\": 0.002950375962604172,\n"
" \"d\": 0.007769109028058599,\n"
" \"c\": 0.014530580027381331,\n"
" \"q\": 0.008315946817549687,\n"
" \"e\": 0.009539594175645224,\n"
" \"g\": 0.029443553983378914,\n"
" \"h\": 0.006732535197201616,\n"
" \"i\": 0.010808115403891736,\n"
" \"l\": 0.060195581153481746,\n"
" \"k\": 0.008951567181016987,\n"
" \"m\": 0.010555663336917303,\n"
" \"f\": 0.0616978021285267,\n"
" \"p\": 0.006695490413134814,\n"
" \"s\": 0.038212253709776114,\n"
" \"t\": 0.00709903625430727,\n"
" \"y\": 0.09201112174649106,\n"
" \"v\": 0.027185641450749077\n"
" },\n"
" \"y\": {\n"
" \"a\": 0.021886969285046808,\n"
" \"r\": 0.017607469004000554,\n"
" \"n\": 0.04455304950572163,\n"
" \"d\": 0.019500214003853017,\n"
" \"c\": 0.011020136009079829,\n"
" \"q\": 0.008777466312335109,\n"
" \"e\": 0.011961464230035605,\n"
" \"g\": 0.009052296308401283,\n"
" \"h\": 0.0993189262032023,\n"
" \"i\": 0.02137227848464673,\n"
" \"l\": 0.03606601168515469,\n"
" \"k\": 0.008675478337595343,\n"
" \"m\": 0.008769408797025511,\n"
" \"f\": 0.2603324248333642,\n"
" \"p\": 0.010376485217862514,\n"
" \"s\": 0.057419065463181936,\n"
" \"t\": 0.018643294553408254,\n"
" \"w\": 0.03752495581282767,\n"
" \"v\": 0.023417796621482002\n"
" },\n"
" \"v\": {\n"
" \"a\": 0.18238095522253409,\n"
" \"r\": 0.011622647218428121,\n"
" \"n\": 0.008050973990147188,\n"
" \"d\": 0.009120248012124089,\n"
" \"c\": 0.020307188236350606,\n"
" \"q\": 0.011613384691259207,\n"
" \"e\": 0.03587354649502602,\n"
" \"g\": 0.016360520123346732,\n"
" \"h\": 0.0030348190413582296,\n"
" \"i\": 0.39783659402615,\n"
" \"l\": 0.16289049535457858,\n"
" \"k\": 0.01988373492139735,\n"
" \"m\": 0.042133124679327796,\n"
" \"f\": 0.026213297260082417,\n"
" \"p\": 0.01512372504372714,\n"
" \"s\": 0.016980654055163764,\n"
" \"t\": 0.08889355516052984,\n"
" \"w\": 0.005516420191751408,\n"
" \"y\": 0.011651555831186707\n"
" }\n"
" }\n"
"}\n"
;
| evoldoers/historian | src/wag.cpp | C++ | bsd-3-clause | 16,124 |
<?php
/*
* This file is part of the HRis Software package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @version alpha
*
* @author Bertrand Kintanar <bertrand.kintanar@gmail.com>
* @license BSD License (3-clause)
* @copyright (c) 2014-2016, b8 Studios, Ltd
*
* @link http://github.com/HB-Co/HRis
*/
namespace Api\Requests;
use Irradiate\Api\Requests\Request;
class UserRequest extends Request
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:4',
];
}
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
}
| bkintanar/HRis | app/Api/Requests/UserRequest.php | PHP | bsd-3-clause | 1,088 |
;; R3000 and TX39 pipeline description.
;; Copyright (C) 2004, 2005 Free Software Foundation, Inc.
;;
;; This file is part of GCC.
;; GCC 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, or (at your
;; option) any later version.
;; GCC 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 GCC; see the file COPYING. If not, write to the
;; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
;; MA 02110-1301, USA.
;; This file overrides parts of generic.md. It is derived from the
;; old define_function_unit description.
(define_insn_reservation "r3k_load" 2
(and (eq_attr "cpu" "r3000,r3900")
(eq_attr "type" "load,fpload,fpidxload"))
"alu")
(define_insn_reservation "r3k_imul" 12
(and (eq_attr "cpu" "r3000,r3900")
(eq_attr "type" "imul,imul3,imadd"))
"imuldiv*12")
(define_insn_reservation "r3k_idiv" 35
(and (eq_attr "cpu" "r3000,r3900")
(eq_attr "type" "idiv"))
"imuldiv*35")
(define_insn_reservation "r3k_fmove" 1
(and (eq_attr "cpu" "r3000,r3900")
(eq_attr "type" "fabs,fneg,fmove"))
"alu")
(define_insn_reservation "r3k_fadd" 2
(and (eq_attr "cpu" "r3000,r3900")
(eq_attr "type" "fcmp,fadd"))
"alu")
(define_insn_reservation "r3k_fmul_single" 4
(and (eq_attr "cpu" "r3000,r3900")
(and (eq_attr "type" "fmul,fmadd")
(eq_attr "mode" "SF")))
"alu")
(define_insn_reservation "r3k_fmul_double" 5
(and (eq_attr "cpu" "r3000,r3900")
(and (eq_attr "type" "fmul,fmadd")
(eq_attr "mode" "DF")))
"alu")
(define_insn_reservation "r3k_fdiv_single" 12
(and (eq_attr "cpu" "r3000,r3900")
(and (eq_attr "type" "fdiv,frdiv")
(eq_attr "mode" "SF")))
"alu")
(define_insn_reservation "r3k_fdiv_double" 19
(and (eq_attr "cpu" "r3000,r3900")
(and (eq_attr "type" "fdiv,frdiv")
(eq_attr "mode" "DF")))
"alu")
| avaitla/Haskell-to-C---Bridge | gccxml/GCC/gcc/config/mips/3000.md | Markdown | bsd-3-clause | 2,266 |
## Percona Clustercheck ##
Script to make a proxy (ie HAProxy) capable of monitoring Percona XtraDB Cluster nodes properly.
## Usage ##
Below is a sample configuration for HAProxy on the client. The point of this is that the application will be able to connect to localhost port 3307, so although we are using Percona XtraDB Cluster with several nodes, the application will see this as a single MySQL server running on localhost.
`/etc/haproxy/haproxy.cfg`
...
listen percona-cluster 0.0.0.0:3307
balance leastconn
option httpchk
mode tcp
server node1 1.2.3.4:3306 check port 9200 inter 5000 fastinter 2000 rise 2 fall 2
server node2 1.2.3.5:3306 check port 9200 inter 5000 fastinter 2000 rise 2 fall 2
server node3 1.2.3.6:3306 check port 9200 inter 5000 fastinter 2000 rise 2 fall 2 backup
MySQL connectivity is checked via HTTP on port 9200. The clustercheck script is a simple shell script which accepts HTTP requests and checks MySQL on an incoming request. If the Percona XtraDB Cluster node is ready to accept requests, it will respond with HTTP code 200 (OK), otherwise a HTTP error 503 (Service Unavailable) is returned.
## Setup with xinetd ##
This setup will create a process that listens on TCP port 9200 using xinetd. This process uses the clustercheck script from this repository to report the status of the node.
First, create a clustercheckuser that will be doing the checks.
mysql> GRANT PROCESS ON *.* TO 'clustercheckuser'@'localhost' IDENTIFIED BY 'clustercheckpassword!'
Copy the clustercheck from the repository to a location (`/usr/bin` in the example below) and make it executable. Then add the following service to xinetd (make sure to match your location of the script with the 'server'-entry).
`/etc/xinetd.d/mysqlchk`:
# default: on
# description: mysqlchk
service mysqlchk
{
disable = no
flags = REUSE
socket_type = stream
port = 9200
wait = no
user = nobody
server = /usr/bin/clustercheck
log_on_failure += USERID
only_from = 0.0.0.0/0
per_source = UNLIMITED
}
Also, you should add the mysqlchk service to `/etc/services` before restarting xinetd.
xinetd 9098/tcp # ...
mysqlchk 9200/tcp # MySQL check <--- Add this line
git 9418/tcp # Git Version Control System
zope 9673/tcp # ...
Clustercheck will now listen on port 9200 after xinetd restart, and HAproxy is ready to check MySQL via HTTP poort 9200.
## Setup with shell return values ##
If you do not want to use the setup with xinetd, you can also execute `clustercheck` on the commandline and check for the return value.
First, create a clustercheckuser that will be doing the checks.
mysql> GRANT PROCESS ON *.* TO 'clustercheckuser'@'localhost' IDENTIFIED BY 'clustercheckpassword!'
Then, you can execute the script. In case of a synced node:
# /usr/bin/clustercheck > /dev/null
# echo $?
0
In case of an un-synced node:
# /usr/bin/clustercheck > /dev/null
# echo $?
1
You can use this return value with monitoring tools like Zabbix or Zenoss.
## Configuration options ##
The clustercheck script accepts several arguments:
clustercheck <user> <pass> <available_when_donor=0|1> <log_file>
- **user** and **pass** (default clustercheckuser and clustercheckpassword!): defines the username and password for the check. You can pass an empty username and/or password by supplying ""
- **available_when_donor** (default 0): By default, the node is reported unavailable if it’s a donor for SST. If you want to allow queries on a node which is a donor for SST, you can set this variable to 1. Note: when you set this variable to 1, you will also need to use a non-blocking SST method like xtrabackup
- **log_file** (default "/dev/null"): defines where logs and errors from the checks should go
- **available_when_readonly** (default 1): Depending on this setting and the MySQL status variable 'read_only', the node is reported available
- **defaults_extra_file** (default /etc/my.cnf): This file (if exists) will be passed to the mysql-command with the commandline option --defaults-extra-file
Note: You can also specify the username and password for the check in the **defaults_extra_file** and pass empty values for **user** and **pass**. That way, nobody can see the username and password (which can otherwise be seen, since they are passed to the MySQL CLI)
## Manually removing a node from the cluster ##
By touching /var/tmp/clustercheck.disabled, an admin may force clustercheck to return 503, regardless as to the actual state of the node. This is useful when the node is being put into maintenance mode.
| boomfish/percona-clustercheck | README.md | Markdown | bsd-3-clause | 4,801 |
from __future__ import absolute_import, unicode_literals
import pickle
from io import StringIO, BytesIO
from kombu import version_info_t
from kombu import utils
from kombu.five import python_2_unicode_compatible
from kombu.utils.text import version_string_as_tuple
from kombu.tests.case import Case, Mock, patch, mock
@python_2_unicode_compatible
class OldString(object):
def __init__(self, value):
self.value = value
def __str__(self):
return self.value
def split(self, *args, **kwargs):
return self.value.split(*args, **kwargs)
def rsplit(self, *args, **kwargs):
return self.value.rsplit(*args, **kwargs)
class test_kombu_module(Case):
def test_dir(self):
import kombu
self.assertTrue(dir(kombu))
class test_utils(Case):
def test_maybe_list(self):
self.assertEqual(utils.maybe_list(None), [])
self.assertEqual(utils.maybe_list(1), [1])
self.assertEqual(utils.maybe_list([1, 2, 3]), [1, 2, 3])
def test_fxrange_no_repeatlast(self):
self.assertEqual(list(utils.fxrange(1.0, 3.0, 1.0)),
[1.0, 2.0, 3.0])
def test_fxrangemax(self):
self.assertEqual(list(utils.fxrangemax(1.0, 3.0, 1.0, 30.0)),
[1.0, 2.0, 3.0, 3.0, 3.0, 3.0,
3.0, 3.0, 3.0, 3.0, 3.0])
self.assertEqual(list(utils.fxrangemax(1.0, None, 1.0, 30.0)),
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])
def test_reprkwargs(self):
self.assertTrue(utils.reprkwargs({'foo': 'bar', 1: 2, 'k': 'v'}))
def test_reprcall(self):
self.assertTrue(
utils.reprcall('add', (2, 2), {'copy': True}),
)
class test_UUID(Case):
def test_uuid4(self):
self.assertNotEqual(utils.uuid4(),
utils.uuid4())
def test_uuid(self):
i1 = utils.uuid()
i2 = utils.uuid()
self.assertIsInstance(i1, str)
self.assertNotEqual(i1, i2)
class MyStringIO(StringIO):
def close(self):
pass
class MyBytesIO(BytesIO):
def close(self):
pass
class test_emergency_dump_state(Case):
@mock.stdouts
def test_dump(self, stdout, stderr):
fh = MyBytesIO()
utils.emergency_dump_state(
{'foo': 'bar'}, open_file=lambda n, m: fh)
self.assertDictEqual(
pickle.loads(fh.getvalue()), {'foo': 'bar'})
self.assertTrue(stderr.getvalue())
self.assertFalse(stdout.getvalue())
@mock.stdouts
def test_dump_second_strategy(self, stdout, stderr):
fh = MyStringIO()
def raise_something(*args, **kwargs):
raise KeyError('foo')
utils.emergency_dump_state(
{'foo': 'bar'},
open_file=lambda n, m: fh, dump=raise_something
)
self.assertIn('foo', fh.getvalue())
self.assertIn('bar', fh.getvalue())
self.assertTrue(stderr.getvalue())
self.assertFalse(stdout.getvalue())
class test_retry_over_time(Case):
def setup(self):
self.index = 0
class Predicate(Exception):
pass
def myfun(self):
if self.index < 9:
raise self.Predicate()
return 42
def errback(self, exc, intervals, retries):
interval = next(intervals)
sleepvals = (None, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 16.0)
self.index += 1
self.assertEqual(interval, sleepvals[self.index])
return interval
@mock.sleepdeprived(module=utils)
def test_simple(self):
prev_count, utils.count = utils.count, Mock()
try:
utils.count.return_value = list(range(1))
x = utils.retry_over_time(self.myfun, self.Predicate,
errback=None, interval_max=14)
self.assertIsNone(x)
utils.count.return_value = list(range(10))
cb = Mock()
x = utils.retry_over_time(self.myfun, self.Predicate,
errback=self.errback, callback=cb,
interval_max=14)
self.assertEqual(x, 42)
self.assertEqual(self.index, 9)
cb.assert_called_with()
finally:
utils.count = prev_count
@mock.sleepdeprived(module=utils)
def test_retry_once(self):
with self.assertRaises(self.Predicate):
utils.retry_over_time(
self.myfun, self.Predicate,
max_retries=1, errback=self.errback, interval_max=14,
)
self.assertEqual(self.index, 1)
# no errback
with self.assertRaises(self.Predicate):
utils.retry_over_time(
self.myfun, self.Predicate,
max_retries=1, errback=None, interval_max=14,
)
@mock.sleepdeprived(module=utils)
def test_retry_always(self):
Predicate = self.Predicate
class Fun(object):
def __init__(self):
self.calls = 0
def __call__(self, *args, **kwargs):
try:
if self.calls >= 10:
return 42
raise Predicate()
finally:
self.calls += 1
fun = Fun()
self.assertEqual(
utils.retry_over_time(
fun, self.Predicate,
max_retries=0, errback=None, interval_max=14,
),
42,
)
self.assertEqual(fun.calls, 11)
class test_cached_property(Case):
def test_deleting(self):
class X(object):
xx = False
@utils.cached_property
def foo(self):
return 42
@foo.deleter # noqa
def foo(self, value):
self.xx = value
x = X()
del(x.foo)
self.assertFalse(x.xx)
x.__dict__['foo'] = 'here'
del(x.foo)
self.assertEqual(x.xx, 'here')
def test_when_access_from_class(self):
class X(object):
xx = None
@utils.cached_property
def foo(self):
return 42
@foo.setter # noqa
def foo(self, value):
self.xx = 10
desc = X.__dict__['foo']
self.assertIs(X.foo, desc)
self.assertIs(desc.__get__(None), desc)
self.assertIs(desc.__set__(None, 1), desc)
self.assertIs(desc.__delete__(None), desc)
self.assertTrue(desc.setter(1))
x = X()
x.foo = 30
self.assertEqual(x.xx, 10)
del(x.foo)
class test_symbol_by_name(Case):
def test_instance_returns_instance(self):
instance = object()
self.assertIs(utils.symbol_by_name(instance), instance)
def test_returns_default(self):
default = object()
self.assertIs(
utils.symbol_by_name('xyz.ryx.qedoa.weq:foz', default=default),
default,
)
def test_no_default(self):
with self.assertRaises(ImportError):
utils.symbol_by_name('xyz.ryx.qedoa.weq:foz')
def test_imp_reraises_ValueError(self):
imp = Mock()
imp.side_effect = ValueError()
with self.assertRaises(ValueError):
utils.symbol_by_name('kombu.Connection', imp=imp)
def test_package(self):
from kombu.entity import Exchange
self.assertIs(
utils.symbol_by_name('.entity:Exchange', package='kombu'),
Exchange,
)
self.assertTrue(utils.symbol_by_name(':Consumer', package='kombu'))
class test_ChannelPromise(Case):
def test_repr(self):
obj = Mock(name='cb')
self.assertIn(
'promise',
repr(utils.ChannelPromise(obj)),
)
obj.assert_not_called()
class test_entrypoints(Case):
@mock.mask_modules('pkg_resources')
def test_without_pkg_resources(self):
self.assertListEqual(list(utils.entrypoints('kombu.test')), [])
@mock.module_exists('pkg_resources')
def test_with_pkg_resources(self):
with patch('pkg_resources.iter_entry_points', create=True) as iterep:
eps = iterep.return_value = [Mock(), Mock()]
self.assertTrue(list(utils.entrypoints('kombu.test')))
iterep.assert_called_with('kombu.test')
eps[0].load.assert_called_with()
eps[1].load.assert_called_with()
class test_shufflecycle(Case):
def test_shuffles(self):
prev_repeat, utils.repeat = utils.repeat, Mock()
try:
utils.repeat.return_value = list(range(10))
values = {'A', 'B', 'C'}
cycle = utils.shufflecycle(values)
seen = set()
for i in range(10):
next(cycle)
utils.repeat.assert_called_with(None)
self.assertTrue(seen.issubset(values))
with self.assertRaises(StopIteration):
next(cycle)
next(cycle)
finally:
utils.repeat = prev_repeat
class test_version_string_as_tuple(Case):
def test_versions(self):
self.assertTupleEqual(
version_string_as_tuple('3'),
version_info_t(3, 0, 0, '', ''),
)
self.assertTupleEqual(
version_string_as_tuple('3.3'),
version_info_t(3, 3, 0, '', ''),
)
self.assertTupleEqual(
version_string_as_tuple('3.3.1'),
version_info_t(3, 3, 1, '', ''),
)
self.assertTupleEqual(
version_string_as_tuple('3.3.1a3'),
version_info_t(3, 3, 1, 'a3', ''),
)
self.assertTupleEqual(
version_string_as_tuple('3.3.1a3-40c32'),
version_info_t(3, 3, 1, 'a3', '40c32'),
)
self.assertEqual(
version_string_as_tuple('3.3.1.a3.40c32'),
version_info_t(3, 3, 1, 'a3', '40c32'),
)
class test_maybe_fileno(Case):
def test_maybe_fileno(self):
self.assertEqual(utils.maybe_fileno(3), 3)
f = Mock(name='file')
self.assertIs(utils.maybe_fileno(f), f.fileno())
f.fileno.side_effect = ValueError()
self.assertIsNone(utils.maybe_fileno(f))
| Elastica/kombu | kombu/tests/utils/test_utils.py | Python | bsd-3-clause | 10,301 |
<?php
Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
//dependency injection container
Yii::$container->set(\common\service\SerializerInterface::class, \common\service\JsonSerializer::class);
Yii::$container->set('requestCrawler', [
'class' => \common\service\RequestCrawlerService::class,
'pathToSave' => dirname(__DIR__) . '/file',
'on infoAfterSave' => function($event)
{
$test = new \common\service\Test();
$test->info($event);
},
]);
| VictorFursa/millionaire | common/config/bootstrap.php | PHP | bsd-3-clause | 675 |
var should = require('should');
var path = require('path');
var _ = require('underscore');
var Graft = require('../server');
var utils = require('./utils');
var sinon = require('sinon');
var testPort = 8924;
function setupSpies() {
sinon.spy(Graft.Server, 'trigger');
}
function restoreSpies() {
Graft.Server.trigger.restore();
}
describe('Systems: Running', function() {
before(setupSpies);
before(function() {
Graft.system('ServerOnly', 'server-only', {
kind: 'server_only'
});
Graft.system('ClientToo', 'client-too', {
kind: 'client_too'
});
require('./fixture/direct-load');
Graft.load(__dirname + '/fixture');
Graft.start({ port: testPort });
});
it('should have all systems and submodules present', function() {
Graft.should.have.property('DirectLoad');
Graft.should.have.property('ServerOnly');
Graft.ServerOnly.should.have.property('SubModule');
Graft.should.have.property('ClientToo');
Graft.ClientToo.should.have.property('SubModule');
});
it('should have called all the mount triggers', function() {
sinon.assert.calledWith(Graft.Server.trigger, 'mount:server');
sinon.assert.calledWith(Graft.Server.trigger, 'before:mount:server');
sinon.assert.calledWith(Graft.Server.trigger, 'after:mount:server');
sinon.assert.calledWith(Graft.Server.trigger, 'mount:static');
sinon.assert.calledWith(Graft.Server.trigger, 'before:mount:static');
sinon.assert.calledWith(Graft.Server.trigger, 'after:mount:static');
sinon.assert.calledWith(Graft.Server.trigger, 'mount:router');
sinon.assert.calledWith(Graft.Server.trigger, 'before:mount:router');
sinon.assert.calledWith(Graft.Server.trigger, 'after:mount:router');
sinon.assert.calledWith(Graft.Server.trigger, 'listen');
sinon.assert.calledWith(Graft.Server.trigger, 'before:listen');
sinon.assert.calledWith(Graft.Server.trigger, 'after:listen');
});
after(restoreSpies);
describe('stop server', utils.stopServer);
});
| ONCHoldings/graft.js | test/210System.running.js | JavaScript | bsd-3-clause | 2,169 |
/*
* Copyright (c) 1982, 1986, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)uio.h 8.5 (Berkeley) 2/22/94
*/
#ifndef _SYS_UIO_H_
#define _SYS_UIO_H_
/*
* XXX
* iov_base should be a void *.
*/
struct iovec {
char *iov_base; /* Base address. */
size_t iov_len; /* Length. */
};
enum uio_rw { UIO_READ, UIO_WRITE };
/* Segment flag values. */
enum uio_seg {
UIO_USERSPACE, /* from user data space */
UIO_SYSSPACE, /* from system space */
UIO_USERISPACE /* from user I space */
};
#ifdef KERNEL
struct uio {
struct iovec *uio_iov;
int uio_iovcnt;
off_t uio_offset;
int uio_resid;
enum uio_seg uio_segflg;
enum uio_rw uio_rw;
struct proc *uio_procp;
};
/*
* Limits
*/
#define UIO_MAXIOV 1024 /* max 1K of iov's */
#define UIO_SMALLIOV 8 /* 8 on stack, else malloc */
#endif /* KERNEL */
#ifndef KERNEL
#include <sys/cdefs.h>
__BEGIN_DECLS
ssize_t readv __P((int, const struct iovec *, int));
ssize_t writev __P((int, const struct iovec *, int));
__END_DECLS
#endif /* !KERNEL */
#endif /* !_SYS_UIO_H_ */
| antonycourtney/anp | generic/sys/uio.h | C | bsd-3-clause | 2,887 |
// vim:ts=8:expandtab
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#ifdef LINUX
#include <iwlib.h>
#endif
#include "i3status.h"
static const char *get_wireless_essid(const char *interface) {
static char part[512];
#ifdef LINUX
int skfd;
if ((skfd = iw_sockets_open()) < 0) {
perror("socket");
exit(-1);
}
struct wireless_config wcfg;
if (iw_get_basic_config(skfd, interface, &wcfg) >= 0)
snprintf(part, sizeof(part), "%s", wcfg.essid);
else part[0] = '\0';
(void)close(skfd);
#else
part[0] = '\0';
#endif
return part;
}
/*
* Just parses /proc/net/wireless looking for lines beginning with
* wlan_interface, extracting the quality of the link and adding the
* current IP address of wlan_interface.
*
*/
void print_wireless_info(const char *interface, const char *format_up, const char *format_down) {
char buf[1024];
int quality = -1;
char *interfaces;
const char *walk;
memset(buf, 0, sizeof(buf));
if (!slurp("/proc/net/wireless", buf, sizeof(buf)))
die("Could not open \"/proc/net/wireless\"\n");
interfaces = skip_character(buf, '\n', 1) + 1;
while ((interfaces = skip_character(interfaces, '\n', 1)+1) < buf+strlen(buf)) {
while (isspace((int)*interfaces))
interfaces++;
if (!BEGINS_WITH(interfaces, interface))
continue;
if (sscanf(interfaces, "%*[^:]: 0000 %d", &quality) != 1)
continue;
break;
}
/* Interface could not be found */
if (quality == -1)
return;
if ((quality == UCHAR_MAX) || (quality == 0)) {
walk = format_down;
printf("%s", color("#FF0000"));
} else {
printf("%s", color("#00FF00"));
walk = format_up;
}
for (; *walk != '\0'; walk++) {
if (*walk != '%') {
putchar(*walk);
continue;
}
if (BEGINS_WITH(walk+1, "quality")) {
(void)printf("%03d%%", quality);
walk += strlen("quality");
}
if (BEGINS_WITH(walk+1, "essid")) {
(void)printf("%s", get_wireless_essid(interface));
walk += strlen("essid");
}
if (BEGINS_WITH(walk+1, "ip")) {
const char *ip_address = get_ip_addr(interface);
if (ip_address != NULL)
(void)printf("%s", get_ip_addr(interface));
else (void)printf("no IP");
walk += strlen("ip");
}
}
(void)printf("%s", endcolor());
}
| stettberger/i3status | src/print_wireless_info.c | C | bsd-3-clause | 3,025 |
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ARKode.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ARKode.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/ARKode"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ARKode"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
| liuqx315/Sundials | doc/guide/Makefile | Makefile | bsd-3-clause | 5,573 |
nrfutil
==========
nrfutil is a Python package that includes the nrfutil command line utility and the nordicsemi library.
About
-----
The library is written for Python 2.7.
Prerequisites
-------------
To install nrfutil the following prerequisites must be satisfied:
* Python 2.7 (2.7.6 or newer, not Python 3)
* pip (https://pip.pypa.io/en/stable/installing.html)
* setuptools (upgrade to latest version: pip install -U setuptools)
* install required modules: pip install -r requirements.txt
py2exe prerequisites (Windows only):
* py2exe (Windows only) (v0.6.9) (pip install http://sourceforge.net/projects/py2exe/files/latest/download?source=files)
* VC compiler for Python (Windows only) (http://www.microsoft.com/en-us/download/confirmation.aspx?id=44266)
Installation
------------
To install the library to the local Python site-packages and script folder:
```
python setup.py install
```
To generate a self-contained Windows exe version of the utility (Windows only):
```
python setup.py py2exe
```
NOTE: Some anti-virus programs will stop py2exe from executing correctly when it modifies the .exe file.
Usage
-----
To get info on usage of nrfutil:
```
nrfutil --help
```
| strobo-inc/pc-nrfutil | README.md | Markdown | bsd-3-clause | 1,194 |
import React, { Component } from 'react';
import { Text, View, ScrollView } from 'react-native';
import Button from 'react-native-button'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import {
Card,
CardImage,
CardTitle,
CardContent,
CardAction
} from 'react-native-card-view';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import AppActions from '../../../actions';
import CheckoutWebViewWrap from './checkoutWebViewWrap'
import SaveCardOptionBox from './saveCardOptionBox';
import * as userTypes from '../../../statics/actions/user';
class CheckoutWebView extends Component {
componentWillMount() {
const {userAction} = this.props.user;
if (userAction === userTypes.SETTING_ONE_TIME_PAYMENT) {
this.props.actions.closeSetOneTimePayment()
}
}
onSaveCardToggle(checked) {
this.props.actions.persistPaymentMethod(!checked);
}
render() {
const {userAction, auth, persistPaymentMethod} = this.props.user;
const {navigation} = this.props;
const isLoggedIn = auth && auth.token;
const isRemoteAuthorized = auth && auth.remoteAuthorized;
const show = userAction === userTypes.SETTING_ONE_TIME_PAYMENT;
return (
<View
style={{
height: '100%',
position: 'absolute',
opacity: show ? 1 : 0,
top: show ? 0 : '100%',
width: '100%'
}}
>
<View
style={{
backgroundColor: 'rgba(0,0,0, .85)',
height: '100%',
position: 'absolute',
top: 0,
width: '100%'
}}
/>
<KeyboardAwareScrollView
enableOnAndroid={true}
>
<Card
styles={{
card: {
minHeight: !isLoggedIn || !isRemoteAuthorized ? 290 : 285,
}
}}
>
<View
style={{
flex: 1,
margin: 10,
maxHeight: !isLoggedIn || !isRemoteAuthorized ? 290 : 285,
width: '100%',
}}
>
<CheckoutWebViewWrap />
</View>
</Card>
<Card
styles={{
card: {
minHeight: !isLoggedIn || !isRemoteAuthorized ? 120 : 45
}
}}
>
<View
style={{
height: '100%',
width: '100%'
}}
>
<SaveCardOptionBox
style={{
flex: 1,
padding: 10,
width: '100%'
}}
navigate={navigation.navigate}
isLoggedIn={isLoggedIn}
isRemoteAuthorized={isRemoteAuthorized}
checkboxCb={this.onSaveCardToggle.bind(this, persistPaymentMethod)}
persistPaymentMethod={persistPaymentMethod}
/>
</View>
</Card>
<View
style={{
flexDirection: 'row',
alignContent: 'center',
justifyContent: 'center',
width: '100%'
}}
>
<Button
style={{
...styles.buttonStyle,
alignSelf: 'center'
}}
onPress={persistPaymentMethod ? this.props.actions.saveCard : this.props.actions.saveNonce}
>
Save
</Button>
<Button
style={{
...styles.buttonStyle,
alignSelf: 'center'
}}
onPress={this.props.actions.closeSetOneTimePayment}
>
Cancel
</Button>
</View>
</KeyboardAwareScrollView>
</View>
);
}
}
const mapState = (state) => {
return {
user: state.user
};
};
const mapDispatch = dispatch => ({
actions: bindActionCreators(AppActions, dispatch)
});
export default
connect(mapState, mapDispatch)(CheckoutWebView);
const buttonStyle = {
padding:15,
margin: 10,
height:55,
overflow:'hidden',
borderRadius:4,
backgroundColor: '#41495a',
fontSize: 20,
color: 'grey',
};
const styles = {
tabContainer: {
flex: 1,
backgroundColor: '#1f232b',
},
container: {
backgroundColor: '#1f232b',
height: '100%',
},
buttonStyle,
buttonDisabledStyle: {
...buttonStyle,
backgroundColor: '#313744',
borderWidth: 0,
},
buttonDisabledTextStyle: {
color: '#BCBCBC',
},
};
| ronanamsterdam/squaredcoffee | application/components/shared/checkoutWebView/index.js | JavaScript | bsd-3-clause | 6,443 |
#! /usr/bin/env ruby -S rspec
require 'spec_helper_acceptance'
describe 'size function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
describe 'success' do
it 'single string size' do
pp = <<-EOS
$a = 'discombobulate'
$o = size($a)
notice(inline_template('size is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/size is 14/)
end
end
it 'with empty string' do
pp = <<-EOS
$a = ''
$o = size($a)
notice(inline_template('size is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/size is 0/)
end
end
it 'with undef' do
pp = <<-EOS
$a = undef
$o = size($a)
notice(inline_template('size is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/size is 0/)
end
end
it 'strings in array' do
pp = <<-EOS
$a = ['discombobulate', 'moo']
$o = size($a)
notice(inline_template('size is <%= @o.inspect %>'))
EOS
apply_manifest(pp, :catch_failures => true) do |r|
expect(r.stdout).to match(/size is 2/)
end
end
end
describe 'failure' do
it 'handles no arguments'
it 'handles non strings or arrays'
end
end
| renandanton/codeorders | puphpet/puppet/modules/stdlib/spec/acceptance/size_spec.rb | Ruby | bsd-3-clause | 1,478 |
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''Unit tests for the admin template gatherer.'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
import StringIO
import tempfile
import unittest
from grit.gather import admin_template
from grit import util
from grit import grd_reader
from grit import grit_runner
from grit.tool import build
class AdmGathererUnittest(unittest.TestCase):
def testParsingAndTranslating(self):
pseudofile = StringIO.StringIO(
'bingo bongo\n'
'ding dong\n'
'[strings] \n'
'whatcha="bingo bongo"\n'
'gotcha = "bingolabongola "the wise" fingulafongula" \n')
gatherer = admin_template.AdmGatherer.FromFile(pseudofile)
gatherer.Parse()
self.failUnless(len(gatherer.GetCliques()) == 2)
self.failUnless(gatherer.GetCliques()[1].GetMessage().GetRealContent() ==
'bingolabongola "the wise" fingulafongula')
translation = gatherer.Translate('en')
self.failUnless(translation == gatherer.GetText().strip())
def testErrorHandling(self):
pseudofile = StringIO.StringIO(
'bingo bongo\n'
'ding dong\n'
'whatcha="bingo bongo"\n'
'gotcha = "bingolabongola "the wise" fingulafongula" \n')
gatherer = admin_template.AdmGatherer.FromFile(pseudofile)
self.assertRaises(admin_template.MalformedAdminTemplateException,
gatherer.Parse)
_TRANSLATABLES_FROM_FILE = (
'Google', 'Google Desktop', 'Preferences',
'Controls Google Desktop preferences',
'Indexing and Capture Control',
'Controls what files, web pages, and other content will be indexed by Google Desktop.',
'Prevent indexing of email',
# there are lots more but we don't check any further
)
def VerifyCliquesFromAdmFile(self, cliques):
self.failUnless(len(cliques) > 20)
for ix in range(len(self._TRANSLATABLES_FROM_FILE)):
text = cliques[ix].GetMessage().GetRealContent()
self.failUnless(text == self._TRANSLATABLES_FROM_FILE[ix])
def testFromFile(self):
fname = util.PathFromRoot('grit/testdata/GoogleDesktop.adm')
gatherer = admin_template.AdmGatherer.FromFile(fname)
gatherer.Parse()
cliques = gatherer.GetCliques()
self.VerifyCliquesFromAdmFile(cliques)
def MakeGrd(self):
grd = grd_reader.Parse(StringIO.StringIO('''<?xml version="1.0" encoding="UTF-8"?>
<grit latest_public_release="2" source_lang_id="en-US" current_release="3">
<release seq="3">
<structures>
<structure type="admin_template" name="IDAT_GOOGLE_DESKTOP_SEARCH"
file="GoogleDesktop.adm" exclude_from_rc="true" />
<structure type="txt" name="BINGOBONGO"
file="README.txt" exclude_from_rc="true" />
</structures>
</release>
<outputs>
<output filename="de_res.rc" type="rc_all" lang="de" />
</outputs>
</grit>'''), util.PathFromRoot('grit/testdata'))
grd.SetOutputContext('en', {})
grd.RunGatherers(recursive=True)
return grd
def testInGrd(self):
grd = self.MakeGrd()
cliques = grd.children[0].children[0].children[0].GetCliques()
self.VerifyCliquesFromAdmFile(cliques)
def testFileIsOutput(self):
grd = self.MakeGrd()
dirname = tempfile.mkdtemp()
try:
tool = build.RcBuilder()
tool.o = grit_runner.Options()
tool.output_directory = dirname
tool.res = grd
tool.Process()
self.failUnless(os.path.isfile(
os.path.join(dirname, 'de_GoogleDesktop.adm')))
self.failUnless(os.path.isfile(
os.path.join(dirname, 'de_README.txt')))
finally:
for f in os.listdir(dirname):
os.unlink(os.path.join(dirname, f))
os.rmdir(dirname)
if __name__ == '__main__':
unittest.main()
| JoKaWare/WTL-DUI | tools/grit/grit/gather/admin_template_unittest.py | Python | bsd-3-clause | 3,990 |
<?php
namespace Apps\Common\Models;
/**
* 美容院V2.0扩展属性Model
* @author chenxiaolin
* @date 2016年1月19日
* @version 2.0.0
* @copyright Copyright 2016 meelier.com
*/
class BeautyParlorAttr extends \PhalconPlus\Database\Model
{
/**
*
* @var integer
*/
public $attr_id;
public $beauty_parlor_id;
public $open_year;
public $shop_area;
public $service_num;
/**
* @var DateTime
*/
public $open_time;
public $close_time;
/**
*
* @var decimal
*/
public $low_price;
/**
* @var string
*/
public $facilities;
/**
* Initialize method for model.
*/
public function initialize()
{
$this->hasOne('beauty_parlor_id', 'Apps\Common\Models\BeautyParlor', 'bp_id', array('alias' => 'BeautyParlor'));
}
/**
* Returns table name mapped in the model.
*
* @return string
*/
public function getSource()
{
return 'beauty_parlor_attr';
}
/**
* Allows to query a set of records that match the specified conditions
*
* @param mixed $parameters
* @return BeautyParlorAttr[]
*/
public static function find($parameters = null)
{
return parent::find($parameters);
}
/**
* Allows to query the first record that match the specified conditions
*
* @param mixed $parameters
* @return BeautyParlorAttr
*/
public static function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
/**
* Independent Column Mapping.
* Keys are the real names in the table and the values their names in the application
*
* @return array
*/
public function columnMap()
{
return array(
'attr_id' => 'attr_id',
'beauty_parlor_id' => 'beauty_parlor_id',
'open_time' => 'open_time',
'close_time' => 'close_time',
'low_price' => 'low_price',
'open_year' => 'open_year',
'shop_area' => 'shop_area',
'service_num' => 'service_num',
'facilities' => 'facilities'
);
}
}
?> | fu-tao/meelier_c2.0 | common/models/BeautyParlorAttr.php | PHP | bsd-3-clause | 2,369 |
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
testinfo = "s, t 3, s, t 6.1, s, q"
tags = "MoveBy"
import cocos
from cocos.director import director
from cocos.actions import MoveBy
from cocos.sprite import Sprite
import pyglet
class TestLayer(cocos.layer.Layer):
def __init__(self):
super( TestLayer, self ).__init__()
x,y = director.get_window_size()
self.sprite = Sprite( 'grossini.png', (x/2, y/2) )
self.add( self.sprite, name='sprite' )
self.sprite.do( MoveBy( (x/2,y/2), 6 ) )
def main():
director.init()
test_layer = TestLayer ()
main_scene = cocos.scene.Scene()
main_scene.add(test_layer, name='test_layer')
director.run (main_scene)
if __name__ == '__main__':
main()
| eevee/cocos2d-mirror | test/test_moveby.py | Python | bsd-3-clause | 867 |
; The CHK macro causes a checksum to be computed and deposited at the current location.
; The starting point of the checksum calculation is indicated as an argument.
;
; The checksum is calculated as the simple arithmetic sum of all bytes starting
; at the provided address up to but not including the address of the CHK macro instance.
; The least significant byte is all that is used.
;
; The macro requires the virtual DEVICE memory (checksum needs access to previously
; defined machine code bytes).
; CHK macro definition
MACRO .CHK address?
OPT push listoff
.SUM = 0 ; init values for checksumming
.ADR = address? : ASSERT address? < $ ; starting address must be below current
DUP $ - address? ; do simple sum of all bytes
.SUM = .SUM + {B .ADR}
.ADR = .ADR + 1
EDUP
OPT pop
DB low .SUM
ENDM
; similar as .CHK macro, but does use XOR to calculate checksum
MACRO .CHKXOR address?
OPT push listoff
.CSUM = 0 ; init values for checksumming
.ADR = address? : ASSERT address? < $ ; starting address must be below current
DUP $ - address? ; do simple sum of all bytes
.CSUM = .CSUM ^ {B .ADR}
.ADR = .ADR + 1
EDUP
OPT pop
DB .CSUM
ENDM
; Examples and verification (ZX Spectrum 48 virtual device is used for the test)
DEVICE ZXSPECTRUM48 : OUTPUT "sum_checksum.bin"
TEST1 DB 'A'
.CHK TEST1 ; expected 'A'
TEST2 DS 300, 'b'
DB 'B' - ((300*'b')&$FF) ; adjust checksum to become 'B'
.CHK TEST2 ; expected 'B'
TEST3 inc hl ; $23
inc h ; $24
.CHK TEST3 ; expected 'G' ($47)
TESTXOR
HEX 20 50 49 38 30 20
HEX 20 20 20 20 20 43 01 00
HEX 40 08 40 20 20 20 20 20
HEX 20 43 41
.CHKXOR TESTXOR ; expected $79
| z00m128/sjasmplus | tests/macro_examples/sum_checksum.asm | Assembly | bsd-3-clause | 1,989 |
/*
* discursive_debug.cpp
*
* Created on: Aug 19, 2010
* Author: Hunter Davis
*/
#include "./discursive_print.h"
#include "../main/configuration_agent.h"
extern ConfigurationAgent configAgent;
// -------------------------------------------------------------------------
// API :: DiscursivePrint
// PURPOSE :: it's printf that can be updated to work with guis etc
// ::
// PARAMETERS :: std::string printMessage - printf first argument
// :: ... - any formatting arguments or parameters to printf
// RETURN :: void - this is a 100% replacement for printf
// -------------------------------------------------------------------------
void DiscursivePrint(std::string printMessage,...)
{
int printMode = configAgent.returnOptionByName("printMode");
if(printMode == 0)
{
va_list args;
va_start( args, printMessage );
vprintf(printMessage.c_str(), args );
va_end( args );
}
else if(printMode == 1)
{
FILE * outFile;
std::string outputFileName = configAgent.returnPrintModeFileName();
outFile = fopen (outputFileName.c_str(),"a");
va_list args;
va_start( args, printMessage );
vfprintf(outFile,printMessage.c_str(), args );
va_end( args );
fclose (outFile);
}
else if(printMode == 2)
{
// ignore 2 - it's the ignore flag
}
else
{
DiscursiveError("Incorrect Print Mode Set %d\n",printMode);
}
}
| huntergdavis/Source-Tree-Visualizer | src/dis/stv/system/discursive_print.cpp | C++ | bsd-3-clause | 1,363 |
/*
* Licensed under BSD http://en.wikipedia.org/wiki/BSD_License
* Copyright (c) 2010, Duponchel David
* 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 GraouPack 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 DUPONCHEL DAVID 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.
*/
"use strict";
$.namespace("izpack.compatibility");
/*global XMLSerializer, ActiveXObject */
(function () {
var console = window.console,
xmlCompat;
/*DEBUG_START*/
if (typeof console === "undefined") {
console = {};
console.debug =
console.log =
console.info =
console.warn =
console.error =
console.groupCollapsed =
console.time =
console.timeEnd =
console.groupEnd =
function () {};
window.console = console;
} else if (console.log && !console.debug) {
// IE 8 implements console.log in his "developer tools" but not console.debug...
console.debug = console.log;
}
/*DEBUG_END*/
xmlCompat = izpack.compatibility.xml = {
w3c : typeof XMLSerializer !== "undefined" &&
document.implementation && document.implementation.createDocument && typeof document.implementation.createDocument !== "undefined",
ie : typeof window.ActiveXObject !== "undefined"
};
if (!xmlCompat.w3c && !xmlCompat.ie) {
alert("this browser doesn't seem to be recent enough to support this app.");
}
}());
| dduponchel/GraouPack | js/src/CompatibilityCheck.js | JavaScript | bsd-3-clause | 2,679 |
/* $OpenBSD: rsa_saos.c,v 1.23 2017/05/02 03:59:45 deraadt Exp $ */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <string.h>
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/objects.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
int
RSA_sign_ASN1_OCTET_STRING(int type, const unsigned char *m, unsigned int m_len,
unsigned char *sigret, unsigned int *siglen, RSA *rsa)
{
ASN1_OCTET_STRING sig;
int i, j, ret = 1;
unsigned char *p, *s;
sig.type = V_ASN1_OCTET_STRING;
sig.length = m_len;
sig.data = (unsigned char *)m;
i = i2d_ASN1_OCTET_STRING(&sig, NULL);
j = RSA_size(rsa);
if (i > (j - RSA_PKCS1_PADDING_SIZE)) {
RSAerror(RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY);
return 0;
}
s = malloc(j + 1);
if (s == NULL) {
RSAerror(ERR_R_MALLOC_FAILURE);
return 0;
}
p = s;
i2d_ASN1_OCTET_STRING(&sig, &p);
i = RSA_private_encrypt(i, s, sigret, rsa, RSA_PKCS1_PADDING);
if (i <= 0)
ret = 0;
else
*siglen = i;
freezero(s, (unsigned int)j + 1);
return ret;
}
int
RSA_verify_ASN1_OCTET_STRING(int dtype, const unsigned char *m,
unsigned int m_len, unsigned char *sigbuf, unsigned int siglen, RSA *rsa)
{
int i, ret = 0;
unsigned char *s;
const unsigned char *p;
ASN1_OCTET_STRING *sig = NULL;
if (siglen != (unsigned int)RSA_size(rsa)) {
RSAerror(RSA_R_WRONG_SIGNATURE_LENGTH);
return 0;
}
s = malloc(siglen);
if (s == NULL) {
RSAerror(ERR_R_MALLOC_FAILURE);
goto err;
}
i = RSA_public_decrypt((int)siglen, sigbuf, s, rsa, RSA_PKCS1_PADDING);
if (i <= 0)
goto err;
p = s;
sig = d2i_ASN1_OCTET_STRING(NULL, &p, (long)i);
if (sig == NULL)
goto err;
if ((unsigned int)sig->length != m_len ||
memcmp(m, sig->data, m_len) != 0) {
RSAerror(RSA_R_BAD_SIGNATURE);
} else
ret = 1;
err:
ASN1_OCTET_STRING_free(sig);
freezero(s, (unsigned int)siglen);
return ret;
}
| GaloisInc/hacrypto | src/C/libressl/libressl-2.7.2/crypto/rsa/rsa_saos.c | C | bsd-3-clause | 4,999 |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import subprocess
from devtoolslib.shell import Shell
from devtoolslib import http_server
class LinuxShell(Shell):
"""Wrapper around Mojo shell running on Linux.
Args:
executable_path: path to the shell binary
command_prefix: optional list of arguments to prepend to the shell command,
allowing e.g. to run the shell under debugger.
"""
def __init__(self, executable_path, command_prefix=None):
self.executable_path = executable_path
self.command_prefix = command_prefix if command_prefix else []
def ServeLocalDirectory(self, local_dir_path, port=0):
"""Serves the content of the local (host) directory, making it available to
the shell under the url returned by the function.
The server will run on a separate thread until the program terminates. The
call returns immediately.
Args:
local_dir_path: path to the directory to be served
port: port at which the server will be available to the shell
Returns:
The url that the shell can use to access the content of |local_dir_path|.
"""
return 'http://%s:%d/' % http_server.StartHttpServer(local_dir_path, port)
def Run(self, arguments):
"""Runs the shell with given arguments until shell exits, passing the stdout
mingled with stderr produced by the shell onto the stdout.
Returns:
Exit code retured by the shell or None if the exit code cannot be
retrieved.
"""
command = self.command_prefix + [self.executable_path] + arguments
return subprocess.call(command, stderr=subprocess.STDOUT)
def RunAndGetOutput(self, arguments):
"""Runs the shell with given arguments until shell exits.
Args:
arguments: list of arguments for the shell
Returns:
A tuple of (return_code, output). |return_code| is the exit code returned
by the shell or None if the exit code cannot be retrieved. |output| is the
stdout mingled with the stderr produced by the shell.
"""
command = self.command_prefix + [self.executable_path] + arguments
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(output, _) = p.communicate()
return p.returncode, output
| collinjackson/mojo | mojo/devtools/common/devtoolslib/linux_shell.py | Python | bsd-3-clause | 2,385 |
var allTestFiles = [];
var TEST_REGEXP = /\.spec\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
allTestFiles.push(pathToModule(file));
}
});
window.expect = window.chai.expect;
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
paths: {
"underscore" : "node_modules/underscore/underscore",
"backbone" : "node_modules/backbone/backbone",
"jquery" : "node_modules/jquery/dist/jquery"
},
shim: {
"underscore": {
exports: "_"
}
},
// dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
| effektif/backbone-partialput | test/test-main.js | JavaScript | bsd-3-clause | 904 |
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii message/extract' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'<i class="fa fa-cog"></i>' => '',
'Cancel Membership' => '',
'Security' => '',
'This option will hide new content from this space at your dashboard' => '',
'This option will show new content from this space at your dashboard' => '',
'Hide posts on dashboard' => 'Mesajları gizle',
'Members' => 'Üyeler',
'Modules' => 'Modüller',
'Show posts on dashboard' => 'Mesajları göster',
];
| LeonidLyalin/vova | common/humhub/protected/humhub/modules/space/messages/tr/widgets_SpaceAdminMenuWidget.php | PHP | bsd-3-clause | 1,111 |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'recipe_engine/buildbucket',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/platform',
'recipe_engine/properties',
'recipe_engine/raw_io',
'recipe_engine/step',
'git',
]
def RunSteps(api):
url = 'https://chromium.googlesource.com/chromium/src.git'
# git.checkout can optionally dump GIT_CURL_VERBOSE traces to a log file,
# useful for debugging git access issues that are reproducible only on bots.
curl_trace_file = None
if api.properties.get('use_curl_trace'):
curl_trace_file = api.path['start_dir'].join('curl_trace.log')
submodule_update_force = api.properties.get('submodule_update_force', False)
submodule_update_recursive = api.properties.get('submodule_update_recursive',
True)
# You can use api.git.checkout to perform all the steps of a safe checkout.
revision = (api.buildbucket.gitiles_commit.ref or
api.buildbucket.gitiles_commit.id)
retVal = api.git.checkout(
url,
ref=revision,
recursive=True,
submodule_update_force=submodule_update_force,
set_got_revision=api.properties.get('set_got_revision'),
curl_trace_file=curl_trace_file,
remote_name=api.properties.get('remote_name'),
display_fetch_size=api.properties.get('display_fetch_size'),
file_name=api.properties.get('checkout_file_name'),
submodule_update_recursive=submodule_update_recursive,
use_git_cache=api.properties.get('use_git_cache'),
tags=api.properties.get('tags'))
assert retVal == "deadbeef", (
"expected retVal to be %r but was %r" % ("deadbeef", retVal))
# count_objects shows number and size of objects in .git dir.
api.git.count_objects(
name='count-objects',
can_fail_build=api.properties.get('count_objects_can_fail_build'),
git_config_options={'foo': 'bar'})
# Get the remote URL.
api.git.get_remote_url(
step_test_data=lambda: api.raw_io.test_api.stream_output('foo'))
api.git.get_timestamp(test_data='foo')
# You can use api.git.fetch_tags to fetch all tags from the remote
api.git.fetch_tags(api.properties.get('remote_name'))
# If you need to run more arbitrary git commands, you can use api.git itself,
# which behaves like api.step(), but automatically sets the name of the step.
with api.context(cwd=api.path['checkout']):
api.git('status')
api.git('status', name='git status can_fail_build',
can_fail_build=True)
api.git('status', name='git status cannot_fail_build',
can_fail_build=False)
# You should run git new-branch before you upload something with git cl.
api.git.new_branch('refactor') # Upstream is origin/master by default.
# And use upstream kwarg to set up different upstream for tracking.
api.git.new_branch('feature', upstream='refactor')
# You can use api.git.rebase to rebase the current branch onto another one
api.git.rebase(name_prefix='my repo', branch='origin/master',
dir_path=api.path['checkout'],
remote_name=api.properties.get('remote_name'))
if api.properties.get('cat_file', None):
step_result = api.git.cat_file_at_commit(api.properties['cat_file'],
revision,
stdout=api.raw_io.output())
if 'TestOutput' in step_result.stdout:
pass # Success!
# Bundle the repository.
api.git.bundle_create(
api.path['start_dir'].join('all.bundle'))
def GenTests(api):
yield api.test('basic')
yield api.test('basic_tags') + api.properties(tags=True)
yield api.test('basic_ref') + api.buildbucket.ci_build(git_ref='refs/foo/bar')
yield api.test('basic_branch') + api.buildbucket.ci_build(
git_ref='refs/heads/testing')
yield api.test('basic_hash') + api.buildbucket.ci_build(
revision='abcdef0123456789abcdef0123456789abcdef01', git_ref=None)
yield api.test('basic_file_name') + api.properties(checkout_file_name='DEPS')
yield api.test('basic_submodule_update_force') + api.properties(
submodule_update_force=True)
yield api.test('platform_win') + api.platform.name('win')
yield (
api.test('curl_trace_file') +
api.properties(use_curl_trace=True) +
api.buildbucket.ci_build(git_ref='refs/foo/bar')
)
yield (
api.test('can_fail_build') +
api.step_data('git status can_fail_build', retcode=1)
)
yield (
api.test('cannot_fail_build') +
api.step_data('git status cannot_fail_build', retcode=1)
)
yield (
api.test('set_got_revision') +
api.properties(set_got_revision=True)
)
yield (
api.test('rebase_failed') +
api.step_data('my repo rebase', retcode=1)
)
yield api.test('remote_not_origin') + api.properties(remote_name='not_origin')
yield (
api.test('count-objects_delta') +
api.properties(display_fetch_size=True))
yield (
api.test('count-objects_failed') +
api.step_data('count-objects', retcode=1))
yield (
api.test('count-objects_with_bad_output') +
api.step_data(
'count-objects',
stdout=api.raw_io.output(api.git.count_objects_output('xxx'))))
yield (
api.test('count-objects_with_bad_output_fails_build') +
api.step_data(
'count-objects',
stdout=api.raw_io.output(api.git.count_objects_output('xxx'))) +
api.properties(count_objects_can_fail_build=True))
yield (
api.test('cat-file_test') +
api.step_data('git cat-file abcdef12345:TestFile',
stdout=api.raw_io.output('TestOutput')) +
api.buildbucket.ci_build(revision='abcdef12345', git_ref=None) +
api.properties(cat_file='TestFile'))
yield (
api.test('git-cache-checkout') +
api.properties(use_git_cache=True))
| endlessm/chromium-browser | third_party/depot_tools/recipes/recipe_modules/git/examples/full.py | Python | bsd-3-clause | 5,942 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/shell/content/client/shell_browser_main_parts.h"
#include <memory>
#include <utility>
#include "ash/display/privacy_screen_controller.h"
#include "ash/login_status.h"
#include "ash/public/cpp/event_rewriter_controller.h"
#include "ash/session/test_pref_service_provider.h"
#include "ash/shell.h"
#include "ash/shell/content/client/shell_new_window_delegate.h"
#include "ash/shell/content/embedded_browser.h"
#include "ash/shell/example_app_list_client.h"
#include "ash/shell/example_session_controller_client.h"
#include "ash/shell/shell_delegate_impl.h"
#include "ash/shell/shell_views_delegate.h"
#include "ash/shell/window_type_launcher.h"
#include "ash/shell/window_watcher.h"
#include "ash/sticky_keys/sticky_keys_controller.h"
#include "ash/test/ash_test_helper.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/run_loop.h"
#include "chromeos/dbus/biod/biod_client.h"
#include "chromeos/dbus/shill/shill_clients.h"
#include "chromeos/network/network_handler.h"
#include "components/exo/file_helper.h"
#include "content/public/browser/context_factory.h"
#include "content/public/common/content_switches.h"
#include "content/shell/browser/shell_browser_context.h"
#include "net/base/net_module.h"
#include "ui/base/ui_base_features.h"
#include "ui/chromeos/events/event_rewriter_chromeos.h"
#include "ui/views/examples/examples_window_with_content.h"
namespace ash {
namespace shell {
namespace {
ShellBrowserMainParts* main_parts = nullptr;
}
// static
content::BrowserContext* ShellBrowserMainParts::GetBrowserContext() {
DCHECK(main_parts);
return main_parts->browser_context();
}
ShellBrowserMainParts::ShellBrowserMainParts(
const content::MainFunctionParams& parameters)
: parameters_(parameters) {
DCHECK(!main_parts);
main_parts = this;
}
ShellBrowserMainParts::~ShellBrowserMainParts() {
DCHECK(main_parts);
main_parts = nullptr;
}
void ShellBrowserMainParts::PostEarlyInitialization() {
content::BrowserMainParts::PostEarlyInitialization();
chromeos::shill_clients::InitializeFakes();
chromeos::NetworkHandler::Initialize();
}
void ShellBrowserMainParts::PreMainMessageLoopStart() {}
void ShellBrowserMainParts::PostMainMessageLoopStart() {
chromeos::BiodClient::InitializeFake();
}
void ShellBrowserMainParts::ToolkitInitialized() {
// A ViewsDelegate is required.
views_delegate_ = std::make_unique<ShellViewsDelegate>();
}
void ShellBrowserMainParts::PreMainMessageLoopRun() {
browser_context_.reset(new content::ShellBrowserContext(false));
if (!parameters_.ui_task)
new_window_delegate_ = std::make_unique<ShellNewWindowDelegate>();
// TODO(oshima): Separate the class for ash_shell to reduce the test binary
// size.
ash_test_helper_ = std::make_unique<AshTestHelper>(
parameters_.ui_task ? AshTestHelper::kPerfTest : AshTestHelper::kShell,
content::GetContextFactory());
AshTestHelper::InitParams init_params;
init_params.delegate = std::make_unique<ShellDelegateImpl>();
ash_test_helper_->SetUp(std::move(init_params));
window_watcher_ = std::make_unique<WindowWatcher>();
Shell::Get()->InitWaylandServer(nullptr);
if (!parameters_.ui_task) {
// Install Rewriter so that function keys are properly re-mapped.
auto* event_rewriter_controller = EventRewriterController::Get();
bool privacy_screen_supported = false;
if (Shell::Get()->privacy_screen_controller() &&
Shell::Get()->privacy_screen_controller()->IsSupported()) {
privacy_screen_supported = true;
}
event_rewriter_controller->AddEventRewriter(
std::make_unique<ui::EventRewriterChromeOS>(
nullptr, Shell::Get()->sticky_keys_controller(),
privacy_screen_supported));
// Initialize session controller client and create fake user sessions. The
// fake user sessions makes ash into the logged in state.
example_session_controller_client_ =
std::make_unique<ExampleSessionControllerClient>(
Shell::Get()->session_controller(),
ash_test_helper_->prefs_provider());
example_session_controller_client_->Initialize();
example_app_list_client_ = std::make_unique<ExampleAppListClient>(
Shell::Get()->app_list_controller());
InitWindowTypeLauncher(
base::BindRepeating(views::examples::ShowExamplesWindowWithContent,
base::Passed(base::OnceClosure()),
base::Unretained(browser_context_.get()), nullptr),
base::BindRepeating(base::IgnoreResult(&EmbeddedBrowser::Create),
base::Unretained(browser_context_.get()),
GURL("https://www.google.com"), base::nullopt));
}
}
bool ShellBrowserMainParts::MainMessageLoopRun(int* result_code) {
if (parameters_.ui_task) {
std::move(*parameters_.ui_task).Run();
delete parameters_.ui_task;
} else {
base::RunLoop run_loop;
example_session_controller_client_->set_quit_closure(
run_loop.QuitWhenIdleClosure());
run_loop.Run();
}
return true;
}
void ShellBrowserMainParts::PostMainMessageLoopRun() {
window_watcher_.reset();
example_app_list_client_.reset();
example_session_controller_client_.reset();
ash_test_helper_.reset();
views_delegate_.reset();
// The keyboard may have created a WebContents. The WebContents is destroyed
// with the UI, and it needs the BrowserContext to be alive during its
// destruction. So destroy all of the UI elements before destroying the
// browser context.
browser_context_.reset();
}
void ShellBrowserMainParts::PostDestroyThreads() {
chromeos::NetworkHandler::Shutdown();
chromeos::shill_clients::Shutdown();
content::BrowserMainParts::PostDestroyThreads();
}
} // namespace shell
} // namespace ash
| endlessm/chromium-browser | ash/shell/content/client/shell_browser_main_parts.cc | C++ | bsd-3-clause | 5,973 |
#!/usr/bin/env node
var fs = require("fs"),
_ = require("underscore"),
express = require("express"),
redis = require("redis"),
mongo = require("mongoskin"),
connect_redis = require("connect-redis")(express),
everyauth = require("everyauth");
shortid = require("shortid"),
mediainfo = require("mediainfo"),
common = require("./lib/common");
common.ctx.add_function("nice_time", function(input, args) {
return (input || "").toString();
});
var rds = redis.createClient();
var db = mongo.db(process.env.MONGODB),
clips = db.collection("clips"),
users = db.collection("users");
clips.ensureIndex({id: 1}, {unique: true}, function(){});
users.ensureIndex({id: 1}, {unique: true}, function(){});
everyauth.everymodule.findUserById(function(id, done) {
users.findOne({id: id}, done);
});
everyauth.twitter.consumerKey("jdlTWPGKYNZqUTyvENmdcw").consumerSecret("drEQioZFW3UwMOWbr3P7jdr2nzSIPa1VHBBQbIjs").findOrCreateUser(function(session, access_token, access_token_secret, metadata) {
var promise = this.Promise();
users.findOne({id: metadata.id}, {_id: false}, function(err, doc) {
if (err) {
throw err;
}
if (doc) {
promise.fulfill(doc);
} else {
var user = {
id: metadata.id,
name: metadata.screen_name,
created_at: new Date(),
friends: [],
};
users.save(user, {safe: true}, function(err, doc) {
if (err) {
throw err;
}
promise.fulfill(doc);
});
}
});
return promise;
}).redirectPath("/");
var app = express.createServer();
app.configure(function() {
app.use(function(req, res, next) {
for (var i in common) {
res[i] = common[i];
}
next();
});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({secret: "sillysession", store: new connect_redis()}));
app.use(everyauth.middleware());
app.use(express.static(__dirname + "/public"));
app.use(express.logger());
});
app.get("/", function(req, res) {
res.send_response("pages/index.html", {app: {user: req.user}, page: {title: "Home"}});
});
app.get("/clips", function(req, res) {
clips.find(null, {_id: false}).sort({created_at: -1}).limit(10).toArray(function(err, docs) {
if (err) {
return res.send(500);
}
res.send_response("pages/clips/list.html", {app: {user: req.user}, page: {title: "Clips"}, clips: docs});
});
});
app.get("/clips/mine", common.ensure_logged_in, function(req, res) {
clips.find({app: {user: req.user}.name}, {_id: false}).sort({created_at: -1}).limit(10).toArray(function(err, docs) {
if (err) {
return res.send(500);
}
res.send_response("pages/clips/list.html", {app: {user: req.user}, page: {title: "My Clips"}, clips: docs});
});
});
app.get("/clips/upload", common.ensure_logged_in, function(req, res) {
res.send_response("pages/clips/upload.html", {app: {user: req.user}, page: {title: "Upload Clip"}});
});
app.get("/clips/:id", function(req, res) {
clips.findOne({id: req.param("id")}, {_id: false}, function(err, doc) {
if (err) {
return res.send(500);
}
if (!doc) {
return res.send(404);
}
return res.send_response("pages/clips/view.html", {app: {user: req.user}, page: {title: doc.name}, clip: doc});
});
});
app.post("/clips", common.ensure_logged_in, function(req, res) {
var doc = req.body;
doc.id = shortid.generate();
doc.created_at = new Date();
doc.created_by = req.user.name;
doc.formats = [];
doc.encoded = false;
if (!req.files || !req.files.file) {
return res.send(406);
}
mediainfo(req.files.file.path, function(err, info) {
if (err) {
return res.send(500);
}
fs.rename(req.files.file.path, __dirname + "/uploads/" + doc.id, function(err) {
if (err) {
return res.send(500);
}
clips.save(doc, {safe: true}, function(err, doc) {
if (err) {
return res.send(500);
}
rds.rpush("riffmint_encoding", [doc.id, "libvorbis", "ogg"].join(":"));
rds.rpush("riffmint_encoding", [doc.id, "libmp3lame", "mp3"].join(":"));
return res.redirect("/clips/" + doc.id);
});
});
});
});
app.get("/download/:id.:format", function(req, res) {
clips.findOne({id: req.param("id")}, {_id: false}, function(err, doc) {
if (err) {
return res.send(500);
}
if (!doc) {
return res.send(404);
}
if (_.indexOf(doc.formats, req.param("format")) === -1) {
return res.send(404);
}
res.setHeader("Content-Type", "audio/" + req.param("format"));
res.sendfile("downloads/" + req.param("id") + "." + req.param("format"));
});
});
app.get("/:user", function(req, res) {
users.findOne({name: req.param("user")}, function(err, doc) {
if (err) {
return res.send(500);
}
if (!doc) {
return res.send(404);
}
return res.send_response("pages/user/view.html", {});
});
});
app.listen(process.env.PORT, process.env.HOST);
| deoxxa/riffmint | app.js | JavaScript | bsd-3-clause | 5,087 |
/*
*
* Copyright 2015, Google Inc.
* 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 Google Inc. 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.
*
*/
#include <cctype>
#include <map>
#include <vector>
#include "src/compiler/config.h"
#include "src/compiler/csharp_generator_helpers.h"
#include "src/compiler/csharp_generator.h"
using grpc::protobuf::FileDescriptor;
using grpc::protobuf::Descriptor;
using grpc::protobuf::ServiceDescriptor;
using grpc::protobuf::MethodDescriptor;
using grpc::protobuf::io::Printer;
using grpc::protobuf::io::StringOutputStream;
using grpc_generator::MethodType;
using grpc_generator::GetMethodType;
using grpc_generator::METHODTYPE_NO_STREAMING;
using grpc_generator::METHODTYPE_CLIENT_STREAMING;
using grpc_generator::METHODTYPE_SERVER_STREAMING;
using grpc_generator::METHODTYPE_BIDI_STREAMING;
using grpc_generator::StringReplace;
using std::map;
using std::vector;
namespace grpc_csharp_generator {
namespace {
// TODO(jtattermusch): make GetFileNamespace part of libprotoc public API.
// NOTE: Implementation needs to match exactly to GetFileNamespace
// defined in csharp_helpers.h in protoc csharp plugin.
// We cannot reference it directly because google3 protobufs
// don't have a csharp protoc plugin.
std::string GetFileNamespace(const FileDescriptor* file) {
if (file->options().has_csharp_namespace()) {
return file->options().csharp_namespace();
}
return file->package();
}
std::string ToCSharpName(const std::string& name, const FileDescriptor* file) {
std::string result = GetFileNamespace(file);
if (result != "") {
result += '.';
}
std::string classname;
if (file->package().empty()) {
classname = name;
} else {
// Strip the proto package from full_name since we've replaced it with
// the C# namespace.
classname = name.substr(file->package().size() + 1);
}
result += StringReplace(classname, ".", ".Types.", false);
return "global::" + result;
}
// TODO(jtattermusch): make GetClassName part of libprotoc public API.
// NOTE: Implementation needs to match exactly to GetClassName
// defined in csharp_helpers.h in protoc csharp plugin.
// We cannot reference it directly because google3 protobufs
// don't have a csharp protoc plugin.
std::string GetClassName(const Descriptor* message) {
return ToCSharpName(message->full_name(), message->file());
}
std::string GetServiceClassName(const ServiceDescriptor* service) {
return service->name();
}
std::string GetClientInterfaceName(const ServiceDescriptor* service) {
return "I" + service->name() + "Client";
}
std::string GetClientClassName(const ServiceDescriptor* service) {
return service->name() + "Client";
}
std::string GetServerInterfaceName(const ServiceDescriptor* service) {
return "I" + service->name();
}
std::string GetCSharpMethodType(MethodType method_type) {
switch (method_type) {
case METHODTYPE_NO_STREAMING:
return "MethodType.Unary";
case METHODTYPE_CLIENT_STREAMING:
return "MethodType.ClientStreaming";
case METHODTYPE_SERVER_STREAMING:
return "MethodType.ServerStreaming";
case METHODTYPE_BIDI_STREAMING:
return "MethodType.DuplexStreaming";
}
GOOGLE_LOG(FATAL)<< "Can't get here.";
return "";
}
std::string GetServiceNameFieldName() {
return "__ServiceName";
}
std::string GetMarshallerFieldName(const Descriptor *message) {
return "__Marshaller_" + message->name();
}
std::string GetMethodFieldName(const MethodDescriptor *method) {
return "__Method_" + method->name();
}
std::string GetMethodRequestParamMaybe(const MethodDescriptor *method) {
if (method->client_streaming()) {
return "";
}
return GetClassName(method->input_type()) + " request, ";
}
std::string GetMethodReturnTypeClient(const MethodDescriptor *method) {
switch (GetMethodType(method)) {
case METHODTYPE_NO_STREAMING:
return "AsyncUnaryCall<" + GetClassName(method->output_type()) + ">";
case METHODTYPE_CLIENT_STREAMING:
return "AsyncClientStreamingCall<" + GetClassName(method->input_type())
+ ", " + GetClassName(method->output_type()) + ">";
case METHODTYPE_SERVER_STREAMING:
return "AsyncServerStreamingCall<" + GetClassName(method->output_type())
+ ">";
case METHODTYPE_BIDI_STREAMING:
return "AsyncDuplexStreamingCall<" + GetClassName(method->input_type())
+ ", " + GetClassName(method->output_type()) + ">";
}
GOOGLE_LOG(FATAL)<< "Can't get here.";
return "";
}
std::string GetMethodRequestParamServer(const MethodDescriptor *method) {
switch (GetMethodType(method)) {
case METHODTYPE_NO_STREAMING:
case METHODTYPE_SERVER_STREAMING:
return GetClassName(method->input_type()) + " request";
case METHODTYPE_CLIENT_STREAMING:
case METHODTYPE_BIDI_STREAMING:
return "IAsyncStreamReader<" + GetClassName(method->input_type())
+ "> requestStream";
}
GOOGLE_LOG(FATAL)<< "Can't get here.";
return "";
}
std::string GetMethodReturnTypeServer(const MethodDescriptor *method) {
switch (GetMethodType(method)) {
case METHODTYPE_NO_STREAMING:
case METHODTYPE_CLIENT_STREAMING:
return "Task<" + GetClassName(method->output_type()) + ">";
case METHODTYPE_SERVER_STREAMING:
case METHODTYPE_BIDI_STREAMING:
return "Task";
}
GOOGLE_LOG(FATAL)<< "Can't get here.";
return "";
}
std::string GetMethodResponseStreamMaybe(const MethodDescriptor *method) {
switch (GetMethodType(method)) {
case METHODTYPE_NO_STREAMING:
case METHODTYPE_CLIENT_STREAMING:
return "";
case METHODTYPE_SERVER_STREAMING:
case METHODTYPE_BIDI_STREAMING:
return ", IServerStreamWriter<" + GetClassName(method->output_type())
+ "> responseStream";
}
GOOGLE_LOG(FATAL)<< "Can't get here.";
return "";
}
// Gets vector of all messages used as input or output types.
std::vector<const Descriptor*> GetUsedMessages(
const ServiceDescriptor *service) {
std::set<const Descriptor*> descriptor_set;
std::vector<const Descriptor*> result; // vector is to maintain stable ordering
for (int i = 0; i < service->method_count(); i++) {
const MethodDescriptor *method = service->method(i);
if (descriptor_set.find(method->input_type()) == descriptor_set.end()) {
descriptor_set.insert(method->input_type());
result.push_back(method->input_type());
}
if (descriptor_set.find(method->output_type()) == descriptor_set.end()) {
descriptor_set.insert(method->output_type());
result.push_back(method->output_type());
}
}
return result;
}
void GenerateMarshallerFields(Printer* out, const ServiceDescriptor *service) {
std::vector<const Descriptor*> used_messages = GetUsedMessages(service);
for (size_t i = 0; i < used_messages.size(); i++) {
const Descriptor *message = used_messages[i];
out->Print(
"static readonly Marshaller<$type$> $fieldname$ = Marshallers.Create((arg) => arg.ToByteArray(), $type$.ParseFrom);\n",
"fieldname", GetMarshallerFieldName(message), "type",
GetClassName(message));
}
out->Print("\n");
}
void GenerateStaticMethodField(Printer* out, const MethodDescriptor *method) {
out->Print(
"static readonly Method<$request$, $response$> $fieldname$ = new Method<$request$, $response$>(\n",
"fieldname", GetMethodFieldName(method), "request",
GetClassName(method->input_type()), "response",
GetClassName(method->output_type()));
out->Indent();
out->Indent();
out->Print("$methodtype$,\n", "methodtype",
GetCSharpMethodType(GetMethodType(method)));
out->Print("\"$methodname$\",\n", "methodname", method->name());
out->Print("$requestmarshaller$,\n", "requestmarshaller",
GetMarshallerFieldName(method->input_type()));
out->Print("$responsemarshaller$);\n", "responsemarshaller",
GetMarshallerFieldName(method->output_type()));
out->Print("\n");
out->Outdent();
out->Outdent();
}
void GenerateClientInterface(Printer* out, const ServiceDescriptor *service) {
out->Print("// client interface\n");
out->Print("public interface $name$\n", "name",
GetClientInterfaceName(service));
out->Print("{\n");
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
const MethodDescriptor *method = service->method(i);
MethodType method_type = GetMethodType(method);
if (method_type == METHODTYPE_NO_STREAMING) {
// unary calls have an extra synchronous stub method
out->Print(
"$response$ $methodname$($request$ request, Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken));\n",
"methodname", method->name(), "request",
GetClassName(method->input_type()), "response",
GetClassName(method->output_type()));
}
std::string method_name = method->name();
if (method_type == METHODTYPE_NO_STREAMING) {
method_name += "Async"; // prevent name clash with synchronous method.
}
out->Print(
"$returntype$ $methodname$($request_maybe$Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken));\n",
"methodname", method_name, "request_maybe",
GetMethodRequestParamMaybe(method), "returntype",
GetMethodReturnTypeClient(method));
}
out->Outdent();
out->Print("}\n");
out->Print("\n");
}
void GenerateServerInterface(Printer* out, const ServiceDescriptor *service) {
out->Print("// server-side interface\n");
out->Print("public interface $name$\n", "name",
GetServerInterfaceName(service));
out->Print("{\n");
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
const MethodDescriptor *method = service->method(i);
out->Print("$returntype$ $methodname$($request$$response_stream_maybe$, ServerCallContext context);\n",
"methodname", method->name(), "returntype",
GetMethodReturnTypeServer(method), "request",
GetMethodRequestParamServer(method), "response_stream_maybe",
GetMethodResponseStreamMaybe(method));
}
out->Outdent();
out->Print("}\n");
out->Print("\n");
}
void GenerateClientStub(Printer* out, const ServiceDescriptor *service) {
out->Print("// client stub\n");
out->Print(
"public class $name$ : ClientBase, $interface$\n",
"name", GetClientClassName(service), "interface",
GetClientInterfaceName(service));
out->Print("{\n");
out->Indent();
// constructors
out->Print(
"public $name$(Channel channel) : base(channel)\n",
"name", GetClientClassName(service));
out->Print("{\n");
out->Print("}\n");
for (int i = 0; i < service->method_count(); i++) {
const MethodDescriptor *method = service->method(i);
MethodType method_type = GetMethodType(method);
if (method_type == METHODTYPE_NO_STREAMING) {
// unary calls have an extra synchronous stub method
out->Print(
"public $response$ $methodname$($request$ request, Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken))\n",
"methodname", method->name(), "request",
GetClassName(method->input_type()), "response",
GetClassName(method->output_type()));
out->Print("{\n");
out->Indent();
out->Print("var call = CreateCall($servicenamefield$, $methodfield$, headers);\n",
"servicenamefield", GetServiceNameFieldName(), "methodfield",
GetMethodFieldName(method));
out->Print("return Calls.BlockingUnaryCall(call, request, cancellationToken);\n");
out->Outdent();
out->Print("}\n");
}
std::string method_name = method->name();
if (method_type == METHODTYPE_NO_STREAMING) {
method_name += "Async"; // prevent name clash with synchronous method.
}
out->Print(
"public $returntype$ $methodname$($request_maybe$Metadata headers = null, CancellationToken cancellationToken = default(CancellationToken))\n",
"methodname", method_name, "request_maybe",
GetMethodRequestParamMaybe(method), "returntype",
GetMethodReturnTypeClient(method));
out->Print("{\n");
out->Indent();
out->Print("var call = CreateCall($servicenamefield$, $methodfield$, headers);\n",
"servicenamefield", GetServiceNameFieldName(), "methodfield",
GetMethodFieldName(method));
switch (GetMethodType(method)) {
case METHODTYPE_NO_STREAMING:
out->Print("return Calls.AsyncUnaryCall(call, request, cancellationToken);\n");
break;
case METHODTYPE_CLIENT_STREAMING:
out->Print("return Calls.AsyncClientStreamingCall(call, cancellationToken);\n");
break;
case METHODTYPE_SERVER_STREAMING:
out->Print(
"return Calls.AsyncServerStreamingCall(call, request, cancellationToken);\n");
break;
case METHODTYPE_BIDI_STREAMING:
out->Print("return Calls.AsyncDuplexStreamingCall(call, cancellationToken);\n");
break;
default:
GOOGLE_LOG(FATAL)<< "Can't get here.";
}
out->Outdent();
out->Print("}\n");
}
out->Outdent();
out->Print("}\n");
out->Print("\n");
}
void GenerateBindServiceMethod(Printer* out, const ServiceDescriptor *service) {
out->Print(
"// creates service definition that can be registered with a server\n");
out->Print(
"public static ServerServiceDefinition BindService($interface$ serviceImpl)\n",
"interface", GetServerInterfaceName(service));
out->Print("{\n");
out->Indent();
out->Print(
"return ServerServiceDefinition.CreateBuilder($servicenamefield$)\n",
"servicenamefield", GetServiceNameFieldName());
out->Indent();
out->Indent();
for (int i = 0; i < service->method_count(); i++) {
const MethodDescriptor *method = service->method(i);
out->Print(".AddMethod($methodfield$, serviceImpl.$methodname$)",
"methodfield", GetMethodFieldName(method), "methodname",
method->name());
if (i == service->method_count() - 1) {
out->Print(".Build();");
}
out->Print("\n");
}
out->Outdent();
out->Outdent();
out->Outdent();
out->Print("}\n");
out->Print("\n");
}
void GenerateNewStubMethods(Printer* out, const ServiceDescriptor *service) {
out->Print("// creates a new client\n");
out->Print("public static $classname$ NewClient(Channel channel)\n",
"classname", GetClientClassName(service));
out->Print("{\n");
out->Indent();
out->Print("return new $classname$(channel);\n", "classname",
GetClientClassName(service));
out->Outdent();
out->Print("}\n");
out->Print("\n");
}
void GenerateService(Printer* out, const ServiceDescriptor *service) {
out->Print("public static class $classname$\n", "classname",
GetServiceClassName(service));
out->Print("{\n");
out->Indent();
out->Print("static readonly string $servicenamefield$ = \"$servicename$\";\n",
"servicenamefield", GetServiceNameFieldName(), "servicename",
service->full_name());
out->Print("\n");
GenerateMarshallerFields(out, service);
for (int i = 0; i < service->method_count(); i++) {
GenerateStaticMethodField(out, service->method(i));
}
GenerateClientInterface(out, service);
GenerateServerInterface(out, service);
GenerateClientStub(out, service);
GenerateBindServiceMethod(out, service);
GenerateNewStubMethods(out, service);
out->Outdent();
out->Print("}\n");
}
} // anonymous namespace
grpc::string GetServices(const FileDescriptor *file) {
grpc::string output;
{
// Scope the output stream so it closes and finalizes output to the string.
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
// Don't write out any output if there no services, to avoid empty service
// files being generated for proto files that don't declare any.
if (file->service_count() == 0) {
return output;
}
// Write out a file header.
out.Print("// Generated by the protocol buffer compiler. DO NOT EDIT!\n");
out.Print("// source: $filename$\n", "filename", file->name());
out.Print("#region Designer generated code\n");
out.Print("\n");
out.Print("using System;\n");
out.Print("using System.Threading;\n");
out.Print("using System.Threading.Tasks;\n");
out.Print("using Grpc.Core;\n");
// TODO(jtattermusch): add using for protobuf message classes
out.Print("\n");
out.Print("namespace $namespace$ {\n", "namespace", GetFileNamespace(file));
out.Indent();
for (int i = 0; i < file->service_count(); i++) {
GenerateService(&out, file->service(i));
}
out.Outdent();
out.Print("}\n");
out.Print("#endregion\n");
}
return output;
}
} // namespace grpc_csharp_generator
| meisterpeeps/grpc | src/compiler/csharp_generator.cc | C++ | bsd-3-clause | 18,320 |
// Copyright (c) 2009, Object Computing, Inc.
// All rights reserved.
// See the file license.txt for licensing information.
#ifdef _MSC_VER
# pragma once
#endif
#ifndef COMMANDARGHANDLER_H
#define COMMANDARGHANDLER_H
namespace QuickFAST
{
/// @brief Abstract interface to be implemented by objects
/// that handle command line options.
class CommandArgHandler
{
public:
/// @brief Parse a single argument from the command line.
///
/// Each call should consume one logical argument. You will be called again
/// to consume subsequent arguments. For example if your implementation accepts
/// arguments -f [file] and -v, and argc is -f output -x -v you should interpret
/// [-f output] and return 2. Do NOT go looking for the -v.
/// @param argc the count of remaining, unparsed arguments
/// @param argv the remaining, unparsed arguments from the command line
/// @return the number of arguments consumed. 0 means argv[0] was not recognized.
virtual int parseSingleArg(int argc, char * argv[]) = 0;
/// @brief Report command line arguments recognized by this handler.
/// @param out is the device to which the known arguments should be reported.
virtual void usage(std::ostream & out) const = 0;
/// @brief After all arguments a parsed apply them.
///
/// This will be called only if all arguments are parsed successfully.
/// @returns true if successful
virtual bool applyArgs() = 0;
};
}
#endif // COMMANDARGHANDLER_H
| alepharchives/quickfast | src/Examples/Examples/CommandArgHandler.h | C | bsd-3-clause | 1,511 |
/*
* Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
* Copyright (c) 1993, 1994, 1995 Rick Sladkey <jrs@world.std.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
[ 0] = { 0, 0, SEN(restart_syscall), "restart_syscall" },
[ 1] = { 1, TP|SE, SEN(exit), "exit" },
[ 2] = { 0, TP, SEN(fork), "fork" },
[ 3] = { 3, TD, SEN(read), "read" },
[ 4] = { 3, TD, SEN(write), "write" },
[ 5] = { 3, TD|TF, SEN(open), "open" },
[ 6] = { 1, TD, SEN(close), "close" },
[ 7] = { 3, TP, SEN(waitpid), "waitpid" },
[ 8] = { 2, TD|TF, SEN(creat), "creat" },
[ 9] = { 2, TF, SEN(link), "link" },
[ 10] = { 1, TF, SEN(unlink), "unlink" },
[ 11] = { 3, TF|TP|SE|SI, SEN(execve), "execve" },
[ 12] = { 1, TF, SEN(chdir), "chdir" },
[ 13] = { 1, 0, SEN(time), "time" },
[ 14] = { 3, TF, SEN(mknod), "mknod" },
[ 15] = { 2, TF, SEN(chmod), "chmod" },
[ 16] = { 3, TF, SEN(chown), "lchown" },
[ 17] = { 0, TM, SEN(break), "break" },
[ 18] = { 2, TF, SEN(oldstat), "oldstat" },
[ 19] = { 3, TD, SEN(lseek), "lseek" },
[ 20] = { 0, 0, SEN(getpid), "getpid" },
[ 21] = { 5, TF, SEN(mount), "mount" },
[ 22] = { 1, TF, SEN(umount), "umount" },
[ 23] = { 1, 0, SEN(setuid), "setuid" },
[ 24] = { 0, NF, SEN(getuid), "getuid" },
[ 25] = { 1, 0, SEN(stime), "stime" },
[ 26] = { 4, 0, SEN(ptrace), "ptrace" },
[ 27] = { 1, 0, SEN(alarm), "alarm" },
[ 28] = { 2, TD, SEN(oldfstat), "oldfstat" },
[ 29] = { 0, TS, SEN(pause), "pause" },
[ 30] = { 2, TF, SEN(utime), "utime" },
[ 31] = { 2, 0, SEN(stty), "stty" },
[ 32] = { 2, 0, SEN(gtty), "gtty" },
[ 33] = { 2, TF, SEN(access), "access" },
[ 34] = { 1, 0, SEN(nice), "nice" },
[ 35] = { 0, 0, SEN(ftime), "ftime" },
[ 36] = { 0, 0, SEN(sync), "sync" },
[ 37] = { 2, TS, SEN(kill), "kill" },
[ 38] = { 2, TF, SEN(rename), "rename" },
[ 39] = { 2, TF, SEN(mkdir), "mkdir" },
[ 40] = { 1, TF, SEN(rmdir), "rmdir" },
[ 41] = { 1, TD, SEN(dup), "dup" },
[ 42] = { 1, TD, SEN(pipe), "pipe" },
[ 43] = { 1, 0, SEN(times), "times" },
[ 44] = { 0, 0, SEN(prof), "prof" },
[ 45] = { 1, TM|SI, SEN(brk), "brk" },
[ 46] = { 1, 0, SEN(setgid), "setgid" },
[ 47] = { 0, NF, SEN(getgid), "getgid" },
[ 48] = { 3, TS, SEN(signal), "signal" },
[ 49] = { 0, NF, SEN(geteuid), "geteuid" },
[ 50] = { 0, NF, SEN(getegid), "getegid" },
[ 51] = { 1, TF, SEN(acct), "acct" },
[ 52] = { 2, TF, SEN(umount2), "umount2" },
[ 53] = { 0, 0, SEN(lock), "lock" },
[ 54] = { 3, TD, SEN(ioctl), "ioctl" },
[ 55] = { 3, TD, SEN(fcntl), "fcntl" },
[ 56] = { 0, 0, SEN(mpx), "mpx" },
[ 57] = { 2, 0, SEN(setpgid), "setpgid" },
[ 58] = { 2, 0, SEN(ulimit), "ulimit" },
[ 59] = { 1, 0, SEN(oldolduname), "oldolduname" },
[ 60] = { 1, 0, SEN(umask), "umask" },
[ 61] = { 1, TF, SEN(chroot), "chroot" },
[ 62] = { 2, 0, SEN(ustat), "ustat" },
[ 63] = { 2, TD, SEN(dup2), "dup2" },
[ 64] = { 0, 0, SEN(getppid), "getppid" },
[ 65] = { 0, 0, SEN(getpgrp), "getpgrp" },
[ 66] = { 0, 0, SEN(setsid), "setsid" },
[ 67] = { 3, TS, SEN(sigaction), "sigaction" },
[ 68] = { 0, TS, SEN(siggetmask), "sgetmask" },
[ 69] = { 1, TS, SEN(sigsetmask), "ssetmask" },
[ 70] = { 2, 0, SEN(setreuid), "setreuid" },
[ 71] = { 2, 0, SEN(setregid), "setregid" },
[ 72] = { 3, TS, SEN(sigsuspend), "sigsuspend" },
[ 73] = { 1, TS, SEN(sigpending), "sigpending" },
[ 74] = { 2, 0, SEN(sethostname), "sethostname" },
[ 75] = { 2, 0, SEN(setrlimit), "setrlimit" },
[ 76] = { 2, 0, SEN(getrlimit), "getrlimit" },
[ 77] = { 2, 0, SEN(getrusage), "getrusage" },
[ 78] = { 2, 0, SEN(gettimeofday), "gettimeofday" },
[ 79] = { 2, 0, SEN(settimeofday), "settimeofday" },
[ 80] = { 2, 0, SEN(getgroups), "getgroups" },
[ 81] = { 2, 0, SEN(setgroups), "setgroups" },
[ 82] = { 1, TD, SEN(oldselect), "select" },
[ 83] = { 2, TF, SEN(symlink), "symlink" },
[ 84] = { 2, TF, SEN(oldlstat), "oldlstat" },
[ 85] = { 3, TF, SEN(readlink), "readlink" },
[ 86] = { 1, TF, SEN(uselib), "uselib" },
[ 87] = { 2, TF, SEN(swapon), "swapon" },
[ 88] = { 4, 0, SEN(reboot), "reboot" },
[ 89] = { 3, TD, SEN(readdir), "readdir" },
[ 90] = { 6, TD|TM|SI, SEN(mmap), "mmap" },
[ 91] = { 2, TM|SI, SEN(munmap), "munmap" },
[ 92] = { 2, TF, SEN(truncate), "truncate" },
[ 93] = { 2, TD, SEN(ftruncate), "ftruncate" },
[ 94] = { 2, TD, SEN(fchmod), "fchmod" },
[ 95] = { 3, TD, SEN(fchown), "fchown" },
[ 96] = { 2, 0, SEN(getpriority), "getpriority" },
[ 97] = { 3, 0, SEN(setpriority), "setpriority" },
[ 98] = { 4, 0, SEN(profil), "profil" },
[ 99] = { 2, TF, SEN(statfs), "statfs" },
[100] = { 2, TD, SEN(fstatfs), "fstatfs" },
[101] = { 3, 0, SEN(ioperm), "ioperm" },
[102] = { 2, TD, SEN(socketcall), "socketcall" },
[103] = { 3, 0, SEN(syslog), "syslog" },
[104] = { 3, 0, SEN(setitimer), "setitimer" },
[105] = { 2, 0, SEN(getitimer), "getitimer" },
[106] = { 2, TF, SEN(stat), "stat" },
[107] = { 2, TF, SEN(lstat), "lstat" },
[108] = { 2, TD, SEN(fstat), "fstat" },
[109] = { 1, 0, SEN(olduname), "olduname" },
[110] = { 5, 0, SEN(printargs), "iopl" },
[111] = { 0, 0, SEN(vhangup), "vhangup" },
[112] = { 0, 0, SEN(idle), "idle" },
[113] = { 5, 0, SEN(vm86), "vm86" },
[114] = { 4, TP, SEN(wait4), "wait4" },
[115] = { 1, TF, SEN(swapoff), "swapoff" },
[116] = { 1, 0, SEN(sysinfo), "sysinfo" },
[117] = { 6, TI, SEN(ipc), "ipc" },
[118] = { 1, TD, SEN(fsync), "fsync" },
[119] = { 0, TS, SEN(sigreturn), "sigreturn" },
[120] = { 5, TP, SEN(clone), "clone" },
[121] = { 2, 0, SEN(setdomainname), "setdomainname" },
[122] = { 1, 0, SEN(uname), "uname" },
[123] = { 5, 0, SEN(printargs), "modify_ldt" },
[124] = { 1, 0, SEN(adjtimex), "adjtimex" },
[125] = { 3, TM|SI, SEN(mprotect), "mprotect" },
[126] = { 3, TS, SEN(sigprocmask), "sigprocmask" },
[127] = { 2, 0, SEN(create_module), "create_module" },
[128] = { 3, 0, SEN(init_module), "init_module" },
[129] = { 2, 0, SEN(delete_module), "delete_module" },
[130] = { 1, 0, SEN(get_kernel_syms), "get_kernel_syms" },
[131] = { 4, TF, SEN(quotactl), "quotactl" },
[132] = { 1, 0, SEN(getpgid), "getpgid" },
[133] = { 1, TD, SEN(fchdir), "fchdir" },
[134] = { 2, 0, SEN(bdflush), "bdflush" },
[135] = { 3, 0, SEN(sysfs), "sysfs" },
[136] = { 1, 0, SEN(personality), "personality" },
[137] = { 5, 0, SEN(afs_syscall), "afs_syscall" },
[138] = { 1, NF, SEN(setfsuid), "setfsuid" },
[139] = { 1, NF, SEN(setfsgid), "setfsgid" },
[140] = { 5, TD, SEN(llseek), "_llseek" },
[141] = { 3, TD, SEN(getdents), "getdents" },
[142] = { 5, TD, SEN(select), "_newselect" },
[143] = { 2, TD, SEN(flock), "flock" },
[144] = { 3, TM, SEN(msync), "msync" },
[145] = { 3, TD, SEN(readv), "readv" },
[146] = { 3, TD, SEN(writev), "writev" },
[147] = { 1, 0, SEN(getsid), "getsid" },
[148] = { 1, TD, SEN(fdatasync), "fdatasync" },
[149] = { 1, 0, SEN(sysctl), "_sysctl" },
[150] = { 2, TM, SEN(mlock), "mlock" },
[151] = { 2, TM, SEN(munlock), "munlock" },
[152] = { 1, TM, SEN(mlockall), "mlockall" },
[153] = { 0, TM, SEN(munlockall), "munlockall" },
[154] = { 2, 0, SEN(sched_setparam), "sched_setparam" },
[155] = { 2, 0, SEN(sched_getparam), "sched_getparam" },
[156] = { 3, 0, SEN(sched_setscheduler), "sched_setscheduler" },
[157] = { 1, 0, SEN(sched_getscheduler), "sched_getscheduler" },
[158] = { 0, 0, SEN(sched_yield), "sched_yield" },
[159] = { 1, 0, SEN(sched_get_priority_max), "sched_get_priority_max"},
[160] = { 1, 0, SEN(sched_get_priority_min), "sched_get_priority_min"},
[161] = { 2, 0, SEN(sched_rr_get_interval), "sched_rr_get_interval" },
[162] = { 2, 0, SEN(nanosleep), "nanosleep" },
[163] = { 5, TM|SI, SEN(mremap), "mremap" },
[164] = { 3, 0, SEN(setresuid), "setresuid" },
[165] = { 3, 0, SEN(getresuid), "getresuid" },
[166] = { 5, 0, SEN(query_module), "query_module" },
[167] = { 3, TD, SEN(poll), "poll" },
[168] = { 3, 0, SEN(nfsservctl), "nfsservctl" },
[169] = { 3, 0, SEN(setresgid), "setresgid" },
[170] = { 3, 0, SEN(getresgid), "getresgid" },
[171] = { 5, 0, SEN(prctl), "prctl" },
[172] = { 0, TS, SEN(rt_sigreturn), "rt_sigreturn" },
[173] = { 4, TS, SEN(rt_sigaction), "rt_sigaction" },
[174] = { 4, TS, SEN(rt_sigprocmask), "rt_sigprocmask" },
[175] = { 2, TS, SEN(rt_sigpending), "rt_sigpending" },
[176] = { 4, TS, SEN(rt_sigtimedwait), "rt_sigtimedwait" },
[177] = { 3, TS, SEN(rt_sigqueueinfo), "rt_sigqueueinfo" },
[178] = { 2, TS, SEN(rt_sigsuspend), "rt_sigsuspend" },
[179] = { 6, TD, SEN(pread), "pread64" },
[180] = { 6, TD, SEN(pwrite), "pwrite64" },
[181] = { 3, TF, SEN(chown), "chown" },
[182] = { 2, TF, SEN(getcwd), "getcwd" },
[183] = { 2, 0, SEN(capget), "capget" },
[184] = { 2, 0, SEN(capset), "capset" },
[185] = { 2, TS, SEN(sigaltstack), "sigaltstack" },
[186] = { 4, TD|TN, SEN(sendfile), "sendfile" },
[187] = { 5, TN, SEN(getpmsg), "getpmsg" },
[188] = { 5, TN, SEN(putpmsg), "putpmsg" },
[189] = { 0, TP, SEN(vfork), "vfork" },
[190] = { 2, 0, SEN(getrlimit), "ugetrlimit" },
[191] = { 5, TD, SEN(readahead), "readahead" },
[192 ... 197] = { },
[198] = { 5, 0, SEN(printargs), "pciconfig_read" },
[199] = { 5, 0, SEN(printargs), "pciconfig_write" },
[200] = { 3, 0, SEN(printargs), "pciconfig_iobase" },
[201] = { 6, 0, SEN(printargs), "multiplexer" },
[202] = { 3, TD, SEN(getdents64), "getdents64" },
[203] = { 2, TF, SEN(pivotroot), "pivot_root" },
[204] = { },
[205] = { 3, TM, SEN(madvise), "madvise" },
[206] = { 3, TM, SEN(mincore), "mincore" },
[207] = { 0, 0, SEN(gettid), "gettid" },
[208] = { 2, TS, SEN(kill), "tkill" },
[209] = { 5, TF, SEN(setxattr), "setxattr" },
[210] = { 5, TF, SEN(setxattr), "lsetxattr" },
[211] = { 5, TD, SEN(fsetxattr), "fsetxattr" },
[212] = { 4, TF, SEN(getxattr), "getxattr" },
[213] = { 4, TF, SEN(getxattr), "lgetxattr" },
[214] = { 4, TD, SEN(fgetxattr), "fgetxattr" },
[215] = { 3, TF, SEN(listxattr), "listxattr" },
[216] = { 3, TF, SEN(listxattr), "llistxattr" },
[217] = { 3, TD, SEN(flistxattr), "flistxattr" },
[218] = { 2, TF, SEN(removexattr), "removexattr" },
[219] = { 2, TF, SEN(removexattr), "lremovexattr" },
[220] = { 2, TD, SEN(fremovexattr), "fremovexattr" },
[221] = { 6, 0, SEN(futex), "futex" },
[222] = { 3, 0, SEN(sched_setaffinity), "sched_setaffinity" },
[223] = { 3, 0, SEN(sched_getaffinity), "sched_getaffinity" },
[224] = { },
[225] = { 5, 0, SEN(printargs), "tuxcall" },
[226] = { },
[227] = { 2, 0, SEN(io_setup), "io_setup" },
[228] = { 1, 0, SEN(io_destroy), "io_destroy" },
[229] = { 5, 0, SEN(io_getevents), "io_getevents" },
[230] = { 3, 0, SEN(io_submit), "io_submit" },
[231] = { 3, 0, SEN(io_cancel), "io_cancel" },
[232] = { 1, 0, SEN(set_tid_address), "set_tid_address" },
[233] = { 6, TD, SEN(fadvise64), "fadvise64" },
[234] = { 1, TP|SE, SEN(exit), "exit_group" },
[235] = { 4, 0, SEN(lookup_dcookie), "lookup_dcookie" },
[236] = { 1, TD, SEN(epoll_create), "epoll_create" },
[237] = { 4, TD, SEN(epoll_ctl), "epoll_ctl" },
[238] = { 4, TD, SEN(epoll_wait), "epoll_wait" },
[239] = { 5, TM|SI, SEN(remap_file_pages), "remap_file_pages" },
[240] = { 3, 0, SEN(timer_create), "timer_create" },
[241] = { 4, 0, SEN(timer_settime), "timer_settime" },
[242] = { 2, 0, SEN(timer_gettime), "timer_gettime" },
[243] = { 1, 0, SEN(timer_getoverrun), "timer_getoverrun" },
[244] = { 1, 0, SEN(timer_delete), "timer_delete" },
[245] = { 2, 0, SEN(clock_settime), "clock_settime" },
[246] = { 2, 0, SEN(clock_gettime), "clock_gettime" },
[247] = { 2, 0, SEN(clock_getres), "clock_getres" },
[248] = { 4, 0, SEN(clock_nanosleep), "clock_nanosleep" },
[249] = { 2, 0, SEN(printargs), "swapcontext" },
[250] = { 3, TS, SEN(tgkill), "tgkill" },
[251] = { 2, TF, SEN(utimes), "utimes" },
[252] = { 3, TF, SEN(statfs64), "statfs64" },
[253] = { 3, TD, SEN(fstatfs64), "fstatfs64" },
[254] = { },
[255] = { 1, 0, SEN(printargs), "rtas" },
[256] = { 5, 0, SEN(printargs), "sys_debug_setcontext" },
[257] = { 5, 0, SEN(vserver), "vserver" },
[258] = { 4, TM, SEN(migrate_pages), "migrate_pages" },
[259] = { 6, TM, SEN(mbind), "mbind" },
[260] = { 5, TM, SEN(get_mempolicy), "get_mempolicy" },
[261] = { 3, TM, SEN(set_mempolicy), "set_mempolicy" },
[262] = { 4, 0, SEN(mq_open), "mq_open" },
[263] = { 1, 0, SEN(mq_unlink), "mq_unlink" },
[264] = { 5, 0, SEN(mq_timedsend), "mq_timedsend" },
[265] = { 5, 0, SEN(mq_timedreceive), "mq_timedreceive" },
[266] = { 2, 0, SEN(mq_notify), "mq_notify" },
[267] = { 3, 0, SEN(mq_getsetattr), "mq_getsetattr" },
[268] = { 4, 0, SEN(kexec_load), "kexec_load" },
[269] = { 5, 0, SEN(add_key), "add_key" },
[270] = { 4, 0, SEN(request_key), "request_key" },
[271] = { 5, 0, SEN(keyctl), "keyctl" },
[272] = { 5, TP, SEN(waitid), "waitid" },
[273] = { 3, 0, SEN(ioprio_set), "ioprio_set" },
[274] = { 2, 0, SEN(ioprio_get), "ioprio_get" },
[275] = { 0, TD, SEN(inotify_init), "inotify_init" },
[276] = { 3, TD, SEN(inotify_add_watch), "inotify_add_watch" },
[277] = { 2, TD, SEN(inotify_rm_watch), "inotify_rm_watch" },
[278] = { 5, 0, SEN(printargs), "spu_run" },
[279] = { 5, 0, SEN(printargs), "spu_create" },
[280] = { 6, TD, SEN(pselect6), "pselect6" },
[281] = { 5, TD, SEN(ppoll), "ppoll" },
[282] = { 1, TP, SEN(unshare), "unshare" },
[283] = { 6, TD, SEN(splice), "splice" },
[284] = { 4, TD, SEN(tee), "tee" },
[285] = { 4, TD, SEN(vmsplice), "vmsplice" },
[286] = { 4, TD|TF, SEN(openat), "openat" },
[287] = { 3, TD|TF, SEN(mkdirat), "mkdirat" },
[288] = { 4, TD|TF, SEN(mknodat), "mknodat" },
[289] = { 5, TD|TF, SEN(fchownat), "fchownat" },
[290] = { 3, TD|TF, SEN(futimesat), "futimesat" },
[291] = { 4, TD|TF, SEN(newfstatat), "newfstatat" },
[292] = { 3, TD|TF, SEN(unlinkat), "unlinkat" },
[293] = { 4, TD|TF, SEN(renameat), "renameat" },
[294] = { 5, TD|TF, SEN(linkat), "linkat" },
[295] = { 3, TD|TF, SEN(symlinkat), "symlinkat" },
[296] = { 4, TD|TF, SEN(readlinkat), "readlinkat" },
[297] = { 3, TD|TF, SEN(fchmodat), "fchmodat" },
[298] = { 3, TD|TF, SEN(faccessat), "faccessat" },
[299] = { 3, 0, SEN(get_robust_list), "get_robust_list" },
[300] = { 2, 0, SEN(set_robust_list), "set_robust_list" },
[301] = { 6, TM, SEN(move_pages), "move_pages" },
[302] = { 3, 0, SEN(getcpu), "getcpu" },
[303] = { 6, TD, SEN(epoll_pwait), "epoll_pwait" },
[304] = { 4, TD|TF, SEN(utimensat), "utimensat" },
[305] = { 3, TD|TS, SEN(signalfd), "signalfd" },
[306] = { 2, TD, SEN(timerfd_create), "timerfd_create" },
[307] = { 1, TD, SEN(eventfd), "eventfd" },
[308] = { 6, TD, SEN(sync_file_range2), "sync_file_range2" },
[309] = { 6, TD, SEN(fallocate), "fallocate" },
[310] = { 3, 0, SEN(subpage_prot), "subpage_prot" },
[311] = { 4, TD, SEN(timerfd_settime), "timerfd_settime" },
[312] = { 2, TD, SEN(timerfd_gettime), "timerfd_gettime" },
[313] = { 4, TD|TS, SEN(signalfd4), "signalfd4" },
[314] = { 2, TD, SEN(eventfd2), "eventfd2" },
[315] = { 1, TD, SEN(epoll_create1), "epoll_create1" },
[316] = { 3, TD, SEN(dup3), "dup3" },
[317] = { 2, TD, SEN(pipe2), "pipe2" },
[318] = { 1, TD, SEN(inotify_init1), "inotify_init1" },
[319] = { 5, TD, SEN(perf_event_open), "perf_event_open" },
[320] = { 5, TD, SEN(preadv), "preadv" },
[321] = { 5, TD, SEN(pwritev), "pwritev" },
[322] = { 4, TP|TS, SEN(rt_tgsigqueueinfo), "rt_tgsigqueueinfo" },
[323] = { 2, TD, SEN(fanotify_init), "fanotify_init" },
[324] = { 6, TD|TF, SEN(fanotify_mark), "fanotify_mark" },
[325] = { 4, 0, SEN(prlimit64), "prlimit64" },
[326] = { 3, TN, SEN(socket), "socket" },
[327] = { 3, TN, SEN(bind), "bind" },
[328] = { 3, TN, SEN(connect), "connect" },
[329] = { 2, TN, SEN(listen), "listen" },
[330] = { 3, TN, SEN(accept), "accept" },
[331] = { 3, TN, SEN(getsockname), "getsockname" },
[332] = { 3, TN, SEN(getpeername), "getpeername" },
[333] = { 4, TN, SEN(socketpair), "socketpair" },
[334] = { 4, TN, SEN(send), "send" },
[335] = { 6, TN, SEN(sendto), "sendto" },
[336] = { 4, TN, SEN(recv), "recv" },
[337] = { 6, TN, SEN(recvfrom), "recvfrom" },
[338] = { 2, TN, SEN(shutdown), "shutdown" },
[339] = { 5, TN, SEN(setsockopt), "setsockopt" },
[340] = { 5, TN, SEN(getsockopt), "getsockopt" },
[341] = { 3, TN, SEN(sendmsg), "sendmsg" },
[342] = { 3, TN, SEN(recvmsg), "recvmsg" },
[343] = { 5, TN, SEN(recvmmsg), "recvmmsg" },
[344] = { 4, TN, SEN(accept4), "accept4" },
[345] = { 5, TD|TF, SEN(name_to_handle_at), "name_to_handle_at" },
[346] = { 3, TD, SEN(open_by_handle_at), "open_by_handle_at" },
[347] = { 2, 0, SEN(clock_adjtime), "clock_adjtime" },
[348] = { 1, TD, SEN(syncfs), "syncfs" },
[349] = { 4, TN, SEN(sendmmsg), "sendmmsg" },
[350] = { 2, TD, SEN(setns), "setns" },
[351] = { 6, 0, SEN(process_vm_readv), "process_vm_readv" },
[352] = { 6, 0, SEN(process_vm_writev), "process_vm_writev" },
[353] = { 3, TD, SEN(finit_module), "finit_module" },
[354] = { 5, 0, SEN(kcmp), "kcmp" },
[355] = { 3, 0, SEN(sched_setattr), "sched_setattr" },
[356] = { 4, 0, SEN(sched_getattr), "sched_getattr" },
[357] = { 5, TD|TF, SEN(renameat2), "renameat2" },
[358] = { 3, 0, SEN(seccomp), "seccomp", },
[359] = { 3, 0, SEN(getrandom), "getrandom", },
[360] = { 2, TD, SEN(memfd_create), "memfd_create", },
[361] = { 3, TD, SEN(bpf), "bpf", },
[362] = { 5, TD|TF|TP|SE|SI, SEN(execveat), "execveat", },
[363] = { 0, 0, SEN(printargs), "switch_endian" },
[364] = { 1, TD, SEN(userfaultfd), "userfaultfd", },
[365] = { 2, 0, SEN(membarrier), "membarrier", },
[366] = { 3, TI, SEN(semop), "semop" },
[367] = { 3, TI, SEN(semget), "semget" },
[368] = { 4, TI, SEN(semctl), "semctl" },
[369] = { 4, TI, SEN(semtimedop), "semtimedop" },
[370] = { 4, TI, SEN(msgsnd), "msgsnd" },
[371] = { 5, TI, SEN(msgrcv), "msgrcv" },
[372] = { 2, TI, SEN(msgget), "msgget" },
[373] = { 3, TI, SEN(msgctl), "msgctl" },
[374] = { 3, TI|TM|SI, SEN(shmat), "shmat" },
[375] = { 1, TI|TM|SI, SEN(shmdt), "shmdt" },
[376] = { 3, TI, SEN(shmget), "shmget" },
[377] = { 3, TI, SEN(shmctl), "shmctl" },
[378] = { 3, TM, SEN(mlock2), "mlock2" },
[379 ... 399] = { },
#define SYS_socket_subcall 400
#include "subcall.h"
| kapdop/android_external_strace | linux/powerpc64/syscallent.h | C | bsd-3-clause | 20,431 |
/*
* Copyright (C) 2012 Company 100, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 CoordinatedCustomFilterProgram_h
#define CoordinatedCustomFilterProgram_h
#if USE(COORDINATED_GRAPHICS) && ENABLE(CSS_SHADERS)
#include "CustomFilterConstants.h"
#include "CustomFilterProgram.h"
namespace WebCore {
class CoordinatedCustomFilterProgram : public CustomFilterProgram {
public:
static PassRefPtr<CoordinatedCustomFilterProgram> create(const String& vertexShaderString, const String& fragmentShaderString, CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
{
return adoptRef(new CoordinatedCustomFilterProgram(vertexShaderString, fragmentShaderString, programType, mixSettings, meshType));
}
virtual bool isLoaded() const OVERRIDE { return true; }
protected:
virtual String vertexShaderString() const OVERRIDE { return m_vertexShaderString; }
virtual String fragmentShaderString() const OVERRIDE { return m_fragmentShaderString; }
virtual void willHaveClients() OVERRIDE { notifyClients(); }
virtual void didRemoveLastClient() OVERRIDE { }
private:
CoordinatedCustomFilterProgram(const String& vertexShaderString, const String& fragmentShaderString, CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
: CustomFilterProgram(programType, mixSettings, meshType)
, m_vertexShaderString(vertexShaderString)
, m_fragmentShaderString(fragmentShaderString)
{
}
String m_vertexShaderString;
String m_fragmentShaderString;
};
} // namespace WebCore
#endif // USE(COORDINATED_GRAPHICS) && ENABLE(CSS_SHADERS)
#endif // CoordinatedCustomFilterProgram_h
| klim-iv/phantomjs-qt5 | src/webkit/Source/WebCore/platform/graphics/texmap/coordinated/CoordinatedCustomFilterProgram.h | C | bsd-3-clause | 3,055 |
from django.test import TestCase
import time
from .models import SimpleTree, MPTTTree, TBMP, TBNS
def timeit(method):
""" Measure time of method's execution.
"""
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '\n%r: %2.2f sec' % \
(method.__name__, te - ts)
return result
return timed
CYCLES = 8
class Benchmark(object):
@timeit
def test_creation(self):
self._create_tree()
def test_delete(self):
self._create_tree(cycles=7)
@timeit
def test_deletion():
for _ in xrange(pow(2, CYCLES) / 2):
self._delete_last()
test_deletion()
def test_get(self):
self._create_tree(cycles=7)
@timeit
def test_get_tree():
root = self._get_root()
for _ in xrange(100):
self._get_tree(root)
test_get_tree()
def _create_tree(self, cycles=CYCLES):
root = self._create_root(title='root1')
nodes = [root]
for _ in xrange(CYCLES):
new_nodes = []
for node in nodes:
new_nodes.append(self._create_child(parent=node))
new_nodes.append(self._create_child(parent=node))
nodes = new_nodes
return nodes
def _create_root(self, **params):
pass
def _create_child(self, parent, **params):
pass
def _delete_last(self):
pass
def _get_root(self):
pass
def _get_tree(self, parent):
pass
class SimpleTest(TestCase, Benchmark):
def setUp(self):
print "\nSimpleTree benchmark"
def _create_root(self, **params):
return SimpleTree.objects.create(**params)
def _create_child(self, parent, **params):
return SimpleTree.objects.create(parent=parent, **params)
def _delete_last(self):
SimpleTree.objects.order_by('-id')[0].delete()
def _get_root(self):
return SimpleTree.objects.get(parent=None)
def _get_tree(self, parent):
return parent.get_tree()
class MPTTTest(TestCase, Benchmark):
def setUp(self):
print "\nMPTT benchmark"
def _create_root(self, **params):
return MPTTTree.objects.create(**params)
def _create_child(self, parent, **params):
return MPTTTree.objects.create(parent=parent, **params)
def _delete_last(self):
MPTTTree.objects.order_by('-id')[0].delete()
def _get_root(self):
return MPTTTree.objects.get(parent=None)
def _get_tree(self, parent):
return list(parent.get_ancestors()) + list(parent.get_descendants(include_self=False))
class TreeBeardMP(TestCase, Benchmark):
def setUp(self):
print "\nTreebeard MP benchmark"
def _create_root(self, **params):
return TBMP.add_root(**params)
def _create_child(self, parent, **params):
return parent.add_child(**params)
def _delete_last(self):
TBMP.objects.order_by('-id')[0].delete()
def _get_root(self):
return TBMP.get_root_nodes()[0]
def _get_tree(self, parent):
TBMP.get_tree(parent=parent)
class TreeBeardNS(TreeBeardMP):
def setUp(self):
print "\nTreebeard NS benchmark"
def _create_root(self, **params):
return TBNS.add_root(**params)
def _delete_last(self):
TBNS.objects.order_by('-id')[0].delete()
def _get_root(self):
return TBNS.get_root_nodes()[0]
def _get_tree(self, parent):
TBNS.get_tree(parent=parent)
| klen/simpletree | benchmark/main/tests.py | Python | bsd-3-clause | 3,596 |
$(document).ready(function () {
function update_cart(pro_id,type)
{
$.ajax({
url: '/fontend/cart/delete-cart.html',
cache: false,
type: 'post',
data: {product_id: pro_id,type:type},
success: function (result)
{
// document.location = '/fontend/cart/index.html';
},
error: function (result) {
alert("Có lỗi xẩy ra, vui lòng thử lại sau.");
}
});
}
function formatPrice(b1,pra_class) {
var b = b1.toString();
var j = "";
var f = "";
var c = b.length;
if ((c > 0)) {
if (!(b === "") && (b != null)) {
var a = 0;
var d = 0;
for (i = c - 1; i >= 0; i--) {
a++;
if ((a % 3 == 0) && (a < c)) {
var e = c - a;
var g = b.substr(e, 3);
f = g + " " + f;
d++
}
}
var h = c - (d * 3);
j = b.substring(0, h) + " " + f;
if (j.charAt(j.length - 1) == " ") {
j = j.substr(0, (j.length - 1))
}
var string = j.split(' ').join('.');
return string;
//var string = j.replace('/" "/g','.');
$("#"+pra_class).attr("value", string)
}
}
}
$("input.input_price").keydown(function (b) {
var a = (b.which) ? b.which : b.keyCode;
if (a == 46 || a == 8 || a == 37 || a == 39 || a == 9 || a == 229) {
} else {
if (a > 31 && (a < 48 || a > 57) && (a < 96 || a > 105)) {
return false
}
}
});
$("input.input_price").on("keyup", function () {
var p_id = $(this).attr("name");
var value = $(this).val();
if(value == '')
{
value = 0;
}
var p_price = $('#p-'+p_id).text();
var formart_price = p_price.replace(/\./g, "");
var total_price = parseInt(formart_price)*parseInt(value);
var a = formatPrice(total_price,'p-final-'+p_id);
$('#p-final-'+p_id).text(a);
});
$(".action .delete-product").on("click",function(e){
e.preventDefault();
var id = $(this).data('value');
$('.tr-'+id).css("display","none");
update_cart(id,'delete');
});
}); | thanhdv193/cuteshop | web/js/product/process_cart.js | JavaScript | bsd-3-clause | 2,606 |
<?php
echo ' <script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-download fade">
{% if (file.error) { %}
<td></td>
<td class="name"><span>{%=file.name%}</span></td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td class="error" colspan="2"><span class="label label-important">Error</span> {%=file.error%}</td>
{% } else { %}
<td class="preview">{% if (file.thumbnail_url) { %}
<a href="{%=file.url%}" title="{%=file.name%}" data-gallery="gallery" download="{%=file.name%}"><img src="{%=file.thumbnail_url%}"></a>
{% } %}</td>
<td class="name">
<a href="{%=file.url%}" title="{%=file.name%}" data-gallery="{%=file.thumbnail_url&&\'gallery\'%}" download="{%=file.name%}">{%=file.name%}</a>
</td>
<td class="size"><span>{%=o.formatFileSize(file.size)%}</span></td>
<td colspan="2"></td>
{% } %}
<td>
<button class="btn button_oc btn-danger delete" data-type="{%=file.delete_type%}" data-url="{%=file.delete_url%}"{% if (file.delete_with_credentials) { %} data-xhr-fields=\'{"withCredentials":true}\'{% } %}>
<i class="icon-trash icon-white"></i>
<span style="margin-right:18px;">Delete</span>
</button>
<input type="checkbox" name="delete" value="1" class="toggle">
</td>
</tr>
{% } %}
</script>';
?> | idmteam/oc-big | bin/template_download.php | PHP | bsd-3-clause | 1,465 |
<?php
use yii\helpers\Html;
use kartik\widgets\ActiveForm;
use kartik\widgets\DateTimePicker;
?>
<h2><?= $type ?></h2>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'money')->textInput() ?>
<?= $form->field($model, 'create_time')->widget('kartik\widgets\DateTimePicker') ?>
<?= $form->field($model, 'out_account_id')->dropDownList($me) ?>
<?= $form->field($model, 'in_account_id')->dropDownList($persons, ['onchange'=>'refundChooseLS(2)']) ?>
<?= $form->field($model, 'lr_id')->dropDownList($records) ?>
<?= $form->field($model, 'description')->textInput() ?>
<?= Html::submitButton( 'Create' , ['class' => 'btn btn-success' ]) ?>
<?php $form = ActiveForm::end(); ?>
<?= Html::jsFile('/js/fund.js') ?>
<?= Html::a('返回','/index.php?r=fund/currency/index')?>
| jh27408079/magenet | frontend/modules/fund/views/borrow/refundout.php | PHP | bsd-3-clause | 789 |
package org.irods.jargon.extensions.searchplugin.implementation;
import java.util.concurrent.Callable;
import org.irods.jargon.extensions.searchplugin.SearchIndexInventory;
import org.irods.jargon.extensions.searchplugin.SearchPluginRegistrationConfig;
import org.irods.jargon.extensions.searchplugin.model.SearchAttributes;
import org.irods.jargon.irodsext.jwt.AbstractJwtIssueService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Callable to obtain information
*
* @author Mike Conway - NIEHS
*
*/
public class SchemaAttributesCallable implements Callable<SearchAttributes> {
private final SearchPluginRegistrationConfig searchPluginRegistrationConfig;
private final String endpointUrl;
private final AbstractJwtIssueService jwtIssueService;
private final SearchIndexInventory searchIndexInventory;
private final String schemaId;
public static final Logger log = LoggerFactory.getLogger(PluginInventoryCallable.class);
public SchemaAttributesCallable(final SearchPluginRegistrationConfig searchPluginRegistrationConfig,
final String endpointUrl, final String schemaId, final AbstractJwtIssueService jwtIssueService,
final SearchIndexInventory searchIndexInventory) {
if (searchPluginRegistrationConfig == null) {
throw new IllegalArgumentException("null searchPluginRegistrationConfig");
}
if (endpointUrl == null || endpointUrl.isEmpty()) {
throw new IllegalArgumentException("null or empty endpointUrl");
}
if (schemaId == null || schemaId.isEmpty()) {
throw new IllegalArgumentException("null or empty schemaId");
}
if (jwtIssueService == null) {
throw new IllegalArgumentException("null jwtIssueService");
}
if (searchIndexInventory == null) {
throw new IllegalArgumentException("null searchIndexInventory");
}
this.searchPluginRegistrationConfig = searchPluginRegistrationConfig;
this.endpointUrl = endpointUrl;
this.schemaId = schemaId;
this.jwtIssueService = jwtIssueService;
this.searchIndexInventory = searchIndexInventory;
}
@Override
public SearchAttributes call() throws Exception {
log.info("call()");
IndexInventoryUtility indexUtility = new IndexInventoryUtility();
SearchAttributes searchAttributes = indexUtility.inventoryAttributes(searchPluginRegistrationConfig,
endpointUrl, schemaId, jwtIssueService);
log.debug("got attribs:{}", searchAttributes);
searchIndexInventory.getIndexInventoryEntries().get(endpointUrl).getSearchAttributesMap().put(schemaId,
searchAttributes);
log.info("attribs updated in schema registry");
return searchAttributes;
}
}
| DICE-UNC/jargon-extensions-if | src/main/java/org/irods/jargon/extensions/searchplugin/implementation/SchemaAttributesCallable.java | Java | bsd-3-clause | 2,594 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-28 17:08
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('voting', '0002_auto_20150813_2010'),
]
operations = [
migrations.CreateModel(
name='VoteToken',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ticket_code', models.CharField(max_length=255)),
('token_sent', models.DateTimeField(blank=True, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| WebCampZg/conference-web | voting/migrations/0003_votetoken.py | Python | bsd-3-clause | 880 |
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build ignore
// This program generates internet protocol constatns and tables by
// reading IANA protocol registries.
//
// Usage of this program:
// go run gen.go > iana.go
package main
import (
"bytes"
"encoding/xml"
"fmt"
"go/format"
"io"
"net/http"
"os"
"strconv"
"strings"
)
var registries = []struct {
url string
parse func(io.Writer, io.Reader) error
}{
{
"http://www.iana.org/assignments/icmp-parameters",
parseICMPv4Parameters,
},
{
"http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml",
parseProtocolNumbers,
},
}
func main() {
var bb bytes.Buffer
fmt.Fprintf(&bb, "// go run gen.go\n")
fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n")
fmt.Fprintf(&bb, "package ipv4\n\n")
for _, r := range registries {
resp, err := http.Get(r.url)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url)
os.Exit(1)
}
if err := r.parse(&bb, resp.Body); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Fprintf(&bb, "\n")
}
b, err := format.Source(bb.Bytes())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Stdout.Write(b)
}
func parseICMPv4Parameters(w io.Writer, r io.Reader) error {
dec := xml.NewDecoder(r)
var icp icmpv4Parameters
if err := dec.Decode(&icp); err != nil {
return err
}
prs := icp.escape(0)
fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated)
fmt.Fprintf(w, "const (\n")
for _, pr := range prs {
if pr.Descr == "" {
continue
}
fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Descr, pr.Value)
fmt.Fprintf(w, "// %s\n", pr.OrigDescr)
}
fmt.Fprintf(w, ")\n\n")
fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated)
fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n")
for _, pr := range prs {
if pr.Descr == "" {
continue
}
fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigDescr))
}
fmt.Fprintf(w, "}\n")
return nil
}
type icmpv4Parameters struct {
XMLName xml.Name `xml:"registry"`
Title string `xml:"title"`
Updated string `xml:"updated"`
Registries []icmpv4ParamRegistry `xml:"registry"`
}
type icmpv4ParamRegistry struct {
Title string `xml:"title"`
Records []icmpv4ParamRecord `xml:"record"`
}
type icmpv4ParamRecord struct {
Value string `xml:"value"`
Descr string `xml:"description"`
}
type canonICMPv4ParamRecord struct {
OrigDescr string
Descr string
Value int
}
func (icp *icmpv4Parameters) escape(id int) []canonICMPv4ParamRecord {
prs := make([]canonICMPv4ParamRecord, len(icp.Registries[id].Records))
sr := strings.NewReplacer(
"Messages", "",
"Message", "",
"ICMP", "",
"+", "P",
"-", "",
"/", "",
".", "",
" ", "",
)
for i, pr := range icp.Registries[id].Records {
if strings.Contains(pr.Descr, "Reserved") ||
strings.Contains(pr.Descr, "Unassigned") ||
strings.Contains(pr.Descr, "Deprecated") ||
strings.Contains(pr.Descr, "Experiment") ||
strings.Contains(pr.Descr, "experiment") {
continue
}
ss := strings.Split(pr.Descr, "\n")
if len(ss) > 1 {
prs[i].Descr = strings.Join(ss, " ")
} else {
prs[i].Descr = ss[0]
}
s := strings.TrimSpace(prs[i].Descr)
prs[i].OrigDescr = s
prs[i].Descr = sr.Replace(s)
prs[i].Value, _ = strconv.Atoi(pr.Value)
}
return prs
}
func parseProtocolNumbers(w io.Writer, r io.Reader) error {
dec := xml.NewDecoder(r)
var pn protocolNumbers
if err := dec.Decode(&pn); err != nil {
return err
}
prs := pn.escape()
prs = append([]canonProtocolRecord{{
Name: "IP",
Descr: "IPv4 encapsulation, pseudo protocol number",
Value: 0,
}}, prs...)
fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated)
fmt.Fprintf(w, "const (\n")
for _, pr := range prs {
if pr.Name == "" {
continue
}
fmt.Fprintf(w, "ianaProtocol%s = %d", pr.Name, pr.Value)
s := pr.Descr
if s == "" {
s = pr.OrigName
}
fmt.Fprintf(w, "// %s\n", s)
}
fmt.Fprintf(w, ")\n")
return nil
}
type protocolNumbers struct {
XMLName xml.Name `xml:"registry"`
Title string `xml:"title"`
Updated string `xml:"updated"`
RegTitle string `xml:"registry>title"`
Note string `xml:"registry>note"`
Records []protocolRecord `xml:"registry>record"`
}
type protocolRecord struct {
Value string `xml:"value"`
Name string `xml:"name"`
Descr string `xml:"description"`
}
type canonProtocolRecord struct {
OrigName string
Name string
Descr string
Value int
}
func (pn *protocolNumbers) escape() []canonProtocolRecord {
prs := make([]canonProtocolRecord, len(pn.Records))
sr := strings.NewReplacer(
"-in-", "in",
"-within-", "within",
"-over-", "over",
"+", "P",
"-", "",
"/", "",
".", "",
" ", "",
)
for i, pr := range pn.Records {
prs[i].OrigName = pr.Name
s := strings.TrimSpace(pr.Name)
switch pr.Name {
case "ISIS over IPv4":
prs[i].Name = "ISIS"
case "manet":
prs[i].Name = "MANET"
default:
prs[i].Name = sr.Replace(s)
}
ss := strings.Split(pr.Descr, "\n")
for i := range ss {
ss[i] = strings.TrimSpace(ss[i])
}
if len(ss) > 1 {
prs[i].Descr = strings.Join(ss, " ")
} else {
prs[i].Descr = ss[0]
}
prs[i].Value, _ = strconv.Atoi(pr.Value)
}
return prs
}
| andrewzeneski/go.net | ipv4/gen.go | GO | bsd-3-clause | 5,632 |
-- | Helper functions for dealing with text values
module Language.Terraform.Util.Text(
template,
show
) where
import Prelude hiding(show)
import qualified Prelude(show)
import qualified Data.Text as T
show :: (Show a) => a -> T.Text
show = T.pack . Prelude.show
-- | `template src substs` will replace all occurences the string $i
-- in src with `substs !! i`
template :: T.Text -> [T.Text] -> T.Text
template t substs = foldr replace t (zip [1,2..] substs)
where
replace (i,s) t = T.replace (T.pack ('$':Prelude.show i)) s t
| timbod7/terraform-hs | src/Language/Terraform/Util/Text.hs | Haskell | bsd-3-clause | 547 |
import uuid
import os
import shutil
import urlparse
import re
import hashlib
from lxml import html
from PIL import Image, ImageFile
from django.conf import settings
import views
ImageFile.MAXBLOCKS = 10000000
def match_or_none(string, rx):
"""
Tries to match a regular expression and returns an integer if it can.
Otherwise, returns None.
@param string: String to match against
@type string: basestring
@param rx: compiled regular expression
@return: number or None
@rtype: int/long or None
"""
if string is None:
return None
match = rx.search(string)
if match:
return int(match.groups()[0])
return None
width_rx = re.compile(r'width\s*:\s*(\d+)(px)?')
height_rx = re.compile(r'height\s*:\s*(\d+)(px)?')
def get_dimensions(img):
"""
Attempts to get the dimensions of an image from the img tag.
It first tries to grab it from the css styles and then falls back
to looking at the attributes.
@param img: Image tag.
@type img: etree._Element
@return: width and height of the image
@rtype: (int or None, int or None)
"""
styles = img.attrib.get('style')
width = match_or_none(styles, width_rx) or img.attrib.get('width')
if isinstance(width, basestring):
width = int(width)
height = match_or_none(styles, height_rx) or img.attrib.get('height')
if isinstance(height, basestring):
height= int(height)
return width, height
def get_local_path(url):
"""
Converts a url to a local path
@param url: Url to convert
@type url: basestring
@return: Local path of the url
@rtype: basestring
"""
url = urlparse.unquote(url)
local_path = settings.STATIC_ROOT + os.path.normpath(url[len(settings.STATIC_URL):])
return local_path
# `buffer` is needed since hashlib apparently isn't unicode safe
hexhash = lambda s: hashlib.md5(buffer(s)).hexdigest()
def new_rendered_path(orig_path, width, height, ext=None):
"""
Builds a new rendered path based on the original path, width, and height.
It takes a hash of the original path to prevent users from accidentally
(or purposely) overwritting other's rendered thumbnails.
This isn't perfect: we are assuming that the original file's conents never
changes, which is the django default. We could make this function more
robust by hashing the file everytime we save but that has the obvious
disadvantage of having to hash the file everytime. YMMV.
@param orig_path: Path to the original image.
@type orig_path: "/path/to/file"
@param width: Desired width of the rendered image.
@type width: int or None
@param height: Desired height of the rendered image.
@type height: int or None
@param ext: Desired extension of the new image. If None, uses
the original extension.
@type ext: basestring or None
@return: Absolute path to where the rendered image should live.
@rtype: "/path/to/rendered/image"
"""
dirname = os.path.dirname(orig_path)
rendered_path = os.path.join(dirname, 'rendered')
if not os.path.exists(rendered_path):
os.mkdir(rendered_path)
hash_path = hexhash(orig_path)
if ext is None:
ext = os.path.splitext(os.path.basename(orig_path))[1]
if ext and ext[0] != u'.':
ext = u'.' + ext
name = '%s_%sx%s' % (hash_path, width, height)
return os.path.join(rendered_path, name) + ext
def is_rendered(path, width, height):
"""
Checks whether or not an image has been rendered to the given path
with the given dimensions
@param path: path to check
@type path: u"/path/to/image"
@param width: Desired width
@type width: int
@param height: Desired height
@type height: int
@return: Whether or not the image is correct
@rtype: bool
"""
if os.path.exists(path):
old_width, old_height = Image.open(path).size
return old_width == width and old_height == height
return False
def transcode_to_jpeg(image, path, width, height):
"""
Transcodes an image to JPEG.
@param image: Opened image to transcode to jpeg.
@type image: PIL.Image
@param path: Path to the opened image.
@type path: u"/path/to/image"
@param width: Desired width of the transcoded image.
@type width: int
@param height: Desired height of the transcoded image.
@type height: int
@return: Path to the new transcoded image.
@rtype: "/path/to/image"
"""
i_width, i_height = image.size
new_width = i_width if width is None else width
new_height = i_height if height is None else height
new_path = new_rendered_path(path, width, height, ext='jpg')
if is_rendered(new_path, new_width, new_height):
return new_path
new_image = image.resize((new_width, new_height), Image.ANTIALIAS)
new_image.save(new_path, quality=80, optimize=1)
return new_path
def re_render(path, width, height):
"""
Given an original image, width, and height, creates a thumbnailed image
of the exact dimensions given. We skip animated gifs because PIL can't
resize those automatically whereas browsers can contort them easily. We
also don't stretch images at all and return the original in that case.
@param path: Path to the original image
@type path: "/path/to/image"
@param width: Desired width
@type width: int or None
@param height: Desired height
@type height: int or None
@return: Path to the 'rendered' image.
@rtype: "/path/to/image"
"""
try:
image = Image.open(path)
except IOError:
# Probably doesn't exist or isn't an image
return path
# We have to call image.load first due to a PIL 1.1.7 bug
image.load()
if image.format == 'PNG' and getattr(settings, 'CKEDITOR_PNG_TO_JPEG', False):
pixels = reduce(lambda a,b: a*b, image.size)
# check that our entire alpha channel is set to full opaque
if image.mode == 'RGB' or image.split()[-1].histogram()[-1] == pixels:
return transcode_to_jpeg(image, path, width, height)
if image.size <= (width, height):
return path
if width is None and height is None:
return path
# We can't resize animated gifs
if image.format == 'GIF':
try:
image.seek(1)
return path
except EOFError:
# Static GIFs should throw an EOF on seek
pass
new_path = new_rendered_path(path, width, height)
if is_rendered(new_path, width, height):
return new_path
# Re-render the image, optimizing for filesize
new_image = image.resize((width, height), Image.ANTIALIAS)
new_image.save(new_path, quality=80, optimize=1)
return new_path
def get_html_tree(content):
return html.fragment_fromstring(content, create_parent='div')
def render_html_tree(tree):
return html.tostring(tree)[5:-6]
def resize_images(post_content):
"""
Goes through all images, resizing those that we know to be local to the
correct image size.
@param post_content: Raw html of the content to search for images with.
@type post_content: basestring containg HTML fragments
@return: Modified contents.
@rtype: basestring
"""
# Get tree
tree = get_html_tree(post_content)
# Get images
imgs = tree.xpath('//img[starts-with(@src, "%s")]' % settings.STATIC_URL)
for img in imgs:
orig_url = img.attrib['src']
orig_path = get_local_path(orig_url)
width, height = get_dimensions(img)
rendered_path = re_render(orig_path, width, height)
# If we haven't changed the image, move along.
if rendered_path == orig_path:
continue
# Flip to the rendered
img.attrib['data-original'] = orig_url
img.attrib['src'] = views.get_media_url(rendered_path)
# Strip of wrapping div tag
return render_html_tree(tree)
def swap_in_originals(content):
if 'data-original' not in content:
return content
tree = get_html_tree(content)
for img in tree.xpath('//img[@data-original]'):
img.attrib['src'] = img.attrib['data-original']
del img.attrib['data-original']
return render_html_tree(tree)
| ZG-Tennis/django-ckeditor | ckeditor/utils.py | Python | bsd-3-clause | 8,404 |
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 300;
src: local('Source Sans Pro Light'), local('SourceSansPro-Light'), url('../fonts/sourcesanspro300.woff') format('woff');
}
@font-face {
font-family: 'Source Sans Pro';
font-style: normal;
font-weight: 400;
src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url('../fonts/sourcesanspro400.woff') format('woff');
}
@font-face {
font-family: 'digi';
src: url('../fonts/dsdigi-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'headliner';
src: url('../fonts/headliner-webfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
body {
background-color: black;
font-family: 'Source Sans Pro';
font-weight: 300;
overflow: hidden;
}
.font-digi {
font-family: 'digi';
}
.font-headliner {
font-family: 'headliner';
}
.beamer-viewport {
width: 1024px;
height: 768px;
background: url('../img/bg.jpg');
background-size: 100% auto;
color: white;
position: relative;
margin: 0 auto;
}
p {
margin: 0;
}
.title.font-headliner {
font-size: 45px;
line-height: 45px;
letter-spacing: 5px;
-webkit-transform: rotate(1deg);
-moz-transform: rotate(1deg);
-o-transform: rotate(1deg);
writing-mode: lr-tb;
}
.bl-message {
position: absolute;
left: 0;
top: 0;
width: 500px;
font-family: 'Source Sans Pro';
font-weight: 300;
}
.bl-message .title {
margin: 20px 0 0 20px;
}
.bl-message > .content {
margin: 20px 20px 0 20px;
height: 140px;
position: relative;
overflow: hidden;
font-size: 18px;
line-height: 22px;
}
.message-info {
position: absolute;
right: 10px;
top: 30px;
width: 180px;
text-align: center;
line-height: 14px;
color: #c5c5c5;
}
.message-template > .content {
display: block;
}
.message-template > .about {
display: block;
font-size: 14px;
color: #c5c5c5;
margin-top: 8px;
}
.bl-tweet {
position: absolute;
right: 0;
top: 0;
width: 470px;
height: 280px;
}
.bl-tweet > .content {
margin: 20px 0 0 0;
padding: 0 30px 0 0px;
font-family: 'Source Sans Pro';
font-weight: 300;
height: 180px;
overflow: hidden;
position: relative;
}
.bl-tweet .title {
margin: 0 0 0 0;
color: #00ffed;
}
.bl-tweet .slider {
width: 440px;
position: absolute;
top: 0;
}
.tweet-template {
width: 440px;
height: 180px;
float: left;
}
.tweet-template .content {
margin-top: 20px;
display: block;
font-size: 18px;
line-height: 22px;
max-height: 90px;
overflow: hidden;
padding: 0 0 0 20px;
}
.tweet-template .about {
font-size: 14px;
color: #c5c5c5;
margin-top: 8px;
display: block;
margin-left: 40px;
}
.tweet-info {
color: #008176;
line-height: 14px;
position: absolute;
left: 302px;
bottom: -6px;
text-align: center;
width: 50px;
font-size: 16px;
font-weight: 400;
}
.bl-score {
position: absolute;
left: 20px;
bottom: 0;
right: 0;
height: 54%;
}
.bl-score .title {
margin-top: -110px;
margin-left: 20px;
font-size: 80px;
}
.bl-score .content {
margin: 50px 14px 0 14px;
}
.bottle-wrap {
position: absolute;
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}
.bottle {
height: 401px;
width: 147px;
float: left;
margin: 0 6px;
position: relative;
}
.bottle .digit {
position: absolute;
top: 30px;
right: 0;
font-size: 30px;
text-align: center;
width: 68px;
color: #00ffed;
}
.bottle .digit.mo-large {
font-size: 24px;
}
.bottle .bar .relative {
position: relative;
width: 63px;
height: 262px;
}
.bottle .bar {
position: absolute;
top: 110px;
left: 30px;
right: 54px;
bottom: 29px;
}
.bottle .bar .fill {
background-color: white;
opacity: 0.35;
position: absolute;
height: 0%;
bottom: 0;
right: 0;
left: 0;
}
.bottle .rotate {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
width: 250px;
height: 147px;
position: absolute;
left: -9px;
top: 166px;
}
.bottle .info .nr {
display: block;
margin: 0 0 0 0;
font-size: 12px;
text-transform: uppercase;
text-shadow: 0px 0px 3px rgba(0, 0, 0, 0.8);
font-family: 'Source Sans Pro';
font-weight: 400;
}
.bottle .info .name {
display: block;
margin: -6px 0 0 0;
font-size: 20px;
font-weight: bold;
line-height: 24px;
text-transform: uppercase;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
text-shadow: 0px 0px 3px rgba(0, 0, 0, 0.8);
font-family: 'Source Sans Pro';
font-weight: 300;
}
#message-template {
display: none;
}
.bl-message > .content {
position: relative;
}
.bl-message .slider {
position: absolute;
width: 460px;
top: 0;
}
.message-template {
float: left;
width: 460px;
height: 140px;
position: relative;
overflow:hidden;
} | jaspermeijaard/Event-Intranet | public/css/beamer.css | CSS | bsd-3-clause | 5,285 |
// Copyright 2013 Traceur Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {
AttachModuleNameTransformer
} from '../codegeneration/module/AttachModuleNameTransformer';
import {FromOptionsTransformer} from '../codegeneration/FromOptionsTransformer';
import {ExportListBuilder} from '../codegeneration/module/ExportListBuilder';
import {ModuleSpecifierVisitor} from
'../codegeneration/module/ModuleSpecifierVisitor';
import {ModuleSymbol} from '../codegeneration/module/ModuleSymbol';
import {Parser} from '../syntax/Parser';
import {options} from '../options';
import {SourceFile} from '../syntax/SourceFile';
import {systemjs} from '../runtime/system-map';
import {UniqueIdentifierGenerator} from
'../codegeneration/UniqueIdentifierGenerator';
import {isAbsolute, resolveUrl} from '../util/url';
import {webLoader} from './webLoader';
import {assert} from '../util/assert';
// TODO These CodeUnit (aka Load) states are used by code in this file
// that belongs in Loader.
var NOT_STARTED = 0;
var LOADING = 1;
var LOADED = 2;
var PARSED = 3;
var TRANSFORMING = 4
var TRANSFORMED = 5;
var COMPLETE = 6;
var ERROR = 7;
var identifierGenerator = new UniqueIdentifierGenerator();
export class LoaderHooks {
constructor(reporter, baseURL,
fileLoader = webLoader,
moduleStore = $traceurRuntime.ModuleStore) {
this.reporter = reporter;
this.baseURL_ = baseURL;
this.moduleStore_ = moduleStore;
this.fileLoader = fileLoader;
this.exportListBuilder_ = new ExportListBuilder(this.reporter);
}
get(normalizedName) {
return this.moduleStore_.get(normalizedName);
}
set(normalizedName, module) {
this.moduleStore_.set(normalizedName, module);
}
normalize(name, referrerName, referrerAddress) {
var normalizedName =
this.moduleStore_.normalize(name, referrerName, referrerAddress);
if (System.map)
return systemjs.applyMap(System.map, normalizedName, referrerName);
else
return normalizedName;
}
get baseURL() {
return this.baseURL_;
}
set baseURL(value) {
this.baseURL_ = String(value);
}
getModuleSpecifiers(codeUnit) {
// Parse
if (!this.parse(codeUnit))
return;
codeUnit.state = PARSED;
// Analyze to find dependencies
var moduleSpecifierVisitor = new ModuleSpecifierVisitor(this.reporter);
moduleSpecifierVisitor.visit(codeUnit.metadata.tree);
return moduleSpecifierVisitor.moduleSpecifiers;
}
parse(codeUnit) {
assert(!codeUnit.metadata.tree);
var reporter = this.reporter;
var normalizedName = codeUnit.normalizedName;
var program = codeUnit.source;
// For error reporting, prefer loader URL, fallback if we did not load text.
var url = codeUnit.url || normalizedName;
var file = new SourceFile(url, program);
var parser = new Parser(file, reporter);
if (codeUnit.type == 'module')
codeUnit.metadata.tree = parser.parseModule();
else
codeUnit.metadata.tree = parser.parseScript();
codeUnit.metadata.moduleSymbol =
new ModuleSymbol(codeUnit.metadata.tree, normalizedName);
return !reporter.hadError();
}
transform(codeUnit) {
var transformer = new AttachModuleNameTransformer(codeUnit.normalizedName);
var transformedTree = transformer.transformAny(codeUnit.metadata.tree);
transformer = new FromOptionsTransformer(this.reporter,
identifierGenerator);
return transformer.transform(transformedTree);
}
fetch(load) {
return new Promise((resolve, reject) => {
this.fileLoader.load(load.address, resolve, reject);
});
}
translate(load) {
return new Promise((resolve, reject) => {
resolve(load.source);
});
}
instantiate({name, metadata, address, source, sourceMap}) {
return new Promise((resolve, reject) => {
resolve(undefined);
});
}
locate(load) {
load.url = this.locate_(load);
return load.url;
}
locate_(load) {
var normalizedModuleName = load.normalizedName;
var asJS;
if (load.type === 'script') {
asJS = normalizedModuleName;
} else {
asJS = normalizedModuleName + '.js';
}
if (options.referrer) {
if (asJS.indexOf(options.referrer) === 0) {
asJS = asJS.slice(options.referrer.length);
load.metadata.locateMap = {
pattern: options.referrer,
replacement: ''
};
}
}
if (isAbsolute(asJS))
return asJS;
var baseURL = load.metadata && load.metadata.baseURL;
baseURL = baseURL || this.baseURL;
if (baseURL) {
load.metadata.baseURL = baseURL;
return resolveUrl(baseURL, asJS);
}
return asJS;
}
nameTrace(load) {
var trace = '';
if (load.metadata.locateMap) {
trace += this.locateMapTrace(load);
}
var base = load.metadata.baseURL || this.baseURL;
if (base) {
trace += this.baseURLTrace(base);
} else {
trace += 'No baseURL\n';
}
return trace;
}
locateMapTrace(load) {
var map = load.metadata.locateMap;
return `LoaderHooks.locate found \'${map.pattern}\' -> \'${map.replacement}\'\n`;
}
baseURLTrace(base) {
return 'LoaderHooks.locate resolved against base \'' + base + '\'\n';
}
evaluateCodeUnit(codeUnit) {
// Source for modules compile into calls to registerModule(url, fnc).
//
// TODO(arv): Eval in the right context.
var result = ('global', eval)(codeUnit.metadata.transcoded);
codeUnit.metadata.transformedTree = null;
return result;
}
analyzeDependencies(dependencies, loader) {
var deps = []; // metadata for each dependency
for (var i = 0; i < dependencies.length; i++) {
var codeUnit = dependencies[i];
// We should not have gotten here if not all are PARSED or larget.
assert(codeUnit.state >= PARSED);
if (codeUnit.state == PARSED) {
deps.push(codeUnit.metadata);
}
}
this.exportListBuilder_.buildExportList(deps, loader);
}
get options() {
return options;
}
bundledModule(name) {
return this.moduleStore_.bundleStore[name];
}
}
| google/FakeMaker | extension/third_party/traceur-compiler/src/runtime/LoaderHooks.js | JavaScript | bsd-3-clause | 6,627 |
<?php
namespace frontend\modules\vendor\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\modules\vendor\models\VendorInfo;
/**
* VendorInfoSearch represents the model behind the search form about `frontend\modules\vendor\models\VendorInfo`.
*/
class VendorInfoSearch extends VendorInfo
{
/**
* @inheritdoc
*/
public function rules()
{
return [
[['vendorInfoId', 'vendorId', 'createdBy', 'updatedBy'], 'integer'],
[['firstName', 'lastName', 'telephone', 'mobile', 'fax', 'createdDate', 'updatedDate'], 'safe'],
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
if(isset($params['searchnewType']) && ($params['searchnewType'] == 'vendor'))
{
$query = VendorInfo::find()->where(['vendorId' => Yii::$app->vendoruser->vendorid]);
}
else {
$query = VendorInfo::find();
}
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'vendorInfoId' => $this->vendorInfoId,
'vendorId' => $this->vendorId,
'createdBy' => $this->createdBy,
'updatedBy' => $this->updatedBy,
'createdDate' => $this->createdDate,
'updatedDate' => $this->updatedDate,
]);
$query->andFilterWhere(['like', 'firstName', $this->firstName])
->andFilterWhere(['like', 'lastName', $this->lastName])
->andFilterWhere(['like', 'telephone', $this->telephone])
->andFilterWhere(['like', 'mobile', $this->mobile])
->andFilterWhere(['like', 'fax', $this->fax]);
return $dataProvider;
}
}
| ewwgit/weavesme | frontend/modules/vendor/models/VendorInfoSearch.php | PHP | bsd-3-clause | 2,385 |
Deface::Override.new( virtual_path: 'spree/admin/shared/_order_submenu',
name: 'order_history_menu',
insert_bottom: "[data-hook='admin_order_tabs']",
text: "
<li <%== 'class=\"active\"' if current == 'Order History' %>><%= link_to_with_icon 'icon-shopping-cart', Spree.t(:order_history), versions_admin_order_path(@order) %></li>
"
) | Sinetheta/solidus_papertrail | app/overrides/add_order_history_to_order_menu.rb | Ruby | bsd-3-clause | 448 |
/*****************************************************************************
* Copyright (c) 2011, Marcello Bonfe'
* ENDIF - ENgineering Department In Ferrara,
* University of Ferrara.
* 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 University of Ferrara 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 MARCELLO BONFE' BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*****************************************************************************
* *
* Author: Marco Altafini *
* *
* Filename: InputCapture.h *
* Date: 15/05/2012 *
* File Version: 1.3 *
* Compiler: MPLAB C30 v3.23 *
* *
***********************************************************************
* Code Description
*
* Header file for Input capture module.
*
**********************************************************************/
#ifndef INPUTCAPTURE_H
#define INPUTCAPTURE_H
//INPUT CAPTURE FOR TIMER SELECT BIT
#define IC_TIMER2 1
#define IC_TIMER3 0
//SELECT NUMBER OF CAPTURE FOR INTERRUPT BIT
#define IC_INT_1CAPTURE 0
#define IC_INT_2CAPTURE 1
#define IC_INT_3CAPTURE 2
#define IC_INT_4CAPTURE 3
//INPUT CAPTURE FOR MODE SELECT BIT
#define IC_TURNED_OFF 0
#define IC_EVERY_RFEDGE 1 // every rising and falling edge
#define IC_EVERY_FEDGE 2 // every falling edge
#define IC_EVERY_REDGE 3 // every rising edge
#define IC_EVERY_4EDGE 4 // every 4 rising edge
#define IC_EVERY_16EDGE 5 // every 16 rising edge
#define UNUSED 6
//INPUT CAPTURE FIRST USE
extern uint8_t IC1_FIRST;
extern uint8_t IC2_FIRST;
//extern uint8_t IC7_FIRST;
//PERIOD AND PULSE VARIABLE FOR INPUT CAPTURE
extern int32_t IC1Period, IC2Period, IC7Period;
extern int16_t IC1Pulse, IC2Pulse, IC7Pulse;
//extern uint16_t IC1currentPeriod_temp, IC1previousPeriod_temp;
//extern uint16_t IC2currentPeriod_temp, IC2previousPeriod_temp;
//Functions with Global Scope
void IC1_Init(void);
void IC2_Init(void);
//void IC7_Init(void);
void __attribute__((interrupt,auto_psv)) _IC1Interrupt(void);
void __attribute__((interrupt,auto_psv)) _IC2Interrupt(void);
//void __attribute__((interrupt,auto_psv)) _IC7Interrupt(void);
#endif
| Roberto5/rawbot | include/InputCapture.h | C | bsd-3-clause | 4,075 |
px4_add_board(
PLATFORM nuttx
VENDOR px4
MODEL fmu-v5x
LABEL default
TOOLCHAIN arm-none-eabi
ARCHITECTURE cortex-m7
ROMFSROOT px4fmu_common
IO px4_io-v2_default
TESTING
UAVCAN_INTERFACES 2
SERIAL_PORTS
GPS1:/dev/ttyS0
TEL1:/dev/ttyS6
TEL2:/dev/ttyS4
TEL3:/dev/ttyS2
GPS2:/dev/ttyS0
DRIVERS
adc
barometer # all available barometer drivers
batt_smbus
camera_capture
camera_trigger
differential_pressure # all available differential pressure drivers
distance_sensor # all available distance sensor drivers
gps
#heater
imu/adis16448
imu/adis16497
#imu # all available imu drivers
imu/bmi088
# TBD imu/ism330dlc - needs bus selection
imu/mpu6000
irlock
lights/blinkm
lights/oreoled
lights/pca8574
lights/rgbled
lights/rgbled_ncp5623c
magnetometer # all available magnetometer drivers
#md25
mkblctrl
optical_flow # all available optical flow drivers
pca9685
power_monitor/ina226
#protocol_splitter
pwm_input
pwm_out_sim
px4fmu
px4io
rc_input
roboclaw
safety_button
tap_esc
telemetry # all available telemetry drivers
test_ppm
tone_alarm
uavcan
MODULES
attitude_estimator_q
camera_feedback
commander
dataman
ekf2
events
fw_att_control
fw_pos_control_l1
land_detector
landing_target_estimator
load_mon
local_position_estimator
logger
mavlink
mc_att_control
mc_pos_control
navigator
rover_pos_control
sensors
sih
vmount
vtol_att_control
airspeed_selector
SYSTEMCMDS
bl_update
config
dmesg
dumpfile
esc_calib
hardfault_log
i2cdetect
led_control
mixer
motor_ramp
motor_test
mtd
nshterm
param
perf
pwm
reboot
reflect
sd_bench
shutdown
tests # tests and test runner
top
topic_listener
tune_control
usb_connected
ver
EXAMPLES
bottle_drop # OBC challenge
fixedwing_control # Tutorial code from https://px4.io/dev/example_fixedwing_control
hello
hwtest # Hardware test
#matlab_csv_serial
px4_mavlink_debug # Tutorial code from http://dev.px4.io/en/debug/debug_values.html
px4_simple_app # Tutorial code from http://dev.px4.io/en/apps/hello_sky.html
rover_steering_control # Rover example app
segway
uuv_example_app
)
| dagar/Firmware | boards/px4/fmu-v5x/default.cmake | CMake | bsd-3-clause | 2,230 |
<?php
/**
* PhoneNormalizer
*
* Copyright (c) 2015, Dmitry Mamontov <d.slonyara@gmail.com>.
* 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 Dmitry Mamontov nor the names of his
* 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.
*
* @package phone-normalizer
* @author Dmitry Mamontov <d.slonyara@gmail.com>
* @copyright 2015 Dmitry Mamontov <d.slonyara@gmail.com>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @since File available since Release 1.0.1
*/
namespace DmitryMamontov\PhoneNormalizer\Object;
/**
* PhoneObject - The object of the phone number.
*
* @author Dmitry Mamontov <d.slonyara@gmail.com>
* @copyright 2015 Dmitry Mamontov <d.slonyara@gmail.com>
* @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License
* @version Release: 1.0.1
* @link https://github.com/dmamontov/phone-normalizer/
* @since Class available since Release 1.0.1
*/
class PhoneObject
{
/**
* Data on the country.
*
* @var array
* @access protected
*/
protected $country = array('code' => null, 'name' => null, 'iso' => null);
/**
* Region code, city or mobile operator.
*
* @var string
* @access protected
*/
protected $code;
/**
* Phone without any codes.
*
* @var string
* @access protected
*/
protected $number;
/**
* Create an object of a phone number.
*
* @param integer $countryCode
* @param string $countryName
* @param string $code
* @param string $number
* @access public
*/
public function __construct($countryCode = null, $countryName = null, $code = null, $number = null, $countryIso = null)
{
if (!is_null($countryCode)) {
$this->setCountryCode($countryCode);
}
if (!is_null($countryName)) {
$this->setCountryName($countryName);
}
if (!is_null($countryIso)) {
$this->setCountryIso($countryIso);
}
if (!is_null($code)) {
$this->setCode($code);
}
if (!is_null($number)) {
$this->setNumber($number);
}
}
/**
* Get the code for the country.
*
* @return integer
* @access public
*/
public function getCountryCode()
{
return $this->country['code'];
}
/**
* Set the country code.
*
* @param integer $countryCode
* @return PhoneObject
* @access public
*/
public function setCountryCode($countryCode)
{
$this->country['code'] = $countryCode;
return $this;
}
/**
* Get the name of the country.
*
* @return string
* @access public
*/
public function getCountryName()
{
return $this->country['name'];
}
/**
* Set the name of the country.
*
* @param string $countryName
* @return PhoneObject
* @access public
*/
public function setCountryName($countryName)
{
$this->country['name'] = $countryName;
return $this;
}
/**
* Get the iso code of the country.
*
* @return string
* @access public
*/
public function getCountryIso()
{
return $this->country['iso'];
}
/**
* Set the iso code of the country.
*
* @param string $countryIso
* @return PhoneObject
* @access public
*/
public function setCountryIso($countryIso)
{
$this->country['iso'] = $countryIso;
return $this;
}
/**
* Get the code for the region, city or mobile operator.
*
* @return string
* @access public
*/
public function getCode()
{
return $this->code;
}
/**
* Set the area code, city or mobile operator.
*
* @param string $code
* @return PhoneObject
* @access public
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
/**
* Get the phone number without any codes.
*
* @return string
* @access public
*/
public function getNumber()
{
return $this->number;
}
/**
* Set the phone number without any codes.
*
* @param string $number
* @return PhoneObject
* @access public
*/
public function setNumber($number)
{
$this->number = $number;
return $this;
}
/**
* Format phone number in a given format.
* The variables available in the format:
* - # indicates one telephone number. It does not take into account the country code and area code.
* - #CC# сode of the country.
* - #CN# the name of the country.
* - #c# area code, city or mobile operator.
*
* @param string $format
* @return string
* @access public
*/
public function format($format = '+#CC#(#c#)###-##-##')
{
if (strpos($format, '#c#') !== false) {
$format = str_replace('#c#', $this->getCode(), $format);
}
if (strpos($format, '#CC#') !== false) {
$format = str_replace('#CC#', $this->getCountryCode(), $format);
}
if (strpos($format, '#CN#') !== false) {
$format = str_replace('#CN#', $this->getCountryName(), $format);
}
$number = $this->getNumber();
for ($length = 0, $position = 0; $length < strlen($format); $length++) {
if ($position < strlen($number) && $format[$length] == '#') {
$format[$length] = $number[$position++];
} else if ($format[$length] == '#') {
$format[$length] = ' ';
}
}
$format = preg_replace('/[\s|\n|\t]+/', ' ', $format);
$format = str_replace(array('()', '[]'), '', $format);
$format = str_replace(array('- '), ' ', $format);
return trim($format);
}
}
| dmamontov/phone-normalizer | lib/DmitryMamontov/PhoneNormalizer/Object/PhoneObject.php | PHP | bsd-3-clause | 7,400 |
import React from 'react';
import intersection from 'lodash/intersection';
import uniq from 'lodash/uniq';
import xor from 'lodash/xor';
import BulkNotice from './bulkNotice';
type RenderProps = {
/**
* Are all rows on current page selected?
*/
isPageSelected: boolean;
/**
* Callback for toggling single row
*/
onRowToggle: (id: string) => void;
/**
* Callback for toggling all rows across all pages
*/
onAllRowsToggle: (select: boolean) => void;
/**
* Callback for toggling all rows on current page
*/
onPageRowsToggle: (select: boolean) => void;
/**
* Ready to be rendered summary component showing how many items are selected,
* with buttons to select everything, cancel everything, etc...
*/
renderBulkNotice: () => React.ReactNode;
} & Pick<State, 'selectedIds' | 'isAllSelected'>;
type State = {
/**
* Selected ids on the current page
*/
selectedIds: string[];
/**
* Are all rows across all pages selected?
*/
isAllSelected: boolean;
};
type Props = {
/**
* Array of ids on current page
*/
pageIds: string[];
/**
* Number of all rows across all pages
*/
allRowsCount: number;
/**
* Number of grid columns to stretch the selection summary (used in BulkNotice)
*/
columnsCount: number;
/**
* Children with render props
*/
children: (props: RenderProps) => React.ReactNode;
/**
* Maximum number of rows that can be bulk manipulated at once (used in BulkNotice)
*/
bulkLimit?: number;
};
class BulkController extends React.Component<Props, State> {
state: State = {
selectedIds: [],
isAllSelected: false,
};
static getDerivedStateFromProps(props: Props, state: State) {
return {
...state,
selectedIds: intersection(state.selectedIds, props.pageIds),
};
}
handleRowToggle = (id: string) => {
this.setState(state => ({
selectedIds: xor(state.selectedIds, [id]),
isAllSelected: false,
}));
};
handleAllRowsToggle = (select: boolean) => {
const {pageIds} = this.props;
this.setState({
selectedIds: select ? [...pageIds] : [],
isAllSelected: select,
});
};
handlePageRowsToggle = (select: boolean) => {
const {pageIds} = this.props;
this.setState(state => ({
selectedIds: select
? uniq([...state.selectedIds, ...pageIds])
: state.selectedIds.filter(id => !pageIds.includes(id)),
isAllSelected: false,
}));
};
render() {
const {pageIds, children, columnsCount, allRowsCount, bulkLimit} = this.props;
const {selectedIds, isAllSelected} = this.state;
const isPageSelected =
pageIds.length > 0 && pageIds.every(id => selectedIds.includes(id));
const renderProps: RenderProps = {
selectedIds,
isAllSelected,
isPageSelected,
onRowToggle: this.handleRowToggle,
onAllRowsToggle: this.handleAllRowsToggle,
onPageRowsToggle: this.handlePageRowsToggle,
renderBulkNotice: () => (
<BulkNotice
allRowsCount={allRowsCount}
selectedRowsCount={selectedIds.length}
onUnselectAllRows={() => this.handleAllRowsToggle(false)}
onSelectAllRows={() => this.handleAllRowsToggle(true)}
columnsCount={columnsCount}
isPageSelected={isPageSelected}
isAllSelected={isAllSelected}
bulkLimit={bulkLimit}
/>
),
};
return children(renderProps);
}
}
export default BulkController;
| beeftornado/sentry | src/sentry/static/sentry/app/components/bulkController/index.tsx | TypeScript | bsd-3-clause | 3,491 |
//! Defines some usefull constants
/// Properties names constant for HTTP headers
pub mod properties {
pub const CONTENT_LENGTH: &'static str = "Content-Length";
pub const CONTENT_TYPE: &'static str = "Content-Type";
pub const ACCEPT: &'static str = "Accept";
pub const DATE: &'static str = "Date";
pub const LOCATION: &'static str = "Location";
}
/// Mime types constants
pub mod mimetypes {
pub const TEXT_PLAIN: &'static str = "text/plain";
pub const APP_JSON: &'static str = "application/json";
pub const APP_XML: &'static str = "application/xml";
pub const APP_OCTET_STREAM: &'static str = "application/octet-stream";
}
| phsym/http-rs | src/http/constants.rs | Rust | bsd-3-clause | 654 |
<?php
/**
* Check if input is a number
*
* @author Sitebase (Wim Mostmans)
* @copyright Copyright (c) 2011, Sitebase (http://www.sitebase.be)
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
*/
class WpFramework_Validators_Integer extends WpFramework_Validators_Abstract
{
private $_min;
private $_max;
/**
* Constructor
*
* @param string $message
* @param int $min
* @param int $max
*/
public function __construct($message, $min=null, $max=null){
$this->failMessage = $message;
$this->_min = $min;
$this->_max = $max;
}
/**
* Validate this element
*
* @access public
* @param int $var
* @return bool
*/
public function validate($var){
$valid = TRUE;
if(is_numeric($this->_min) && $this->_min > $var){
$valid = FALSE;
}
if(is_numeric($this->_max) && $this->_max < $var){
$valid = FALSE;
}
if(!is_numeric($var)){
$valid = FALSE;
}
return $valid;
}
} | Sitebase/wpframework | library/wp-framework/Validators/Integer.php | PHP | bsd-3-clause | 988 |
See also [releases](https://github.com/NLog/NLog/releases) and [milestones](https://github.com/NLog/NLog/milestones).
Date format: (year/month/day)
## Change Log
### v5.0-RC2 (2022/01/19)
#### Features
- [#4761](https://github.com/NLog/NLog/pull/4761) LogFactory fluent Setup with AddCallSiteHiddenAssembly (#4761) (@snakefoot)
- [#4757](https://github.com/NLog/NLog/pull/4757) Updated JetBrains Annotations with StructuredMessageTemplateAttribute (#4757) (@snakefoot)
- [#4754](https://github.com/NLog/NLog/pull/4754) JsonArrayLayout - Render LogEvent in Json-Array format (#4754) (@snakefoot)
- [#4613](https://github.com/NLog/NLog/pull/4613) Added LogFactory.ReconfigureExistingLoggers with purgeObsoleteLoggers option (#4613) (@sjafarianm)
- [#4711](https://github.com/NLog/NLog/pull/4711) Added WithProperties-method for Logger-class (#4711) (@simoneserra93)
#### Improvements
- [#4730](https://github.com/NLog/NLog/pull/4730) MemoryTarget - Updated to implement TargetWithLayoutHeaderAndFooter (#4730) (@snakefoot)
- [#4730](https://github.com/NLog/NLog/pull/4730) TraceTarget - Updated to implement TargetWithLayoutHeaderAndFooter (#4730) (@snakefoot)
- [#4717](https://github.com/NLog/NLog/pull/4717) DatabaseTarget - Improved parsing of DbType (#4717) (@Orace)
### v5.0-RC1 (2021/12/20)
#### Features
- [#4662](https://github.com/NLog/NLog/pull/4662) LogFactory Setup fluent with SetupLogFactory for general options (#4662) (@snakefoot)
- [#4648](https://github.com/NLog/NLog/pull/4648) LogFactory fluent Setup with FilterDynamicIgnore + FilterDynamicLog (#4648) (@snakefoot)
- [#4642](https://github.com/NLog/NLog/pull/4642) TargetWithContext - Added support for ExcludeProperties (#4642) (@snakefoot)
#### Improvements
- [#4656](https://github.com/NLog/NLog/pull/4656) FallbackGroupTarget - Added support for EnableBatchWrite (#4656) (@snakefoot)
- [#4655](https://github.com/NLog/NLog/pull/4655) JsonLayout - ExcludeProperties should also handle IncludeScopeProperties (#4655) (@snakefoot)
- [#4645](https://github.com/NLog/NLog/pull/4645) TargetWithContext - IncludeEmptyValue false by default (#4645) (@snakefoot)
- [#4646](https://github.com/NLog/NLog/pull/4646) PropertiesDictionary - Generate unique message-template-names on duplicate keys (#4646) (@snakefoot)
- [#4661](https://github.com/NLog/NLog/pull/4661) LoggingRule - Fix XML documentation (#4661) (@GitHubPang)
- [#4671](https://github.com/NLog/NLog/pull/4671) Fixed RegisterObjectTransformation to handle conversion to simple values (#4671) (@snakefoot)
- [#4669](https://github.com/NLog/NLog/pull/4669) LogLevel - Replaced IConvertible with IFormattable for better Json output (#4669) (@snakefoot)
- [#4676](https://github.com/NLog/NLog/pull/4676) NLog.Wcf - Updated nuget dependencies to System.ServiceModel ver. 4.4.4 (#4676) (@snakefoot)
- [#4675](https://github.com/NLog/NLog/pull/4675) FileTarget - Improve fallback logic when running on Linux without File BirthTIme (#4675) (@snakefoot)
- [#4680](https://github.com/NLog/NLog/pull/4680) FileTarget - Better handling of relative paths with FileSystemWatcher (#4680) (@snakefoot)
- [#4689](https://github.com/NLog/NLog/pull/4689) Renamed AppSettingLayoutRenderer2 to AppSettingLayoutRenderer after removing NLog.Extended (#4689) (@snakefoot)
- [#4563](https://github.com/NLog/NLog/pull/4563) Added alias ToUpper and ToLower as alternative to UpperCase and LowerCase (#4563) (@snakefoot)
- [#4695](https://github.com/NLog/NLog/pull/4695) Ignore dash (-) when parsing layouts, layoutrenderers and targets (#4695) (@304NotModified)
- [#4713](https://github.com/NLog/NLog/pull/4713) Logger SetProperty marked as obsolete, instead use WithProperty or the unsafe Properties-property (#4713) (@snakefoot)
- [#4714](https://github.com/NLog/NLog/pull/4714) Hide obsolete methods from intellisense (#4714) (@snakefoot)
#### Performance
- [#4672](https://github.com/NLog/NLog/pull/4672) PaddingLayoutRendererWrapper - Pad operation with reduced string allocation (#4672) (@snakefoot)
- [#4698](https://github.com/NLog/NLog/pull/4698) FileTarget - Use Environment.TickCount to trigger File.Exists checks (#4698) (@snakefoot)
- [#4699](https://github.com/NLog/NLog/pull/4699) AsyncTargetWrapper - Fix performance for OverflowAction Block on NetCore (#4699) (@snakefoot)
- [#4705](https://github.com/NLog/NLog/pull/4705) LogEventInfo - Faster clone of messageTemplateParameters by caching Count (#4705) (@snakefoot)
### v5.0-Preview 2 (2021/10/02)
#### Bugfixes
- [#4533](https://github.com/NLog/NLog/pull/4533) Fixed validation of nlog-element when using include-files (#4533) (@snakefoot)
- [#4555](https://github.com/NLog/NLog/pull/4555) Fixed validation of nlog-element when nested within configuration-element (#4555) (@snakefoot)
#### Features
- [#4542](https://github.com/NLog/NLog/pull/4542) NetworkTarget - Added OnQueueOverflow with default Discard (#4542) (@snakefoot)
#### Improvements
- [#4544](https://github.com/NLog/NLog/pull/4544) ScopeContext - Renamed IncludeScopeNestedStates to IncludeScopeNested for consistency (#4544) (@snakefoot)
- [#4545](https://github.com/NLog/NLog/pull/4545) ScopeContext - Renamed PushScopeState to PushScopeNested for consistency (#4545) (@snakefoot)
- [#4556](https://github.com/NLog/NLog/pull/4556) NetworkTarget - Explicit assigning LineEnding activates NewLine automatically (#4556) (@snakefoot)
- [#4549](https://github.com/NLog/NLog/pull/4549) NetworkTarget - UdpNetworkSender changed to QueuedNetworkSender with correct message split (#4549) (@snakefoot)
- [#4542](https://github.com/NLog/NLog/pull/4542) NetworkTarget - Changed OnConnectionOverflow to discard by default (#4542) (@snakefoot)
- [#4564](https://github.com/NLog/NLog/pull/4564) Fixed LayoutParser so Typed Layout works for LayoutRenderer (#4564) (@snakefoot)
- [#4580](https://github.com/NLog/NLog/pull/4580) LayoutRenderer and Layout are now always threadsafe by default (#4580) (@snakefoot)
- [#4586](https://github.com/NLog/NLog/pull/4586) ScopeTiming - No Format specified renders TimeSpan.TotalMilliseconds (#4586) (@snakefoot)
- [#4583](https://github.com/NLog/NLog/pull/4583) ExceptionLayoutRenderer - Separator with basic layout support (#4583) (@snakefoot)
- [#4588](https://github.com/NLog/NLog/pull/4588) StackTraceLayoutRenderer - Separator with basic layout support (#4588) (@snakefoot)
- [#4589](https://github.com/NLog/NLog/pull/4589) ScopeNestedLayoutRenderer - Separator with basic layout support (#4589) (@snakefoot)
### v5.0-Preview 1 (2021/08/25)
See NLog 5 release post: https://nlog-project.org/2021/08/25/nlog-5-0-preview1-ready.html
- [Breaking Changes](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22breaking%20change%22+is%3Amerged+milestone:%225.0%20%28new%29%22)
- [Breaking Behavior Changes](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22breaking%20behavior%20change%22+is%3Amerged+milestone:%225.0%20%28new%29%22)
- [Features](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22Feature%22+is%3Amerged+milestone:%225.0%20%28new%29%22)
- [Improvements](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22Enhancement%22+is%3Amerged+milestone:%225.0%20%28new%29%22)
- [Performance](https://github.com/NLog/NLog/pulls?q=is%3Apr+label%3A%22Performance%22+is%3Amerged+milestone:%225.0%20%28new%29%22)
### v4.7.13 (2021/12/05)
### Bugfixes
- [#4700](https://github.com/NLog/NLog/pull/4700) AsyncTargetWrapper - Fix performance for OverflowAction Block on NetCore (#4700) (@snakefoot)
- [#4644](https://github.com/NLog/NLog/pull/4644) AsyncTargetWrapper - Swallow OutOfMemoryException instead of crashing (#4644) (@snakefoot)
### Improvements
- [#4649](https://github.com/NLog/NLog/pull/4649) Fix broken XML doc comment (#4649) (@GitHubPang)
### v4.7.12 (2021/10/24)
#### Bugfixes
- [#4627](https://github.com/NLog/NLog/pull/4627) PropertiesDictionary - Fixed threading issue in EventProperties (#4627) (@snakefoot)
- [#4631](https://github.com/NLog/NLog/pull/4631) FileTarget - Failing to CleanupInitializedFiles should not stop logging (#4631) (@snakefoot)
#### Features
- [#4629](https://github.com/NLog/NLog/pull/4629) LogEventInfo constructor with eventProperties as IReadOnlyList (#4629) (@snakefoot)
### v4.7.11 (2021/08/18)
#### Bugfixes
- [#4519](https://github.com/NLog/NLog/pull/4519) JsonSerializer - Fix CultureNotFoundException with Globalization Invariant Mode (#4519) (@snakefoot)
#### Features
- [#4475](https://github.com/NLog/NLog/pull/4475) WebServiceTarget - Added support for assigning UserAgent-Header (#4475) (@snakefoot)
### v4.7.10 (2021/05/14)
#### Bugfixes
- [#4401](https://github.com/NLog/NLog/pull/4401) JsonSerializer - Fixed bug when handling custom IConvertible returning TypeCode.Empty (#4401) (@snakefoot)
#### Improvements
- [#4391](https://github.com/NLog/NLog/pull/4391) Support TargetDefaultParameters and TargetDefaultWrapper (#4391) (@snakefoot)
- [#4403](https://github.com/NLog/NLog/pull/4403) JsonLayout - Apply EscapeForwardSlash for LogEventInfo.Properties (#4403) (@snakefoot)
- [#4393](https://github.com/NLog/NLog/pull/4393) NLog.Config package: Updated hyperlink (#4393) (@snakefoot)
### v4.7.9 (2021/03/24)
#### Bugfixes
- [#4349](https://github.com/NLog/NLog/pull/4349) Fixed TrimDirectorySeparators to not use the root-path on Linux (#4349) (@snakefoot)
- [#4353](https://github.com/NLog/NLog/pull/4353) Fixed FileTarget archive cleanup within same folder at startup (#4353) (@snakefoot)
- [#4352](https://github.com/NLog/NLog/pull/4352) Fixed FileTarget archive cleanup when using short filename (#4352) (@snakefoot)
#### Improvements
- [#4326](https://github.com/NLog/NLog/pull/4326) Make it possible to extend the FuncLayoutRenderer (#4326) (@304NotModified)
- [#4369](https://github.com/NLog/NLog/pull/4369) + [#4375](https://github.com/NLog/NLog/pull/4375) LoggingConfigurationParser - Recognize LoggingRule.FilterDefaultAction (#4369 + #4375) (@snakefoot)
#### Performance
- [#4337](https://github.com/NLog/NLog/pull/4337) JsonLayout - Avoid constant string-escape of JsonAttribute Name-property (#4337) (@snakefoot)
### V4.7.8 (2021/02/25)
#### Bugfixes
- [#4316](https://github.com/NLog/NLog/pull/4316) Fix TrimDirectorySeparators to handle root-path on Windows and Linux to load Nlog.config from root-path (#4316) (@snakefoot)
#### Improvements
- [#4273](https://github.com/NLog/NLog/pull/4273) Handle Breaking change with string.IndexOf(string) in .NET 5 (#4273) (@snakefoot)
- [#4301](https://github.com/NLog/NLog/pull/4301) Update docs, remove ArrayList in docs (#4301) (@304NotModified)
### V4.7.7 (2021/01/20)
#### Bugfixes
- [#4229](https://github.com/NLog/NLog/pull/4229) Skip lookup MainModule.FileName on Android platform to avoid crash (#4229) (@snakefoot)
- [#4202](https://github.com/NLog/NLog/pull/4202) JsonLayout - Generate correct json for keys that contain quote (#4202) (@virgilp)
- [#4245](https://github.com/NLog/NLog/pull/4245) JsonLayout - Unwind after invalid property value to avoid invalid Json (#4245) (@snakefoot)
#### Improvements
- [#4222](https://github.com/NLog/NLog/pull/4222) Better handling of low memory (#4222) (@snakefoot)
- [#4221](https://github.com/NLog/NLog/pull/4221) JsonLayout - Added new ExcludeEmptyProperties to skip GDC/MDC/MLDC properties with null or empty values (#4221) (@pruiz)
#### Performance
- [#4207](https://github.com/NLog/NLog/pull/4207) Skip allocation of SingleCallContinuation when ThrowExceptions = false (#4207) (@snakefoot)
### V4.7.6 (2020/12/06)
#### Bugfixes
- [#4142](https://github.com/NLog/NLog/pull/4142) JsonSerializer - Ensure invariant formatting of DateTimeOffset (#4142) (@snakefoot)
- [#4172](https://github.com/NLog/NLog/pull/4172) AsyncTaskTarget - Flush when buffer is full should not block forever (#4172) (@snakefoot)
- [#4182](https://github.com/NLog/NLog/pull/4182) Failing to lookup ProcessName because of Access Denied should fallback to Win32-API (#4182) (@snakefoot)
#### Features
- [#4153](https://github.com/NLog/NLog/pull/4153) ExceptionLayoutRenderer - Added FlattenException option (#4153) (@snakefoot)
#### Improvements
- [#4141](https://github.com/NLog/NLog/pull/4141) NetworkTarget - Improve handling of synchronous exceptions from UdpClient.SendAsync (#4141) (@snakefoot)
- [#4176](https://github.com/NLog/NLog/pull/4176) AsyncTaskTarget - Include TaskScheduler in ContinueWith (#4176) (@snakefoot)
- [#4190](https://github.com/NLog/NLog/pull/4190) Improving debugger-display for Logger.Properties and LogEventInfo.Properties (@snakefoot)
#### Performance
- [#4132](https://github.com/NLog/NLog/pull/4132) Improve thread concurrency when using wrapper cached=true (#4132) (@snakefoot)
- [#4171](https://github.com/NLog/NLog/pull/4171) ConditionLayoutExpression - Skip allocating StringBuilder for every condition check (#4171) (@snakefoot)
### V4.7.5 (2020/09/27)
#### Bugfixes
- [#4106](https://github.com/NLog/NLog/pull/4106) FileTarget - New current file should write start header, when archive operation is performed on previous file (#4106) (@snakefoot)
#### Improvements
- [#4102](https://github.com/NLog/NLog/pull/4102) LoggingConfiguration - ValidateConfig should only throw when enabled (#4102) (@snakefoot)
- [#4114](https://github.com/NLog/NLog/pull/4114) Fix VerificationException Operation could destabilize the runtime (#4114) (@snakefoot)
#### Performance
- [#4115](https://github.com/NLog/NLog/pull/4115) Removed EmptyDefaultDictionary from MappedDiagnosticsContext (#4115) (@snakefoot)
#### Other
- [#4109](https://github.com/NLog/NLog/pull/4109) Fix root .editorconfig to use end_of_line = CRLF. Remove local .editorconfig (#4109) (@snakefoot)
- [#4097](https://github.com/NLog/NLog/pull/4097) Improve docs (#4097) (@304NotModified)
### V4.7.4 (2020/08/22)
#### Features
- [#4076](https://github.com/NLog/NLog/pull/4076) DatabaseTarget - Added AllowDbNull for easier support for nullable parameters (#4076) (@snakefoot)
#### Bugfixes
- [#4069](https://github.com/NLog/NLog/pull/4069) Fluent LogBuilder should suppress exception on invalid callerFilePath (#4069) (@snakefoot)
#### Improvements
- [#4073](https://github.com/NLog/NLog/pull/4073) FileTarget - Extra validation of the LogEvent-timestamp before checking time to archive (#4073) (@snakefoot)
- [#4068](https://github.com/NLog/NLog/pull/4068) FileTarget - Improve diagnostic logging to see reason for archiving (@snakefoot)
### V4.7.3 (2020/07/31)
#### Features
- [#4017](https://github.com/NLog/NLog/pull/4017) Allow to change the RuleName of a LoggingRule (#4017) (@304NotModified)
- [#3974](https://github.com/NLog/NLog/pull/3974) logging of AggregrateException.Data to prevent it from losing it after Flatten call (#3974) (@chaos0307)
#### Bugfixes
- [#4011](https://github.com/NLog/NLog/pull/4011) LocalIpAddressLayoutRenderer - IsDnsEligible and PrefixOrigin throws PlatformNotSupportedException on Linux (#4011) (@snakefoot)
#### Improvements
- [#4057](https://github.com/NLog/NLog/pull/4057) ObjectReflectionCache - Reduce noise from properties that throws exceptions like Stream.ReadTimeout (#4057) (@snakefoot)
- [#4053](https://github.com/NLog/NLog/pull/4053) MessageTemplates - Changed Literal.Skip to be Int32 to support message templates longer than short.MaxValue (#4053) (@snakefoot)
- [#4043](https://github.com/NLog/NLog/pull/4043) ObjectReflectionCache - Skip reflection for Stream objects (#4043) (@snakefoot)
- [#3999](https://github.com/NLog/NLog/pull/3999) LogFactory Shutdown is public so it can be used from NLogLoggerProvider (#3999) (@snakefoot)
- [#3972](https://github.com/NLog/NLog/pull/3972) Editor config with File header template (#3972) (@304NotModified)
#### Performance
- [#4058](https://github.com/NLog/NLog/pull/4058) FileTarget - Skip delegate capture in GetFileCreationTimeSource. Fallback only necessary when appender has been closed. (#4058) (@snakefoot)
- [#4021](https://github.com/NLog/NLog/pull/4021) ObjectReflectionCache - Reduce initial memory allocation until needed (#4021) (@snakefoot)
- [#3977](https://github.com/NLog/NLog/pull/3977) FilteringTargetWrapper - Remove delegate allocation (#3977) (@snakefoot)
### V4.7.2 (2020/05/18)
#### Bugfixes
- [#3969](https://github.com/NLog/NLog/pull/3969) FileTarget - ArchiveOldFileOnStartup not working together with ArchiveAboveSize (@snakefoot)
#### Improvements
- [#3962](https://github.com/NLog/NLog/pull/3962) XSD: Added Enabled attribute for <logger> (@304NotModified)
### V4.7.1 (2020/05/15)
#### Features
- [#3871](https://github.com/NLog/NLog/pull/3871) LogManager.Setup().LoadConfigurationFromFile("NLog.config") added to fluent setup (@snakefoot + @304NotModified)
- [#3909](https://github.com/NLog/NLog/pull/3909) LogManager.Setup().GetCurrentClassLogger() added to fluent setup (@snakefoot + @304NotModified)
- [#3861](https://github.com/NLog/NLog/pull/3861) LogManager.Setup().SetupInternalLogger(s => s.AddLogSubscription()) added to fluent setup (@snakefoot + @304NotModified)
- [#3891](https://github.com/NLog/NLog/pull/3891) ColoredConsoleTarget - Added Condition option to control when to do word-highlight (@snakefoot)
- [#3915](https://github.com/NLog/NLog/pull/3915) Added new option CaptureStackTrace to ${stacktrace} and ${callsite} to skip implicit capture by Logger (@snakefoot)
- [#3940](https://github.com/NLog/NLog/pull/3940) Exception-LayoutRenderer with new option BaseException for rendering innermost exception (@snakefoot)
#### Improvements
- [#3857](https://github.com/NLog/NLog/pull/3857) FileTarget - Batch write to filestream in max chunksize of 100 times BufferSize (@snakefoot)
- [#3867](https://github.com/NLog/NLog/pull/3867) InternalLogger include whether NLog comes from GlobalAssemblyCache when logging NLog version (@snakefoot)
- [#3862](https://github.com/NLog/NLog/pull/3862) InternalLogger LogToFile now support ${processdir} to improve support for single-file-publish (@snakefoot)
- [#3877](https://github.com/NLog/NLog/pull/3877) Added ${processdir} that matches ${basedir:processDir=true} for consistency with InternalLogger (@snakefoot)
- [#3881](https://github.com/NLog/NLog/pull/3881) Object property reflection now support IReadOnlyDictionary as expando object (@snakefoot)
- [#3884](https://github.com/NLog/NLog/pull/3884) InternalLogger include more details like FilePath when loading NLog.config file (@snakefoot)
- [#3895](https://github.com/NLog/NLog/pull/3895) Added support for Nullable when doing conversion of property types (@304NotModified)
- [#3896](https://github.com/NLog/NLog/pull/3896) InternalLogger Warnings when skipping unrecognized LayoutRenderer options (@snakefoot)
- [#3901](https://github.com/NLog/NLog/pull/3901) MappedDiagnosticsLogicalContext - SetScoped with IReadOnlyList also for Xamarin (@snakefoot)
- [#3904](https://github.com/NLog/NLog/pull/3904) Object property reflection automatically performs ToString for System.Reflection.Module (@snakefoot)
- [#3921](https://github.com/NLog/NLog/pull/3921) Improve ${basedir:fixtempdir=true} to work better on Linux when TMPDIR not set (@snakefoot)
- [#3928](https://github.com/NLog/NLog/pull/3928) NetworkTarget respect MaxQueueSize for http- / https-protocol (@snakefoot)
- [#3930](https://github.com/NLog/NLog/pull/3930) LogFactory.LoadConfiguration() reports searched paths when throwing FileNotFoundException (@304NotModified)
- [#3949](https://github.com/NLog/NLog/pull/3949) ReplaceNewLines-LayoutRenderer will also remove windows newlines on the Linux platform (@Silvenga)
#### Bugfixes
- [#3868](https://github.com/NLog/NLog/pull/3868) SplitGroup Target Wrapper should not skip remaining targets when single target fails (@snakefoot)
- [#3918](https://github.com/NLog/NLog/pull/3918) ColoredConsoleTarget - Fix bug in handling of newlines without word-highlight (@snakefoot)
- [#3941](https://github.com/NLog/NLog/pull/3941) ${processid} will no longer fail because unable to lookup ${processdir} on Mono Android (@snakefoot)
#### Performance
- [#3855](https://github.com/NLog/NLog/pull/3855) FileTarget - Skip checking file-length when only using ArchiveEvery (@snakefoot)
- [#3898](https://github.com/NLog/NLog/pull/3898) ObjectGraphScanner performs caching of property reflection for NLog config items (@snakefoot)
- [#3894](https://github.com/NLog/NLog/pull/3894) Condition expressions now handles operator like '==' without memory boxing (@snakefoot)
- [#3903](https://github.com/NLog/NLog/pull/3903) ObjectGraphScanner should only check for layout-attributes on Layouts and LayoutRenderers (@snakefoot)
- [#3902](https://github.com/NLog/NLog/pull/3902) MessageTemplate parsing of properties skips unnecessary array allocation (@snakefoot)
### V4.7 (2020/03/20)
#### Features
- [#3686](https://github.com/NLog/NLog/pull/3686) + [#3740](https://github.com/NLog/NLog/pull/3740) LogManager.Setup() allows fluent configuration of LogFactory options (@snakefoot + @304NotModified)
- [#3610](https://github.com/NLog/NLog/pull/3610) LogManager.Setup().SetupSerialization(s => s.RegisterObjectTransformation(...)) for overriding default property reflection (@snakefoot + @304NotModified + @Giorgi + @mmurrell)
- [#3787](https://github.com/NLog/NLog/pull/3787) LogManager.Setup().SetupExtensions(s => s.RegisterConditionMethod(...)) can use lambda methods and not just static methods (@snakefoot)
- [#3713](https://github.com/NLog/NLog/pull/3713) ${level:format=FullName} will expand Info + Warn to their full name (@snakefoot)
- [#3714](https://github.com/NLog/NLog/pull/3714) + [#3734](https://github.com/NLog/NLog/pull/3734) FileTarget - Supports MaxArchiveDays for cleanup of old files based on their age (@snakefoot)
- [#3737](https://github.com/NLog/NLog/pull/3737) + [#3769](https://github.com/NLog/NLog/pull/3769) Layout.FromMethod to create Layout directly from a lambda method (@snakefoot)
- [#3771](https://github.com/NLog/NLog/pull/3771) Layout.FromString to create Layout directly from string along with optional parser validation (@snakefoot)
- [#3793](https://github.com/NLog/NLog/pull/3793) ${dir-separator} for rendering platform specific directory path separator (@304NotModified)
- [#3755](https://github.com/NLog/NLog/pull/3755) FileTarget - Supports ArchiveOldFileOnStartupAboveSize for cleanup of existing file when above size (@Sam13)
- [#3796](https://github.com/NLog/NLog/pull/3796) + [#3823](https://github.com/NLog/NLog/pull/3823) InternalLogger - Added LogMessageReceived event (@304NotModified + @snakefoot)
- [#3829](https://github.com/NLog/NLog/pull/3829) DatabaseTarget - Assign connection properties like SqlConnection.AccessToken (@304NotModified + @snakefoot)
- [#3839](https://github.com/NLog/NLog/pull/3839) DatabaseTarget - Assign command properties like SqlCommand.CommandTimeout (@snakefoot)
- [#3833](https://github.com/NLog/NLog/pull/3833) ${onHasProperties} for only rendering when logevent includes properties from structured logging (@snakefoot)
#### Improvements
- [#3521](https://github.com/NLog/NLog/pull/3521) XmlLoggingConfiguration - Marked legacy constructors with ignoreErrors parameter as obsolete (@snakefoot)
- [#3689](https://github.com/NLog/NLog/pull/3689) LoggingConfiguration - Perform checking of unused targets during initialization for better validation (@snakefoot)
- [#3704](https://github.com/NLog/NLog/pull/3704) EventLogTarget - Improve diagnostics logging when using dynamic EventLog source (@snakefoot)
- [#3706](https://github.com/NLog/NLog/pull/3706) ${longdate} now also supports raw value for use as DatabaseTarget parameter with DbType (@snakefoot)
- [#3728](https://github.com/NLog/NLog/pull/3728) SourceLink for GitHub for easy debugging into the NLog source code (@304NotModified)
- [#3743](https://github.com/NLog/NLog/pull/3743) JsonLayout - EscapeForwardSlash now automatically applies to sub-attributes (@snakefoot)
- [#3742](https://github.com/NLog/NLog/pull/3742) TraceTarget - Introduced EnableTraceFail=false to avoid Environment.FailFast (@snakefoot)
- [#3750](https://github.com/NLog/NLog/pull/3750) ExceptionLayoutRenderer - Improved error message when Format-token parsing fails (@snakefoot)
- [#3747](https://github.com/NLog/NLog/pull/3747) AutoFlushWrapper - Set AutoFlush=false for AsyncTaskTarget by default (@snakefoot)
- [#3754](https://github.com/NLog/NLog/pull/3754) LocalIpAddressLayoutRenderer - Higher priority to network-addresses that has valid gateway adddress (@snakefoot)
- [#3762](https://github.com/NLog/NLog/pull/3762) LogFactory - Flush reports to InternalLogger what targets produces timeouts (@snakefoot)
#### Bugfixes
- [#3758](https://github.com/NLog/NLog/pull/3758) LogFactory - Fix deadlock issue with AutoReload (@snakefoot)
- [#3766](https://github.com/NLog/NLog/pull/3766) JsonLayout - Fixed ThreadAgnostic to correctly capture context when using nested JsonLayout (@snakefoot)
- [#3700](https://github.com/NLog/NLog/pull/3700) ExceptionLayoutRenderer - Fixed so Format option HResult also works for NetCore (@snakefoot)
- [#3761](https://github.com/NLog/NLog/pull/3761) + [#3784](https://github.com/NLog/NLog/pull/3784) Log4JXml Layout will render NDLC + NDC scopes in correct order (@adanek + @304NotModified)
- [#3821](https://github.com/NLog/NLog/pull/3821) Logger - Added exception handler for CallSite capture for platform that fails to capture StackTrace (@snakefoot)
- [#3835](https://github.com/NLog/NLog/pull/3835) StringSplitter - Fixed quote handling when reading elements for config list-properties (@snakefoot)
- [#3828](https://github.com/NLog/NLog/pull/3828) Utilities: fix ConversionHelpers.TryParseEnum for white space (@304NotModified)
#### Performance
- [#3683](https://github.com/NLog/NLog/pull/3683) ObjectGraphScanner - Avoid holding list.SyncRoot lock while scanning (@snakefoot)
- [#3691](https://github.com/NLog/NLog/pull/3691) FileTarget - ConcurrentWrites=true on NetCore now much faster when archive enabled (@snakefoot)
- [#3694](https://github.com/NLog/NLog/pull/3694) + [#3705](https://github.com/NLog/NLog/pull/3705) JsonConverter - Write DateTime directly without string allocation (@snakefoot)
- [#3692](https://github.com/NLog/NLog/pull/3692) XmlLayout - Removed unnecessary double conversion to string (@snakefoot)
- [#3735](https://github.com/NLog/NLog/pull/3735) WebServiceTarget - Reduced memory allocations by removing unnecessary delegate capture (@snakefoot)
- [#3739](https://github.com/NLog/NLog/pull/3739) NetworkTarget - Reduced memory allocation for encoding into bytes without string allocation (@snakefoot)
- [#3748](https://github.com/NLog/NLog/pull/3748) AsyncTaskTarget - Skip default AsyncWrapper since already having internal queue (@snakefoot)
- [#3767](https://github.com/NLog/NLog/pull/3767) Mark Condition Expressions as ThreadSafe to improve concurrency in Layouts (@snakefoot)
- [#3764](https://github.com/NLog/NLog/pull/3764) DatabaseTarget - Added IsolationLevel option that activates transactions for better batching performance (@snakefoot)
- [#3779](https://github.com/NLog/NLog/pull/3779) SimpleLayout - Assignment of string-reference with null-value will translate into FixedText (@304NotModified)
- [#3790](https://github.com/NLog/NLog/pull/3790) AsyncWrapper - Less aggressive with scheduling timer events for background writing (@snakefoot)
- [#3830](https://github.com/NLog/NLog/pull/3830) Faster assignment of properties accessed through reflection (@304NotModified)
- [#3832](https://github.com/NLog/NLog/pull/3832) ${replace} - Faster search and replace when not explicitly have requested regex support (@snakefoot)
- [#3828](https://github.com/NLog/NLog/pull/3828) Skip need for Activator.CreateInstance in DbTypeSetter (@304NotModified)
### V4.6.8 (2019/11/04)
#### Bugfixes
- [#3566](https://github.com/NLog/NLog/pull/3566) DatabaseTarget - Auto escape special chars in password, and improve handling of empty username/password (@304NotModified)
- [#3584](https://github.com/NLog/NLog/pull/3584) LoggingRule - Fixed IndexOutOfRangeException for SetLoggingLevels with LogLevel.Off (@snakefoot)
- [#3609](https://github.com/NLog/NLog/pull/3609) FileTarget - Improved handling of relative path in ArchiveFileName (@snakefoot)
- [#3631](https://github.com/NLog/NLog/pull/3631) ExceptionLayoutRenderer - Fixed missing separator when Format-value gives empty result (@brinko99)
- [#3647](https://github.com/NLog/NLog/pull/3647) ${substring} - Length should not be mandatory (@304NotModified)
- [#3653](https://github.com/NLog/NLog/pull/3653) SimpleLayout - Fixed NullReferenceException in PreCalculate during TryGetRawValue optimization (@snakefoot)
#### Features
- [#3578](https://github.com/NLog/NLog/pull/3578) LogFactory - AutoShutdown can be configured to unhook from AppDomain-Unload, and avoid premature shutdown with IHostBuilder (@snakefoot)
- [#3579](https://github.com/NLog/NLog/pull/3579) PerformanceCounterLayoutRenderer - Added Layout-support for Instance-property (@snakefoot)
- [#3583](https://github.com/NLog/NLog/pull/3583) ${local-ip} Layout Renderer for local machine ip-address (@snakefoot + @304NotModified)
- [#3583](https://github.com/NLog/NLog/pull/3583) CachedLayoutRendererWrapper - Added CachedSeconds as ambient property. Ex. ${local-ip:cachedSeconds=60} (@snakefoot)
- [#3586](https://github.com/NLog/NLog/pull/3586) JsonLayout - Added EscapeForwardSlash-option to skip Json-escape of forward slash (@304NotModified)
- [#3593](https://github.com/NLog/NLog/pull/3593) AllEventPropertiesLayoutRenderer - Added Exclude-option that specifies property-keys to skip (@snakefoot)
- [#3611](https://github.com/NLog/NLog/pull/3611) ${Exception} - Added new Format-option values HResult and Properties (@snakefoot)
#### Improvements
- [#3622](https://github.com/NLog/NLog/pull/3622) + [#3651](https://github.com/NLog/NLog/pull/3651) ConcurrentRequestQueue refactoring to reduce code complexity (@snakefoot)
- [#3636](https://github.com/NLog/NLog/pull/3636) AsyncTargetWrapper now fallback to clearing internal queue if flush fails to release blocked writer threads (@snakefoot)
- [#3641](https://github.com/NLog/NLog/pull/3641) ${CallSite} - Small improvements for recognizing async callsite cases (@snakefoot)
- [#3642](https://github.com/NLog/NLog/pull/3642) LogManager.GetCurrentClassLogger - Improved capture of Logger name when called within lambda_method (@snakefoot)
- [#3649](https://github.com/NLog/NLog/pull/3649) ${BaseDir:FixTempDir=true} fallback to process directory for .NET Core 3 Single File Publish (@snakefoot)
- [#3649](https://github.com/NLog/NLog/pull/3649) Auto-loading NLog configuration from process.exe.nlog will priotize process directory for .NET Core 3 Single File Publish (@snakefoot)
- [#3654](https://github.com/NLog/NLog/pull/3654) ObjectPathRendererWrapper minor refactorings (@snakefoot)
- [#3660](https://github.com/NLog/NLog/pull/3660) ObjectHandleSerializer.GetObjectData includes SerializationFormatter=true for use in MDLC + NDLC (@snakefoot)
- [#3662](https://github.com/NLog/NLog/pull/3662) FileTarget - Extra logging when FileName Layout renders empty string (@snakefoot)
#### Performance
- [#3618](https://github.com/NLog/NLog/pull/3618) LogFactory - Faster initial assembly reflection and config loading (@snakefoot)
- [#3635](https://github.com/NLog/NLog/pull/3635) ConsoleTarget - Added WriteBuffer option that allows batch writing to console-stream with reduced allocations (@snakefoot)
- [#3635](https://github.com/NLog/NLog/pull/3635) ConsoleTarget - Added global lock to prevent any threadsafety issue from unsafe console (@snakefoot)
### V4.6.7 (2019/08/25)
#### Features
- [#3531](https://github.com/NLog/NLog/pull/3531) Added ${object-path} / ${exception:objectpath=PropertyName}, for rendering a property of an object (e.g. an exception) (#3531) (@304NotModified)
- [#3560](https://github.com/NLog/NLog/pull/3560) WhenMethodFilter - Support dynamic filtering using lambda (#3560) (@snakefoot)
- [#3184](https://github.com/NLog/NLog/pull/3184) Added support for dynamic layout renderer in log level filters (e.g. minLevel, maxLevel) (#3184) (@snakefoot)
- [#3558](https://github.com/NLog/NLog/pull/3558) ExceptionLayoutRenderer - Added Source as new format parameter. (@snakefoot)
- [#3523](https://github.com/NLog/NLog/pull/3523) ColoredConsoleTarget - Added DetectOutputRedirected to skip coloring on redirect (@snakefoot)
#### Improvements
- [#3541](https://github.com/NLog/NLog/pull/3541) MessageTemplateParameters - Improve validation of parameters when isPositional (#3541) (@snakefoot)
- [#3546](https://github.com/NLog/NLog/pull/3546) NetworkTarget - HttpNetworkSender no longer sends out-of-order (@snakefoot)
- [#3522](https://github.com/NLog/NLog/pull/3522) NetworkTarget - Fix InternalLogger.Trace to include Target name (#3522) (@snakefoot)
- [#3562](https://github.com/NLog/NLog/pull/3562) XML config - Support ThrowConfigExceptions=true even when xml is invalid (@snakefoot)
- [#3532](https://github.com/NLog/NLog/pull/3532) Fix summary of NoRawValueLayoutRendererWrapper class (#3532) (@304NotModified)
#### Performance
- [#3540](https://github.com/NLog/NLog/pull/3540) MessageTemplateParameters - Skip object allocation when no parameters (@snakefoot)
- [#3527](https://github.com/NLog/NLog/pull/3527) XmlLayout - Defer allocation of ObjectReflectionCache until needed (#3527) (@snakefoot)
### V4.6.6 (2019/07/14)
#### Features
- [#3514](https://github.com/NLog/NLog/pull/3514) Added XmlLoggingConfiguration(XmlReader reader) ctor, improved docs and annotations (@dmitrychilli, @304NotModified)
- [#3513](https://github.com/NLog/NLog/pull/3513) AutoFlushTargetWrapper - Added FlushOnConditionOnly property (@snakefoot)
#### Performance
- [#3492](https://github.com/NLog/NLog/pull/3492) FileTarget - improvements when ConcurrentWrites=false (@snakefoot)
### V4.6.5 (2019/06/13)
#### Bugfixes
- [#3476](https://github.com/NLog/NLog/pull/3476) Fix broken XSD schema - NLog.Schema package (@snakefoot, @304NotModified)
#### Features
- [#3478](https://github.com/NLog/NLog/pull/3478) XSD: Support `<value>` in `<variable>` (@304NotModified)
- [#3477](https://github.com/NLog/NLog/pull/3477) ${AppSetting} - Added support for ConnectionStrings Lookup (@snakefoot)
- [#3469](https://github.com/NLog/NLog/pull/3469) LogLevel - Added support for TypeConverter (@snakefoot)
- [#3453](https://github.com/NLog/NLog/pull/3453) Added null terminator line ending for network target (@Kahath)
- [#3442](https://github.com/NLog/NLog/pull/3442) Log4JXmlEventLayout - Added IncludeCallSite + IncludeSourceInfo (@snakefoot)
#### Improvements
- [#3482](https://github.com/NLog/NLog/pull/3482) Fix typos in docs and comments (@304NotModified)
#### Performance
- [#3444](https://github.com/NLog/NLog/pull/3444) RetryingMultiProcessFileAppender - better init BufferSize (@snakefoot)
### V4.6.4 (2019/05/28)
#### Bugfixes
- [#3392](https://github.com/NLog/NLog/pull/3392) NLog.Schema: Added missing defaultAction attribute on filters element in XSD (@304NotModified)
- [#3415](https://github.com/NLog/NLog/pull/3415) AsyncWrapper in Blocking Mode can cause deadlock (@snakefoot)
#### Features
- [#3430](https://github.com/NLog/NLog/pull/3430) Added "Properties" property on Logger for reading and editing properties.(@snakefoot, @304NotModified)
- [#3423](https://github.com/NLog/NLog/pull/3423) ${all-event-properties}: Added IncludeEmptyValues option (@304NotModified)
- [#3394](https://github.com/NLog/NLog/pull/3394) ${when}, support for non-string values (@304NotModified)
- [#3398](https://github.com/NLog/NLog/pull/3398) ${whenEmpty} support for non-string values (@snakefoot, @304NotModified)
- [#3391](https://github.com/NLog/NLog/pull/3391) Added ${environment-user} (@snakefoot)
- [#3389](https://github.com/NLog/NLog/pull/3389) Log4JXmlEventLayout - Added support for configuration of Parameters (@snakefoot)
- [#3411](https://github.com/NLog/NLog/pull/3411) LoggingConfigurationParser - Recognize LoggingRule.RuleName property (@snakefoot)
#### Improvements
- [#3393](https://github.com/NLog/NLog/pull/3393) Update package descriptions to note the issues with `<PackageReference>` (@304NotModified)
- [#3409](https://github.com/NLog/NLog/pull/3409) Various XSD improvements (NLog.Schema package) (@304NotModified)
#### Performance
- [#3398](https://github.com/NLog/NLog/pull/3398) ${whenEmpty} faster rendering of string values (@snakefoot, @304NotModified)
- [#3405](https://github.com/NLog/NLog/pull/3405) FilteringTargetWrapper: Add support for batch writing (@snakefoot, @304NotModified)
- [#3405](https://github.com/NLog/NLog/pull/3405) PostFilteringTargetWrapper: performance optimizations (@snakefoot, @304NotModified)
- [#3435](https://github.com/NLog/NLog/pull/3435) Async / buffering wrapper: Improve performance when blocking (@snakefoot)
- [#3434](https://github.com/NLog/NLog/pull/3434) ObjectReflectionCache - Skip property-reflection for IFormattable (@snakefoot)
### V4.6.3 (2019/04/30)
#### Bugfixes
- [#3345](https://github.com/NLog/NLog/pull/3345) Fixed potential memory issue and message duplication with large strings (@snakefoot)
- [#3316](https://github.com/NLog/NLog/pull/3316) TargetWithContext - serialize MDC and MDLC values properly (@304NotModified)
#### Features
- [#3298](https://github.com/NLog/NLog/pull/3298) Added WithProperty and SetProperty on Logger (@snakefoot)
- [#3329](https://github.com/NLog/NLog/pull/3329) ${EventProperties} - Added ObjectPath for rendering nested property (@snakefoot, @304NotModified)
- [#3337](https://github.com/NLog/NLog/pull/3337) ${ShortDate} added support for IRawValue + IStringValueRenderer (@snakefoot)
- [#3328](https://github.com/NLog/NLog/pull/3328) Added truncate ambient property, e.g. ${message:truncate=80} (@snakefoot)
- [#3278](https://github.com/NLog/NLog/pull/3278) ConsoleTarget & ColoredConsoleTarget - Added AutoFlush and improve default flush behavior (@snakefoot)
#### Improvements
- [#3322](https://github.com/NLog/NLog/pull/3322) FileTarget - Introduced EnableFileDeleteSimpleMonitor without FileSystemWatcher for non-Windows (@snakefoot)
- [#3332](https://github.com/NLog/NLog/pull/3332) LogFactory - GetLogger should validate name of logger (@snakefoot)
- [#3320](https://github.com/NLog/NLog/pull/3320) FallbackGroupTarget - Fixed potential issue with WINDOWS_PHONE (@snakefoot)
- [#3261](https://github.com/NLog/NLog/pull/3261) NLog config file loading: use process name (e.g. applicationname.exe.nlog) when app.config is not available (@snakefoot)
#### Performance
- [#3311](https://github.com/NLog/NLog/pull/3311) Split string - avoid allocation of object array. Added StringHelpers.SplitAndTrimTokens (@snakefoot)
- [#3305](https://github.com/NLog/NLog/pull/3305) AppSettingLayoutRenderer - Mark as ThreadSafe and ThreadAgnostic (@snakefoot)
#### Misc
- [#3338](https://github.com/NLog/NLog/pull/3338) Update docs of various context classes (@304NotModified)
- [#3288](https://github.com/NLog/NLog/pull/3288) Move NLogPackageLoaders for better unittest debugging experience of NLog (@304NotModified)
- [#3274](https://github.com/NLog/NLog/pull/3274) Make HttpNetworkSender mockable, add unit test, introduce NSubsitute (@304NotModified)
- 10 pull requests with refactorings (@snakefoot, @304NotModified)
### V4.6.2 (2019/04/02)
#### Bugfixes
- [#3260](https://github.com/NLog/NLog/pull/3260) Fix escaping nested close brackets when parsing layout renderers (@lobster2012-user)
- [#3271](https://github.com/NLog/NLog/pull/3271) NLog config - Fixed bug where empty xml-elements were ignored (@snakefoot, @jonreis)
### V4.6.1 (2019/03/29)
#### Bugfixes
- [#3199](https://github.com/NLog/NLog/pull/3199) LoggingConfigurationParser - Fixed bug in handling of extensions prefix (@snakefoot)
- [#3253](https://github.com/NLog/NLog/pull/3253) Fix wrong warnings on `<nlog>` element (only wrong warnings) (#3253) (@snakefoot, @304NotModified)
- [#3195](https://github.com/NLog/NLog/pull/3195) SimpleStringReader: fix DebuggerDisplay value (#3195) (@lobster2012-user)
- [#3198](https://github.com/NLog/NLog/pull/3198) XmlLayout - Fixed missing encode of xml element value (@snakefoot)
- [#3191](https://github.com/NLog/NLog/pull/3191) VariableLayoutRenderer - Fixed format-string for internal logger warning (@snakefoot, @lobster2012-user)
- [#3258](https://github.com/NLog/NLog/pull/3258) Fix error with Embedded Assembly in LogAssemblyVersion (@snakefoot)
#### Improvements
- [#3255](https://github.com/NLog/NLog/pull/3255) Auto-flush on process exit improvements (@snakefoot)
- [#3189](https://github.com/NLog/NLog/pull/3189) AsyncTaskTarget - Respect TaskDelayMilliseconds on low activity (@snakefoot)
#### Performance
- [#3256](https://github.com/NLog/NLog/pull/3256) ${NDLC} + ${NDC} - Faster checking when TopFrames = 1 (@snakefoot)
- [#3201](https://github.com/NLog/NLog/pull/3201) ${GDC} reading is now lockfree (#3201) (@snakefoot)
### V4.6
#### Features
- [#2363](https://github.com/NLog/NLog/pull/2363) + [#2899](https://github.com/NLog/NLog/pull/2899) + [#3085](https://github.com/NLog/NLog/pull/3085) + [#3091](https://github.com/NLog/NLog/pull/3091) Database target: support for DbType for parameters (including SqlDbType) - (@hubo0831,@ObikeDev,@sorvis, @304NotModified, @snakefoot)
- [#2610](https://github.com/NLog/NLog/pull/2610) AsyncTargetWrapper with LogEventDropped- + LogEventQueueGrow-events (@Pomoinytskyi)
- [#2670](https://github.com/NLog/NLog/pull/2670) + [#3014](https://github.com/NLog/NLog/pull/3014) XmlLayout - Render LogEventInfo.Properties as XML (@snakefoot)
- [#2678](https://github.com/NLog/NLog/pull/2678) NetworkTarget - Support for SSL & TLS (@snakefoot)
- [#2709](https://github.com/NLog/NLog/pull/2709) XML Config: Support for constant variable in level attributes (level, minlevel, etc) (@304NotModified)
- [#2848](https://github.com/NLog/NLog/pull/2848) Added defaultAction for `<filter>` (@304NotModified)
- [#2849](https://github.com/NLog/NLog/pull/2849) IRawValue-interface and ${db-null} layout renderer (@304NotModified)
- [#2902](https://github.com/NLog/NLog/pull/2902) JsonLayout with support for System.Dynamic-objects (@304NotModified)
- [#2907](https://github.com/NLog/NLog/pull/2907) New Substring, Left & Right Wrappers (@304NotModified)
- [#3098](https://github.com/NLog/NLog/pull/3098) `<rule>` support for one or more '*' and '?' wildcards and in any position (@beppemarazzi)
- [#2909](https://github.com/NLog/NLog/pull/2909) AsyncTaskTarget - BatchSize + RetryCount (@snakefoot)
- [#3018](https://github.com/NLog/NLog/pull/3018) ColoredConsoleTarget - Added EnableAnsiOutput option (VS Code support) (@jp7677 + @snakefoot)
- [#3031](https://github.com/NLog/NLog/pull/3031) + [#3092](https://github.com/NLog/NLog/pull/3092) Support ${currentdir},${basedir},${tempdir} and Environment Variables for internalLogFile when parsing nlog.config (@snakefoot)
- [#3050](https://github.com/NLog/NLog/pull/3050) Added IncludeGdc property in JsonLayout (@casperc89)
- [#3071](https://github.com/NLog/NLog/pull/3071) ${HostName} Layout Renderer for full computer DNS name (@amitsaha)
- [#3053](https://github.com/NLog/NLog/pull/3053) ${AppSetting} Layout Renderer (app.config + web.config) moved from NLog.Extended for NetFramework (@snakefoot)
- [#3060](https://github.com/NLog/NLog/pull/3060) TargetWithContext - Support for PropertyType using IRawValue-interface (@snakefoot)
- [#3124](https://github.com/NLog/NLog/pull/3124) NetworkTarget - Added support for KeepAliveTimeSeconds (@snakefoot)
- [#3129](https://github.com/NLog/NLog/pull/3129) ConfigSetting - Preregister so it can be accessed without extension registration (#3129) (@snakefoot)
* [#3165](https://github.com/NLog/NLog/pull/3165) Added noRawValue layout wrapper (@snakefoot)
#### Enhancements
- [#2989](https://github.com/NLog/NLog/pull/2989) JsonLayout includes Type-property when rendering Exception-object (@snakefoot)
- [#2891](https://github.com/NLog/NLog/pull/2891) LoggingConfigurationParser - Extracted from XmlLoggingConfiguration (Prepare for appsettings.json) (@snakefoot)
- [#2910](https://github.com/NLog/NLog/pull/2910) Added support for complex objects in MDLC and NDLC on Net45 (@snakefoot)
- [#2918](https://github.com/NLog/NLog/pull/2918) PerformanceCounter - Improve behavior for CPU usage calculation (@snakefoot)
- [#2941](https://github.com/NLog/NLog/pull/2941) TargetWithContext - Include all properties even when duplicate names (@snakefoot)
- [#2974](https://github.com/NLog/NLog/pull/2974) Updated resharper annotations for better validation (@imanushin)
- [#2979](https://github.com/NLog/NLog/pull/2979) Improve default reflection support on NetCore Native (@snakefoot)
- [#3017](https://github.com/NLog/NLog/pull/3017) EventLogTarget with better support for MaximumKilobytes configuration (@Coriolanuss)
- [#3039](https://github.com/NLog/NLog/pull/3039) Added Xamarin PreserveAttribute for the entire Assembly to improve AOT-linking (@snakefoot)
- [#3045](https://github.com/NLog/NLog/pull/3045) Create snupkg packages and use portable PDB (@snakefoot)
- [#3048](https://github.com/NLog/NLog/pull/3048) KeepFileOpen + ConcurrentWrites on Xamarin + UWP - [#3079](https://github.com/NLog/NLog/pull/3079) (@304NotModified)
- [#3082](https://github.com/NLog/NLog/pull/3082) + [#3100](https://github.com/NLog/NLog/pull/3100) WebService Target allow custom override of SoapAction-header for Soap11 (@AlexeyRokhin)
- [#3162](https://github.com/NLog/NLog/pull/3162) ContextProperty with IncludeEmptyValue means default value for ValueType (#3162) (@snakefoot)
- [#3159](https://github.com/NLog/NLog/pull/3159) AppSettingLayoutRenderer - Include Item for NLog.Extended (@snakefoot)
- [#3187](https://github.com/NLog/NLog/pull/3187) AsyncTaskTarget - Fixed unwanted delay caused by slow writer (@snakefoot)
- Various refactorings (19 pull requests) (@beppemarazzi, @304NotModified, @snakefoot)
#### Performance
- [#2650](https://github.com/NLog/NLog/pull/2650) AsyncTargetWrapper using ConcurrentQueue for NetCore2 for better thread-concurrency (@snakefoot)
- [#2890](https://github.com/NLog/NLog/pull/2890) AsyncTargetWrapper - TimeToSleepBetweenBatches changed default to 1ms (@snakefoot)
- [#2897](https://github.com/NLog/NLog/pull/2897) InternalLogger performance optimization when LogLevel.Off (@snakefoot)
- [#2935](https://github.com/NLog/NLog/pull/2935) InternalLogger LogLevel changes to LogLevel.Off by default unless being used. (@snakefoot)
- [#2934](https://github.com/NLog/NLog/pull/2934) CsvLayout - Allocation optimizations and optional skip quoting-check for individual columns. (@snakefoot)
- [#2949](https://github.com/NLog/NLog/pull/2949) MappedDiagnosticsLogicalContext - SetScoped with IReadOnlyList (Prepare for MEL BeginScope) (@snakefoot)
- [#2973](https://github.com/NLog/NLog/pull/2973) IRenderString-interface to improve performance for Layout with single LayoutRenderer (@snakefoot)
- [#3103](https://github.com/NLog/NLog/pull/3103) StringBuilderPool - Reduce memory overhead until required (@snakefoot)
**LibLog Breaking change**
* [damianh/LibLog#181](https://github.com/damianh/LibLog/pull/181) - Sub-components using LibLog ver. 5.0.3 (or newer) will now use MDLC + NDLC (Instead of MDC + NDC) when detecting application is using NLog ver. 4.6. Make sure to update NLog.config to match this change. Make sure that all sub-components have upgraded to LibLog ver. 5.0.3 (or newer) if they make use of `OpenNestedContext` or `OpenMappedContext`.
See also [NLog 4.6 Milestone](https://github.com/NLog/NLog/milestone/44?closed=1)
### V4.5.11 (2018/11/06)
#### Enhancements
- [#2985](https://github.com/NLog/NLog/pull/2985) LogBuilder - Support fluent assignment of message-template after properties (@snakefoot)
- [#2983](https://github.com/NLog/NLog/pull/2983) JsonSerializer - Use ReferenceEquals instead of object.Equals when checking for cyclic object loops (#2983) (@snakefoot)
- [#2988](https://github.com/NLog/NLog/pull/2988) NullAppender - Added missing SecuritySafeCritical (@snakefoot)
#### Fixes
- [#2987](https://github.com/NLog/NLog/pull/2987) JSON encoding should create valid JSON for non-string dictionary-keys (@snakefoot)
### V4.5.10 (2018/09/17)
#### Fixes
- [#2883](https://github.com/NLog/NLog/pull/2883) Fix LoadConfiguration for not found config file (@snakefoot, @304NotModified)
### v4.5.9 (2018/08/24)
#### Fixes
- [#2865](https://github.com/NLog/NLog/pull/2865) JSON encoding should create valid JSON for special double values (@snakefoot)
#### Enhancements
- [#2846](https://github.com/NLog/NLog/pull/2846) Include Entry Assembly File Location when loading candidate NLog.config (@snakefoot)
### v4.5.8 (2018/08/05)
#### Features
- [#2809](https://github.com/NLog/NLog/pull/2809) MethodCallTarget - Support for Lamba method (@snakefoot)
- [#2816](https://github.com/NLog/NLog/pull/2816) MessageTemplates - Support rendering of alignment + padding (@snakefoot)
#### Fixes
- [#2827](https://github.com/NLog/NLog/pull/2827) FileTarget - Failing to CreateArchiveMutex should not stop logging (@snakefoot)
- [#2830](https://github.com/NLog/NLog/pull/2830) Auto loading of assemblies was broken in some cases (@snakefoot)
#### Enhancements
- [#2814](https://github.com/NLog/NLog/pull/2814) LoggingConfiguration - Improves CheckUnusedTargets to handle target wrappers (@snakefoot)
#### Performance
- [#2817](https://github.com/NLog/NLog/pull/2817) Optimize LayoutRendererWrappers to reduce string allocations (#2817) (@snakefoot)
### v4.5.7 (2018/07/19)
#### Features
- [#2792](https://github.com/nlog/nlog/pull/2792) OutputDebugStringTarget - Support Xamarin iOS and Android (@snakefoot)
- [#2776](https://github.com/nlog/nlog/pull/2776) FileTarget - Introduced OpenFileFlushTimeout to help when AutoFlush = false (@snakefoot)
#### Fixes
- [#2761](https://github.com/nlog/nlog/pull/2761) ${Callsite} fix class naming when includeNamespace=false and cleanNamesOfAnonymousDelegates=true (@Azatey)
- [#2752](https://github.com/nlog/nlog/pull/2752) JSON: Fixes issue where char types are not properly escaped (#2752) (@smbecker)
#### Enhancements
- [#2804](https://github.com/nlog/nlog/pull/2804) FileTarget - Do not trust Last File Write TimeStamp when AutoFlush=false (@snakefoot)
- [#2763](https://github.com/nlog/nlog/pull/2763) Throw better error when target name is null (@masters3d)
- [#2788](https://github.com/nlog/nlog/pull/2788) ${Assembly-version} make GetAssembly protected and virtual (@alexangas)
- [#2756](https://github.com/nlog/nlog/pull/2756) LongDateLayoutRenderer: Improve comments (@stic)
- [#2749](https://github.com/nlog/nlog/pull/2749) NLog.WindowsEventLog: Update dependency System.Diagnostics.EventLog to RTM version (@304NotModified)
#### Performance
- [#2797](https://github.com/nlog/nlog/pull/2797) Better performance with Activator.CreateInstance (@tangdf)
### v4.5.6 (2018/05/29)
#### Fixes
- [#2747](https://github.com/nlog/nlog/pull/2747) JsonSerializer - Generate valid Json when hitting the MaxRecursionLimit (@snakefoot)
- Fixup for [NLog.WindowsEventLog package](https://www.nuget.org/packages/NLog.WindowsEventLog)
#### Enhancements
- [#2745](https://github.com/nlog/nlog/pull/2745) FileTarget - Improve support for Linux FileSystem without BirthTime (@snakefoot)
#### Performance
- [#2744](https://github.com/nlog/nlog/pull/2744) LogEventInfo - HasProperties should allocate PropertiesDicitonary when needed (@snakefoot)
- [#2743](https://github.com/nlog/nlog/pull/2743) JsonLayout - Reduce allocations when needing to escape string (44% time improvement) (@snakefoot)
### v4.5.5 (2018/05/25)
#### Fixes
- [#2736](https://github.com/NLog/NLog/pull/2736) FileTarget - Calculate correct archive date when multiple file appenders (@snakefoot)
#### Features
- [#2726](https://github.com/nlog/nlog/pull/2726) WhenRepeated - Support logging rules with multiple targets (@snakefoot)
- [#2727](https://github.com/nlog/nlog/pull/2727) Support for custom targets that implements IUsesStackTrace (@snakefoot)
- [#2719](https://github.com/nlog/nlog/pull/2719) DatabaseTarget: use parameters on install (@Jejuni)
#### Enhancements
- [#2718](https://github.com/nlog/nlog/pull/2718) JsonLayout - Always stringify when requested (@snakefoot)
- [#2739](https://github.com/nlog/nlog/pull/2739) Target.WriteAsyncLogEvents(IList) to public
#### Performance
- [#2704](https://github.com/nlog/nlog/pull/2704) Allocation improvement in precalculating layouts (@snakefoot)
### v4.5.4 (2018/05/05)
#### Fixes
- [#2688](https://github.com/nlog/nlog/pull/2688) Faulty invalidate of FormattedMessage when getting PropertiesDictionary (@snakefoot)
- [#2687](https://github.com/nlog/nlog/pull/2687) Fix: NLog.config build-action and copy for non-core projects, it's now "copy if newer" (@304NotModified)
- [#2698](https://github.com/nlog/nlog/pull/2698) FileTarget - Calculate correct archive date, when using Monthly archive (@snakefoot)
#### Enhancements
- [#2673](https://github.com/nlog/nlog/pull/2673) TargetWithContext - Easier to use without needing to override ContextProperties (@snakefoot)
- [#2684](https://github.com/nlog/nlog/pull/2684) DatabaseTarget - Skip static assembly lookup for .Net Standard (@snakefoot)
- [#2689](https://github.com/nlog/nlog/pull/2689) LogEventInfo - Structured logging parameters are not always immutable (@snakefoot)
- [#2679](https://github.com/nlog/nlog/pull/2679) Target.WriteAsyncThreadSafe should always have exception handler (@snakefoot)
- [#2586](https://github.com/nlog/nlog/pull/2586) Target.MergeEventProperties is now obsolete (@snakefoot)
- Sonar warning fixes: [#2691](https://github.com/nlog/nlog/pull/2691), [#2694](https://github.com/nlog/nlog/pull/2694), [#2693](https://github.com/nlog/nlog/pull/2693), [#2690](https://github.com/nlog/nlog/pull/2690), [#2685](https://github.com/nlog/nlog/pull/2685), [#2683](https://github.com/nlog/nlog/pull/2683), [#2696](https://github.com/NLog/NLog/pull/2696) (@snakefoot, @304NotModified)
### v4.5.3 (2018/04/16)
#### Fixes
- [#2662](https://github.com/nlog/nlog/pull/2662) FileTarget - Improve handling of archives with multiple active files (@snakefoot)
#### Enhancements
- [#2587](https://github.com/nlog/nlog/pull/2587) Internal Log - Include target type and target name in the log messages (@snakefoot)
- [#2651](https://github.com/nlog/nlog/pull/2651) Searching for NLog Extension Files should handle DirectoryNotFoundException (@snakefoot)
#### Performance
- [#2653](https://github.com/nlog/nlog/pull/2653) LayoutRenderer ThreadSafe Attribute introduced to allow lock free Precalculate + other small performance improvements (@snakefoot)
### v4.5.2 (2018/04/06)
#### Features
- [#2648](https://github.com/nlog/nlog/pull/2648) ${processtime} and ${time} added invariant option (@snakefoot)
#### Fixes
- [#2643](https://github.com/nlog/nlog/pull/2643) UWP with NetStandard2 on Net Native does not support Assembly.CodeBase + Handle native methods in StackTrace (#2643) (@snakefoot)
- [#2644](https://github.com/nlog/nlog/pull/2644) FallbackGroupTarget: handle async state on fallback correctly (@snakefoot)
#### Performance
- [#2645](https://github.com/nlog/nlog/pull/2645) Minor performance optimization of some layoutrenderers (@snakefoot)
- [#2642](https://github.com/nlog/nlog/pull/2642) FileTarget - InitializeFile should skip dictionary lookup when same file (@snakefoot)
### v4.5.1 (2018/04/03)
#### Fixes
- [#2637](https://github.com/nlog/nlog/pull/2637) Fix IndexOutOfRangeException in NestedDiagnosticsLogicalContext (@snakefoot)
- [#2638](https://github.com/nlog/nlog/pull/2638) Handle null values correctly in LogReceiverSecureService (@304NotModified)
#### Performance
- [#2639](https://github.com/nlog/nlog/pull/2639) MessageTemplates - Optimize ParseHole for positional templates (@snakefoot)
- [#2640](https://github.com/nlog/nlog/pull/2640) FileTarget - InitializeFile no longer need justData parameter + dispose fileapenders earlier (@snakefoot)
- [#2628](https://github.com/nlog/nlog/pull/2628) RoundRobinGroupTarget - Replaced lock with Interlocked for performance (@snakefoot)
### v4.5 RTM (2018/03/25)
NLog 4.5 adds structured logging and .NET Standard support/UPW without breaking changes! Also a lot features has been added!
List of important changes in NLog 4.5
#### Features
- Support for .Net Standard 2.0 [#2263](https://github.com/nlog/nlog/pull/2263) + [#2402](https://github.com/nlog/nlog/pull/2402) (@snakefoot)
- Support for .Net Standard 1.5 [#2341](https://github.com/nlog/nlog/pull/2341) (@snakefoot)
- Support for .Net Standard 1.3 (and UWP) [#2441](https://github.com/nlog/nlog/pull/2441) + [#2597](https://github.com/nlog/nlog/pull/2597) (Remember to manually flush on app suspend). (@snakefoot)
- Introduced Structured logging [#2208](https://github.com/nlog/nlog/pull/2208) + [#2262](https://github.com/nlog/nlog/pull/2262) + [#2244](https://github.com/nlog/nlog/pull/2244) + [#2544](https://github.com/nlog/nlog/pull/2544) (@snakefoot, @304NotModified, @jods4, @nblumhardt) - see https://github.com/NLog/NLog/wiki/How-to-use-structured-logging
- Json conversion also supports object properties [#2179](https://github.com/nlog/nlog/pull/2179), [#2555](https://github.com/nlog/nlog/pull/2555) (@snakefoot, @304NotModified)
- event-properties layout-renderer can now render objects as json [#2241](https://github.com/nlog/nlog/pull/2241) (@snakefoot, @304NotModified)
- exception layout-renderer can now render exceptions as json [#2357](https://github.com/nlog/nlog/pull/2357) (@snakefoot)
- Default file archive logic is now easier to use [#1993](https://github.com/nlog/nlog/pull/1993) (@snakefoot)
- Introduced InstallationContext.ThrowExceptions [#2214](https://github.com/nlog/nlog/pull/2214) (@rbarillec)
- WebServiceTarget - Allow configuration of proxy address [#2375](https://github.com/nlog/nlog/pull/2375) (@snakefoot)
- WebServiceTarget - JsonPost with JsonLayout without being wrapped in parameter [#2590](https://github.com/nlog/nlog/pull/2590) (@snakefoot)
- ${guid}, added GeneratedFromLogEvent [#2226](https://github.com/nlog/nlog/pull/2226) (@snakefoot)
- TraceTarget RawWrite to always perform Trace.WriteLine independent of LogLevel [#1968](https://github.com/nlog/nlog/pull/1968) (@snakefoot)
- Adding OverflowAction options to BufferingTargetWrapper [#2276](https://github.com/nlog/nlog/pull/2276) (@mikegron)
- WhenRepeatedFilter - Filtering of identical LogEvents [#2123](https://github.com/nlog/nlog/pull/2123) + [#2297](https://github.com/nlog/nlog/pull/2297) (@snakefoot)
- ${callsite} added CleanNamesOfAsyncContinuations option [#2292](https://github.com/nlog/nlog/pull/2292) (@tkhaugen, @304NotModified)
- ${ndlctiming} allows timing of ndlc-scopes [#2377](https://github.com/nlog/nlog/pull/2377) (@snakefoot)
- NLogViewerTarget - Enable override of the Logger-name [#2390](https://github.com/nlog/nlog/pull/2390) (@snakefoot)
- ${sequenceid} added [#2411](https://github.com/nlog/nlog/pull/2411) (@MikeFH)
- Added "regex-matches" for filtering [#2437](https://github.com/nlog/nlog/pull/2437) (@MikeFH)
- ${gdc}, ${mdc} & {mdlc} - Support Format parameter [#2500](https://github.com/nlog/nlog/pull/2500) (@snakefoot)
- ${currentDir} added [#2491](https://github.com/nlog/nlog/pull/2491) (@UgurAldanmaz)
- ${AssemblyVersion}: add type (File, Assembly, Informational) option [#2487](https://github.com/nlog/nlog/pull/2487) (@alexangas)
- FileTarget: Support byte order mark [#2456](https://github.com/nlog/nlog/pull/2456) (@KYegres)
- TargetWithContext - Easier to create custom NLog targets with support for MDLC and NDLC [#2467](https://github.com/nlog/nlog/pull/2467) (@snakefoot)
- ${callname-filename} - Without line number [#2591](https://github.com/nlog/nlog/pull/2591) (@brunotag)
- MDC + MDLC with SetScoped property support [#2592](https://github.com/nlog/nlog/pull/2592) (@MikeFH)
- LoggingConfiguration AddRule includes final-parameter [#2612](https://github.com/nlog/nlog/pull/2612) (@893949088)
#### Fixes
- Improve archive stability during concurrent file access [#1889](https://github.com/nlog/nlog/pull/1889) (@snakefoot)
- FallbackGroup could lose log events [#2265](https://github.com/nlog/nlog/pull/2265) (@frabar666)
- ${exception} - only include separator when items are available [#2257](https://github.com/nlog/nlog/pull/2257) (@jojosardez)
- LogFactory - Fixes broken EventArgs for ConfigurationChanged [#1897](https://github.com/nlog/nlog/pull/1897) (@snakefoot)
- Do not report wrapped targets as unused targets [#2290](https://github.com/nlog/nlog/pull/2290) (@thesmallbang)
- Added IIncludeContext, implemented missing properties [#2117](https://github.com/nlog/nlog/pull/2117) (@304NotModified)
- Improve logging of callsite linenumber for async-methods [#2386](https://github.com/nlog/nlog/pull/2386) (@snakefoot)
- NLogTraceListener - DisableFlush is enabled by default when AutoFlush=true [#2407](https://github.com/nlog/nlog/pull/2407) (@snakefoot)
- NLogViewer - Better defaults for connection limits [#2404](https://github.com/nlog/nlog/pull/2404) (@304NotModified)
- LoggingConfiguration.LoggingRules is not thread safe [#2393](https://github.com/nlog/nlog/pull/2393), [#2418](https://github.com/nlog/nlog/pull/2418)
- Fix XmlLoggingConfiguration reloading [#2475](https://github.com/nlog/nlog/pull/2475) (@snakefoot)
- Database Target now supports EntityFramework ConnectionStrings [#2510](https://github.com/nlog/nlog/pull/2510) (@Misiu, @snakefoot)
- LoggingConfiguration.RemoveTarget now works while actively logging [#2549](https://github.com/nlog/nlog/pull/2549) (@jojosardez, @snakefoot)
- FileTarget does not fail on platforms without global mutex support [#2604](https://github.com/nlog/nlog/pull/2604) (@snakefoot)
- LoggingConfiguration does not fail when AutoReload is not possible on the platforms without FileWatcher [#2603](https://github.com/nlog/nlog/pull/2603) (@snakefoot)
#### Performance
- More targets has OptimizeBufferReuse enabled by default [#1913](https://github.com/nlog/nlog/pull/1913) + [#1923](https://github.com/nlog/nlog/pull/1923) + [#1912](https://github.com/nlog/nlog/pull/1912) + [#1911](https://github.com/nlog/nlog/pull/1911) + [#1910](https://github.com/nlog/nlog/pull/1910) + [#1909](https://github.com/nlog/nlog/pull/1909) + [#1908](https://github.com/nlog/nlog/pull/1908) + [#1907](https://github.com/nlog/nlog/pull/1907) + [#2560](https://github.com/nlog/nlog/pull/2560) (@snakefoot)
- StringBuilderPool - Improved Layout Render Performance by reusing StringBuilders [#2208](https://github.com/nlog/nlog/pull/2208) (@snakefoot)
- JsonLayout - Improved Layout Performance, by optimizing use of StringBuilder [#2208](https://github.com/nlog/nlog/pull/2208) (@snakefoot)
- FileTarget - Faster byte-encoding of log messsages, by using crude Encoding.GetMaxByteCount() instead of exact Encoding.GetByteCount() [#2208](https://github.com/nlog/nlog/pull/2208) (@snakefoot)
- Target - Precalculate Layout should ignore sub-layouts for complex layout (Ex Json) [#2378](https://github.com/nlog/nlog/pull/2378) (@snakefoot)
- MessageLayoutRenderer - Skip `string.Format` allocation (for caching) when writing to a single target, instead format directly into output buffer. [#2507](https://github.com/nlog/nlog/pull/2507) (@snakefoot)
Changes since rc 07:
- [#2621](https://github.com/nlog/nlog/pull/2621) Single Target optimization logic refactored to reuse optimization approval (@snakefoot)
- [#2622](https://github.com/nlog/nlog/pull/2622) NetworkTarget - Http / Https should not throw on async error response (@snakefoot)
- [#2619](https://github.com/nlog/nlog/pull/2619) NetworkTarget - Reduce allocation when buffer is less than MaxMessageSize (@snakefoot)
- [#2616](https://github.com/nlog/nlog/pull/2616) LogManager.Shutdown - Should disable file watcher and avoid auto reload (@snakefoot)
- [#2620](https://github.com/nlog/nlog/pull/2620) Single Target optimization should only be done when parseMessageTemplate = null (@snakefoot)
### v4.5-rc07 (2018/03/07)
- [#2614](https://github.com/nlog/nlog/pull/2614) NLog 4.5 RC7 changelog & version (@304NotModified)
- [#2612](https://github.com/nlog/nlog/pull/2612) add final param to `AddRule` Methods (#2612) (@893949088)
- [#2590](https://github.com/nlog/nlog/pull/2590) WebServiceTarget - JsonPost with support for single nameless parameter (@snakefoot)
- [#2604](https://github.com/nlog/nlog/pull/2604) FileTarget - Failing to CreateArchiveMutex should not stop logging (#2604) (@snakefoot)
- [#2592](https://github.com/nlog/nlog/pull/2592) Make Set methods of MDC and MDLC return IDisposable (#2592) (@MikeFH)
- [#2591](https://github.com/nlog/nlog/pull/2591) callsite-filename renderer (#2591) (@brunotag)
- [#2597](https://github.com/nlog/nlog/pull/2597) Replace WINDOWS_UWP with NETSTANDARD1_3 to support UWP10 shared libraries (@snakefoot)
- [#2599](https://github.com/nlog/nlog/pull/2599) TryImplicitConversion should only check object types (@snakefoot)
- [#2595](https://github.com/nlog/nlog/pull/2595) IsSafeToDeferFormatting - Convert.GetTypeCode is faster and better (@snakefoot)
- [#2609](https://github.com/nlog/nlog/pull/2609) NLog - Fix Callsite when wrapping ILogger in Microsoft Extension Logging (@snakefoot)
- [#2613](https://github.com/nlog/nlog/pull/2613) Attempt to make some unit-tests more stable (@snakefoot)
- [#2603](https://github.com/nlog/nlog/pull/2603) MultiFileWatcher - Improve error handling if FileSystemWatcher fails (@snakefoot)
### v4.5-rc06 (2018/02/20)
- [#2585](https://github.com/nlog/nlog/pull/2585) NLog 4.5 rc6 version and changelog (#2585) (@304NotModified)
- [#2581](https://github.com/nlog/nlog/pull/2581) MessageTemplateParameter(s) ctors to internal (@304NotModified)
- [#2576](https://github.com/nlog/nlog/pull/2576) Fix possible infinite loop in message template parser + better handling incorrect templates (@304NotModified)
- [#2580](https://github.com/nlog/nlog/pull/2580) ColoredConsoleTarget.cs: Fix typo (@perlun)
### v4.5-rc05 (2018/02/13)
- [#2571](https://github.com/nlog/nlog/pull/2571) 4.5 rc5 version and release notes (@304NotModified)
- [#2572](https://github.com/nlog/nlog/pull/2572) copyright 2018 (@304NotModified)
- [#2570](https://github.com/nlog/nlog/pull/2570) Update nuspec NLog.Config and NLog.Schema (@304NotModified)
- [#2542](https://github.com/nlog/nlog/pull/2542) Added TooManyStructuredParametersShouldKeepBeInParamList testcase (@304NotModified)
- [#2467](https://github.com/nlog/nlog/pull/2467) TargetWithContext - Easier to capture snapshot of MDLC and NDLC context (#2467) (@snakefoot)
- [#2555](https://github.com/nlog/nlog/pull/2555) JsonLayout - Added MaxRecursionLimit and set default to 0 (@snakefoot)
- [#2568](https://github.com/nlog/nlog/pull/2568) WebServiceTarget - Rollback added Group-Layout (@snakefoot)
- [#2544](https://github.com/nlog/nlog/pull/2544) MessageTemplate renderer with support for mixed mode templates (@snakefoot)
- [#2538](https://github.com/nlog/nlog/pull/2538) Renamed ValueSerializer to ValueFormatter (@snakefoot)
- [#2554](https://github.com/nlog/nlog/pull/2554) LogBuilder - Check level before allocation of Properties-dictionary (@snakefoot)
- [#2550](https://github.com/nlog/nlog/pull/2550) DefaultJsonSerializer - Reflection should skip index-item-properties (@snakefoot)
- [#2549](https://github.com/nlog/nlog/pull/2549) LoggingConfiguration - FindTargetByName should also find target + fix for logging on a target even after removed (@snakefoot)
- [#2548](https://github.com/nlog/nlog/pull/2548) IAppDomain.FriendlyName should also work on NetStandard15 (@snakefoot)
- [#2563](https://github.com/nlog/nlog/pull/2563) WebService-Target fails internally with PlatformNotSupportedException on NetCore (@snakefoot)
- [#2560](https://github.com/nlog/nlog/pull/2560) Network/NLogViewer/Chainsaw Target - Enabled OptimizeBufferReuse by default, but not for sub classes (@snakefoot)
- [#2551](https://github.com/nlog/nlog/pull/2551) Blackhole LoggingRule without targets (@snakefoot)
- [#2534](https://github.com/nlog/nlog/pull/2534) Docs for DefaultJsonSerializer/(i)ValueSerializer (#2534) (@304NotModified)
- [#2519](https://github.com/nlog/nlog/pull/2519) RegisterItemsFromAssembly - Include assemblies from nuget packages (Strict) (@304NotModified, @snakefoot)
- [#2524](https://github.com/nlog/nlog/pull/2524) FileTarget - Dynamic archive mode with more strict file-mask for cleanup (@snakefoot)
- [#2518](https://github.com/nlog/nlog/pull/2518) DatabaseTarget - Added DbProvider System.Data.SqlClient for NetStandard (@snakefoot)
- [#2514](https://github.com/nlog/nlog/pull/2514) Added missing docgen for different options (Less noise in appveyor) (@snakefoot)
### v4.5-rc04 (2018/01/15)
- [#2490](https://github.com/nlog/nlog/pull/2490) LogEventInfo.MessageTemplateParameters as class instead of interface (#2490) (@snakefoot)
- [#2510](https://github.com/nlog/nlog/pull/2510) Database target entity framework connection string (@snakefoot)
- [#2513](https://github.com/nlog/nlog/pull/2513) Update docs for [AppDomainFixedOutput], remove [AppDomainFixedOutput] on ${currentDir} (@NLog)
- [#2512](https://github.com/nlog/nlog/pull/2512) LogManager.LoadConfiguration - Support relative paths by default (@snakefoot)
- [#2507](https://github.com/nlog/nlog/pull/2507) Reduce string allocations for logevents with single target destination (@snakefoot)
- [#2491](https://github.com/nlog/nlog/pull/2491) Added ${currentDir} (#2491) (@UgurAldanmaz)
- [#2500](https://github.com/nlog/nlog/pull/2500) ${gdc}, ${mdc} & {mdlc} - Support Format parameter (@snakefoot)
- [#2497](https://github.com/nlog/nlog/pull/2497) RegisterItemsFromAssembly - Include assemblies from nuget packages (Fix) (@snakefoot)
- [#2472](https://github.com/nlog/nlog/pull/2472) LogManager.LoadConfiguration - Prepare for custom config file readers (@snakefoot)
- [#2486](https://github.com/nlog/nlog/pull/2486) JsonConverter- Sanitize Exception.Data dictionary keys option (on by default) (@snakefoot)
- [#2495](https://github.com/nlog/nlog/pull/2495) MultiFileWatcher - Detach from FileSystemWatcher before disposing (@snakefoot)
- [#2493](https://github.com/nlog/nlog/pull/2493) RegisterItemsFromAssembly - Include assemblies from nuget packages (@snakefoot)
- [#2487](https://github.com/nlog/nlog/pull/2487) Adds version types to AssemblyVersion layout renderer (#2487) (@alexangas)
- [#2464](https://github.com/nlog/nlog/pull/2464) Add methods to enabling/disabling LogLevels (@MikeFH)
- [#2477](https://github.com/nlog/nlog/pull/2477) fix typo (@heldersepu)
- [#2485](https://github.com/nlog/nlog/pull/2485) FileTarget - Dispose Archive-Mutex after completing file-archive (@snakefoot)
- [#2475](https://github.com/nlog/nlog/pull/2475) Fix XmlLoggingConfiguration reloading (@MikeFH)
- [#2471](https://github.com/nlog/nlog/pull/2471) TreatWarningsAsErrors = true (@snakefoot)
- [#2462](https://github.com/nlog/nlog/pull/2462) AsyncLogEventInfo - Removed private setter (@snakefoot)
### v4.5-rc03 (2017/12/11)
- [#2460](https://github.com/nlog/nlog/pull/2460) NLog 4.5 rc3 version and changelog (@304NotModified)
- [#2459](https://github.com/nlog/nlog/pull/2459) StringBuilderExt.CopyToStream - Optimize MemoryStream allocation (@snakefoot)
- [#2456](https://github.com/nlog/nlog/pull/2456) FileTarget: Support byte order mark (optional) (#2456) (@KYegres)
- [#2453](https://github.com/nlog/nlog/pull/2453) NestedDiagnosticsContext - Only allocate Stack-object on Write (@snakefoot)
- [#2458](https://github.com/nlog/nlog/pull/2458) Document and (minor) refactor on MruCache class (@ie-zero)
- [#2452](https://github.com/nlog/nlog/pull/2452) ThreadLocalStorageHelper - NetStandard only allocate when needed (@snakefoot)
### v4.5-rc02 (2017/12/04)
- [#2444](https://github.com/nlog/nlog/pull/2444) NLog 4.5 RC2 version and changelog (@304NotModified)
- [#2450](https://github.com/nlog/nlog/pull/2450) No need to call type(T) (@304NotModified)
- [#2451](https://github.com/nlog/nlog/pull/2451) FileTarget - Improved and less internal logging (@snakefoot)
- [#2449](https://github.com/nlog/nlog/pull/2449) Refactor: fix comment, remove unused, cleanup, String ->` string etc (#2449) (@304NotModified)
- [#2447](https://github.com/nlog/nlog/pull/2447) CallSiteInformation - Prepare for fast classname lookup from filename and linenumber (@snakefoot)
- [#2446](https://github.com/nlog/nlog/pull/2446) Refactor - split methodes, remove duplicates (#2446) (@304NotModified)
- [#2437](https://github.com/nlog/nlog/pull/2437) Create regex-matches condition method (#2437) (@MikeFH)
- [#2441](https://github.com/nlog/nlog/pull/2441) Support for UWP platform (@snakefoot)
- [#2439](https://github.com/nlog/nlog/pull/2439) Better config Better Code Hub (@304NotModified)
- [#2431](https://github.com/nlog/nlog/pull/2431) NetCoreApp - Improve auto loading of NLog extension dlls (@snakefoot)
- [#2418](https://github.com/nlog/nlog/pull/2418) LoggingConfiguration - Modify and clone LoggingRules under lock (@snakefoot)
- [#2422](https://github.com/nlog/nlog/pull/2422) Avoid unnecessary string-allocation, skip unnecessary lock (@snakefoot)
- [#2419](https://github.com/nlog/nlog/pull/2419) Logger - Added missing MessageTemplateFormatMethodAttribute + removed obsolete internal method (@snakefoot)
- [#2421](https://github.com/nlog/nlog/pull/2421) Changed IIncludeContext to internal interface until someone needs it (@snakefoot)
- [#2417](https://github.com/nlog/nlog/pull/2417) IsMono - Cache Type.GetType to avoid constant AppDomain.TypeResolve events (@snakefoot)
- [#2420](https://github.com/nlog/nlog/pull/2420) Merged CallSite Test from PR1812 (@snakefoot)
### v4.5-rc01 (2017/11/23)
- [#2414](https://github.com/nlog/nlog/pull/2414) Revert breaking change of NestedDiagnosticsLogicalContext.Pop() (@304NotModified)
- [#2415](https://github.com/nlog/nlog/pull/2415) NetStandard15 - Moved dependency System.Xml.XmlSerializer to NLog.Wcf (@snakefoot)
- [#2413](https://github.com/nlog/nlog/pull/2413) NestedDiagnosticsLogicalContext - Protect against double dispose (@snakefoot)
- [#2412](https://github.com/nlog/nlog/pull/2412) MessageTemplate - Render test of DateTime, TimeSpan, DateTimeOffset (@snakefoot)
- [#2411](https://github.com/nlog/nlog/pull/2411) Create SequenceIdLayoutRenderer (@MikeFH)
- [#2409](https://github.com/nlog/nlog/pull/2409) Revert "Avoid struct copy on readonly field access" (@snakefoot)
- [#2403](https://github.com/nlog/nlog/pull/2403) NLog 4.5 beta 8 (@304NotModified)
- [#2406](https://github.com/nlog/nlog/pull/2406) From [StringFormatMethod] to [MessageTemplateFormatMethod] (@304NotModified)
- [#2402](https://github.com/nlog/nlog/pull/2402) Introduced NLog.Wcf and Nlog.WindowsIdentity for .NET standard (@snakefoot)
- [#2404](https://github.com/nlog/nlog/pull/2404) Updated NLog viewer target defaults (@304NotModified)
- [#2405](https://github.com/nlog/nlog/pull/2405) Added unit test for JsonLayout - serialize of objects (@304NotModified)
- [#2407](https://github.com/nlog/nlog/pull/2407) NLogTraceListener - set DisableFlush true by default (@snakefoot)
- [#2401](https://github.com/nlog/nlog/pull/2401) MailTarget is supported by NetStandard2.0 (but without SmtpSection) (@snakefoot)
- [#2398](https://github.com/nlog/nlog/pull/2398) Log4JXml - Fixed initalization of XmlWriterSettings for IndentXml (@snakefoot)
- [#2386](https://github.com/nlog/nlog/pull/2386) LogEventInfo.StackTrace moved into CallSiteInformation (@snakefoot)
- [#2399](https://github.com/nlog/nlog/pull/2399) Avoid struct copy on readonly field access (@snakefoot)
- [#2389](https://github.com/nlog/nlog/pull/2389) Fixed Sonar Lint code analysis warnings (@snakefoot)
- [#2396](https://github.com/nlog/nlog/pull/2396) Update xunit and Microsoft.NET.Test.Sdk (@304NotModified)
- [#2387](https://github.com/nlog/nlog/pull/2387) JsonConverter - Do not include static properties by default (@snakefoot)
- [#2392](https://github.com/nlog/nlog/pull/2392) Removed unneeded default references like System.Drawing for NetFramework (@snakefoot)
- [#2390](https://github.com/nlog/nlog/pull/2390) NLogViewerTarget - Enable override of the Logger-name (@snakefoot)
- [#2385](https://github.com/nlog/nlog/pull/2385) FileTarget - ArchiveMutex only created when needed (@snakefoot)
- [#2378](https://github.com/nlog/nlog/pull/2378) Target - Precalculate Layout should ignore sub-layouts for complex layouts (@snakefoot)
- [#2388](https://github.com/nlog/nlog/pull/2388) PropertiesDictionary - Removed obsolete (private) method (@snakefoot)
- [#2384](https://github.com/nlog/nlog/pull/2384) InternalLogger should work when NetCore loads NetFramework DLL (@snakefoot)
- [#2377](https://github.com/nlog/nlog/pull/2377) NDLC - Perform low resolution scope timing (@snakefoot)
- [#2372](https://github.com/nlog/nlog/pull/2372) Log4JXmlEventLayoutRenderer - Minor platform fixes for IncludeNdlc (@snakefoot)
- [#2371](https://github.com/nlog/nlog/pull/2371) FileTarget - Enable archive mutex for Unix File Appender (if available) (@snakefoot)
- [#2375](https://github.com/nlog/nlog/pull/2375) WebServiceTarget - Allow configuration of proxy address (@snakefoot)
- [#2362](https://github.com/nlog/nlog/pull/2362) NLog - NETSTANDARD1_5 (Cleanup package references) (@snakefoot)
- [#2361](https://github.com/nlog/nlog/pull/2361) Use expression-bodied members (@c0shea)
### v4.5-beta07 (2017/10/15)
- [#2359](https://github.com/nlog/nlog/pull/2359) WrapperLayoutRendererBase - Transform with access to LogEventInfo (@snakefoot)
- [#2357](https://github.com/nlog/nlog/pull/2357) ExceptionLayoutRenderer - Support Serialize Format (@snakefoot)
- [#2358](https://github.com/nlog/nlog/pull/2358) WrapperLayoutRendererBuilderBase - Transform with access to LogEventInfo (@snakefoot)
- [#2314](https://github.com/nlog/nlog/pull/2314) Refactor InternalLogger class (@304NotModified, @ie-zero)
- [#2356](https://github.com/nlog/nlog/pull/2356) NLog - MessageTemplates - Renamed config to parseMessageTemplates (@snakefoot)
- [#2353](https://github.com/nlog/nlog/pull/2353) remove old package.config (@304NotModified)
- [#2354](https://github.com/nlog/nlog/pull/2354) NLog - NETSTANDARD1_5 (revert breaking change) (@snakefoot)
- [#2342](https://github.com/nlog/nlog/pull/2342) Remove redundant qualifiers (#2342) (@c0shea)
- [#2349](https://github.com/nlog/nlog/pull/2349) NLog - NETSTANDARD1_5 (Fix uppercase with culture) (@snakefoot)
- [#2341](https://github.com/nlog/nlog/pull/2341) NLog - NETSTANDARD1_5 (@snakefoot)
### v4.5-beta06 (2017/10/12)
- [#2346](https://github.com/nlog/nlog/pull/2346) Add messageTemplateParser to XSD (@304NotModified)
- [#2348](https://github.com/nlog/nlog/pull/2348) NLog MessageTemplateParameter with CaptureType (@snakefoot)
### v4.5-beta05 (2017/10/12)
- [#2340](https://github.com/nlog/nlog/pull/2340) NLog - MessageTemplateParameters - Always parse when IsPositional (@304NotModified, @snakefoot)
- [#2337](https://github.com/nlog/nlog/pull/2337) Use string interpolation (@c0shea)
- [#2327](https://github.com/nlog/nlog/pull/2327) Naming: consistent private fields (@304NotModified)
### v4.5-beta04 (2017/10/10)
- [#2318](https://github.com/nlog/nlog/pull/2318) NLog 4.5 beta 4 (@304NotModified)
- [#2326](https://github.com/nlog/nlog/pull/2326) NLog - ValueSerializer - Faster integer and enum (@snakefoot)
- [#2328](https://github.com/nlog/nlog/pull/2328) fix xunit warning (@304NotModified)
- [#2117](https://github.com/nlog/nlog/pull/2117) Added IIncludeContext, implemented missing properties, added includeNdlc, sync NDLC and NDC (@304NotModified)
- [#2317](https://github.com/nlog/nlog/pull/2317) More explicit side effect (@304NotModified)
- [#2290](https://github.com/nlog/nlog/pull/2290) Do not report wrapped targets as unused targets (#2290) (@thesmallbang)
- [#2319](https://github.com/nlog/nlog/pull/2319) NLog - MessageTemplateParameter - IsReservedFormat (@snakefoot)
- [#2316](https://github.com/nlog/nlog/pull/2316) LogManager.LogFactory public (@304NotModified)
- [#2208](https://github.com/nlog/nlog/pull/2208) Added Structured events / Message Templates (@snakefoot)
- [#2312](https://github.com/nlog/nlog/pull/2312) Improve stability of unstable test on Travis: BufferingTargetWrapperA… (@304NotModified)
- [#2309](https://github.com/nlog/nlog/pull/2309) 2017 copyright in T4 files (@304NotModified)
- [#2292](https://github.com/nlog/nlog/pull/2292) ${callsite} added CleanNamesOfAsyncContinuations option (#2292) (@304NotModified)
- [#2310](https://github.com/nlog/nlog/pull/2310) Upgrade xUnit to 2.3.0 RTM (@304NotModified)
- [#2313](https://github.com/nlog/nlog/pull/2313) Removal of old package.config files (@304NotModified)
- [#1872](https://github.com/nlog/nlog/pull/1872) FileTarget: more internal logging (@304NotModified)
- [#1897](https://github.com/nlog/nlog/pull/1897) LogFactory - Fixed EventArgs for ConfigurationChanged (@snakefoot)
- [#2301](https://github.com/nlog/nlog/pull/2301) Docs, rename and refactor of PropertiesDictionary/MessageTemplateParameters (@304NotModified)
- [#2302](https://github.com/nlog/nlog/pull/2302) Copyright to 2017 (@304NotModified)
- [#2262](https://github.com/nlog/nlog/pull/2262) LogEventInfo.MessageTemplate - Subset of LogEventInfo.Properties (@snakefoot)
- [#2300](https://github.com/nlog/nlog/pull/2300) Fixed title (@304NotModified)
### v4.5-beta03 (2017/09/30)
- [#2298](https://github.com/nlog/nlog/pull/2298) Search also for lowercase nlog.config (@304NotModified)
- [#2297](https://github.com/nlog/nlog/pull/2297) WhenRepeatedFilter - Log after timeout (@snakefoot)
### v4.5-beta01 (2017/09/16)
- [#2263](https://github.com/nlog/nlog/pull/2263) Support .NET Standard 2.0 and move to VS 2017 (@snakefoot)
### v4.4.13 (2018/02/28)
#### Fixes
- [#2600](https://github.com/nlog/nlog/pull/2600) Fix 'System.ReadOnlySpan`1[System.Char]' cannot be converted to type 'System.String' (@snakefoot)
### v4.4.12 (2017/08/08)
#### Fixes
- [#2229](https://github.com/nlog/nlog/pull/2229) Fix: ReconfigExistingLoggers sometimes throws an Exception (@jpdillingham)
### v4.4.11 (2017/06/17)
#### Fixes
- [#2164](https://github.com/nlog/nlog/pull/2164) JsonLayout - Don't mark ThreadAgnostic when IncludeMdc or IncludeMdlc is enabled (@snakefoot)
### v4.4.10 (2017/05/31)
#### Features
- [#2110](https://github.com/nlog/nlog/pull/2110) NdlcLayoutRenderer - Nested Diagnostics Logical Context (@snakefoot)
- [#2114](https://github.com/nlog/nlog/pull/2114) EventlogTarget: Support for MaximumKilobytes (@304NotModified, @ajitpeter)
- [#2109](https://github.com/nlog/nlog/pull/2109) JsonLayout - IncludeMdc and IncludeMdlc (@snakefoot)
#### Fixes
- [#2138](https://github.com/nlog/nlog/pull/2138) ReloadConfigOnTimer - fix potential NullReferenceException (@snakefoot)
- [#2113](https://github.com/nlog/nlog/pull/2113) BugFix: `<targets>` after `<rules>` won't work (@304NotModified, @Moafak)
- [#2131](https://github.com/nlog/nlog/pull/2131) Fix : LogManager.ReconfigureExistingLoggers() could throw InvalidOperationException (@304NotModified, @jpdillingham)
#### Improvements
- [#2137](https://github.com/nlog/nlog/pull/2137) NLogTraceListener - Reduce overhead by checking LogLevel (@snakefoot)
- [#2112](https://github.com/nlog/nlog/pull/2112) LogReceiverWebServiceTarget - Ensure PrecalculateVolatileLayouts (@snakefoot)
- [#2103](https://github.com/nlog/nlog/pull/2103) Improve Install of targets / crash Install on Databasetarget. (@M4ttsson)
- [#2101](https://github.com/nlog/nlog/pull/2101) LogFactory.Shutdown - Add warning on target flush timeout (@snakefoot)
### v4.4.9
#### Features
- [#2090](https://github.com/nlog/nlog/pull/2090) ${log4jxmlevent} - Added IncludeAllProperties option (@snakefoot)
- [#2090](https://github.com/nlog/nlog/pull/2090) Log4JXmlEvent Layout - Added IncludeAllProperties, IncludeMdlc and IncludeMdc option (@snakefoot)
#### Fixes
- [#2090](https://github.com/nlog/nlog/pull/2090) Log4JXmlEvent Layout - Fixed bug with empty nlog:properties (@snakefoot)
- [#2093](https://github.com/nlog/nlog/pull/2093) Fixed bug to logging by day of week (@RussianDragon)
- [#2095](https://github.com/nlog/nlog/pull/2095) Fix: include ignoreErrors attribute not working for non-existent file (@304NotModified, @ghills)
### v4.4.8 (2017/04/28)
#### Features
- [#2078](https://github.com/nlog/nlog/pull/2078) Include MDLC in log4j renderer (option) (@thoemmi)
### v4.4.7 (2017/04/25)
#### Features
- [#2063](https://github.com/nlog/nlog/pull/2063) JsonLayout - Added JsonAttribute property EscapeUnicode (@snakefoot)
#### Improvements
- [#2075](https://github.com/nlog/nlog/pull/2075) StackTraceLayoutRenderer with Raw format should display source FileName (@snakefoot)
- [#2067](https://github.com/nlog/nlog/pull/2067) ${EventProperties}, ${newline}, ${basedir} & ${tempdir} as ThreadAgnostic (performance improvement) (@snakefoot)
- [#2061](https://github.com/nlog/nlog/pull/2061) MethodCallTarget - Fixed possible null-reference-exception on initialize (@snakefoot)
## v4.4.6 (2017/04/11)
#### Features
- [#2006](https://github.com/nlog/nlog/pull/2006) Added AsyncTaskTarget - Base class for using async methods (@snakefoot)
- [#2051](https://github.com/nlog/nlog/pull/2051) Added LogMessageGenerator overloads for exceptions (#2051) (@c0shea)
- [#2034](https://github.com/nlog/nlog/pull/2034) ${level} add format option (full, single char and ordinal) (#2034) (@c0shea)
- [#2042](https://github.com/nlog/nlog/pull/2042) AutoFlushTargetWrapper - Added AsyncFlush property (@snakefoot)
#### Improvements
- [#2048](https://github.com/nlog/nlog/pull/2048) Layout - Ensure StackTraceUsage works for all types of Layout (@snakefoot)
- [#2041](https://github.com/nlog/nlog/pull/2041) Reduce memory allocations (AsyncContinuation exceptionHandler) & refactor (@snakefoot)
- [#2040](https://github.com/nlog/nlog/pull/2040) WebServiceTarget - Avoid re-throwing exceptions in async completion method (@snakefoot)
### v4.4.5 (2017/03/28)
#### Fixes
- [#2010](https://github.com/nlog/nlog/pull/2010) LogFactory - Ensure to flush and close on shutdown - fixes broken logging (@snakefoot)
- [#2017](https://github.com/nlog/nlog/pull/2017) WebServiceTarget - Fix boolean parameter conversion for Xml and Json (lowercase) (@snakefoot)
#### Improvements
- [#2017](https://github.com/nlog/nlog/pull/2017) Merged the JSON serializer code into DefaultJsonSerializer (@snakefoot)
### 4.4.4 (2017/03/10)
#### Features
- [#2000](https://github.com/nlog/nlog/pull/2000) Add weekly archival option to FileTarget (@dougthor42)
- [#2009](https://github.com/nlog/nlog/pull/2009) Load assembly event (@304NotModified)
- [#1917](https://github.com/nlog/nlog/pull/1917) Call NLogPackageLoader.Preload (static) for NLog packages on load (@304NotModified)
#### Improvements
- [#2007](https://github.com/nlog/nlog/pull/2007) Target.Close() - Extra logging to investigate shutdown order (@snakefoot)
- [#2003](https://github.com/nlog/nlog/pull/2003) Update XSD for `<NLog>` options (@304NotModified)
- [#1977](https://github.com/nlog/nlog/pull/1977) update xsd template (internallogger) for 4.4.3 version (@AuthorProxy)
- [#1956](https://github.com/nlog/nlog/pull/1956) Improve docs ThreadAgnosticAttribute (#1956) (@304NotModified)
- [#1992](https://github.com/nlog/nlog/pull/1992) Fixed merge error of XML documentation for Target Write-methods (@snakefoot)
#### Fixes
- [#1995](https://github.com/nlog/nlog/pull/1995) Proper apply default-target-parameters to nested targets in WrappedTargets (@nazim9214)
### 4.4.3 (2017/02/17)
#### Fixes
- [#1966](https://github.com/nlog/nlog/pull/1966) System.UriFormatException on load (Mono) (@JustArchi)
- [#1960](https://github.com/nlog/nlog/pull/1960) EventLogTarget: Properly parse and set EventLog category (@marinsky)
### 4.4.2 (2017/02/06)
#### Features
- [#1799](https://github.com/nlog/nlog/pull/1799) FileTarget: performance improvement: 10-70% faster, less garbage collecting (3-4 times less) by reusing buffers (@snakefoot, @AndreGleichner)
- [#1919](https://github.com/nlog/nlog/pull/1919) Func overloads for InternalLogger (@304NotModified)
- [#1915](https://github.com/nlog/nlog/pull/1915) allow wildcard (*) in `<include>` (@304NotModified)
- [#1914](https://github.com/nlog/nlog/pull/1914) basedir: added option processDir=true (@304NotModified)
- [#1906](https://github.com/nlog/nlog/pull/1906) Allow Injecting basedir (@304NotModified)
#### Improvements
- [#1927](https://github.com/nlog/nlog/pull/1927) InternalLogger - Better support for multiple threads when using file (@snakefoot)
- [#1871](https://github.com/nlog/nlog/pull/1871) Filetarget - Allocations optimization (#1871) (@nazim9214)
- [#1931](https://github.com/nlog/nlog/pull/1931) FileTarget - Validate File CreationTimeUtc when non-Windows (@snakefoot)
- [#1942](https://github.com/nlog/nlog/pull/1942) FileTarget - KeepFileOpen should watch for file deletion, but not every second (@snakefoot)
- [#1876](https://github.com/nlog/nlog/pull/1876) FileTarget - Faster archive check by caching the static file-create-time (60-70% improvement) (#1876) (@snakefoot)
- [#1878](https://github.com/nlog/nlog/pull/1878) FileTarget - KeepFileOpen should watch for file deletion (#1878) (@snakefoot)
- [#1932](https://github.com/nlog/nlog/pull/1932) FileTarget - Faster rendering of filepath, when not ThreadAgnostic (@snakefoot)
- [#1937](https://github.com/nlog/nlog/pull/1937) LogManager.Shutdown - Verify that active config exists (@snakefoot)
- [#1926](https://github.com/nlog/nlog/pull/1926) RetryingWrapper - Allow closing target, even when busy retrying (@snakefoot)
- [#1925](https://github.com/nlog/nlog/pull/1925) JsonLayout - Support Precalculate for async processing (@snakefoot)
- [#1816](https://github.com/nlog/nlog/pull/1816) EventLogTarget - don't crash with invalid Category / EventId (@304NotModified)
- [#1815](https://github.com/nlog/nlog/pull/1815) Better parsing for Layouts with int/bool type. (@304NotModified, @rymk)
- [#1868](https://github.com/nlog/nlog/pull/1868) WebServiceTarget - FlushAsync - Avoid premature flush (#1868) (@snakefoot)
- [#1899](https://github.com/nlog/nlog/pull/1899) LogManager.Shutdown - Use the official method for closing down (@snakefoot)
#### Fixes
- [#1886](https://github.com/nlog/nlog/pull/1886) FileTarget - Archive should not fail when ArchiveFileName matches FileName (@snakefoot)
- [#1893](https://github.com/nlog/nlog/pull/1893) FileTarget - MONO doesn't like using the native Win32 API (@snakefoot)
- [#1883](https://github.com/nlog/nlog/pull/1883) LogFactory.Dispose - Should always close down created targets (@snakefoot)
### v4.4.1 (2016/12/24)
Summary:
- Fixes for medium trust (@snakefoot, @304notmodified)
- Performance multiple improvements for flush events (@snakefoot)
- FileTarget: Improvements for archiving (@snakefoot)
- FileTarget - Reopen filehandle when file write fails (@snakefoot)
- ConsoleTarget: fix crash when console isn't available (@snakefoot)
- NetworkTarget - UdpNetworkSender should exercise the provided Close-callback (@snakefoot)
Detail:
- [#1874](https://github.com/nlog/nlog/pull/1874) Fixes for medium trust (@snakefoot, @304notmodified)
- [#1873](https://github.com/nlog/nlog/pull/1873) PartialTrustDomain - Handle SecurityException to allow startup and logging (#1873) (@snakefoot)
- [#1859](https://github.com/nlog/nlog/pull/1859) FileTarget - MONO should also check SupportsSharableMutex (#1859) (@snakefoot)
- [#1853](https://github.com/nlog/nlog/pull/1853) AsyncTargetWrapper - Flush should start immediately without waiting (#1853) (@snakefoot)
- [#1858](https://github.com/nlog/nlog/pull/1858) FileTarget - Reopen filehandle when file write fails (#1858) (@snakefoot)
- [#1867](https://github.com/nlog/nlog/pull/1867) FileTarget - Failing to delete old archive files, should not stop logging (@snakefoot)
- [#1865](https://github.com/nlog/nlog/pull/1865) Compile MethodInfo into LateBoundMethod-delegate (ReflectedType is deprecated) (@snakefoot)
- [#1850](https://github.com/nlog/nlog/pull/1850) ConsoleTarget - Apply Encoding on InitializeTarget, if Console available (#1850) (@snakefoot)
- [#1862](https://github.com/nlog/nlog/pull/1862) SHFB config cleanup & simplify (@304NotModified)
- [#1863](https://github.com/nlog/nlog/pull/1863) Minor cosmetic changes on FileTarget class (@ie-zero)
- [#1861](https://github.com/nlog/nlog/pull/1861) Helper class ParameterUtils removed (@ie-zero)
- [#1847](https://github.com/nlog/nlog/pull/1847) LogFactory.Dispose() fixed race condition with reloadtimer (#1847) (@snakefoot)
- [#1849](https://github.com/nlog/nlog/pull/1849) NetworkTarget - UdpNetworkSender should exercise the provided Close-callback (@snakefoot)
- [#1857](https://github.com/nlog/nlog/pull/1857) Fix immutability of LogLevel properties (@ie-zero)
- [#1860](https://github.com/nlog/nlog/pull/1860) FileAppenderCache implements IDisposable (@ie-zero)
- [#1848](https://github.com/nlog/nlog/pull/1848) Standarise implementation of events (@ie-zero)
- [#1844](https://github.com/nlog/nlog/pull/1844) FileTarget - Mono2 runtime detection to skip using named archive-mutex (@snakefoot)
### v4.4 (2016/12/14)
#### Features
- [#1583](https://github.com/nlog/nlog/pull/1583) Don't stop logging when there is an invalid layoutrenderer in the layout. (@304NotModified)
- [#1740](https://github.com/nlog/nlog/pull/1740) WebServiceTarget support for JSON & Injecting JSON serializer into NLog (#1740) (@tetrodoxin)
- [#1754](https://github.com/nlog/nlog/pull/1754) JsonLayout: JsonLayout: add includeAllProperties & excludeProperties (@aireq)
- [#1439](https://github.com/nlog/nlog/pull/1439) Allow comma separated values (List) for Layout Renderers in nlog.config (@304NotModified)
- [#1782](https://github.com/nlog/nlog/pull/1782) Improvement on #1439: Support Generic (I)List and (I)Set for Target/Layout/Layout renderers properties in nlog.config (@304NotModified)
- [#1769](https://github.com/nlog/nlog/pull/1769) Optionally keeping variables during configuration reload (@nazim9214)
- [#1514](https://github.com/nlog/nlog/pull/1514) Add LimitingTargetWrapper (#1514) (@Jeinhaus)
- [#1581](https://github.com/nlog/nlog/pull/1581) Registering Layout renderers with func (one line needed), easier registering layout/layoutrender/targets (@304NotModified)
- [#1735](https://github.com/nlog/nlog/pull/1735) UrlHelper - Added standard support for UTF8 encoding, added support for RFC2396 & RFC3986 (#1735) (@snakefoot)
- [#1768](https://github.com/nlog/nlog/pull/1768) ExceptionLayoutRenderer - Added support for AggregateException (@snakefoot)
- [#1752](https://github.com/nlog/nlog/pull/1752) Layout processinfo with support for custom Format-string (@snakefoot)
- [#1836](https://github.com/nlog/nlog/pull/1836) Callsite: add includeNamespace option (@304NotModified)
- [#1817](https://github.com/nlog/nlog/pull/1817) Added condition to AutoFlushWrappper (@nazim9214)
#### Improvements
- [#1732](https://github.com/nlog/nlog/pull/1732) Handle duplicate attributes (error or using first occurence) in nlog.config (@nazim9214)
- [#1778](https://github.com/nlog/nlog/pull/1778) ConsoleTarget - DetectConsoleAvailable - Disabled by default (@snakefoot)
- [#1585](https://github.com/nlog/nlog/pull/1585) More clear internallog when reading XML config (@304NotModified)
- [#1784](https://github.com/nlog/nlog/pull/1784) ProcessInfoLayoutRenderer - Applied usage of LateBoundMethod (@snakefoot)
- [#1771](https://github.com/nlog/nlog/pull/1771) FileTarget - Added extra archive check is needed, after closing stale file handles (@snakefoot)
- [#1779](https://github.com/nlog/nlog/pull/1779) Improve performance of filters (2-3 x faster) (@snakefoot)
- [#1780](https://github.com/nlog/nlog/pull/1780) PropertiesLayoutRenderer - small performance improvement (@snakefoot)
- [#1776](https://github.com/nlog/nlog/pull/1776) Don't crash on an invalid (xml) app.config by default (@304NotModified)
- [#1763](https://github.com/nlog/nlog/pull/1763) JsonLayout - Performance improvements (@snakefoot)
- [#1755](https://github.com/nlog/nlog/pull/1755) General performance improvement (@snakefoot)
- [#1756](https://github.com/nlog/nlog/pull/1755) WindowsMultiProcessFileAppender (@snakefoot, @AndreGleichner)
### v4.3.11 (2016/11/07)
#### Improvements
- [#1700](https://github.com/nlog/nlog/pull/1700) Improved concurrency when multiple Logger threads are writing to async Target (@snakefoot)
- [#1750](https://github.com/nlog/nlog/pull/1750) Log payload for NLogViewerTarget/NetworkTarget to Internal Logger (@304NotModified)
- [#1745](https://github.com/nlog/nlog/pull/1745) FilePathLayout - Reduce memory-allocation for cleanup of filename (@snakefoot)
- [#1746](https://github.com/nlog/nlog/pull/1746) DateLayout - Reduce memory allocation when low time resolution (@snakefoot)
- [#1719](https://github.com/nlog/nlog/pull/1719) Avoid (Internal)Logger-boxing and params-array-allocation on Exception (@snakefoot)
- [#1683](https://github.com/nlog/nlog/pull/1683) FileTarget - Faster async processing of LogEvents for the same file (@snakefoot)
- [#1730](https://github.com/nlog/nlog/pull/1730) Conditions: Try interpreting first as non-string value (@304NotModified)
- [#1814](https://github.com/nlog/nlog/pull/1814) Improve [Obsolete] warnings - include the Nlog version when it became obsolete (#1814) (@ie-zero)
- [#1809](https://github.com/nlog/nlog/pull/1809) FileTarget - Close stale file handles outside archive mutex lock (@snakefoot)
#### Fixes
- [#1749](https://github.com/nlog/nlog/pull/1749) Try-catch for permission when autoloading - fixing Android permission issue (@304NotModified)
- [#1751](https://github.com/nlog/nlog/pull/1751) ExceptionLayoutRenderer: prevent nullrefexception when exception is null (@304NotModified)
- [#1706](https://github.com/nlog/nlog/pull/1706) Console Target Automatic Detect if console is available on Mono (@snakefoot)
### v4.3.10 (2016/10/11)
#### Features
- [#1680](https://github.com/nlog/nlog/pull/1680) Append to existing archive file (@304NotModified)
- [#1669](https://github.com/nlog/nlog/pull/1669) AsyncTargetWrapper - Allow TimeToSleepBetweenBatches = 0 (@snakefoot)
- [#1668](https://github.com/nlog/nlog/pull/1668) Console Target Automatic Detect if console is available (@snakefoot)
#### Improvements
- [#1697](https://github.com/nlog/nlog/pull/1697) Archiving should never fail writing (@304NotModified)
- [#1695](https://github.com/nlog/nlog/pull/1695) Performance: Counter/ProcessId/ThreadId-LayoutRenderer allocations less memory (@snakefoot)
- [#1693](https://github.com/nlog/nlog/pull/1693) Performance (allocation) improvement in Aysnc handling (@snakefoot)
- [#1694](https://github.com/nlog/nlog/pull/1694) FilePathLayout - CleanupInvalidFilePath - Happy path should not allocate (@snakefoot)
- [#1675](https://github.com/nlog/nlog/pull/1675) unseal databasetarget and make BuildConnectionString protected (@304NotModified)
- [#1690](https://github.com/nlog/nlog/pull/1690) Fix memory leak in AppDomainWrapper (@snakefoot)
- [#1702](https://github.com/nlog/nlog/pull/1702) Performance: InternalLogger should only allocate params-array when needed (@snakefoot)
#### Fixes
- [#1676](https://github.com/nlog/nlog/pull/1676) Fix FileTarget on Xamarin: Remove mutex usage for Xamarin 'cause of runtime exceptions (@304NotModified)
- [#1591](https://github.com/nlog/nlog/pull/1591) Count operation on AsyncRequestQueue is not thread-safe (@snakefoot)
### v4.3.9 (2016/09/18)
#### Features
- [#1641](https://github.com/nlog/nlog/pull/1641) FileTarget: Add WriteFooterOnArchivingOnly parameter. (@bhaeussermann)
- [#1628](https://github.com/nlog/nlog/pull/1628) Add ExceptionDataSeparator option for ${exception} (@FroggieFrog)
- [#1626](https://github.com/nlog/nlog/pull/1626) cachekey option for cache layout wrapper (@304NotModified)
#### Improvements
- [#1643](https://github.com/nlog/nlog/pull/1643) Pause logging when the race condition occurs in (Colored)Console Target (@304NotModified)
- [#1632](https://github.com/nlog/nlog/pull/1632) Prevent possible crash when archiving in folder with non-archived files (@304NotModified)
#### Fixes
- [#1646](https://github.com/nlog/nlog/pull/1646) FileTarget: Fix file archive race-condition. (@bhaeussermann)
- [#1642](https://github.com/nlog/nlog/pull/1642) MDLC: fixing mutable dictionary issue (improvement) (@vlardn)
- [#1635](https://github.com/nlog/nlog/pull/1635) Fix ${tempdir} and ${nlogdir} if both have dir and file. (@304NotModified)
### v4.3.8 (2016/09/05)
#### Features
- [#1619](https://github.com/NLog/NLog/pull/1619) NetworkTarget: Added option to specify EOL (@kevindaub)
#### Improvements
- [#1596](https://github.com/NLog/NLog/pull/1596) Performance tweak in NLog routing (@304NotModified)
- [#1593](https://github.com/NLog/NLog/pull/1593) FileTarget: large performance improvement - back to 1 million/sec (@304NotModified)
- [#1621](https://github.com/nlog/nlog/pull/1621) FileTarget: writing to non-existing drive was slowing down NLog a lot (@304NotModified)
#### Fixes
- [#1616](https://github.com/nlog/nlog/pull/1616) FileTarget: Don't throw an exception if a dir is missing when deleting old files on startup (@304NotModified)
### v4.3.7 (2016/08/06)
#### Features
- [#1469](https://github.com/nlog/nlog/pull/1469) Allow overwriting possible nlog configuration file paths (@304NotModified)
- [#1578](https://github.com/nlog/nlog/pull/1578) Add support for name parameter on ${Assembly-version} (@304NotModified)
- [#1580](https://github.com/nlog/nlog/pull/1580) Added option to not render empty literals on nested json objects (@johnkors)
#### Improvements
- [#1558](https://github.com/nlog/nlog/pull/1558) Callsite layout renderer: improve string comparison test (performance) (@304NotModified)
- [#1582](https://github.com/nlog/nlog/pull/1582) FileTarget: Performance improvement for CleanupInvalidFileNameChars (@304NotModified)
#### Fixes
- [#1556](https://github.com/nlog/nlog/pull/1556) Bugfix: Use the culture when rendering the layout (@304NotModified)
### v4.3.6 (2016/07/24)
#### Features
- [#1531](https://github.com/nlog/nlog/pull/1531) Support Android 4.4 (@304NotModified)
- [#1551](https://github.com/nlog/nlog/pull/1551) Addded CompoundLayout (@luigiberrettini)
#### Fixes
- [#1548](https://github.com/nlog/nlog/pull/1548) Bugfix: Can't update EventLog's Source property (@304NotModified, @Page-Not-Found)
- [#1553](https://github.com/nlog/nlog/pull/1553) Bugfix: Throw configException when registering invalid extension assembly/type. (@304NotModified, @Jeinhaus)
- [#1547](https://github.com/nlog/nlog/pull/1547) LogReceiverWebServiceTarget is leaking communication channels (@MartinTherriault)
### v4.3.5 (2016/06/13)
#### Features
- [#1471](https://github.com/nlog/nlog/pull/1471) Add else option to ${when} (@304NotModified)
- [#1481](https://github.com/nlog/nlog/pull/1481) get items for diagnostic contexts (DiagnosticsContextes, GetNames() method) (@tiljanssen)
#### Fixes
- [#1504](https://github.com/nlog/nlog/pull/1504) Fix ${callsite} with async method with return value (@PELNZ)
### v4.3.4 (2016/05/16)
#### Features
- [#1423](https://github.com/nlog/nlog/pull/1423) Injection of zip-compressor for fileTarget (@AndreGleichner)
- [#1434](https://github.com/nlog/nlog/pull/1434) Added constructors with name argument to the target types (@304NotModified, @flyingcroissant)
- [#1400](https://github.com/nlog/nlog/pull/1400) Added WrapLineLayoutRendererWrapper (@mathieubrun)
#### Improvements
- [#1456](https://github.com/nlog/nlog/pull/1456) FileTarget: Improvements in FileTarget archive cleanup. (@bhaeussermann)
- [#1417](https://github.com/nlog/nlog/pull/1417) FileTarget prevent stackoverflow after setting FileName property on init (@304NotModified)
#### Fixes
- [#1454](https://github.com/nlog/nlog/pull/1454) Fix LoggingRule.ToString (@304NotModified)
- [#1453](https://github.com/nlog/nlog/pull/1453) Fix potential nullref exception in LogManager.Shutdown() (@304NotModified)
- [#1450](https://github.com/nlog/nlog/pull/1450) Fix duplicate Target after config Initialize (@304NotModified)
- [#1446](https://github.com/nlog/nlog/pull/1446) FileTarget: create dir if CreateDirs=true and replacing file content (@304NotModified)
- [#1432](https://github.com/nlog/nlog/pull/1432) Check if directory NLog.dll is detected in actually exists (@gregmac)
#### Other
- [#1440](https://github.com/nlog/nlog/pull/1440) Added extra unit tests for context classes (@304NotModified)
### v4.3.3 (2016/04/28)
- [#1411](https://github.com/nlog/nlog/pull/1411) MailTarget: fix "From" errors (bug introduced in NLog 4.3.2) (@304NotModified)
### v4.3.2 (2016/04/26)
- [#1404](https://github.com/nlog/nlog/pull/1404) FileTarget cleanup: move to background thread. (@304NotModified)
- [#1403](https://github.com/nlog/nlog/pull/1403) Fix filetarget: Thread was being aborted (#2) (@304NotModified)
- [#1402](https://github.com/nlog/nlog/pull/1402) Getting the 'From' when UseSystemNetMailSettings is true (@MoaidHathot)
- [#1401](https://github.com/nlog/nlog/pull/1401) Allow target configuration to support a hierachy of XML nodes (#1401) (@304NotModified)
- [#2](https://github.com/nlog/nlog/pull/2) Fix filetarget: Thread was being aborted (#2) (@304NotModified)
- [#1394](https://github.com/nlog/nlog/pull/1394) Make test methods public (#1394) (@luigiberrettini)
- [#1393](https://github.com/nlog/nlog/pull/1393) Remove test dependency on locale (@luigiberrettini)
### v4.3.1 (2016/04/20)
- [#1386](https://github.com/nlog/nlog/pull/1386) Fix "allLayouts is null" exception (@304NotModified)
- [#1387](https://github.com/nlog/nlog/pull/1387) Fix filetarget: Thread was being aborted (@304NotModified)
- [#1383](https://github.com/nlog/nlog/pull/1383) Fix configuration usage in `${var}` renderer (@bhaeussermann, @304NotModified)
### v4.3.0 (2016/04/16)
- [#1211](https://github.com/nlog/nlog/pull/1211) Update nlog.config for 4.3 (@304NotModified)
- [#1368](https://github.com/nlog/nlog/pull/1368) Update license (@304NotModified)
### v4.3.0-rc3 (2016/04/09)
- [#1348](https://github.com/nlog/nlog/pull/1348) Fix nullref + fix relative path for file archive (@304NotModified)
- [#1352](https://github.com/nlog/nlog/pull/1352) Fix for writing log file to root path (@304NotModified)
- [#1357](https://github.com/nlog/nlog/pull/1357) autoload NLog.config in assets folder (Xamarin Android) (@304NotModified)
- [#1358](https://github.com/nlog/nlog/pull/1358) no-recusive logging in internallogger. (@304NotModified)
- [#1364](https://github.com/nlog/nlog/pull/1364) Fix stacktraceusage with more than 1 rule (@304NotModified)
### v4.3.0-rc2 (2016/03/26)
- [#1335](https://github.com/nlog/nlog/pull/1335) Fix all build warnings (@304NotModified)
- [#1336](https://github.com/nlog/nlog/pull/1336) Throw NLogConfigurationException if TimeToSleepBetweenBatches `<= 0` (@vincechan)
- [#1333](https://github.com/nlog/nlog/pull/1333) Fix ${callsite} when loggerType can't be found due to inlining (@304NotModified)
- [#1329](https://github.com/nlog/nlog/pull/1329) Update SHFB (@304NotModified)
### v4.3.0-rc1 (2016/03/22)
- [#1323](https://github.com/nlog/nlog/pull/1323) Add TimeStamp options to XML, Appsetting and environment var (@304NotModified)
- [#1286](https://github.com/nlog/nlog/pull/1286) Easier api: AddRule methods, fix AllTargets crash, fix IsLevelEnabled(off) crash, refactor internal (@304NotModified)
- [#1317](https://github.com/nlog/nlog/pull/1317) don't require ProviderName attribute when using `<connectionStrings>` (app.config etc) (@304NotModified)
- [#1316](https://github.com/nlog/nlog/pull/1316) Fix scan for stacktrace usage (bug never released) (@304NotModified)
- [#1299](https://github.com/nlog/nlog/pull/1299) Also use logFactory for ThrowConfigExceptions (@304NotModified)
- [#1309](https://github.com/nlog/nlog/pull/1309) Added nested json from xml unit test (@pysco68, @304NotModified)
- [#1310](https://github.com/nlog/nlog/pull/1310) Fix threadsafe issue of GetLogger / GetCurrentClassLogger (+improve performance) (@304NotModified)
- [#1313](https://github.com/nlog/nlog/pull/1313) Added the NLog.Owin.Logging badges to README packages list (@pysco68)
- [#1222](https://github.com/nlog/nlog/pull/1222) internalLogger, write to System.Diagnostics.Debug / System.Diagnostics.Trace #1217 (@bryjamus)
- [#1303](https://github.com/nlog/nlog/pull/1303) Fix threadsafe issue of ScanProperties3 (@304NotModified)
- [#1273](https://github.com/nlog/nlog/pull/1273) Added the ability to allow virtual paths for SMTP pickup directory (@michaeljbaird)
- [#1298](https://github.com/nlog/nlog/pull/1298) NullReferenceException fix for VariableLayoutRenderer (@neris)
- [#1295](https://github.com/nlog/nlog/pull/1295) Fix Callsite render bug introducted in 4.3 beta (@304NotModified)
- [#1285](https://github.com/nlog/nlog/pull/1285) Fix: {$processtime} has incorrect milliseconds formatting (@304NotModified)
- [#1296](https://github.com/nlog/nlog/pull/1296) CachedLayoutRender: allow ClearCache as (ambient) property (@304NotModified)
- [#1294](https://github.com/nlog/nlog/pull/1294) Fix thread-safe issue ScanProperties (@304NotModified)
- [#1281](https://github.com/nlog/nlog/pull/1281) FileTargetTests: Fix runtime overflow-of-minute issue in DateArchive_SkipPeriod. (@bhaeussermann)
- [#1274](https://github.com/nlog/nlog/pull/1274) FileTarget: Fix archive does not work when date in file name. (@bhaeussermann)
- [#1275](https://github.com/nlog/nlog/pull/1275) Less logging for unstable unit tests (and also probably too much) (@304NotModified)
- [#1270](https://github.com/nlog/nlog/pull/1270) Added testcase (NestedJsonAttrTest) (@304NotModified)
- [#1279](https://github.com/nlog/nlog/pull/1279) Fix tests to ensure all AsyncTargetWrapper's are closed. (@bhaeussermann)
- [#1238](https://github.com/nlog/nlog/pull/1238) Control throwing of NLogConfigurationExceptions (LogManager.ThrowConfigExceptions) (@304NotModified)
- [#1265](https://github.com/nlog/nlog/pull/1265) More thread-safe method (@304NotModified)
- [#1260](https://github.com/nlog/nlog/pull/1260) try read nlog.config in ios/android (@304NotModified)
- [#1253](https://github.com/nlog/nlog/pull/1253) Added docs for UrlEncode (@304NotModified)
- [#1252](https://github.com/nlog/nlog/pull/1252) improve InternalLoggerTests unit test (@304NotModified)
- [#1259](https://github.com/nlog/nlog/pull/1259) Internallogger improvements (@304NotModified)
- [#1258](https://github.com/nlog/nlog/pull/1258) fixed typo in NLog.config (@icnocop)
- [#1256](https://github.com/nlog/nlog/pull/1256) Badges Shields.io ->` Badge.fury.io (@304NotModified)
- [#1225](https://github.com/nlog/nlog/pull/1225) XmlLoggingConfiguration: Set config values on correct LogFactory object (@bhaeussermann, @304NotModified)
- [#1](https://github.com/nlog/nlog/pull/1) Fix ambiguity in `cref` in comments. (@304NotModified)
- [#1254](https://github.com/nlog/nlog/pull/1254) Remove SubversionScc / AnkhSVN info from solutions (@304NotModified)
- [#1247](https://github.com/nlog/nlog/pull/1247) Init version issue template (@304NotModified)
- [#1245](https://github.com/nlog/nlog/pull/1245) Add Logger.Swallow(Task task) (@breyed)
- [#1246](https://github.com/nlog/nlog/pull/1246) added badges UWP / web.ASPNET5 (@304NotModified)
- [#1227](https://github.com/nlog/nlog/pull/1227) LogFactory: Add generic-type versions of GetLogger() and GetCurrentClassLogger() (@bhaeussermann)
- [#1242](https://github.com/nlog/nlog/pull/1242) Improve unit test (@304NotModified)
- [#1213](https://github.com/nlog/nlog/pull/1213) Log more to InternalLogger (@304NotModified)
- [#1240](https://github.com/nlog/nlog/pull/1240) Added StringHelpers + StringHelpers.IsNullOrWhiteSpace (@304NotModified)
- [#1239](https://github.com/nlog/nlog/pull/1239) Fix unstable MDLC Unit test + MDLC free dataslot (@304NotModified, @MikeFH)
- [#1236](https://github.com/nlog/nlog/pull/1236) Bugfix: Internallogger creates folder, even when turned off. (@eduardorascon)
- [#1232](https://github.com/nlog/nlog/pull/1232) Fix HttpGet protocol for WebService (@MikeFH)
- [#1223](https://github.com/nlog/nlog/pull/1223) Fix deadlock on Factory (@304NotModified)
### v4.3.0-beta2 (2016/02/04)
- [#1220](https://github.com/nlog/nlog/pull/1220) FileTarget: Add internal logging for archive date. (@bhaeussermann)
- [#1214](https://github.com/nlog/nlog/pull/1214) Better unit test cleanup between tests + fix threadsafe issue ScanProperties (@304NotModified)
- [#1212](https://github.com/nlog/nlog/pull/1212) Support reading nlog.config from Android assets folder (@304NotModified)
- [#1215](https://github.com/nlog/nlog/pull/1215) FileTarget: Archiving not working properly with AsyncWrapper (@bhaeussermann)
- [#1216](https://github.com/nlog/nlog/pull/1216) Added more docs to InternalLogger (@304NotModified)
- [#1207](https://github.com/nlog/nlog/pull/1207) FileTarget: Fix Footer for archiving. (@bhaeussermann)
- [#1210](https://github.com/nlog/nlog/pull/1210) Added extra unit test (@304NotModified)
- [#1191](https://github.com/nlog/nlog/pull/1191) Throw exception when base.InitializeTarget() is not called + inline GetAllLayouts() (@304NotModified)
- [#1208](https://github.com/nlog/nlog/pull/1208) FileTargetTests: Supplemented ReplaceFileContentsOnEachWriteTest() to test with and without header and footer (@bhaeussermann)
- [#1197](https://github.com/nlog/nlog/pull/1197) Improve XML Docs (@304NotModified)
- [#1200](https://github.com/nlog/nlog/pull/1200) Added unit test for K datetime format (@304NotModified)
### 4.3.0-beta1 (2016/01/27)
- [#1143](https://github.com/nlog/nlog/pull/1143) Consistent Exception handling v3 (@304NotModified)
- [#1195](https://github.com/nlog/nlog/pull/1195) FileTarget: added ReplaceFileContentsOnEachWriteTest (@304NotModified)
- [#925](https://github.com/nlog/nlog/pull/925) RegistryLayoutRenderer: Support for layouts, RegistryView (32, 64 bit) and all root key names (HKCU/HKLM etc) (@304NotModified, @Niklas-Peter)
- [#1157](https://github.com/nlog/nlog/pull/1157) FIx (xml-) config classes for thread-safe issues (@304NotModified)
- [#1183](https://github.com/nlog/nlog/pull/1183) FileTarget: Fix compress archive file not working when using concurrentWrites="True" and keepFileOpen="True" (@bhaeussermann)
- [#1187](https://github.com/nlog/nlog/pull/1187) MethodCallTarget: allow optional parameters, no nullref exceptions. +unit tests (@304NotModified)
- [#1171](https://github.com/nlog/nlog/pull/1171) Coloredconsole not compiled regex by default (@304NotModified)
- [#1173](https://github.com/nlog/nlog/pull/1173) Unit test added for Variable node (@UgurAldanmaz)
- [#1138](https://github.com/nlog/nlog/pull/1138) Callsite fix for async methods (@304NotModified)
- [#1126](https://github.com/nlog/nlog/pull/1126) Fix and test archiving when writing to same file from different processes (@bhaeussermann)
- [#1170](https://github.com/nlog/nlog/pull/1170) LogBuilder: add StringFormatMethod Annotations (@304NotModified)
- [#1127](https://github.com/nlog/nlog/pull/1127) Max message length option for Eventlog target (@UgurAldanmaz)
- [#1149](https://github.com/nlog/nlog/pull/1149) Fix crash during delete of old archives & archive delete optimization (@brutaldev)
- [#1154](https://github.com/nlog/nlog/pull/1154) Fix nuget for Xamarin.iOs (@304NotModified)
- [#1159](https://github.com/nlog/nlog/pull/1159) README-developers.md: Added pull request checklist. (@bhaeussermann)
- [#1131](https://github.com/nlog/nlog/pull/1131) Reducing memory allocations in ShortDateLayoutRenderer by caching the formatted date. (@epignosisx)
- [#1141](https://github.com/nlog/nlog/pull/1141) Remove code dup of InternalLogger (T4) (@304NotModified)
- [#1144](https://github.com/nlog/nlog/pull/1144) add doc (@304NotModified)
- [#1142](https://github.com/nlog/nlog/pull/1142) PropertyHelper: rename to readable names (@304NotModified)
- [#1139](https://github.com/nlog/nlog/pull/1139) Reduce Memory Allocations in LongDateLayoutRenderer (@epignosisx)
- [#1112](https://github.com/nlog/nlog/pull/1112) ColoredConsoleTarget performance improvements. (@bhaeussermann)
- [#1135](https://github.com/nlog/nlog/pull/1135) FileTargetTests: Fix DateArchive_SkipPeriod test. (@bhaeussermann)
- [#1119](https://github.com/nlog/nlog/pull/1119) FileTarget: Use last-write-time for archive file name (@bhaeussermann)
- [#1089](https://github.com/nlog/nlog/pull/1089) Support For Relative Paths in the File Targets (@Page-Not-Found)
- [#1068](https://github.com/nlog/nlog/pull/1068) Overhaul ExceptionLayoutRenderer (@Page-Not-Found)
- [#1125](https://github.com/nlog/nlog/pull/1125) FileTarget: Fix continuous archiving bug. (@bhaeussermann)
- [#1113](https://github.com/nlog/nlog/pull/1113) Bugfix: EventLogTarget OnOverflow=Split writes always to Info level (@UgurAldanmaz)
- [#1116](https://github.com/nlog/nlog/pull/1116) Config: Implemented inheritance policy for autoReload in included config files (@bhaeussermann)
- [#1100](https://github.com/nlog/nlog/pull/1100) FileTarget: Fix archive based on time does not always archive. (@bhaeussermann)
- [#1110](https://github.com/nlog/nlog/pull/1110) Fix: Deadlock in NetworkTarget (@kt1996)
- [#1109](https://github.com/nlog/nlog/pull/1109) FileTarget: Fix archiving for ArchiveFileName without a pattern. (@bhaeussermann)
- [#1104](https://github.com/nlog/nlog/pull/1104) Merge from 4.2.3 (Improve performance of FileTarget, performance GDC) (@304NotModified, @epignosisx)
- [#1095](https://github.com/nlog/nlog/pull/1095) Fix find calling method on stack trace (@304NotModified)
- [#1099](https://github.com/nlog/nlog/pull/1099) Added extra callsite unit tests (@304NotModified)
- [#1084](https://github.com/nlog/nlog/pull/1084) Log unused targets to internal logger (@UgurAldanmaz)
### 4.2.3 (2015/12/12)
- [#1083](https://github.com/nlog/nlog/pull/1083) Changed the heading in Readme file (@Page-Not-Found)
- [#1081](https://github.com/nlog/nlog/pull/1081) Update README.md (@UgurAldanmaz)
- [#4](https://github.com/nlog/nlog/pull/4) Update from base repository (@304NotModified, @bhaeussermann, @ie-zero, @epignosisx, @stefandevo, @nathan-schubkegel)
- [#1066](https://github.com/nlog/nlog/pull/1066) Add AllLevels and AllLoggingLevels to LogLevel.cs. (@rellis-of-rhindleton)
- [#1062](https://github.com/nlog/nlog/pull/1062) Fix Xamarin Build in PR (and don't fail in fork) (@304NotModified)
- [#1061](https://github.com/nlog/nlog/pull/1061) skip xamarin-dependent steps in appveyor PR builds (@nathan-schubkegel)
- [#1040](https://github.com/nlog/nlog/pull/1040) Xamarin (iOS, Android) and Windows Phone 8 (@304NotModified, @stefandevo)
- [#1041](https://github.com/nlog/nlog/pull/1041) EventLogTarget: Add overflow action for too large messages (@epignosisx)
### 4.2.2 (2015/11/21)
- [#1054](https://github.com/nlog/nlog/pull/1054) LogReceiverWebServiceTarget.CreateLogReceiver() should be virtual (@304NotModified)
- [#1048](https://github.com/nlog/nlog/pull/1048) Var layout renderer improvements (@304NotModified)
- [#1043](https://github.com/nlog/nlog/pull/1043) Moved sourcecode tests to separate tool (@304NotModified)
### 4.2.1-RC1 (2015/11/13)
- [#1031](https://github.com/nlog/nlog/pull/1031) NetworkTarget: linkedlist + configure max connections (@304NotModified)
- [#1037](https://github.com/nlog/nlog/pull/1037) Added FilterResult tests (@304NotModified)
- [#1036](https://github.com/nlog/nlog/pull/1036) Logbuilder tests + fix passing Off (@304NotModified)
- [#1035](https://github.com/nlog/nlog/pull/1035) Added tests for Conditional logger (@304NotModified)
- [#1033](https://github.com/nlog/nlog/pull/1033) Databasetarget: restored 'UseTransactions' and print warning if used (@304NotModified)
- [#1032](https://github.com/nlog/nlog/pull/1032) Filetarget: Added tests for the 2 kind of slashes (@304NotModified)
- [#1027](https://github.com/nlog/nlog/pull/1027) Reduce memory allocations in Logger.Log when using CsvLayout and JsonLayout (@epignosisx)
- [#1020](https://github.com/nlog/nlog/pull/1020) Reduce memory allocations in Logger.Log by avoiding GetEnumerator. (@epignosisx)
- [#1019](https://github.com/nlog/nlog/pull/1019) Issue #987: Filetarget: Max archives settings sometimes removes to many files (@bhaeussermann)
- [#1021](https://github.com/nlog/nlog/pull/1021) Fix #2 ObjectGraphScanner.ScanProperties: Collection was modified (@304NotModified)
- [#994](https://github.com/nlog/nlog/pull/994) Introduce FileAppenderCache class (@ie-zero)
- [#968](https://github.com/nlog/nlog/pull/968) Fix: LogFactoryTests remove Windows specific values (@ie-zero)
- [#999](https://github.com/nlog/nlog/pull/999) Unit Tests added to LogFactory class (@ie-zero)
- [#1000](https://github.com/nlog/nlog/pull/1000) Fix methods' indentation in LogManager class (@ie-zero)
- [#1001](https://github.com/nlog/nlog/pull/1001) Dump() now uses InternalLogger.Debug() consistent (@ie-zero)
### 4.2.0 (2015/10/24)
- [#996](https://github.com/nlog/nlog/pull/996) ColoredConsoleTarget: Fixed broken WholeWords option of highlight-word. (@bhaeussermann)
- [#995](https://github.com/nlog/nlog/pull/995) ArchiveFileCompression: auto add `.zip` to compressed filename when archiveName isn't specified (@bhaeussermann)
- [#993](https://github.com/nlog/nlog/pull/993) changed to nuget appveyor account (@304NotModified)
- [#992](https://github.com/nlog/nlog/pull/992) added logo (@304NotModified)
- [#988](https://github.com/nlog/nlog/pull/988) Unit test for proving max-archive bug of #987 (@304NotModified)
- [#991](https://github.com/nlog/nlog/pull/991) Document FileTarget inner properties/methods (@ie-zero)
- [#986](https://github.com/nlog/nlog/pull/986) Added more unit tests for max archive with dates in files. (@304NotModified)
- [#984](https://github.com/nlog/nlog/pull/984) Fixes #941. Add annotations for custom string formatting methods (@bhaeussermann)
- [#985](https://github.com/nlog/nlog/pull/985) Fix: file archiving DateAndSequence & FileArchivePeriod.Day won't work always (wrong switching day detected) (@304NotModified)
- [#982](https://github.com/nlog/nlog/pull/982) Document FileTarget inner properties/methods (@ie-zero)
- [#983](https://github.com/nlog/nlog/pull/983) Remove obsolete code from FileTarget (@ie-zero)
- [#981](https://github.com/nlog/nlog/pull/981) More tests inner parse + docs (@304NotModified)
- [#952](https://github.com/nlog/nlog/pull/952) Fixes #931. FileTarget: Log info concerning archiving to internal logger (@bhaeussermann)
- [#976](https://github.com/nlog/nlog/pull/976) Fix SL4/SL5 warnings by adding/editing XML docs (@304NotModified)
- [#973](https://github.com/nlog/nlog/pull/973) More fluent unit tests (@304NotModified)
- [#975](https://github.com/nlog/nlog/pull/975) Fix parse of inner layout (@304NotModified)
- [#3](https://github.com/nlog/nlog/pull/3) Update (@304NotModified, @UgurAldanmaz, @vbfox, @kevindaub, @Niklas-Peter, @bhaeussermann, @breyed, @wrangellboy)
- [#974](https://github.com/nlog/nlog/pull/974) Small Codecoverage improvement (@304NotModified)
- [#966](https://github.com/nlog/nlog/pull/966) Fix: Exception is thrown when archiving is enabled (@304NotModified)
- [#939](https://github.com/nlog/nlog/pull/939) Bugfix: useSystemNetMailSettings=false still uses .config settings + feature: PickupDirectoryLocation from nlog.config (@dnlgmzddr)
- [#972](https://github.com/nlog/nlog/pull/972) Added Codecov.io (@304NotModified)
- [#971](https://github.com/nlog/nlog/pull/971) Removed unneeded System.Drawing references (@304NotModified)
- [#967](https://github.com/nlog/nlog/pull/967) Getcurrentclasslogger documentation / error messages improvements (@304NotModified)
- [#963](https://github.com/nlog/nlog/pull/963) FIx: Collection was modified - GetTargetsByLevelForLogger (@304NotModified)
- [#954](https://github.com/nlog/nlog/pull/954) Issue 941: Add annotations for customer string formatting messages (@wrangellboy)
- [#940](https://github.com/nlog/nlog/pull/940) Documented default fallback value and RanToCompletion (@breyed)
- [#947](https://github.com/nlog/nlog/pull/947) Fixes #319. Added IncrementValue property. (@bhaeussermann)
- [#945](https://github.com/nlog/nlog/pull/945) Added Travis Badge (@304NotModified)
- [#944](https://github.com/nlog/nlog/pull/944) Skipped some unit tests for Mono (@304NotModified)
- [#938](https://github.com/nlog/nlog/pull/938) Issue #913: Log NLog version to internal log. (@bhaeussermann)
- [#937](https://github.com/nlog/nlog/pull/937) Added more registry unit tests (@304NotModified)
- [#933](https://github.com/nlog/nlog/pull/933) Issue #612: Cached Layout Renderer is reevaluated when LoggingConfiguration is changed (@bhaeussermann)
- [#2](https://github.com/nlog/nlog/pull/2) Support object vals for mdlc (@UgurAldanmaz)
- [#927](https://github.com/nlog/nlog/pull/927) Comments change in LogFactory (@Niklas-Peter)
- [#926](https://github.com/nlog/nlog/pull/926) Assure automatic re-configuration after configuration change (@Niklas-Peter)
### 4.1.2 (2015/09/20)
- [#920](https://github.com/nlog/nlog/pull/920) Added AssemblyFileVersion as property to build script (@304NotModified)
- [#912](https://github.com/nlog/nlog/pull/912) added fluent .properties, fix/add fluent unit tests (@304NotModified)
- [#909](https://github.com/nlog/nlog/pull/909) added ThreadAgnostic on AllEventPropertiesLayoutRenderer (@304NotModified)
- [#910](https://github.com/nlog/nlog/pull/910) Fixes "Collection was modified" crash with ReconfigExistingLoggers (@304NotModified)
- [#906](https://github.com/nlog/nlog/pull/906) added some extra tests (@304NotModified)
### 4.1.1 (2015/09/12)
- [#900](https://github.com/nlog/nlog/pull/900) fix generated code after change .tt (#894) (@304NotModified)
- [#901](https://github.com/nlog/nlog/pull/901) Safe autoload (@304NotModified)
- [#894](https://github.com/nlog/nlog/pull/894) fix generated code after change .tt (#894) (@304NotModified)
- [#896](https://github.com/nlog/nlog/pull/896) Support object vals for mdlc (@UgurAldanmaz)
- [#898](https://github.com/nlog/nlog/pull/898) Resolves Internal Logging With Just Filename (@kevindaub)
- [#1](https://github.com/nlog/nlog/pull/1) Update from base repository (@304NotModified, @UgurAldanmaz, @vbfox)
- [#892](https://github.com/nlog/nlog/pull/892) Remove unused windows.forms stuff (@304NotModified)
- [#894](https://github.com/nlog/nlog/pull/894) Obsolete attribute doesn't specify the correct replacement (@vbfox)
### 4.1.0 (2015/08/30)
- [#884](https://github.com/nlog/nlog/pull/884) Changes at MDLC to support .Net 4.0 and .Net 4.5 (@UgurAldanmaz)
- [#881](https://github.com/nlog/nlog/pull/881) Change GitHub for Windows to GitHub Desktop (@campbeb)
- [#874](https://github.com/nlog/nlog/pull/874) Wcf receiver client (@kevindaub, @304NotModified)
- [#871](https://github.com/nlog/nlog/pull/871) ${event-properties} - Added culture and format properties (@304NotModified)
- [#861](https://github.com/nlog/nlog/pull/861) LogReceiverServiceTests: Added one-way unit test (retry) (@304NotModified)
- [#866](https://github.com/nlog/nlog/pull/866) FileTarget.DeleteOldDateArchive minor fix (@remye06)
- [#872](https://github.com/nlog/nlog/pull/872) Updated appveyor.yml (unit test CMD) (@304NotModified)
- [#743](https://github.com/nlog/nlog/pull/743) Support object values for GDC, MDC and NDC contexts. (@williamb1024)
- [#773](https://github.com/nlog/nlog/pull/773) Fixed DateAndSequence archive numbering mode + bugfix no max archives (@remye06)
- [#858](https://github.com/nlog/nlog/pull/858) Fixed travis build with unit tests (@kevindaub, @304NotModified)
- [#856](https://github.com/nlog/nlog/pull/856) Revert "LogReceiverServiceTests: Added one-way unit test" (@304NotModified)
- [#854](https://github.com/nlog/nlog/pull/854) LogReceiverServiceTests: Added one-way unit test (@304NotModified)
- [#855](https://github.com/nlog/nlog/pull/855) Update appveyor.yml (@304NotModified)
- [#853](https://github.com/nlog/nlog/pull/853) Update appveyor config (@304NotModified)
- [#850](https://github.com/nlog/nlog/pull/850) Archive files delete right order (@304NotModified)
- [#848](https://github.com/nlog/nlog/pull/848) Refactor file archive unittest (@304NotModified)
- [#820](https://github.com/nlog/nlog/pull/820) fix unloaded appdomain with xml auto reload (@304NotModified)
- [#789](https://github.com/nlog/nlog/pull/789) added config option for breaking change (Exceptions logging) in NLog 4.0 [WIP] (@304NotModified)
- [#833](https://github.com/nlog/nlog/pull/833) Move MDLC and Traceactivity from Contrib + handle missing dir in filewachter (@304NotModified, @kichristensen)
- [#818](https://github.com/nlog/nlog/pull/818) Updated InternalLogger to Create Directories If Needed (@kevindaub)
- [#844](https://github.com/nlog/nlog/pull/844) Fix ThreadAgnosticAttributeTest unit test (@304NotModified)
- [#834](https://github.com/nlog/nlog/pull/834) Fix SL5 (@304NotModified)
- [#827](https://github.com/nlog/nlog/pull/827) added test: Combine archive every day and archive above size (@304NotModified)
- [#811](https://github.com/nlog/nlog/pull/811) Easier API (@304NotModified)
- [#816](https://github.com/nlog/nlog/pull/816) Overhaul NLog variables (@304NotModified)
- [#788](https://github.com/nlog/nlog/pull/788) Fix: exception is not correctly logged when calling without message [WIP] (@304NotModified)
- [#814](https://github.com/nlog/nlog/pull/814) Bugfix: `<extensions>` needs to be the first element in the config (@304NotModified)
- [#813](https://github.com/nlog/nlog/pull/813) Added unit test: reload after replace (@304NotModified)
- [#812](https://github.com/nlog/nlog/pull/812) Unit tests: added some extra time for completion (@304NotModified)
- [#800](https://github.com/nlog/nlog/pull/800) Replace NewLines Layout Renderer Wrapper (@flower189)
- [#805](https://github.com/nlog/nlog/pull/805) Fix issue #804: Logging to same file from multiple processes misses messages (@bhaeussermann)
- [#797](https://github.com/nlog/nlog/pull/797) added switch to JsonLayout to suppress the extra spaces (@tmusico)
- [#809](https://github.com/nlog/nlog/pull/809) Improve docs `ICreateFileParameters` (@304NotModified)
- [#808](https://github.com/nlog/nlog/pull/808) Added logrecievertest with ServiceHost (@304NotModified)
- [#780](https://github.com/nlog/nlog/pull/780) Call site line number layout renderer - fix (@304NotModified)
- [#776](https://github.com/nlog/nlog/pull/776) added SwallowAsync(Task) (@breyed)
- [#774](https://github.com/nlog/nlog/pull/774) FIxed ArchiveOldFileOnStartup with layout renderer used in ArchiveFileName (@remye06)
- [#750](https://github.com/nlog/nlog/pull/750) Optional encoding for JsonAttribute (@grbinho)
- [#742](https://github.com/nlog/nlog/pull/742) Fix monodevelop build. (@txdv)
- [#781](https://github.com/nlog/nlog/pull/781) All events layout renderer: added `IncludeCallerInformation` option. (@304NotModified)
- [#794](https://github.com/nlog/nlog/pull/794) Support for auto loading UNC paths (@mikeobrien)
- [#786](https://github.com/nlog/nlog/pull/786) added unit test for forwardscomp (@304NotModified)
### 4.0.1 (2015/06/18)
- [#762](https://github.com/nlog/nlog/pull/762) Improved config example (@304NotModified)
- [#760](https://github.com/nlog/nlog/pull/760) Autoload fix for ASP.net + better autoloading logging (@304NotModified)
- [#763](https://github.com/nlog/nlog/pull/763) Fixed reference for Siverlight (broken and fixed in 4.0.1) (@304NotModified)
- [#759](https://github.com/nlog/nlog/pull/759) Check if directory watched exists (@kichristensen)
- [#755](https://github.com/nlog/nlog/pull/755) Fix unneeded breaking change with requirement of MailTarget.SmtpServer (@304NotModified)
- [#758](https://github.com/nlog/nlog/pull/758) Correct obsolete text (@kichristensen)
- [#754](https://github.com/nlog/nlog/pull/754) Optimized references (@304NotModified)
- [#753](https://github.com/nlog/nlog/pull/753) Fix autoflush (@304NotModified)
- [#744](https://github.com/nlog/nlog/pull/744) Alternate fix for #730 (@williamb1024)
- [#751](https://github.com/nlog/nlog/pull/751) Fix incorrect loglevel obsolete message (@SimonCropp)
- [#747](https://github.com/nlog/nlog/pull/747) Correct race condition in AsyncTargetWrapperExceptionTest (@williamb1024)
- [#746](https://github.com/nlog/nlog/pull/746) Fix for #736 (@akamyshanov)
- [#736](https://github.com/nlog/nlog/pull/736) fixes issue (#736) when the NLog assembly is loaded from memory (@akamyshanov)
- [#715](https://github.com/nlog/nlog/pull/715) Message queue target test check if queue exists (@304NotModified)
### 4.0.0 (2015/05/26)
- [#583](https://github.com/nlog/nlog/pull/583) .gitattributes specifies which files should be considered as text (@ilya-g)
### 4.0-RC (2015/05/26)
- [#717](https://github.com/nlog/nlog/pull/717) Improved description and warning. (@304NotModified)
- [#718](https://github.com/nlog/nlog/pull/718) GOTO considered harmful (@304NotModified)
- [#689](https://github.com/nlog/nlog/pull/689) Make alignment stay consistent when fixed-length truncation occurs.(AlignmentOnTruncation property) (@logiclrd)
- [#716](https://github.com/nlog/nlog/pull/716) Flush always explicit (@304NotModified)
- [#714](https://github.com/nlog/nlog/pull/714) added some docs for the ConditionalXXX methods (@304NotModified)
- [#712](https://github.com/nlog/nlog/pull/712) nuspec: added author + added NLog tag (@304NotModified)
- [#707](https://github.com/nlog/nlog/pull/707) Introduce auto flush behaviour again (@kichristensen)
- [#705](https://github.com/nlog/nlog/pull/705) EventLogTarget.Source layoutable & code improvements to EventLogTarget (@304NotModified)
- [#704](https://github.com/nlog/nlog/pull/704) Thread safe: GetCurrentClassLogger test + fix (@304NotModified)
- [#703](https://github.com/nlog/nlog/pull/703) Added 'lost messages' Webservice unittest (@304NotModified)
- [#692](https://github.com/nlog/nlog/pull/692) added Encoding property for consoleTarget + ColorConsoleTarget (@304NotModified)
- [#699](https://github.com/nlog/nlog/pull/699) Added Webservice tests with REST api. (@304NotModified)
- [#654](https://github.com/nlog/nlog/pull/654) Added unit test to validate the [DefaultValue] attribute values + update DefaultAttributes (@304NotModified)
- [#671](https://github.com/nlog/nlog/pull/671) Bugfix: Broken xml stops logging (@304NotModified)
- [#697](https://github.com/nlog/nlog/pull/697) V3.2.1 manual merge (@304NotModified, @kichristensen)
- [#698](https://github.com/nlog/nlog/pull/698) Fixed where log files couldn't use the same name as archive file (@BrandonLegault)
- [#691](https://github.com/nlog/nlog/pull/691) Right way to log exceptions (@304NotModified)
- [#670](https://github.com/nlog/nlog/pull/670) added unit test: string with variable get expanded (@304NotModified)
- [#547](https://github.com/nlog/nlog/pull/547) Fix use of single archive in file target (@kichristensen)
- [#674](https://github.com/nlog/nlog/pull/674) Add a Gitter chat badge to README.md (@gitter-badger)
- [#629](https://github.com/nlog/nlog/pull/629) BOM option/fix for WebserviceTarget + code improvements (@304NotModified)
- [#650](https://github.com/nlog/nlog/pull/650) fix default value of Commandtype (@304NotModified)
- [#651](https://github.com/nlog/nlog/pull/651) init `TimeStamp` and `SequenceID` in all ctors (@304NotModified)
- [#657](https://github.com/nlog/nlog/pull/657) Fixed quite a few typos (@sean-gilliam)
### v3.2.1 (2015/03/26)
- [#600](https://github.com/nlog/nlog/pull/600) Looks good (@kichristensen)
- [#645](https://github.com/nlog/nlog/pull/645) Stacktrace broken fix 321 (@304NotModified)
- [#606](https://github.com/nlog/nlog/pull/606) LineEndingMode type in xml configuration and xsd schema (@ilya-g)
- [#608](https://github.com/nlog/nlog/pull/608) Archiving system runs when new log file is created #390 (@awardle)
- [#584](https://github.com/nlog/nlog/pull/584) Stacktrace broken fix (@304NotModified, @ilya-g)
- [#601](https://github.com/nlog/nlog/pull/601) Mailtarget allow empty 'To' and various code improvements (@304NotModified)
- [#618](https://github.com/nlog/nlog/pull/618) Handle .tt in .csproj better (@304NotModified)
- [#619](https://github.com/nlog/nlog/pull/619) Improved badges (@304NotModified)
- [#616](https://github.com/nlog/nlog/pull/616) Added DEBUG-Conditional trace and debug methods #2 (@304NotModified)
- [#10](https://github.com/nlog/nlog/pull/10) Manual merge with master (@304NotModified, @kichristensen, @YuLad, @ilya-g, @MartinTherriault, @aelij)
- [#602](https://github.com/nlog/nlog/pull/602) Logger overloads generated by T4 (@304NotModified)
- [#613](https://github.com/nlog/nlog/pull/613) Treat warnings as errors (@304NotModified)
- [#9](https://github.com/nlog/nlog/pull/9) 304 not modified stacktrace broken fix (@304NotModified, @kichristensen, @YuLad, @ilya-g, @MartinTherriault, @aelij)
- [#610](https://github.com/nlog/nlog/pull/610) Fixed NLog/NLog#609 (@dodexahedron)
- [#8](https://github.com/nlog/nlog/pull/8) Refactoring + comments (@ilya-g)
- [#4](https://github.com/nlog/nlog/pull/4) HiddenAssemblies list is treated like immutable. (@ilya-g)
- [#6](https://github.com/nlog/nlog/pull/6) Sync back (@304NotModified, @kichristensen, @YuLad, @ilya-g, @MartinTherriault, @aelij)
- [#512](https://github.com/nlog/nlog/pull/512) FileTarget uses time from the current TimeSource for date-based archiving (@ilya-g)
- [#560](https://github.com/nlog/nlog/pull/560) Archive file zip compression (@aelij)
- [#576](https://github.com/nlog/nlog/pull/576) Instance property XmlLoggingConfiguration.DefaultCultureInfo should not change global state (@ilya-g)
- [#585](https://github.com/nlog/nlog/pull/585) improved Cyclomatic complexity of ConditionTokenizer (@304NotModified)
- [#598](https://github.com/nlog/nlog/pull/598) Added nullref checks for MailTarget.To (@304NotModified)
- [#582](https://github.com/nlog/nlog/pull/582) Fix NLog.proj build properties (@ilya-g)
- [#5](https://github.com/nlog/nlog/pull/5) Extend stack trace frame skip condition to types derived from the loggerType (@ilya-g)
- [#575](https://github.com/nlog/nlog/pull/575) Event Log Target unit tests improvement (@ilya-g)
- [#556](https://github.com/nlog/nlog/pull/556) Enable the counter sequence parameter to take layouts (@304NotModified)
- [#559](https://github.com/nlog/nlog/pull/559) Eventlog audit events (@304NotModified)
- [#565](https://github.com/nlog/nlog/pull/565) Set the service contract for LogReceiverTarget as one way (@MartinTherriault)
- [#563](https://github.com/nlog/nlog/pull/563) Added info sync projects + multiple .Net versions (@304NotModified)
- [#542](https://github.com/nlog/nlog/pull/542) Delete stuff moved to NLog.Web (@kichristensen)
- [#543](https://github.com/nlog/nlog/pull/543) Auto load extensions to allow easier integration with extensions (@kichristensen)
- [#555](https://github.com/nlog/nlog/pull/555) SMTP Closing connections fix (@304NotModified)
- [#3](https://github.com/nlog/nlog/pull/3) Sync back (@kichristensen, @304NotModified, @YuLad, @ilya-g)
- [#544](https://github.com/nlog/nlog/pull/544) Escape closing bracket in AppDomainLayoutRenderer test (@kichristensen)
- [#546](https://github.com/nlog/nlog/pull/546) Update nuget packages project url (@kichristensen)
- [#545](https://github.com/nlog/nlog/pull/545) Merge exception tests (@kichristensen)
- [#540](https://github.com/nlog/nlog/pull/540) Added CONTRIBUTING.md and schields (@304NotModified)
- [#2](https://github.com/nlog/nlog/pull/2) sync back (@kichristensen, @304NotModified, @YuLad, @ilya-g)
- [#535](https://github.com/nlog/nlog/pull/535) App domain layout renderer (@304NotModified)
- [#519](https://github.com/nlog/nlog/pull/519) Fluent API available for ILogger interface (@ilya-g)
- [#523](https://github.com/nlog/nlog/pull/523) Fix for issue #507: NLog optional or empty mail recipient (@YuLad)
- [#497](https://github.com/nlog/nlog/pull/497) Remove Windows Forms targets (@kichristensen)
- [#530](https://github.com/nlog/nlog/pull/530) Added Stacktrace layout renderer SkipFrames (@304NotModified)
- [#490](https://github.com/nlog/nlog/pull/490) AllEventProperties Layout Renderer (@vladikk)
- [#517](https://github.com/nlog/nlog/pull/517) Fluent API uses the same time source for timestamping as the Logger. (@ilya-g)
- [#503](https://github.com/nlog/nlog/pull/503) Add missing tags to Nuget packages (@kichristensen)
- [#496](https://github.com/nlog/nlog/pull/496) Fix monodevelop build (@dmitry-shechtman)
- [#489](https://github.com/nlog/nlog/pull/489) Add .editorconfig (@damageboy)
- [#491](https://github.com/nlog/nlog/pull/491) LogFactory Class Refactored (@ie-zero)
- [#422](https://github.com/nlog/nlog/pull/422) Run logging code outside of transaction (@Giorgi)
- [#474](https://github.com/nlog/nlog/pull/474) [Fix] ArchiveFileOnStartTest was failing (@ie-zero)
- [#479](https://github.com/nlog/nlog/pull/479) LogManager class refactored (@ie-zero)
- [#478](https://github.com/nlog/nlog/pull/478) Get[*]Logger() return Logger instead of ILogger (@ie-zero)
- [#481](https://github.com/nlog/nlog/pull/481) JsonLayout (@vladikk)
- [#473](https://github.com/nlog/nlog/pull/473) LineEndingMode Changed to Immutable Class (@ie-zero)
- [#469](https://github.com/nlog/nlog/pull/469) Corrects a copy-pasted code comment. (@JoshuaRogers)
- [#467](https://github.com/nlog/nlog/pull/467) LoggingRule.Final only suppresses matching levels. (@ilya-g)
- [#465](https://github.com/nlog/nlog/pull/465) Fix #283: throwExceptions ="false" but Is still an error (@YuLad)
- [#464](https://github.com/nlog/nlog/pull/464) Added 'enabled' attribute to the logging rule element. (@ilya-g)
### v3.2.0.0 (2014/12/21)
- [#463](https://github.com/nlog/nlog/pull/463) Pluggable time sources support in NLog.xsd generator utility (@ilya-g)
- [#460](https://github.com/nlog/nlog/pull/460) Add exception to NLogEvent (@kichristensen)
- [#457](https://github.com/nlog/nlog/pull/457) Unobsolete XXXExceptions methods (@kichristensen)
- [#449](https://github.com/nlog/nlog/pull/449) Added new archive numbering mode (@1and1-webhosting-infrastructure)
- [#450](https://github.com/nlog/nlog/pull/450) Added support for hidden/blacklisted assemblies (@1and1-webhosting-infrastructure)
- [#454](https://github.com/nlog/nlog/pull/454) DateRenderer now includes milliseconds (@ilivewithian)
- [#448](https://github.com/nlog/nlog/pull/448) Added unit test to identify work around when using colons within when layout renderers (@reedyrm)
- [#447](https://github.com/nlog/nlog/pull/447) Change GetCandidateFileNames() to also yield appname.exe.nlog when confi... (@jltrem)
- [#443](https://github.com/nlog/nlog/pull/443) Implement Flush in LogReceiverWebServiceTarget (@kichristensen)
- [#430](https://github.com/nlog/nlog/pull/430) Make ExceptionLayoutRenderer more extensible (@SurajGupta)
- [#442](https://github.com/nlog/nlog/pull/442) BUG FIX: Modification to LogEventInfo.Properties While Iterating (@tsconn23)
- [#439](https://github.com/nlog/nlog/pull/439) Fix for UDP broadcast (@dmitriyett)
- [#415](https://github.com/nlog/nlog/pull/415) Fixed issue (#414) with AutoFlush on FileTarget. (@richol)
- [#409](https://github.com/nlog/nlog/pull/409) Fix loss of exception info when reading Exception.Message property throw... (@wilbit)
- [#407](https://github.com/nlog/nlog/pull/407) Added some missing [StringFormatMethod]s (@roji)
- [#405](https://github.com/nlog/nlog/pull/405) Close channel (@kichristensen)
- [#404](https://github.com/nlog/nlog/pull/404) Correctly delete first line i RichTextBox (@kichristensen)
- [#402](https://github.com/nlog/nlog/pull/402) Add property to stop scanning properties (@kichristensen)
- [#401](https://github.com/nlog/nlog/pull/401) Pass correct parameters into ConfigurationReloaded (@kichristensen)
- [#397](https://github.com/nlog/nlog/pull/397) Improve test run time (@kichristensen)
- [#398](https://github.com/nlog/nlog/pull/398) Remove obsolete attribute from ErrorException (@kichristensen)
- [#395](https://github.com/nlog/nlog/pull/395) Speed up network target tests (@kichristensen)
- [#394](https://github.com/nlog/nlog/pull/394) Always return exit code 0 from test scripts (@kichristensen)
- [#393](https://github.com/nlog/nlog/pull/393) Avoid uneccassary reflection (@kichristensen)
- [#392](https://github.com/nlog/nlog/pull/392) Remove EnumerableHelpers (@kichristensen)
- [#369](https://github.com/nlog/nlog/pull/369) Add of archiveOldFileOnStartup parameter in FileTarget (@cvanbergen)
- [#377](https://github.com/nlog/nlog/pull/377) Apply small performance patch (@pgatilov)
- [#382](https://github.com/nlog/nlog/pull/382) contribute fluent log builder (@pwelter34)
### v3.1.0 (2014/06/23)
- [#371](https://github.com/nlog/nlog/pull/371) Use merging of event properties in async target wrapper to fix empty collection issue (@tuukkapuranen)
- [#357](https://github.com/nlog/nlog/pull/357) Extended ReplaceLayoutRendererWrapper and LayoutParser to support more advanced Regex replacements and more escape codes (@DannyVarod)
- [#359](https://github.com/nlog/nlog/pull/359) Fix #71 : Removing invalid filename characters from created file (@cvanbergen)
- [#366](https://github.com/nlog/nlog/pull/366) Fix for #365: Behaviour when logging null arguments (@cvanbergen)
- [#372](https://github.com/nlog/nlog/pull/372) Fix #370: EventLogTarget source and log name case insensitive comparison (@cvanbergen)
- [#358](https://github.com/nlog/nlog/pull/358) Made EndpointAddress virtual (@MikeChristensen)
- [#353](https://github.com/nlog/nlog/pull/353) Configuration to disable expensive flushing in NLogTraceListener (@robertvazan)
- [#351](https://github.com/nlog/nlog/pull/351) Obsolete added to LogException() method in Logger class. (@ie-zero)
- [#352](https://github.com/nlog/nlog/pull/352) Remove public constructors from LogLevel (@ie-zero)
- [#349](https://github.com/nlog/nlog/pull/349) Changed all ReSharper annotations to internal (issue 292) (@MichaelLogutov)
### v3.0 (2014/06/02)
- [#346](https://github.com/nlog/nlog/pull/346) Fix: #333 Delete archived files in correct order (@cvanbergen)
- [#347](https://github.com/nlog/nlog/pull/347) Fixed #281: Don't create empty batches when event list is empty (@robertvazan)
- [#246](https://github.com/nlog/nlog/pull/246) Additional Layout Renderer "Assembly-Name" (@Slowpython)
- [#344](https://github.com/nlog/nlog/pull/344) Replacement for [LogLevel]Exception methods (@ie-zero)
- [#337](https://github.com/nlog/nlog/pull/337) Fixes an exception that occurs on startup in apps using NLog. AFAIK shou... (@activescott)
- [#338](https://github.com/nlog/nlog/pull/338) Fix: File target doesn't duplicate header in archived files #245 (@cvanbergen)
- [#341](https://github.com/nlog/nlog/pull/341) SpecialFolderLayoutRenderer honor file and dir (@arjoe)
- [#345](https://github.com/nlog/nlog/pull/345) Default value added in EnviromentLayoutRender (@ie-zero)
- [#335](https://github.com/nlog/nlog/pull/335) Fix/callsite incorrect (@JvanderStad)
- [#334](https://github.com/nlog/nlog/pull/334) Fixes empty "properties" collection. (@erwinwolff)
- [#336](https://github.com/nlog/nlog/pull/336) Fix for invalid XML characters in Log4JXmlEventLayoutRenderer (@JvanderStad)
- [#329](https://github.com/nlog/nlog/pull/329) ExceptionLayoutRenderer extension (@tjandras)
- [#323](https://github.com/nlog/nlog/pull/323) Update DatabaseTarget.cs (@GunsAkimbo)
- [#315](https://github.com/nlog/nlog/pull/315) Dispose of dequeued SocketAsyncEventArgs (@gcschorer)
- [#300](https://github.com/nlog/nlog/pull/300) Avoid NullReferenceException when environment variable not set. (@bkryl)
- [#305](https://github.com/nlog/nlog/pull/305) Redirects Logger.Log(a, b, ex) to Logger.LogException(a, b, ex) (@arangas)
- [#321](https://github.com/nlog/nlog/pull/321) Avoid NullArgumentException when running in a Unity3D application (@mattyway)
- [#285](https://github.com/nlog/nlog/pull/285) Changed modifier of ProcessLogEventInfo (@cincuranet)
- [#270](https://github.com/nlog/nlog/pull/270) Integrate JetBrains Annotations (@damageboy)
### 2.1.0 (2013/10/07)
- [#257](https://github.com/nlog/nlog/pull/257) Fixed SL5 compilation error (@emazv72)
- [#241](https://github.com/nlog/nlog/pull/241) Date Based File Archiving (@mkaltner)
- [#239](https://github.com/nlog/nlog/pull/239) Add layout renderer for retrieving values from AppSettings. (@mpareja)
- [#227](https://github.com/nlog/nlog/pull/227) Pluggable time sources (@robertvazan)
- [#226](https://github.com/nlog/nlog/pull/226) Shared Mutex Improvement (@cjberg)
- [#216](https://github.com/nlog/nlog/pull/216) Optional ConditionMethod arguments, ignoreCase argument for standard condition methods, EventLogTarget enhancements (@tg73)
- [#219](https://github.com/nlog/nlog/pull/219) Avoid Win32-specific file functions in Mono where parts not implemented. (@KeithLRobertson)
- [#215](https://github.com/nlog/nlog/pull/215) Revert "Fix writing NLog properties in Log4JXmlEvent" (@kichristensen)
- [#206](https://github.com/nlog/nlog/pull/206) Correctly use comments in NLog.Config package (@kichristensen)
### v2.0.1 (2013/04/08)
- [#197](https://github.com/nlog/nlog/pull/197) Better request queue logging (@kichristensen)
- [#192](https://github.com/nlog/nlog/pull/192) Allow Form Control Target to specify append direction (@simongh)
- [#182](https://github.com/nlog/nlog/pull/182) Fix locks around layoutCache (@brutaldev)
- [#178](https://github.com/nlog/nlog/pull/178) Anonymous delegate class and method name cleanup (@aalex675)
- [#168](https://github.com/nlog/nlog/pull/168) Deadlock in NLog library using Control-Target (WinForms) (@falstaff84)
- [#176](https://github.com/nlog/nlog/pull/176) Fix for #175 NLogTraceListener not using LogFactory (@HakanL)
- [#163](https://github.com/nlog/nlog/pull/163) #110 Exceptions swallowed in custom target (@johnrey1)
- [#12](https://github.com/nlog/nlog/pull/12) AppDomain testability (@kichristensen)
- [#11](https://github.com/nlog/nlog/pull/11) Updated code to not log exception double times (@ParthDesai)
- [#10](https://github.com/nlog/nlog/pull/10) Improved Fix Code for issue 6575 (@ParthDesai)
- [#7](https://github.com/nlog/nlog/pull/7) Fixed Issue in Code For Invalid XML (@ParthDesai)
- [#6](https://github.com/nlog/nlog/pull/6) Fix For Issue #7031 (@ParthDesai)
- [#5](https://github.com/nlog/nlog/pull/5) Codeplex BUG 6227 - LogManager.Flush throws... (@kichristensen)
- [#4](https://github.com/nlog/nlog/pull/4) Adding a test for pull request #1 which fixes bug 6370 from Codeplex (@sebfischer83)
- [#3](https://github.com/nlog/nlog/pull/3) TraceTarget no longer blocks on error messages. Fixes Codeplex bug 2599 (@kichristensen)
- [#1](https://github.com/nlog/nlog/pull/1) Codeplex Bug 6370 (@sebfischer83)
### NLog-1.0-RC1 (2006/07/10)
- [#27](https://github.com/nlog/nlog/pull/27) added Debugger target (#27), fixed Database ${callsite} (#26) (@jkowalski)
- [#27](https://github.com/nlog/nlog/pull/27) added Debugger target (#27), fixed Database ${callsite} (#26) (@jkowalski)
| NLog/NLog | CHANGELOG.md | Markdown | bsd-3-clause | 151,293 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WindowsUI.WebMonitor.Model;
namespace WindowsUI.WebMonitor.WinUI
{
public partial class WebStatusBox : UserControl
{
private Image Red = global::WindowsUI.WebMonitor.Properties.Resources.webstatus_r;
private Image Yellow = global::WindowsUI.WebMonitor.Properties.Resources.webstatus_y;
private Image Green = global::WindowsUI.WebMonitor.Properties.Resources.webstatus_g;
private Image OutLine = global::WindowsUI.WebMonitor.Properties.Resources.webstatus_o;
/// <summary>
/// 设备对象
/// </summary>
private MonitorBox minfo;
public MonitorBox Info
{
get
{
return minfo;
}
set
{
this.minfo = value;
ShowInfo();
}
}
public WebStatusBox()
{
InitializeComponent();
}
private void ShowInfo()
{
if (Info != null)
{
this.lblNo.Text = Info.Number.ToString();
this.lblName.Text = Info.Name;
this.lblTimes.Text = Info.DelayTimes.ToString()+"ms";
this.lblIP.Text = Info.IP;
if (Info.DelayTimes < 0)
{
this.ptbStatus.Image = OutLine;
//如果离线,将控件的字颜色改成红色
for (int index = 0; index < this.Controls.Count;index++ )
{
this.Controls[index].ForeColor = Color.Red;
}
}
else
{
if(this.Controls[0].ForeColor == Color.Red)
{
for (int index = 0; index < this.Controls.Count;index++ )
{
this.Controls[index].ForeColor = Color.Black;
}
}
if (Info.DelayTimes >= 0 && Info.DelayTimes <= 250)
{
this.ptbStatus.Image = Green;
}
else if (Info.DelayTimes > 250 && Info.DelayTimes <= 500)
{
this.ptbStatus.Image = Yellow;
}
else if (Info.DelayTimes > 500)
{
this.ptbStatus.Image = Red;
}
}
}
}
public string FormatName(string name)
{
string returnStr = "";
if (name.Length > 6)
{
for (int index = 0; index < name.Length; index = index + 6)
{
int strLeng = 6;
if (name.Length - index < 6)
{
strLeng = name.Length - index;
}
returnStr += name.Substring(index, strLeng);
returnStr += "\r\n";
}
}
else
{
returnStr = name;
}
return returnStr;
}
}
}
| Klutzdon/SIOTS_HHZX | WindowsUI.WebMonitor/WinUI/WebStatusBox.cs | C# | bsd-3-clause | 3,392 |
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkCreateSurfaceTool.h"
#include "mitkCreateSurfaceTool.xpm"
#include "mitkProgressBar.h"
#include "mitkShowSegmentationAsSurface.h"
#include "mitkStatusBar.h"
#include "mitkToolManager.h"
#include "itkCommand.h"
namespace mitk
{
MITK_TOOL_MACRO(MITKSEGMENTATION_EXPORT, CreateSurfaceTool, "Surface creation tool");
}
mitk::CreateSurfaceTool::CreateSurfaceTool()
{
}
mitk::CreateSurfaceTool::~CreateSurfaceTool()
{
}
const char **mitk::CreateSurfaceTool::GetXPM() const
{
return mitkCreateSurfaceTool_xpm;
}
const char *mitk::CreateSurfaceTool::GetName() const
{
return "Surface";
}
std::string mitk::CreateSurfaceTool::GetErrorMessage()
{
return "No surfaces created for these segmentations:";
}
bool mitk::CreateSurfaceTool::ProcessOneWorkingData(DataNode *node)
{
if (node)
{
Image::Pointer image = dynamic_cast<Image *>(node->GetData());
if (image.IsNull())
return false;
try
{
mitk::ShowSegmentationAsSurface::Pointer surfaceFilter = mitk::ShowSegmentationAsSurface::New();
// attach observer to get notified about result
itk::SimpleMemberCommand<CreateSurfaceTool>::Pointer goodCommand =
itk::SimpleMemberCommand<CreateSurfaceTool>::New();
goodCommand->SetCallbackFunction(this, &CreateSurfaceTool::OnSurfaceCalculationDone);
surfaceFilter->AddObserver(mitk::ResultAvailable(), goodCommand);
itk::SimpleMemberCommand<CreateSurfaceTool>::Pointer badCommand =
itk::SimpleMemberCommand<CreateSurfaceTool>::New();
badCommand->SetCallbackFunction(this, &CreateSurfaceTool::OnSurfaceCalculationDone);
surfaceFilter->AddObserver(mitk::ProcessingError(), badCommand);
DataNode::Pointer nodepointer = node;
surfaceFilter->SetPointerParameter("Input", image);
surfaceFilter->SetPointerParameter("Group node", nodepointer);
surfaceFilter->SetParameter("Show result", true);
surfaceFilter->SetParameter("Sync visibility", false);
surfaceFilter->SetDataStorage(*m_ToolManager->GetDataStorage());
ProgressBar::GetInstance()->AddStepsToDo(1);
StatusBar::GetInstance()->DisplayText("Surface creation started in background...");
surfaceFilter->StartAlgorithm();
}
catch (...)
{
return false;
}
}
return true;
}
void mitk::CreateSurfaceTool::OnSurfaceCalculationDone()
{
ProgressBar::GetInstance()->Progress();
m_ToolManager->NewNodesGenerated();
}
| fmilano/mitk | Modules/Segmentation/Interactions/mitkCreateSurfaceTool.cpp | C++ | bsd-3-clause | 2,829 |
-- create class and using GREATEST function with string,attribute,time,null,and number
create CLASS t (b string );
insert INTO t values ('22');
SELECT GREATEST('str1', 'str2', 'str3') FROM t;
SELECT GREATEST(b) FROM t;
SELECT GREATEST(null,b) FROM t;
SELECT GREATEST(null,123) FROM t;
SELECT GREATEST(234,123) FROM t;
SELECT GREATEST('01/01/2000',to_date('1000-10-10','yyyy-MM-dd')) FROM t;
SELECT GREATEST(cast (20.00 as float) , cast (15.00 as numeric(4,2))) FROM t;
DROP t;
| CUBRID/cubrid-testcases | sql/_04_operator_function/_07_case_func/_003_gratest/cases/1001.sql | SQL | bsd-3-clause | 482 |
from django.conf import settings
from site_news.models import SiteNewsItem
def site_news(request):
"""
Inserts the currently active news items into the template context.
This ignores MAX_SITE_NEWS_ITEMS.
"""
# Grab all active items in proper date/time range.
items = SiteNewsItem.current_and_active.all()
return {'site_news_items': items}
| glesica/django-site-news | site_news/context_processors.py | Python | bsd-3-clause | 379 |
/*
* OpenWFEru densha - open source ruby workflow and bpm engine
* (c) 2007-2008 John Mettraux
*
* OpenWFEru densha is freely distributable under the terms
* of a BSD-style license.
* For details, see the OpenWFEru web site: http://openwferu.rubyforge.org
*
* Made in Japan
*/
function toggleWadminAddButton (form_id, button_id) {
var form = $(form_id);
var button = $(button_id);
form.toggle();
if (form.visible())
button.hide();
else
button.show();
}
| jmettraux/ruote-web | public/javascripts/densha-worklist.js | JavaScript | bsd-3-clause | 514 |
package com.mastercard.api.mdes.csrapi.v1.reasoncodes.services;
import com.mastercard.api.common.Environment;
import junit.framework.TestCase;
import utils.TestUtils;
public class ReasonCodesServiceTest extends TestCase {
ReasonCodesService service;
TestUtils testUtils = new TestUtils(Environment.SANDBOX);
public void setUp(){
service = new ReasonCodesService(
Environment.SANDBOX,
testUtils.getConsumerKey(),
testUtils.getPrivateKey()
);
}
public void testReasonCodesService(){
assert(testUtils.validateXML(service.getResponse(), "reasonCodes.xsd"));
}
}
| thgriefers/mastercard-api-java | src/test/java/com/mastercard/api/mdes/csrapi/v1/reasoncodes/services/ReasonCodesServiceTest.java | Java | bsd-3-clause | 660 |
# -*- coding: utf-8 -*-
import logging
import re
import importlib
import django
import six
from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.module_loading import import_string
from django.utils.html import conditional_escape
from django.conf import settings
from django.db import models
from django.db.models import Q
from django.urls import (URLResolver as RegexURLResolver, URLPattern as RegexURLPattern, Resolver404, get_resolver,
clear_url_caches)
logger = logging.getLogger(__name__)
class NotSet(object):
""" A singleton to identify unset values (where None would have meaning) """
def __str__(self):
return "NotSet"
def __repr__(self):
return self.__str__()
NotSet = NotSet()
class Literal(object):
""" Wrap literal values so that the system knows to treat them that way """
def __init__(self, value):
self.value = value
def _pattern_resolve_to_name(pattern, path):
if django.VERSION < (2, 0):
match = pattern.regex.search(path)
else:
match = pattern.pattern.regex.search(path)
if match:
name = ""
if pattern.name:
name = pattern.name
elif hasattr(pattern, '_callback_str'):
name = pattern._callback_str
else:
name = "%s.%s" % (pattern.callback.__module__, pattern.callback.func_name)
return name
def _resolver_resolve_to_name(resolver, path):
tried = []
django1 = django.VERSION < (2, 0)
if django1:
match = resolver.regex.search(path)
else:
match = resolver.pattern.regex.search(path)
if match:
new_path = path[match.end():]
for pattern in resolver.url_patterns:
try:
if isinstance(pattern, RegexURLPattern):
name = _pattern_resolve_to_name(pattern, new_path)
elif isinstance(pattern, RegexURLResolver):
name = _resolver_resolve_to_name(pattern, new_path)
except Resolver404 as e:
if django1:
tried.extend([(pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']])
else:
tried.extend([(pattern.pattern.regex.pattern + ' ' + t) for t in e.args[0]['tried']])
else:
if name:
return name
if django1:
tried.append(pattern.regex.pattern)
else:
tried.append(pattern.pattern.regex.pattern)
raise Resolver404({'tried': tried, 'path': new_path})
def resolve_to_name(path, urlconf=None):
try:
return _resolver_resolve_to_name(get_resolver(urlconf), path)
except Resolver404:
return None
def _replace_quot(match):
unescape = lambda v: v.replace('"', '"').replace('&', '&')
return u'<%s%s>' % (unescape(match.group(1)), unescape(match.group(3)))
def escape_tags(value, valid_tags):
""" Strips text from the given html string, leaving only tags.
This functionality requires BeautifulSoup, nothing will be
done otherwise.
This isn't perfect. Someone could put javascript in here:
<a onClick="alert('hi');">test</a>
So if you use valid_tags, you still need to trust your data entry.
Or we could try:
- only escape the non matching bits
- use BeautifulSoup to understand the elements, escape everything
else and remove potentially harmful attributes (onClick).
- Remove this feature entirely. Half-escaping things securely is
very difficult, developers should not be lured into a false
sense of security.
"""
# 1. escape everything
value = conditional_escape(value)
# 2. Reenable certain tags
if valid_tags:
# TODO: precompile somewhere once?
tag_re = re.compile(r'<(\s*/?\s*(%s))(.*?\s*)>' %
u'|'.join(re.escape(tag) for tag in valid_tags))
value = tag_re.sub(_replace_quot, value)
# Allow comments to be hidden
value = value.replace("<!--", "<!--").replace("-->", "-->")
return mark_safe(value)
def _get_seo_content_types(seo_models):
""" Returns a list of content types from the models defined in settings
(SEO_MODELS)
"""
from django.contrib.contenttypes.models import ContentType
try:
return [ContentType.objects.get_for_model(m).id for m in seo_models]
except: # previously caught DatabaseError
# Return an empty list if this is called too early
return []
def get_seo_content_types(seo_models):
return lazy(_get_seo_content_types, list)(seo_models)
def _reload_urlconf():
"""
Reload Django URL configuration and clean caches
"""
module = importlib.import_module(settings.ROOT_URLCONF)
if six.PY2:
reload(module)
else:
importlib.reload(module)
clear_url_caches()
def register_model_in_admin(model, admin_class=None):
"""
Register model in Django admin interface
"""
from django.contrib import admin
admin.site.register(model, admin_class)
_reload_urlconf()
def create_dynamic_model(model_name, app_label='djangoseo', **attrs):
"""
Create dynamic Django model
"""
module_name = '%s.models' % app_label
default_attrs = {
'__module__': module_name,
'__dynamic__': True
}
attrs.update(default_attrs)
if six.PY2:
model_name = str(model_name)
return type(model_name, (models.Model,), attrs)
def import_tracked_models():
"""
Import models
"""
redirects_models = getattr(settings, 'SEO_TRACKED_MODELS', [])
models = []
for model_path in redirects_models:
try:
model = import_string(model_path)
models.append(model)
except ImportError as e:
logging.warning("Failed to import model from path '%s'" % model_path)
return models
def handle_seo_redirects(request):
"""
Handle SEO redirects. Create Redirect instance if exists redirect pattern.
:param request: Django request
"""
from .models import RedirectPattern, Redirect
if not getattr(settings, 'SEO_USE_REDIRECTS', False):
return
full_path = request.get_full_path()
current_site = get_current_site(request)
subdomain = getattr(request, 'subdomain', '')
redirect_patterns = RedirectPattern.objects.filter(
Q(site=current_site),
Q(subdomain=subdomain) | Q(all_subdomains=True)
).order_by('all_subdomains')
for redirect_pattern in redirect_patterns:
if re.match(redirect_pattern.url_pattern, full_path):
kwargs = {
'site': current_site,
'old_path': full_path,
'new_path': redirect_pattern.redirect_path,
'subdomain': redirect_pattern.subdomain,
'all_subdomains': redirect_pattern.all_subdomains
}
try:
Redirect.objects.get_or_create(**kwargs)
except Exception:
logger.warning('Failed to create redirection', exc_info=True, extra=kwargs)
break
| whyflyru/django-seo | djangoseo/utils.py | Python | bsd-3-clause | 7,375 |
/**
*============================================================================
* The Ohio State University Research Foundation, Emory University,
* the University of Minnesota Supercomputing Institute
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-grid-incubation/LICENSE.txt for details.
*============================================================================
**/
/**
*============================================================================
*============================================================================
**/
package org.cagrid.datatype.sdkmapping4.encoding;
import javax.xml.namespace.QName;
import org.apache.axis.encoding.ser.BaseDeserializerFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SDK40DeserializerFactory extends BaseDeserializerFactory {
protected static Log LOG = LogFactory.getLog(SDK40DeserializerFactory.class.getName());
public SDK40DeserializerFactory(Class javaType, QName xmlType) {
super(SDK40Deserializer.class, xmlType, javaType);
LOG.debug("Initializing " + SDK40Deserializer.class.getSimpleName() + " for class:" + javaType + " and QName:" + xmlType);
}
}
| NCIP/cagrid-grid-incubation | grid-incubation/incubator/projects/IntroduceMappingExtension/projects/mappingExtensions/src/java/org/cagrid/datatype/sdkmapping4/encoding/SDK40DeserializerFactory.java | Java | bsd-3-clause | 1,239 |
package cz.vsb.resbill.dto.contract;
import java.io.Serializable;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import cz.vsb.resbill.model.Contract;
public class ContractEditDTO implements Serializable {
private static final long serialVersionUID = 2585516902814048464L;
@Valid
@NotNull
private Contract contract;
@NotNull
private Integer customerId;
private boolean customerEditable;
public ContractEditDTO(Contract contract) {
this.contract = contract;
if (contract != null) {
this.customerId = contract.getCustomer() != null ? contract.getCustomer().getId() : null;
this.customerEditable = contract.getId() == null;
}
}
public Contract getContract() {
return contract;
}
public void setContract(Contract contract) {
this.contract = contract;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public boolean isCustomerEditable() {
return customerEditable;
}
public void setCustomerEditable(boolean customerEditable) {
this.customerEditable = customerEditable;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ContractEditDTO [");
builder.append(super.toString());
builder.append(", contract=");
builder.append(contract);
builder.append(", customerId=");
builder.append(customerId);
builder.append(", customerEditable=");
builder.append(customerEditable);
builder.append("]");
return builder.toString();
}
}
| CIT-VSB-TUO/ResBill | resbill/src/main/java/cz/vsb/resbill/dto/contract/ContractEditDTO.java | Java | bsd-3-clause | 1,634 |
using System;
using System.Collections;
using System.Collections.Generic;
namespace FourGuns
{
/// <summary>
/// Linked list of objects
/// </summary>
/// <typeparam name="T">Type of object stored in list</typeparam>
/// <author>Colden Cullen</author>
/// <contributor>Sean Brennan</contributor>
public class List<T> : IEnumerable<T>, IEnumerable
{
#region Fields, Properties
/// <summary>
/// First item in list</summary>
internal Node<T> head;
/// <summary>
/// Last item in list</summary>
internal Node<T> tail;
/// <summary>
/// Number of items in list</summary>
internal int count;
/// <summary>
/// Number of Nodes in list</summary>
public int Count { get { return count; } }
#endregion
#region Indexer
/// <summary>
/// Indexer for List</summary>
/// <param name="index">
/// Index of List item to get or set</param>
/// <returns>
/// get: Data at index set: nothing</returns>
public T this[ int index ]
{
get
{
Node<T> temp = head;
try
{
for( int ii = 0; ii < index; ii++ )
{
temp = temp.Next;
}
// Return value at index
return temp.Value;
}
catch( Exception )
{
// If at any point, temp == null, return default
return default( T );
}
}
set
{
Node<T> temp = head;
try
{
for( int ii = 0; ii < index; ii++ )
{
temp = temp.Next;
}
}
catch( Exception )
{
throw new IndexOutOfRangeException( "index is not in List" );
}
if( head == null )
{
Add( value );
}
else
{
temp.Value = value;
}
}
}
#endregion
#region Enumerator
/// <summary>
/// Enumerator for for loops</summary>
/// <returns></returns>
public IEnumerator<T> GetEnumerator()
{
Node<T> temp = head;
for( int ii = 0; ii < count; ii++ )
{
yield return temp.Value;
temp = temp.Next;
}
}
/// <summary>
/// Enumerator for for loops</summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}
#endregion
#region Constructor
/// <summary>
/// Default Constructor, sets default values</summary>
public List()
{
count = 0;
head = null;
tail = null;
}
#endregion
#region Add
/// <summary>
/// Adds item to end of list</summary>
/// <param name="value">
/// Data to addX to list</param>
public virtual void Add( T data )
{
Node<T> toBeAdded = new Node<T>( data ); // Node to be put into array
if( head == null )
{
//Console.WriteLine( "First Add" );
head = toBeAdded;
tail = head;
}
else if( head.Next == null )
{
head.Next = toBeAdded;
tail = head.Next;
}
else
{
//Console.WriteLine( "Not First Add" );
tail.Next = toBeAdded;
tail = tail.Next;
}
count++;
}
/// <summary>
/// Adds Item to front of List</summary>
/// <param name="value">
/// Item to addX to front of List</param>
public virtual void AddFront( T data )
{
Node<T> toBeAdded = new Node<T>( data, head );
Node<T> temp = head;
head = toBeAdded;
count++;
}
/// <summary>
/// Inserts an item at the specified 0-based index
/// </summary>
/// <contributor>Zachary Behrmann</contributor>
/// <param name="index">The index you wish to insert it at</param>
/// <param name="value">The item to insert</param>
public void AddAt( T data, int index )
{
Node<T> current = head;
if( index == 0 )
{
head = new Node<T>( data, current );
for( int i = 0; i < count; i++ )
{
if( current.Next != null )
{
current = current.Next;
}
}
count++;
}
else if( index == count )
{
tail.Next = new Node<T>( data );
count++;
}
else if( index > count || index < 0 )
{
throw new Exception( "index is outside the bounds of the list" );
}
else
{
for( int i = 0; i < index; i++ )
{
current = current.Next;
}
Node<T> temp = current.Next;
current.Next = new Node<T>( data, temp );
count++;
}
}
/// <summary>
/// Add all elements from given list to this list
/// </summary>
/// <param name="listToAdd">List to pull data from</param>
public void AddRange( List<T> listToAdd )
{
AddRange( listToAdd, 0, listToAdd.Count );
}
public void AddRange(IEnumerable listToAdd)
{
foreach (T toAdd in listToAdd)
this.Add(toAdd);
}
/// <summary>
/// Add elements from given list to this list
/// </summary>
/// <param name="listToAdd">List to pull data from</param>
/// <param name="startIndex">Index in list to start at</param>
/// <param name="endIndex">Index in list to end at</param>
public void AddRange( List<T> listToAdd, int startIndex, int endIndex )
{
for( int ii = startIndex; ii < endIndex; ii++ )
this.Add( listToAdd[ ii ] );
}
#endregion
#region Remove
/// <summary>
/// <author>Eric Christenson</author>
/// <contributer>Daniel Jost (made compatible with the rest of the List class)</contributer>
/// remove first node with value
/// </summary>
/// <param name="value">object of type T to addX</param>
public virtual void Remove( T data )
{
Node<T> current = head;
Node<T> prev = current;
while( current != null )// && current.Next != null)
{
// The following 2 lines are what I changed to make it work
// EqualityComparer uses the default .Equals of object, comparing the hash code
// of the two objects which will be unique for each instance of an object
if( EqualityComparer<T>.Default.Equals( data, current.Value ) )
//if (current.Data.Equals(value))
{
if( current == head ) // if current is head, it has no previous, need to do something different
{
if( head == tail )
{
tail = null;
}
head = head.Next;
}
else if( current == tail )
{
tail = prev;
prev.Next = null;
}
else
{
prev.Next = current.Next;
}
count--;
break;
}
else
{
prev = current;
current = current.Next;
}
}
}
/// <summary>
/// Removes value at given index</summary>
/// <param name="index">
/// Index to remove from</param>
/// <returns>
/// Successfulness of removal</returns>
public virtual bool RemoveAt( int index )
{
// If index given is higher than count, return false
if( index >= count )
return false;
// Get node previous to one before to be removed
Node<T> remPrev = head;
Node<T> rem = head;
for( int ii = 0; ii < index - 1; ii++ )
{
remPrev = remPrev.Next;
rem = rem.Next;
}
// Make rem go one further than remPrev
if( index != 0 )
rem = rem.Next;
// Remove node
if( rem == head )
{
if( head == tail )
{
head = tail = null;
count--;
return true;
}
head = head.Next;
}
else if( rem == tail )
{
tail = remPrev;
}
else
{
remPrev.Next = remPrev.Next.Next;
}
count--;
// Return true
return true;
}
#endregion
#region Other Methods
/// <summary>
/// Checks to see if element is contained
/// </summary>
/// <param name="data">Data to search for</param>
/// <returns>Whether or not data is contained</returns>
public bool Contains( T data )
{
return IndexOf( data ) != -1;
}
/// <summary>
/// Finds the index of a given data
/// </summary>
/// <param name="target">Data to find</param>
/// <returns>Index of data</returns>
/// <contributor>Sean Brennan</contributor>
public int IndexOf( T target )
{
Node<T> current = head;
for( int ii = 0; ii < count; ii++ )
{
if( current.Value.Equals( target ) )
return ii;
else
current = current.Next;
}
// Return -1 if not found
return -1;
}
/// <summary>
/// Remove everything from list
/// </summary>
public void Clear()
{
Node<T> previous = head; // Last node checked
Node<T> current = head; // Current node being checked
if( current != null )
{
current = null;
tail = null;
}
else if( current != null && current.Next != null )
{
while( current.Next != null )
{
current = current.Next;
previous = null;
previous = current;
}
}
head = null;
count = 0;
}
/// <summary>
/// Returns whether or not the list is empty</summary>
/// <returns>
/// Emptyness of list</returns>
public Boolean IsEmpty()
{
return head == null;
}
/// <summary>
/// Converts the list to an array of type T. @Jim Arnold
/// </summary>
/// <returns>The new array</returns>
public T[] ToArray()
{
if (IsEmpty())
return null;
T[] temp = new T[this.count];
for (int i = 0; i < this.count; i++)
{
temp[i] = this[i];
}
return temp;
}
/// <summary>
/// Returns all items in List</summary>
/// <returns>
/// A string of all items</returns>
public override string ToString()
{
if( head != null )
{
string returnString = this[ 0 ].ToString();
for( int ii = 1; ii < this.Count; ii++ )
returnString += "\n" + this[ ii ].ToString();
return returnString;
}
else return "";
}
#endregion
}
}
#region oldcode
//using System;
//using System.Collections;
//using System.Collections.Generic;
//namespace FourGuns
//{
// /// <summary>
// /// Linked list of objects
// /// </summary>
// /// <typeparam name="T">Type of object stored in list</typeparam>
// /// <author>Colden Cullen</author>
// public class List<T> : IEnumerable<T>
// {
// #region Fields, Properties
// /// <summary>
// /// First item in list</summary>
// internal Node<T> head;
// /// <summary>
// /// Last item in list</summary>
// internal Node<T> tail;
// /// <summary>
// /// Number of items in list</summary>
// internal int count;
// /// <summary>
// /// Number of Nodes in list</summary>
// public int Count { get { return count; } }
// #endregion
// #region Indexer, Enumerator
// /// <summary>
// /// Indexer for List</summary>
// /// <param name="index">
// /// Index of List item to get or set</param>
// /// <returns>
// /// get: Data at index set: nothing</returns>
// public T this[ int index ]
// {
// get
// {
// Node<T> temp = head;
// try
// {
// for( int ii = 0; ii < index; ii++ )
// {
// temp = temp.Next;
// }
// // Return value at index
// return temp.Value;
// }
// catch( Exception )
// {
// // If at any point, temp == null, return default
// return default( T );
// }
// }
// set
// {
// Node<T> temp = head;
// try
// {
// for( int ii = 0; ii < index; ii++ )
// {
// temp = temp.Next;
// }
// }
// catch( Exception )
// {
// throw new IndexOutOfRangeException( "index is not in List" );
// }
// if( head == null )
// {
// Add( value );
// }
// else
// {
// temp.Value = value;
// }
// }
// }
// /// <summary>
// /// Gets the index of the element in the list to check
// /// </summary>
// /// <param name="itemToCheck">The item to check where it is in the list</param>
// /// <returns>The index of the item to check</returns>
// /// <author>Sean Brennan</author>
// public int IndexOf(T itemToCheck)
// {
// Node<T> current = head;
// for (int i = 0; i < Count; i++)
// {
// if (current.Value.Equals(itemToCheck))
// return i;
// else
// current = current.Next;
// }
// return -1;
// /*for (int i = 0; i < Count; i++)
// {
// if (itemToCheck.Equals(this[i]))
// {
// // If this is the item to be checked for, return its index
// return i;
// }
// }
// // If the item was not found in the list, return a number greater than the size of the list
// return Count + 1;*/
// }
// /// <summary>
// /// Enumerator for for loops</summary>
// /// <returns></returns>
// /// <author>Sean Brennan</author>
// public IEnumerator<T> GetEnumerator()
// {
// Node<T> temp = head;
// for( int ii = 0; ii < count; ii++ )
// {
// yield return temp.Value;
// temp = temp.Next;
// }
// }
// /// <summary>
// /// Implements the IEnumerable class
// /// </summary>
// /// <returns></returns>
// /// <author>Sean Brennan</author>
// IEnumerator IEnumerable.GetEnumerator()
// {
// return GetEnumerator();
// }
// #endregion
// #region Constructor
// /// <summary>
// /// Default Constructor, sets default values</summary>
// public List()
// {
// count = 0;
// head = null;
// tail = null;
// }
// #endregion
// #region Add
// /// <summary>
// /// Adds item to end of list</summary>
// /// <param name="value">
// /// Data to addX to list</param>
// public virtual void Add( T data )
// {
// Node<T> toBeAdded = new Node<T>( data ); // Node to be put into array
// if( head == null )
// {
// //Console.WriteLine( "First Add" );
// head = toBeAdded;
// tail = head;
// }
// else if( head.Next == null )
// {
// head.Next = toBeAdded;
// tail = head.Next;
// }
// else
// {
// //Console.WriteLine( "Not First Add" );
// tail.Next = toBeAdded;
// tail = tail.Next;
// }
// count++;
// }
// /// <summary>
// /// Adds Item to front of List</summary>
// /// <param name="value">
// /// Item to addX to front of List</param>
// public virtual void AddFront( T data )
// {
// Node<T> toBeAdded = new Node<T>( data, head );
// Node<T> temp = head;
// head = toBeAdded;
// count++;
// }
// /// <summary>
// /// Inserts an item at the specified 0-based index
// /// </summary>
// /// <contributor>Zachary Behrmann</contributor>
// /// <param name="index">The index you wish to insert it at</param>
// /// <param name="value">The item to insert</param>
// public void AddAt( T data, int index )
// {
// Node<T> current = head;
// if( index == 0 )
// {
// head = new Node<T>( data, current );
// for( int i = 0; i < count; i++ )
// {
// if( current.Next != null )
// {
// current = current.Next;
// }
// }
// count++;
// }
// else if( index == count )
// {
// tail.Next = new Node<T>( data );
// count++;
// }
// else if( index > count || index < 0 )
// {
// throw new Exception( "index is outside the bounds of the list" );
// }
// else
// {
// for( int i = 0; i < index; i++ )
// {
// current = current.Next;
// }
// Node<T> temp = current.Next;
// current.Next = new Node<T>( data, temp );
// count++;
// }
// }
// /// <summary>
// /// Add another list to this one
// /// </summary>
// /// <param name="temp">The list to add</param>
// /// <author>Sean Brennan</author>
// public void AddRange(IEnumerable temp)
// {
// foreach (T toAdd in temp)
// {
// Add(toAdd);
// }
// }
// #endregion
// #region Remove
// /// <summary>
// /// <author>Eric Christenson</author>
// /// <contributer>Daniel Jost (made compatible with the rest of the List class)</contributer>
// /// remove first node with value
// /// </summary>
// /// <param name="value">object of type T to addX</param>
// public virtual void Remove( T data )
// {
// Node<T> current = head;
// Node<T> prev = current;
// while( current != null )// && current.Next != null)
// {
// // The following 2 lines are what I changed to make it work
// // EqualityComparer uses the default .Equals of object, comparing the hash code
// // of the two objects which will be unique for each instance of an object
// if( EqualityComparer<T>.Default.Equals( data, current.Value ) )
// //if (current.Data.Equals(value))
// {
// if( current == head ) // if current is head, it has no previous, need to do something different
// {
// if( head == tail )
// {
// tail = null;
// }
// head = head.Next;
// }
// else if( current == tail )
// {
// tail = prev;
// prev.Next = null;
// }
// else
// {
// prev.Next = current.Next;
// }
// current = null;
// count--;
// break;
// }
// else
// {
// prev = current;
// current = current.Next;
// }
// }
// }
// /// <summary>
// /// Removes value at given index</summary>
// /// <param name="index">
// /// Index to remove from</param>
// /// <returns>
// /// Successfulness of removal</returns>
// public virtual bool RemoveAt( int index )
// {
// // If index given is higher than count, return false
// if( index >= count )
// return false;
// // Get node previous to one before to be removed
// Node<T> remPrev = head;
// Node<T> rem = head;
// for( int ii = 0; ii < index - 1; ii++ )
// {
// remPrev = remPrev.Next;
// rem = rem.Next;
// }
// // Make rem go one further than remPrev
// if (index != 0)
// rem = rem.Next;
// // Remove node
// if( rem == head )
// {
// if( head == tail )
// {
// tail = null;
// }
// head = head.Next;
// }
// else
// {
// remPrev.Next = remPrev.Next.Next;
// }
// count--;
// // Return true
// return true;
// }
// #endregion
// #region Other Methods
// /// <summary>
// /// USE AT YOUR OWN RISK
// /// Checks whether the list contains the specified item
// /// </summary>
// /// <contributor>Zachary Behrmann</contributor>
// /// <param name="value">The item to check against the list</param>
// /// <returns>A boolean value indicating whether item is in the list</returns>
// public bool Contains( T data )
// {
// Node<T> current = head;
// while( !current.Value.Equals( data ) )
// {
// if( current.Next != null )
// {
// current = current.Next;
// }
// else
// {
// return false;
// }
// }
// return true;
// }
// /// <summary>
// /// Remove everything from list
// /// </summary>
// public void Clear()
// {
// Node<T> previous = head; // Last node checked
// Node<T> current = head; // Current node being checked
// if( current != null )
// {
// current = null;
// tail = null;
// }
// else if( current != null && current.Next != null )
// {
// while( current.Next != null )
// {
// current = current.Next;
// previous = null;
// previous = current;
// }
// }
// head = null;
// count = 0;
// }
// /// <summary>
// /// Returns whether or not the list is empty</summary>
// /// <returns>
// /// Emptyness of list</returns>
// public Boolean IsEmpty()
// {
// return head == null;
// }
// /// <summary>
// /// Converts the list to an array of type T. @Jim Arnold
// /// </summary>
// /// <returns>The new array</returns>
// public T[] ToArray()
// {
// if (IsEmpty())
// return null;
// T[] temp = new T[this.count];
// for (int i = 0; i < this.count; i++)
// {
// temp[i] = this[i];
// }
// return temp;
// }
// /// <summary>
// /// Returns all items in List</summary>
// /// <returns>
// /// A string of all items</returns>
// public override string ToString()
// {
// if( head != null )
// {
// string returnString = this[ 0 ].ToString();
// for( int ii = 1; ii < this.Count; ii++ )
// returnString += "\n" + this[ ii ].ToString();
// return returnString;
// }
// else return "";
// }
// #endregion
// }
//}
#endregion
| PxlBuzzard/Four-Guns | FourGuns/FourGuns/Datastructures/List.cs | C# | bsd-3-clause | 26,690 |
/* $Id$
* Author: Daniel Bosk <daniel.bosk@miun.se>
* Date: 22 Dec 2012
*/
/*
* Copyright (c) 2012, Daniel Bosk <daniel.bosk@miun.se>
* 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 University 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.
*/
#include <stdlib.h>
#include <stdio.h>
#include "free.h"
#include "types.h"
#include "swap.h"
#include "sys.h"
static page_t *queue = NULL;
static size_t qsize = 0;
static int qhead = 0;
void
remove_from_queue( int n )
{
if ( n >= qsize )
return;
int i = n;
while ( i != qhead ) {
queue[ i ] = queue[ i+1 ];
i = ( i + 1 ) % qsize;
}
}
int
memalg_esc( page_t p, pagetable_t pt )
{
pentry_t *pe;
int best_lvl = 5;
int i, best_idx;
/* do some setup the first time this function is run */
if ( queue == NULL ) {
qsize = sz_memory;
queue = calloc( qsize, sizeof(page_t) );
if ( queue == NULL )
return ERROR;
qhead = 0;
}
/* if the page is valid, do nothing as no paging is required */
if ( pt[p].valid == 1 )
return OK;
fprintf(stdout, "page %lli generated page fault\n", p);
/* if we have free frames, use one of these */
if ( free_total() > 0 ) {
pt[p].frame = free_getframe();
if ( pt[p].frame == FRAME_ERR )
return ERROR;
fprintf(stdout, "allocated free frame %lli to page %lli\n",
pt[p].frame, p);
}
/* otherwise swap out one page */
else {
for ( i = 0; i < qsize; i++) {
pe = pt + queue[qhead];
if ( pe->valid == 0 )
return ERROR;
/* first class: not referenced, not modified */
else if ( !pe->referenced && !pe->modified &&
best_lvl > 1 ) {
best_idx = qhead;
best_lvl = 1;
}
/* second class: not referenced but modified */
else if ( !pe->referenced && pe->modified &&
best_lvl > 2 ) {
best_idx = qhead;
best_lvl = 2;
}
/* third class: referenced, but not modified */
else if ( pe->referenced && !pe->modified &&
best_lvl > 3 ) {
best_idx = qhead;
best_lvl = 3;
}
/* fourth class: referenced and modified */
else if ( pe->referenced && pe->modified &&
best_lvl > 4 ) {
best_idx = qhead;
best_lvl = 4;
}
pe->referenced = 0;
qhead = ( qhead + 1 ) % qsize;
}
qhead = best_idx;
pt[queue[qhead]].valid = 0;
swap_out(queue[qhead]);
/* allocate the newly freed frame */
pt[p].frame = pt[queue[qhead]].frame;
}
/* update the queue */
queue[qhead] = p;
qhead = ( qhead + 1 ) % qsize;
/* actually swap in the page */
swap_in(p);
pt[p].valid = 1;
pt[p].modified = 0;
pt[p].referenced = 0;
return OK;
}
| dbosk/cpager | memalg_esc.c | C | bsd-3-clause | 3,975 |
/* ----------------------------------------------------------------- */
/* The Japanese TTS System "Open JTalk" */
/* developed by HTS Working Group */
/* http://open-jtalk.sourceforge.net/ */
/* ----------------------------------------------------------------- */
/* */
/* Copyright (c) 2008-2016 Nagoya Institute of Technology */
/* Department of Computer Science */
/* */
/* 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 HTS working group 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. */
/* ----------------------------------------------------------------- */
#ifndef NJD_SET_UNVOICED_VOWEL_RULE_H
#define NJD_SET_UNVOICED_VOWEL_RULE_H
#ifdef __cplusplus
#define NJD_SET_UNVOICED_VOWEL_RULE_H_START extern "C" {
#define NJD_SET_UNVOICED_VOWEL_RULE_H_END }
#else
#define NJD_SET_UNVOICED_VOWEL_RULE_H_START
#define NJD_SET_UNVOICED_VOWEL_RULE_H_END
#endif /* __CPLUSPLUS */
NJD_SET_UNVOICED_VOWEL_RULE_H_START;
/*
\x96\xb3\x90\xba\x8e\x71\x89\xb9: k ky s sh t ty ch ts h f hy p py
Rule 0 \x83\x74\x83\x42\x83\x89\x81\x5b\x82\xcd\x96\xb3\x90\xba\x89\xbb\x82\xb5\x82\xc8\x82\xa2
Rule 1 \x8f\x95\x93\xae\x8e\x8c\x82\xcc\x81\x75\x82\xc5\x82\xb7\x81\x76\x82\xc6\x81\x75\x82\xdc\x82\xb7\x81\x76\x82\xcc\x81\x75\x82\xb7\x81\x76\x82\xaa\x96\xb3\x90\xba\x89\xbb
Rule 2 \x93\xae\x8e\x8c\x81\x43\x8f\x95\x93\xae\x8e\x8c\x81\x43\x8f\x95\x8e\x8c\x82\xcc\x81\x75\x82\xb5\x81\x76\x82\xcd\x96\xb3\x90\xba\x89\xbb\x82\xb5\x82\xe2\x82\xb7\x82\xa2
Rule 3 \x91\xb1\x82\xaf\x82\xc4\x96\xb3\x90\xba\x89\xbb\x82\xb5\x82\xc8\x82\xa2
Rule 4 \x83\x41\x83\x4e\x83\x5a\x83\x93\x83\x67\x8a\x6a\x82\xc5\x96\xb3\x90\xba\x89\xbb\x82\xb5\x82\xc8\x82\xa2
Rule 5 \x96\xb3\x90\xba\x8e\x71\x89\xb9(k ky s sh t ty ch ts h f hy p py)\x82\xc9\x88\xcd\x82\xdc\x82\xea\x82\xbd\x81\x75i\x81\x76\x82\xc6\x81\x75u\x81\x76\x82\xaa\x96\xb3\x90\xba\x89\xbb
\x97\xe1\x8a\x4f\x81\x46s->s, s->sh, f->f, f->h, f->hy, h->f, h->h, h->hy
*/
#define NJD_SET_UNVOICED_VOWEL_FILLER "\x83\x74\x83\x42\x83\x89\x81\x5b"
#define NJD_SET_UNVOICED_VOWEL_DOUSHI "\x93\xae\x8e\x8c"
#define NJD_SET_UNVOICED_VOWEL_JODOUSHI "\x8f\x95\x93\xae\x8e\x8c"
#define NJD_SET_UNVOICED_VOWEL_JOSHI "\x8f\x95\x8e\x8c"
#define NJD_SET_UNVOICED_VOWEL_KANDOUSHI "\x8a\xb4\x93\xae\x8e\x8c"
#define NJD_SET_UNVOICED_VOWEL_TOUTEN "\x81\x41"
#define NJD_SET_UNVOICED_VOWEL_QUESTION "\x81\x48"
#define NJD_SET_UNVOICED_VOWEL_QUOTATION "\x81\x66"
#define NJD_SET_UNVOICED_VOWEL_SHI "\x83\x56"
#define NJD_SET_UNVOICED_VOWEL_MA "\x83\x7d"
#define NJD_SET_UNVOICED_VOWEL_DE "\x83\x66"
#define NJD_SET_UNVOICED_VOWEL_CHOUON "\x81\x5b"
#define NJD_SET_UNVOICED_VOWEL_SU "\x83\x58"
static const char *njd_set_unvoiced_vowel_candidate_list1[] = {
"\x83\x58\x83\x42", /* s i */
"\x83\x58", /* s u */
NULL
};
static const char *njd_set_unvoiced_vowel_next_mora_list1[] = {
"\x83\x4a", /* k ky */
"\x83\x4c",
"\x83\x4e",
"\x83\x50",
"\x83\x52",
"\x83\x5e", /* t ty ch ts */
"\x83\x60",
"\x83\x63",
"\x83\x65",
"\x83\x67",
"\x83\x6e", /* h f hy */
"\x83\x71",
"\x83\x74",
"\x83\x77",
"\x83\x7a",
"\x83\x70", /* p py */
"\x83\x73",
"\x83\x76",
"\x83\x79",
"\x83\x7c",
NULL
};
static const char *njd_set_unvoiced_vowel_candidate_list2[] = {
"\x83\x74\x83\x42", /* f i */
"\x83\x71", /* h i */
"\x83\x74", /* f u */
NULL
};
static const char *njd_set_unvoiced_vowel_next_mora_list2[] = {
"\x83\x4a", /* k ky */
"\x83\x4c",
"\x83\x4e",
"\x83\x50",
"\x83\x52",
"\x83\x54", /* s sh */
"\x83\x56",
"\x83\x58",
"\x83\x5a",
"\x83\x5c",
"\x83\x5e", /* t ty ch ts */
"\x83\x60",
"\x83\x63",
"\x83\x65",
"\x83\x67",
"\x83\x70", /* p py */
"\x83\x73",
"\x83\x76",
"\x83\x79",
"\x83\x7c",
NULL
};
static const char *njd_set_unvoiced_vowel_candidate_list3[] = {
"\x83\x4c\x83\x85", /* ky u */
"\x83\x56\x83\x85", /* sh u */
"\x83\x60\x83\x85", /* ch u */
"\x83\x63\x83\x42", /* ts i */
"\x83\x71\x83\x85", /* hy u */
"\x83\x73\x83\x85", /* py u */
"\x83\x65\x83\x85", /* ty u */
"\x83\x67\x83\x44", /* t u */
"\x83\x65\x83\x42", /* t i */
"\x83\x4c", /* k i */
"\x83\x4e", /* k u */
"\x83\x56", /* sh i */
"\x83\x60", /* ch i */
"\x83\x63", /* ts u */
"\x83\x73", /* p i */
"\x83\x76", /* p u */
NULL
};
static const char *njd_set_unvoiced_vowel_next_mora_list3[] = {
"\x83\x4a", /* k ky */
"\x83\x4c",
"\x83\x4e",
"\x83\x50",
"\x83\x52",
"\x83\x54", /* s sh */
"\x83\x56",
"\x83\x58",
"\x83\x5a",
"\x83\x5c",
"\x83\x5e", /* t ty ch ts */
"\x83\x60",
"\x83\x63",
"\x83\x65",
"\x83\x67",
"\x83\x6e", /* h f hy */
"\x83\x71",
"\x83\x74",
"\x83\x77",
"\x83\x7a",
"\x83\x70", /* p py */
"\x83\x73",
"\x83\x76",
"\x83\x79",
"\x83\x7c",
NULL
};
static const char *njd_set_unvoiced_vowel_mora_list[] = {
"\x83\x94\x83\x87",
"\x83\x94\x83\x85",
"\x83\x94\x83\x83",
"\x83\x94\x83\x48",
"\x83\x94\x83\x46",
"\x83\x94\x83\x42",
"\x83\x94\x83\x40",
"\x83\x94",
"\x83\x93",
"\x83\x92",
"\x83\x91",
"\x83\x90",
"\x83\x8f",
"\x83\x8d",
"\x83\x8c",
"\x83\x8b",
"\x83\x8a\x83\x87",
"\x83\x8a\x83\x85",
"\x83\x8a\x83\x83",
"\x83\x8a\x83\x46",
"\x83\x8a",
"\x83\x89",
"\x83\x88",
"\x83\x87",
"\x83\x86",
"\x83\x85",
"\x83\x84",
"\x83\x83",
"\x83\x82",
"\x83\x81",
"\x83\x80",
"\x83\x7e\x83\x87",
"\x83\x7e\x83\x85",
"\x83\x7e\x83\x83",
"\x83\x7e\x83\x46",
"\x83\x7e",
"\x83\x7d",
"\x83\x7c",
"\x83\x7b",
"\x83\x7a",
"\x83\x79",
"\x83\x78",
"\x83\x77",
"\x83\x76",
"\x83\x75",
"\x83\x74\x83\x48",
"\x83\x74\x83\x46",
"\x83\x74\x83\x42",
"\x83\x74\x83\x40",
"\x83\x74",
"\x83\x73\x83\x87",
"\x83\x73\x83\x85",
"\x83\x73\x83\x83",
"\x83\x73\x83\x46",
"\x83\x73",
"\x83\x72\x83\x87",
"\x83\x72\x83\x85",
"\x83\x72\x83\x83",
"\x83\x72\x83\x46",
"\x83\x72",
"\x83\x71\x83\x87",
"\x83\x71\x83\x85",
"\x83\x71\x83\x83",
"\x83\x71\x83\x46",
"\x83\x71",
"\x83\x70",
"\x83\x6f",
"\x83\x6e",
"\x83\x6d",
"\x83\x6c",
"\x83\x6b",
"\x83\x6a\x83\x87",
"\x83\x6a\x83\x85",
"\x83\x6a\x83\x83",
"\x83\x6a\x83\x46",
"\x83\x6a",
"\x83\x69",
"\x83\x68\x83\x44",
"\x83\x68",
"\x83\x67\x83\x44",
"\x83\x67",
"\x83\x66\x83\x87",
"\x83\x66\x83\x85",
"\x83\x66\x83\x83",
"\x83\x66\x83\x42",
"\x83\x66",
"\x83\x65\x83\x87",
"\x83\x65\x83\x85",
"\x83\x65\x83\x83",
"\x83\x65\x83\x42",
"\x83\x65",
"\x83\x64",
"\x83\x63\x83\x48",
"\x83\x63\x83\x46",
"\x83\x63\x83\x42",
"\x83\x63\x83\x40",
"\x83\x63",
"\x83\x62",
"\x83\x61",
"\x83\x60\x83\x87",
"\x83\x60\x83\x85",
"\x83\x60\x83\x83",
"\x83\x60\x83\x46",
"\x83\x60",
"\x83\x5f",
"\x83\x5e",
"\x83\x5d",
"\x83\x5c",
"\x83\x5b",
"\x83\x5a",
"\x83\x59\x83\x42",
"\x83\x59",
"\x83\x58\x83\x42",
"\x83\x58",
"\x83\x57\x83\x87",
"\x83\x57\x83\x85",
"\x83\x57\x83\x83",
"\x83\x57\x83\x46",
"\x83\x57",
"\x83\x56\x83\x87",
"\x83\x56\x83\x85",
"\x83\x56\x83\x83",
"\x83\x56\x83\x46",
"\x83\x56",
"\x83\x55",
"\x83\x54",
"\x83\x53",
"\x83\x52",
"\x83\x51",
"\x83\x50",
"\x83\x4f",
"\x83\x4e",
"\x83\x4d\x83\x87",
"\x83\x4d\x83\x85",
"\x83\x4d\x83\x83",
"\x83\x4d\x83\x46",
"\x83\x4d",
"\x83\x4c\x83\x87",
"\x83\x4c\x83\x85",
"\x83\x4c\x83\x83",
"\x83\x4c\x83\x46",
"\x83\x4c",
"\x83\x4b",
"\x83\x4a",
"\x83\x49",
"\x83\x48",
"\x83\x47",
"\x83\x46",
"\x83\x45\x83\x48",
"\x83\x45\x83\x46",
"\x83\x45\x83\x42",
"\x83\x45",
"\x83\x44",
"\x83\x43\x83\x46",
"\x83\x43",
"\x83\x42",
"\x83\x41",
"\x83\x40",
"\x81\x5b",
NULL
};
NJD_SET_UNVOICED_VOWEL_RULE_H_END;
#endif /* !NJD_SET_UNVOICED_VOWEL_RULE_H */
| anoyetta/ACT.TTSYukkuri | Thirdparty/openjtalk_buildbatch/open_jtalk_v110/open_jtalk-1.10/open_jtalk/njd_set_unvoiced_vowel/njd_set_unvoiced_vowel_rule_ascii_for_shift_jis.h | C | bsd-3-clause | 10,986 |
#include <QtWidgets/QApplication>
#include <QtWidgets/QTableWidget>
#include <QString>
#include <cstdint>
#include <vector>
#include <map>
#include <dqtx/QDensityWidget.hpp>
#include <random>
class distribution : public QObject
{
Q_OBJECT
private:
QTableWidget m_table;
dqtx::QDensityWidget m_normalWidget;
dqtx::QDensityWidget m_lognormalWidget;
dqtx::QDensityWidget m_bernoulliWidget;
dqtx::QDensityWidget m_bimodalWidget;
std::default_random_engine m_generator;
std::normal_distribution< double > m_normalRand;
std::normal_distribution< double > m_normalRandNonzero;
std::lognormal_distribution< double > m_lognormalRand;
std::bernoulli_distribution m_bernoulliRand;
public:
distribution();
void initialize();
private slots:
void on_timeout();
};
| dcdillon/dqtx | examples/distribution/distribution.hpp | C++ | bsd-3-clause | 819 |
<?xml version="1.0" encoding="utf-8"?>
<!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>Module: Constants::Stat</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<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="classHeader">
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Module</strong></td>
<td class="class-name-in-header">Constants::Stat</td>
</tr>
<tr class="top-aligned-row">
<td><strong>In:</strong></td>
<td>
<a href="../../files/lib/constants_rb.html">
lib/constants.rb
</a>
<br />
</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
</div>
</div>
<!-- if includes -->
<div id="section">
<div id="constants-list">
<h3 class="section-bar">Constants</h3>
<div class="name-list">
<table summary="Constants">
<tr class="top-aligned-row context-row">
<td class="context-item-name">DEFAULT_RANK_ALGO</td>
<td>=</td>
<td class="context-item-value">2</td>
</tr>
</table>
</div>
</div>
<!-- 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> | pld/pairwise | doc/app/classes/Constants/Stat.html | HTML | bsd-3-clause | 2,522 |
# Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password, :SAMLResponse]
| Orasi/code-challenge-grading | config/initializers/filter_parameter_logging.rb | Ruby | bsd-3-clause | 209 |
/*============================================================================
Copyright (c) German Cancer Research Center (DKFZ)
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.
- All advertising materials mentioning features or use of this software must
display the following acknowledgement:
"This product includes software developed by the German Cancer Research
Center (DKFZ)."
- Neither the name of the German Cancer Research Center (DKFZ) 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 GERMAN CANCER RESEARCH CENTER (DKFZ) 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 GERMAN
CANCER RESEARCH CENTER (DKFZ) 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.
============================================================================*/
/*
* $RCSfile$
*--------------------------------------------------------------------
* DESCRIPTION
* the old pic header
*
* $Log$
* Revision 1.5 2002/11/13 17:53:00 ivo
* new ipPic added.
*
* Revision 1.3 2000/05/04 12:52:40 ivo
* inserted BSD style license
*
* Revision 1.2 2000/05/04 12:36:01 ivo
* some doxygen comments.
*
* Revision 1.1.1.1 1997/09/06 19:09:59 andre
* initial import
*
* Revision 0.0 1993/03/26 12:56:26 andre
* Initial revision
*
*
*--------------------------------------------------------------------
*
*/
#ifndef _mitkIpPicOldP_h
#define _mitkIpPicOldP_h
typedef struct
{
mitkIpUInt4_t id,
dummy1,
dummy2,
conv,
rank,
n1,
n2,
n3,
n4,
n5,
n6,
n7,
n8,
type,
ntxt,
ltxt;
} _mitkIpPicOldHeader;
#endif /* ifdef _mitkIpPicOldP_h */
/* DON'T ADD ANYTHING AFTER THIS #endif */
| fmilano/mitk | Utilities/IpPic/mitkIpPicOldP.h | C | bsd-3-clause | 3,056 |
/*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Common Public License (CPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/cpl1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.mmtk.utility.options;
/**
* GCspy Tile Size.
*/
public final class GCspyTileSize extends org.vmutil.options.IntOption {
/**
* Create the option.
*/
public GCspyTileSize() {
super(Options.set, "GCspy Tile Size",
"GCspy Tile Size",
131072);
}
/**
* Ensure the tile size is positive
*/
protected void validate() {
failIf(this.value <= 0, "Unreasonable gcspy tilesize");
}
}
| ut-osa/laminar | jikesrvm-3.0.0/MMTk/src/org/mmtk/utility/options/GCspyTileSize.java | Java | bsd-3-clause | 873 |
<?php
/**
* Pop PHP Framework (http://www.popphp.org/)
*
* @link https://github.com/nicksagona/PopPHP
* @category Pop
* @package Pop_Auth
* @author Nick Sagona, III <nick@popphp.org>
* @copyright Copyright (c) 2009-2014 Moc 10 Media, LLC. (http://www.moc10media.com)
* @license http://www.popphp.org/license New BSD License
*/
/**
* @namespace
*/
namespace Pop\Auth;
/**
* Auth adapter exception class
*
* @category Pop
* @package Pop_Auth
* @author Nick Sagona, III <nick@popphp.org>
* @copyright Copyright (c) 2009-2014 Moc 10 Media, LLC. (http://www.moc10media.com)
* @license http://www.popphp.org/license New BSD License
* @version 1.7.0
*/
class Exception extends \Exception {} | nicksagona/PopPHP | vendor/PopPHPFramework/src/Pop/Auth/Exception.php | PHP | bsd-3-clause | 748 |
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 2.1.1 - TBD
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.1.0 - 2016-10-17
### Added
- [#267](https://github.com/zfcampus/zf-apigility-doctrine/pull/267) adds
support for version 3 releases of zend-servicemanager and zend-eventmanager,
while retaining compatibility for v2 releases.
### Changes
- [#267](https://github.com/zfcampus/zf-apigility-doctrine/pull/267) exposes the
module to [zendframework/zend-component-installer](https://github.com/zendframework/zend-component-installer),
exposing both `ZF\Apigility\Doctrine\Admin` and
`ZF\Apigility\Doctrine\Server`. The former should be isntalled in the
development configuration, and the latter in your application modules.
- [#267](https://github.com/zfcampus/zf-apigility-doctrine/pull/267) updates
dependency requirements for the following modules and components:
- zfcampus/zf-apigilty-admin ^1.5
- phpro/zf-doctrine-hydration-module ^3.0
- doctrine/DoctrineModule ^1.2
- doctrine/DoctrineORMModule ^1.1
- doctrine/DoctrineMongoODMModule ^0.11
### Deprecated
- Nothing.
### Removed
- [#267](https://github.com/zfcampus/zf-apigility-doctrine/pull/267) removes
support for PHP 5.5.
### Fixed
- [#267](https://github.com/zfcampus/zf-apigility-doctrine/pull/267) adds a ton
of tests to the module, and fixes a number of issues encountered.
| kusmierz/zf-apigility-doctrine | CHANGELOG.md | Markdown | bsd-3-clause | 1,518 |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kitchen_sink.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| publica-io/django-publica-kitchen-sink | kitchen_sink/manage.py | Python | bsd-3-clause | 255 |
using Mle.Util;
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
namespace Mle.IO {
public class JsonUtils : JsonUtilsBase {
private static JsonUtils instance = null;
public static JsonUtils Instance {
get {
if (instance == null)
instance = new JsonUtils();
return instance;
}
}
private StorageFolder localFolder = ApplicationData.Current.LocalFolder;
public override async Task WithWriter(string filePath, Func<Stream, Task> writingCode) {
using (var stream = await localFolder.OpenStreamForWriteAsync(filePath, CreationCollisionOption.ReplaceExisting)) {
await writingCode(stream);
}
}
//public override T DeserializeFileOrElse<T>(string filePath, T orElse = default(T)) {
// StorageFile.C
//}
}
}
| malliina/musicpimp-win | Common-WinStore/Mle/IO/JsonUtils.cs | C# | bsd-3-clause | 940 |
---
id: 5900f43e1000cf542c50ff50
challengeType: 5
title: 'Problem 210: Obtuse Angled Triangles'
forumTopicId: 301852
---
## Description
<section id='description'>
Consider the set S(r) of points (x,y) with integer coordinates satisfying |x| + |y| ≤ r.
Let O be the point (0,0) and C the point (r/4,r/4).
Let N(r) be the number of points B in S(r), so that the triangle OBC has an obtuse angle, i.e. the largest angle α satisfies 90°<α<180°.
So, for example, N(4)=24 and N(8)=100.
What is N(1,000,000,000)?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler210()</code> should return 1598174770174689500.
testString: assert.strictEqual(euler210(), 1598174770174689500);
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler210() {
// Good luck!
return true;
}
euler210();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>
| BhaveshSGupta/FreeCodeCamp | curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-210-obtuse-angled-triangles.english.md | Markdown | bsd-3-clause | 1,033 |
package org.broadinstitute.macarthurlab.matchbox.match;
import org.broadinstitute.macarthurlab.matchbox.entities.Patient;
import org.monarchinitiative.exomiser.core.phenotype.*;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author Jules Jacobsen <j.jacobsen@qmul.ac.uk>
*/
@Service
public class PhenotypeSimilarityServiceImpl implements PhenotypeSimilarityService {
private final PhenotypeMatchService phenotypeMatchService;
public PhenotypeSimilarityServiceImpl(PhenotypeMatchService phenotypeMatchService) {
this.phenotypeMatchService = phenotypeMatchService;
}
@Override
public PhenotypeSimilarityScorer buildPhenotypeSimilarityScorer(Patient patient) {
ModelScorer modelScorer = setUpModelScorer(patient);
return new PhenotypeSimilarityScorerImpl(modelScorer);
}
private ModelScorer setUpModelScorer(Patient patient) {
List<String> queryPatientPhenotypes = PhenotypeSimilarityService.getObservedPhenotypeIds(patient);
List<PhenotypeTerm> queryPhenotypeTerms = phenotypeMatchService.makePhenotypeTermsFromHpoIds(queryPatientPhenotypes);
PhenotypeMatcher hpHpQueryMatcher = phenotypeMatchService.getHumanPhenotypeMatcherForTerms(queryPhenotypeTerms);
return PhenodigmModelScorer.forSameSpecies(hpHpQueryMatcher);
}
}
| macarthur-lab/matchbox | src/main/java/org/broadinstitute/macarthurlab/matchbox/match/PhenotypeSimilarityServiceImpl.java | Java | bsd-3-clause | 1,348 |
package org.basex.api.client;
import java.io.*;
import org.basex.core.*;
import org.basex.io.out.*;
/**
* <p>This class defines methods for executing commands, either locally or via the
* client/server architecture.</p>
*
* <p>The results of database commands are returned as strings. If an output stream is specified in
* the constructor or with {@link #setOutputStream(OutputStream)}, results are instead serialized
* to that stream.</p>
*
* <p>The class is implemented by the {@link ClientSession} and {@link LocalSession} classes.</p>
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public abstract class Session implements Closeable {
/** Client output stream. */
protected OutputStream out;
/** Command info. */
protected String info = "";
/**
* Executes a {@link Command} and returns the result as string or serializes
* it to the specified output stream.
* @param command command to be executed
* @return result or {@code null} reference
* @throws IOException I/O exception
*/
public final String execute(final Command command) throws IOException {
final ArrayOutput ao = out == null ? new ArrayOutput() : null;
execute(command, ao != null ? ao : out);
return ao != null ? ao.toString() : null;
}
/**
* Executes a command and returns the result as string or serializes
* it to the specified output stream.
* @param command command to be parsed
* @return result or {@code null} reference
* @throws IOException I/O exception
*/
public final String execute(final String command) throws IOException {
final ArrayOutput ao = out == null ? new ArrayOutput() : null;
execute(command, ao != null ? ao : out);
return ao != null ? ao.toString() : null;
}
/**
* Returns a query object for the specified query string.
* @param query query string
* @return query
* @throws IOException I/O exception
*/
public abstract Query query(String query) throws IOException;
/**
* Creates a database.
* @param name name of database
* @param input xml input
* @throws IOException I/O exception
*/
public abstract void create(String name, InputStream input) throws IOException;
/**
* Adds a document to the opened database.
* @param path target path
* @param input xml input
* @throws IOException I/O exception
*/
public abstract void add(String path, InputStream input) throws IOException;
/**
* Replaces a document in an open database.
* @param path document(s) to replace
* @param input new content
* @throws IOException I/O exception
*/
public abstract void replace(String path, InputStream input) throws IOException;
/**
* Stores raw data in an open database.
* @param path target path
* @param input binary input
* @throws IOException I/O exception
*/
public abstract void store(String path, InputStream input) throws IOException;
/**
* Returns command info as a string, regardless of whether an output stream
* was specified.
* @return command info
*/
public final String info() {
return info;
}
/**
* Specifies an output stream. The output stream can be invalidated by
* passing on {@code null} as argument.
* @param output client output stream
*/
public final void setOutputStream(final OutputStream output) {
out = output;
}
/**
* Returns the assigned output stream.
* @return client output stream
*/
public OutputStream getOutputStream() {
return out;
}
// PROTECTED METHODS ============================================================================
/**
* Constructor.
* @param output client output stream; if set to {@code null}, all
* results will be returned as strings
*/
Session(final OutputStream output) {
out = output;
}
/**
* Executes a command and prints the result to the specified output stream.
* @param command command to be parsed
* @param output output stream
* @throws IOException I/O exception
*/
protected abstract void execute(String command, OutputStream output) throws IOException;
/**
* Executes a command and prints the result to the specified output stream.
* @param command command to be executed
* @param output output stream
* @throws IOException I/O exception
*/
protected abstract void execute(Command command, OutputStream output) throws IOException;
}
| BaseXdb/basex | basex-core/src/main/java/org/basex/api/client/Session.java | Java | bsd-3-clause | 4,433 |
/* Please refer to license.txt */
#pragma once
#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>
namespace GEngine
{
namespace mnet
{
class Client : public boost::enable_shared_from_this<Client>
{
private:
boost::asio::io_service io_service;
boost::asio::ip::tcp::resolver *resolver;
boost::asio::ip::tcp::resolver::query *query;
boost::asio::ip::tcp::resolver::iterator endpoint_iterator;
boost::asio::ip::tcp::socket *socket;
boost::array<char, 128> buffer;
bool run = true;
public:
typedef boost::shared_ptr<Client> Pointer_t;
//static Pointer_t create(boost::asio::io_service &ioService);
void handleWrite(const boost::system::error_code &error, size_t bytes_transferred_);
void handleRead(const boost::system::error_code &error, size_t bytes_transferred_);
std::vector<std::string> data_received; //Stores the data received so far.
Client();
~Client();
/*
Initializes a brand new client and attempts to connect to the specified host.
Returns false on failure.
TODO: Update to use the error module.
Parameters:
std::string host : the host to connect to.
std::string port : the port to connect to.
*/
bool newConnection(std::string host, int port);
void update();
void stop();
/*
Returns true if the client is running.
Returns false if the client has stopped (such as when connection to the server is lost.)
*/
bool running();
void sendMessage(std::string message);
/*
Returns the data.
One problem I foresee with this is getting more data than is being deciphered.
*/
std::string getData();
};
} //namespace mnet
} //namespace GEngine
| addictgamer/GEngine | src/net/client/client.hpp | C++ | bsd-3-clause | 1,722 |
/* **********************************************************
* Copyright (c) 2000-2010 VMware, Inc. 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 VMware, Inc. 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 VMWARE, INC. 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.
*/
/* Copyright (c) 2003-2007 Determina Corp. */
/* Copyright (c) 2001-2003 Massachusetts Institute of Technology */
/* Copyright (c) 2000-2001 Hewlett-Packard Company */
/*
* dispatch.c - central dynamo control manager
*/
#include "globals.h"
#include "link.h"
#include "fragment.h"
#include "fcache.h"
#include "monitor.h"
#include "synch.h"
#include "string_wrapper.h" /* for strstr */
#ifdef CLIENT_INTERFACE
# include "emit.h"
# include "arch.h"
# include "instrument.h"
#endif
#ifdef DGC_DIAGNOSTICS
# include "instr.h"
# include "disassemble.h"
#endif
#ifdef RCT_IND_BRANCH
# include "rct.h"
#endif
#ifdef X64
# include "instr.h"
# include "decode.h" /* get_x86_mode */
#endif
#ifdef VMX86_SERVER
# include "vmkuw.h"
#endif
#ifdef LINUX_KERNEL
# include "kernel_interface.h"
#endif
/* forward declarations */
static void
dispatch_enter_dynamorio(dcontext_t *dcontext);
static bool
dispatch_enter_fcache(dcontext_t *dcontext, fragment_t *targetf);
static void
dispatch_enter_fcache_stats(dcontext_t *dcontext, fragment_t *targetf);
static void
enter_fcache(dcontext_t *dcontext, fcache_enter_func_t entry, cache_pc pc);
static void
dispatch_enter_native(dcontext_t *dcontext);
static void
dispatch_exit_fcache(dcontext_t *dcontext);
static void
dispatch_exit_fcache_stats(dcontext_t *dcontext);
static void
handle_post_system_call(dcontext_t *dcontext);
static bool
is_kernel_exit_point(dcontext_t *dcontext);
static void
dispatch_exit_kernel(dcontext_t *dcontext);
#ifdef WINDOWS
static void
handle_callback_return(dcontext_t *dcontext);
#endif
#ifdef CLIENT_INTERFACE
/* PR 356503: detect clients making syscalls via sysenter */
static inline void
found_client_sysenter(void)
{
CLIENT_ASSERT(false, "Is your client invoking raw system calls via vdso sysenter? "
"While such behavior is not recommended and can create problems, "
"it may work with the -sysenter_is_int80 runtime option.");
}
#endif
#ifdef LINUX_KERNEL
# define ASSERT_SANE_DISPATCH_TARGET(pc) do {\
ASSERT(!is_in_dynamo_dll((pc)));\
ASSERT(!is_dynamo_address((pc)));\
ASSERT(is_kernel_code((pc)));\
} while (0)
#else
# define ASSERT_SANE_DISPATCH_TARGET(pc) do {\
ASSERT(!is_in_dynamo_dll((pc)));\
ASSERT(!is_dynamo_address((pc)));\
ASSERT(is_user_address((pc)));\
} while (0)
#endif
#ifdef LINUX_KERNEL
static void
exiting_for_breakpoint(void)
{
/* Useful for setting breakpoints. */
}
#endif
/* This is the central hub of control management in DynamoRIO.
* It is entered with a clean dstack at startup and after every cache
* exit, whether normal or kernel-mediated via a trampoline context switch.
* Having no stack state kept across cache executions avoids
* self-protection issues with the dstack.
*/
void
dispatch(dcontext_t *dcontext)
{
fragment_t *targetf;
fragment_t coarse_f;
#ifdef HAVE_TLS
ASSERT(dcontext == get_thread_private_dcontext());
#else
# ifdef LINUX
/* CAUTION: for !HAVE_TLS, upon a fork, the child's
* get_thread_private_dcontext() will return NULL because its thread
* id is different and tls_table hasn't been updated yet (will be
* done in post_system_call()). NULL dcontext thus returned causes
* logging/core dumping to malfunction; kstats trigger asserts.
*/
ASSERT(dcontext == get_thread_private_dcontext() || pid_cached != get_process_id());
# endif
#endif
dcontext->current_fragment = NULL;
dispatch_enter_dynamorio(dcontext);
LOG(THREAD, LOG_INTERP, 2, "\ndispatch: target = "PFX"\n", dcontext->next_tag);
ASSERT(is_dynamo_address((app_pc) dcontext));
#ifdef DEBUG
if (dcontext->next_tag != (app_pc) fake_user_return_exit_target &&
!is_stopping_point(dcontext, dcontext->next_tag)) {
ASSERT_SANE_DISPATCH_TARGET(dcontext->next_tag);
}
#endif
/* This is really a 1-iter loop most of the time: we only iterate
* when we obtain a target fragment but then fail to enter the
* cache due to flushing before we get there.
*/
do {
if (is_stopping_point(dcontext, dcontext->next_tag)) {
LOG(THREAD, LOG_INTERP, 1,
"\nFound DynamoRIO stopping point: thread %d returning to app @"PFX"\n",
get_thread_id(), dcontext->next_tag);
#ifdef LINUX_KERNEL
if (*dcontext->next_tag == 0xcc) {
/* Disable interrupts so we actually get to the breakpoint
* before being interrupted. */
get_mcontext(dcontext)->xflags &= ~EFLAGS_IF;
exiting_for_breakpoint();
}
#endif
dispatch_enter_native(dcontext);
ASSERT_NOT_REACHED();
}
#ifdef LINUX_KERNEL
else if (is_kernel_exit_point(dcontext)) {
dispatch_exit_kernel(dcontext);
ASSERT_NOT_REACHED();
}
#endif
ASSERT_SANE_DISPATCH_TARGET(dcontext->next_tag);
/* Neither hotp_only nor thin_client should have any fragment
* fcache related work to do.
*/
ASSERT(!RUNNING_WITHOUT_CODE_CACHE());
targetf = fragment_lookup_fine_and_coarse(dcontext, dcontext->next_tag,
&coarse_f, dcontext->last_exit);
do {
if (targetf != NULL) {
KSTART(monitor_enter);
/* invoke monitor to continue or start a trace
* may result in changing or nullifying targetf
*/
targetf = monitor_cache_enter(dcontext, targetf);
KSTOP_NOT_MATCHING(monitor_enter); /* or monitor_enter_thci */
}
if (targetf != NULL)
break;
if (USE_BB_BUILDING_LOCK()) {
mutex_lock(&bb_building_lock);
/* must re-lookup while holding lock and keep the lock until we've
* built the bb and added it to the lookup table
* FIXME: optimize away redundant lookup: flags to know why came out?
*/
targetf = fragment_lookup_fine_and_coarse(dcontext, dcontext->next_tag,
&coarse_f, dcontext->last_exit);
}
if (targetf == NULL) {
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
targetf =
build_basic_block_fragment(dcontext, dcontext->next_tag,
0, true/*link*/, true/*visible*/
_IF_CLIENT(false/*!for_trace*/)
_IF_CLIENT(NULL));
SELF_PROTECT_LOCAL(dcontext, READONLY);
if (dcontext->emulating_interrupt_return) {
STATS_INC(num_fragment_tails_iret);
}
}
ASSERT(targetf != NULL);
if (TEST(FRAG_COARSE_GRAIN, targetf->flags)) {
/* targetf is a static temp fragment protected by bb_building_lock,
* so we must make a local copy to use before releasing the lock.
* FIXME: best to pass local wrapper to build_basic_block_fragment
* and all the way through emit and link? Would need linkstubs
* tailing the fragment_t.
*/
ASSERT(USE_BB_BUILDING_LOCK());
fragment_coarse_wrapper(&coarse_f, targetf->tag,
FCACHE_ENTRY_PC(targetf));
targetf = &coarse_f;
}
if (USE_BB_BUILDING_LOCK())
mutex_unlock(&bb_building_lock);
/* loop around and re-do monitor check */
} while (true);
dcontext->emulating_interrupt_return = false;
if (dispatch_enter_fcache(dcontext, targetf)) {
/* won't reach here: will re-enter dispatch() with a clean stack */
ASSERT_NOT_REACHED();
} else
targetf = NULL; /* targetf was flushed */
} while (true);
ASSERT_NOT_REACHED();
}
#ifdef LINUX_KERNEL
/* Not part of is_stopping_point because is_stopping_point is called by code
* other than dispatch.
*/
static bool
is_kernel_exit_point(dcontext_t *dcontext)
{
ASSERT(!TESTANY(LINK_IRET | LINK_SYSRET, dcontext->last_exit->flags) ||
dcontext->next_tag == (app_pc) fake_user_return_exit_target);
if (TEST(LINK_IRET, dcontext->last_exit->flags)) {
if (emulate_interrupt_return(dcontext)) {
dcontext->emulating_interrupt_return = true;
} else {
LOG(THREAD, LOG_INTERP, 1, "dispatching native iret from frag @ %p\n",
dcontext->last_fragment->start_pc);
/* TODO(peter) We could set this in build_bb_ilist rather than setting
* fake_user_return_exit_target. */
ASSERT(!interrupts_enabled(dcontext));
/* TODO(peter): iret can generate exceptions. We should handle these.
*/
dcontext->next_tag = (app_pc) dr_native_iret;
return true;
}
} else if (TEST(LINK_SYSRET, dcontext->last_exit->flags)) {
ASSERT(!DYNAMO_OPTION(optimize_sys_call_ret));
LOG(THREAD, LOG_INTERP, 1, "dispatching native sysret from frag @ %p\n",
dcontext->last_fragment->start_pc);
/* TODO(peter) We could set this in build_bb_ilist rather than setting
* fake_user_return_exit_target. */
ASSERT(!interrupts_enabled(dcontext));
/* TODO(peter): sysret can generate exceptions. We should handle these.
*/
dcontext->next_tag = (app_pc) native_sysret;
return true;
}
ASSERT(dcontext->next_tag != (app_pc) fake_user_return_exit_target);
return false;
}
#endif
/* returns true if pc is a point at which DynamoRIO should stop interpreting */
bool
is_stopping_point(dcontext_t *dcontext, app_pc pc)
{
if ((pc == BACK_TO_NATIVE_AFTER_SYSCALL &&
/* case 6253: app may xfer to this "address" in which case pass
* exception to app
*/
dcontext->native_exec_postsyscall != NULL)
#ifdef DR_APP_EXPORTS
|| (!automatic_startup &&
(pc == (app_pc)dr_smp_exit ||
pc == (app_pc)dynamorio_app_exit ||
/* FIXME: Is this a holdover from long ago? dymamo_thread_exit
* should not be called from the cache.
*/
pc == (app_pc)dynamo_thread_exit ||
pc == (app_pc)dr_app_stop))
#endif
#ifdef LINUX_KERNEL
|| (is_kernel_code(pc) && *pc == 0xcc) /* int3 opcode */
#endif
#ifdef WINDOWS
/* we go all the way to NtTerminateThread/NtTerminateProcess */
#else /* LINUX */
/* we go all the way to SYS_exit or SYS_{,t,tg}kill(SIGABRT) */
#endif
)
return true;
return false;
}
static void
dispatch_enter_fcache_stats(dcontext_t *dcontext, fragment_t *targetf)
{
#ifdef DEBUG
# ifdef DGC_DIAGNOSTICS
if (TEST(FRAG_DYNGEN, targetf->flags) && !is_dyngen_vsyscall(targetf->tag)) {
char buf[MAXIMUM_SYMBOL_LENGTH];
bool stack = is_address_on_stack(dcontext, targetf->tag);
LOG(THREAD, LOG_DISPATCH, 1, "Entry into dyngen F%d("PFX"%s%s) via:",
targetf->id, targetf->tag,
stack ? " stack":"",
(targetf->flags & FRAG_DYNGEN_RESTRICTED) != 0 ? " BAD":"");
if (!LINKSTUB_FAKE(dcontext->last_exit)) {
app_pc translated_pc;
/* can't recreate if fragment is deleted -- but should be fake then */
ASSERT(!TEST(FRAG_WAS_DELETED, dcontext->last_fragment->flags));
translated_pc = recreate_app_pc(dcontext, EXIT_CTI_PC(dcontext->last_fragment,
dcontext->last_exit),
dcontext->last_fragment);
if (translated_pc != NULL) {
disassemble(dcontext, translated_pc, THREAD);
print_symbolic_address(translated_pc, buf, sizeof(buf), false);
LOG(THREAD, LOG_DISPATCH, 1, " %s\n", buf);
}
if (!stack &&
(strstr(buf, "user32.dll") != NULL || strstr(buf, "USER32.DLL") != NULL)) {
/* try to find who set up user32 callback */
dump_mcontext_callstack(dcontext);
}
DOLOG(stack ? 1U : 2U, LOG_DISPATCH, {
LOG(THREAD, LOG_DISPATCH, 1, "Originating bb:\n");
disassemble_app_bb(dcontext, dcontext->last_fragment->tag, THREAD);
});
} else {
/* FIXME: print type from last_exit */
LOG(THREAD, LOG_DISPATCH, 1, "\n");
}
if (stack) {
/* try to understand where code is on stack */
LOG(THREAD, LOG_DISPATCH, 1, "cur esp="PFX" ebp="PFX"\n",
get_mcontext(dcontext)->xsp, get_mcontext(dcontext)->xbp);
dump_mcontext_callstack(dcontext);
}
}
# endif
if (stats->loglevel >= 2 && (stats->logmask & LOG_DISPATCH) != 0) {
/* FIXME: this should use a different mask - and get printed at level 2 when turned on */
DOLOG(4, LOG_DISPATCH, {
dump_mcontext(get_mcontext(dcontext), THREAD, DUMP_NOT_XML); });
DOLOG(6, LOG_DISPATCH, { dump_mcontext_callstack(dcontext); });
DOKSTATS({ DOLOG(6, LOG_DISPATCH, { kstats_dump_stack(dcontext); }); });
# ifdef RETURN_STACK
DOLOG(3, LOG_DISPATCH, { print_return_stack(dcontext); });
# endif
# ifdef NATIVE_RETURN_CALLDEPTH
LOG(THREAD, LOG_DISPATCH, 3, "\tCall depth is %d\n",
dcontext->call_depth);
# endif
LOG(THREAD, LOG_DISPATCH, 2, "Entry into F%d("PFX")."PFX" %s%s",
targetf->id,
targetf->tag,
FCACHE_ENTRY_PC(targetf),
TEST(FRAG_COARSE_GRAIN, targetf->flags) ? "(coarse)" : "",
((targetf->flags & FRAG_IS_TRACE_HEAD)!=0)?
"(trace head)" : "",
((targetf->flags & FRAG_IS_TRACE)!=0)? "(trace)" : "");
LOG(THREAD, LOG_DISPATCH, 2, "%s",
TEST(FRAG_SHARED, targetf->flags) ? "(shared)":"");
# ifdef DGC_DIAGNOSTICS
LOG(THREAD, LOG_DISPATCH, 2, "%s",
TEST(FRAG_DYNGEN, targetf->flags) ? "(dyngen)":"");
# endif
LOG(THREAD, LOG_DISPATCH, 2, "\n");
DOLOG(3, LOG_SYMBOLS, {
char symbuf[MAXIMUM_SYMBOL_LENGTH];
print_symbolic_address(targetf->tag,
symbuf, sizeof(symbuf), true);
LOG(THREAD, LOG_SYMBOLS, 3, "\t%s\n", symbuf);
});
}
#endif /* DEBUG */
}
/* Executes a target fragment in the fragment cache */
static bool
dispatch_enter_fcache(dcontext_t *dcontext, fragment_t *targetf)
{
fcache_enter_func_t fcache_enter;
dcontext->current_fragment = targetf;
ASSERT(targetf != NULL);
/* ensure we don't take over when we should be going native */
ASSERT(dcontext->native_exec_postsyscall == NULL);
/* We wait until here, rather than at cache exit time, to do lazy
* linking so we can link to newly created fragments.
*/
if (dcontext->last_exit == get_coarse_exit_linkstub() ||
/* We need to lazy link if either of src or tgt is coarse */
(LINKSTUB_DIRECT(dcontext->last_exit->flags) &&
TEST(FRAG_COARSE_GRAIN, targetf->flags))) {
coarse_lazy_link(dcontext, targetf);
}
if (!enter_nolinking(dcontext, targetf, true)) {
/* not actually entering cache, so back to couldbelinking */
enter_couldbelinking(dcontext, NULL, true);
LOG(THREAD, LOG_DISPATCH, 2, "Just flushed targetf, next_tag is "PFX"\n",
dcontext->next_tag);
STATS_INC(num_entrances_aborted);
/* shared entrance cannot-tell-if-deleted -> invalidate targetf
* but then may double-do the trace!
* FIXME: for now, we abort every time, ok to abort twice (first time
* b/c there was a real flush of targetf), but could be perf hit.
*/
trace_abort(dcontext);
return false;
}
dispatch_enter_fcache_stats(dcontext, targetf);
/* FIXME: for now we do this before the synch point to avoid complexity of
* missing a KSTART(fcache_* for cases like NtSetContextThread where a thread
* appears back at dispatch() from the synch point w/o ever entering the cache.
* To truly fix we need to have the NtSetContextThread handler determine
* whether its suspended target is at this synch point or in the cache.
*/
DOKSTATS({
/* stopped in dispatch_exit_fcache_stats */
if (TEST(FRAG_IS_TRACE, targetf->flags))
KSTART(fcache_trace_trace);
else
KSTART(fcache_default); /* fcache_bb_bb or fcache_bb_trace */
/* FIXME: overestimates fcache time by counting in
* fcache_enter/fcache_return for it - proper reading of this
* value should discount the minimal cost of
* fcache_enter/fcache_return for actual code cache times
*/
/* FIXME: asynch events currently continue their current kstat
* until they get back to dispatch, so in-fcache kstats are counting
* the in-DR trampoline execution time!
*/
});
#ifdef WINDOWS
/* synch point for suspend, terminate, and detach */
/* assumes mcontext is valid including errno but not pc (which we fix here)
* assumes that thread is holding no locks
* also assumes past enter_nolinking, so could_be_linking is false
* for safety with respect to flush */
/* a fast check before the heavy lifting */
if (should_wait_at_safe_spot(dcontext)) {
/* FIXME : we could put this synch point in enter_fcache but would need
* to use SYSCALL_PC for syscalls (see issues with that in win32/os.c)
*/
dr_mcontext_t *mcontext = get_mcontext(dcontext);
cache_pc save_pc = mcontext->pc;
/* FIXME : implementation choice, we could do recreate_app_pc
* (fairly expensive but this is rare) instead of using the tag
* which is a little hacky but should always be right */
mcontext->pc = targetf->tag;
/* could be targeting interception code or our dll main, would be
* incorrect for GetContextThread and racy for detach, though we
* would expect it to be very rare */
if (!is_dynamo_address(mcontext->pc)) {
check_wait_at_safe_spot(dcontext, THREAD_SYNCH_VALID_MCONTEXT);
/* If we don't come back here synch-er is responsible for ensuring
* our kstat stack doesn't get off (have to do a KSTART here) -- we
* don't want to do the KSTART of fcache_* before this to avoid
* counting synch time.
*/
} else {
LOG(THREAD, LOG_SYNCH, 1,
"wait_at_safe_spot - unable to wait, targeting dr addr "PFX,
mcontext->pc);
STATS_INC(no_wait_entries);
}
mcontext->pc = save_pc;
}
#endif
#if defined(LINUX) && defined(DEBUG) && !defined(LINUX_KERNEL)
/* i#238/PR 499179: check that libc errno hasn't changed. It's
* not worth actually saving+restoring since to we'd also need to
* preserve on clean calls, a perf hit. Better to catch all libc
* routines that need it and wrap just those.
*/
ASSERT(get_libc_errno() == dcontext->libc_errno ||
/* only when pthreads is loaded does libc switch to a per-thread
* errno, so our raw thread tests end up using the same errno
* for each thread!
*/
check_filter("linux.thread;linux.clone",
get_short_name(get_application_name())));
#endif
IF_X64(ASSERT(get_x86_mode(dcontext) == TEST(FRAG_32_BIT, targetf->flags)));
if (TEST(FRAG_SHARED, targetf->flags))
fcache_enter = get_fcache_enter_shared_routine(dcontext);
else
fcache_enter = get_fcache_enter_private_routine(dcontext);
enter_fcache(dcontext, fcache_enter, FCACHE_ENTRY_PC(targetf));
ASSERT_NOT_REACHED();
return true;
}
/* Enters the cache at the specified entrance routine to execute the
* target pc.
* Does not return.
* Caller must do a KSTART to avoid kstats stack mismatches.
* FIXME: only allow access to fcache_enter routine through here?
* Indirect routine needs special treatment for handle_callback_return
*/
static void
enter_fcache(dcontext_t *dcontext, fcache_enter_func_t entry, cache_pc pc)
{
ASSERT(!is_couldbelinking(dcontext));
ASSERT(entry != NULL);
ASSERT(pc != NULL);
ASSERT(check_should_be_protected(DATASEC_RARELY_PROT));
/* CANNOT hold any locks across cache execution, as our thread synch
* assumes none are held
*/
ASSERT_OWN_NO_LOCKS();
ASSERT(dcontext->try_except_state == NULL);
/* prepare to enter fcache */
LOG(THREAD, LOG_DISPATCH, 4, "fcache_enter = "PFX", target = "PFX"\n", entry, pc);
ASSERT(is_dynamo_address(pc));
set_fcache_target(dcontext, pc);
ASSERT(pc != NULL);
#ifdef PROFILE_RDTSC
if (dynamo_options.profile_times) {
/* prepare to enter fcache */
dcontext->prev_fragment = NULL;
/* top ten cache times */
dcontext->cache_frag_count = (uint64) 0;
dcontext->cache_enter_time = get_time();
}
#endif
dcontext->whereami = WHERE_FCACHE;
(*entry)(dcontext);
ASSERT_NOT_REACHED();
}
#if defined(DR_APP_EXPORTS) || defined(LINUX)
static void
dispatch_at_stopping_point(dcontext_t *dcontext)
{
/* start/stop interface */
KSTOP_NOT_MATCHING(dispatch_num_exits);
/* if we stop in middle of tracing, thread-shared state may be messed
* up (e.g., monitor grabs fragment lock for unlinking),
* so abort the trace
*/
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_INTERP, 1, "squashing trace-in-progress\n");
trace_abort(dcontext);
}
LOG(THREAD, LOG_INTERP, 1, "\nappstart_cleanup: found stopping point\n");
# ifdef DEBUG
# ifdef DR_APP_EXPORTS
if (dcontext->next_tag == (app_pc)dynamo_thread_exit)
LOG(THREAD, LOG_INTERP, 1, "\t==dynamo_thread_exit\n");
else if (dcontext->next_tag == (app_pc)dynamorio_app_exit)
LOG(THREAD, LOG_INTERP, 1, "\t==dynamorio_app_exit\n");
else if (dcontext->next_tag == (app_pc)dr_app_stop) {
# ifdef NATIVE_RETURN_TRY_TO_PUT_APP_RETURN_PC_ON_STACK
/* FIXME: restore app ret pc before we give control back */
*((int *)(get_mcontext(dcontext)->xsp)) =
# endif
LOG(THREAD, LOG_INTERP, 1, "\t==dr_app_stop\n");
}
# endif
# endif
# ifdef NATIVE_RETURN
/* HACK: end now and avoid having to get app return pc
* assumes single thread, entire-app run
*/
{
byte *app_esp = get_mcontext(dcontext)->xsp;
asm("movl %0, %%esp" : : "m"(app_esp));
dynamorio_app_exit();
exit(0);
}
# else
dynamo_thread_not_under_dynamo(dcontext);
# endif
}
#endif
/* Called when we reach an interpretation stopping point either for
* start/stop control of DR or for native_exec. In both cases we give up
* control and "go native", but we do not clean up the current thread,
* assuming we will either take control back, or the app will explicitly
* request we clean up.
*/
static void
dispatch_enter_native(dcontext_t *dcontext)
{
/* The new fcache_enter's clean dstack design makes it usable for
* entering native execution as well as the fcache.
*/
fcache_enter_func_t go_native = get_fcache_enter_private_routine(dcontext);
ASSERT_OWN_NO_LOCKS();
if (dcontext->next_tag == BACK_TO_NATIVE_AFTER_SYSCALL) {
/* we're simply going native again after an intercepted syscall,
* not finalizing this thread or anything
*/
IF_WINDOWS(DEBUG_DECLARE(extern dcontext_t *early_inject_load_helper_dcontext;))
ASSERT(DYNAMO_OPTION(native_exec_syscalls)); /* else wouldn't have intercepted */
/* Assert here we have a reason for going back to native (-native_exec and
* non-empty native_exec_areas, RUNNING_WITHOUT_CODE_CACHE, hotp nudge thread
* pretending to be native while loading a dll, or on win2k
* early_inject_init() pretending to be native to find the inject address). */
ASSERT((DYNAMO_OPTION(native_exec) && native_exec_areas != NULL &&
!vmvector_empty(native_exec_areas)) ||
IF_WINDOWS((DYNAMO_OPTION(early_inject) &&
early_inject_load_helper_dcontext ==
get_thread_private_dcontext()) ||)
IF_HOTP(dcontext->nudge_thread ||)
RUNNING_WITHOUT_CODE_CACHE());
ASSERT(dcontext->native_exec_postsyscall != NULL);
LOG(THREAD, LOG_ASYNCH, 1, "Returning to native "PFX" after a syscall\n",
dcontext->native_exec_postsyscall);
dcontext->next_tag = dcontext->native_exec_postsyscall;
dcontext->native_exec_postsyscall = NULL;
LOG(THREAD, LOG_DISPATCH, 2, "Entry into native_exec after intercepted syscall\n");
/* restore state as though never came out for syscall */
set_last_exit(dcontext, (linkstub_t *) get_native_exec_linkstub());
KSTART(fcache_default);
enter_nolinking(dcontext, NULL, true);
}
else {
#if defined(DR_APP_EXPORTS) || defined(LINUX)
dispatch_at_stopping_point(dcontext);
enter_nolinking(dcontext, NULL, false);
#else
ASSERT_NOT_REACHED();
#endif
}
set_fcache_target(dcontext, dcontext->next_tag);
dcontext->whereami = WHERE_APP;
LOG(THREAD, LOG_INTERP, 1, "Going native ... \n");
(*go_native)(dcontext);
ASSERT_NOT_REACHED();
}
#ifdef LINUX_KERNEL
static void
dispatch_exit_kernel(dcontext_t *dcontext) {
/* Kill any trace in progress. */
if (is_building_trace(dcontext)) {
LOG(THREAD, LOG_INTERP, 1, "squashing trace-in-progress\n");
trace_abort(dcontext);
}
/* We assume that next_tag was set by is_kernel_exit_point to the
* appropriate kernel exit stub. */
set_fcache_target(dcontext, dcontext->next_tag);
enter_nolinking(dcontext, NULL, false);
LOG(THREAD, LOG_INTERP, 1, "Returning to user mode ... \n");
/* Stopped in dispatch_exit_fcache_stats. */
if (DYNAMO_OPTION(optimize_sys_call_ret)) {
dcontext->whereami = WHERE_FCACHE;
KSTART(fcache_default);
} else {
ASSERT(false);
dcontext->whereami = WHERE_USERMODE;
KSTART(usermode);
}
ASSERT_OWN_NO_LOCKS();
fcache_enter_routine(dcontext)(dcontext);
ASSERT_NOT_REACHED();
}
#endif
static void
dispatch_enter_dynamorio(dcontext_t *dcontext)
{
/* We're transitioning to DynamoRIO from somewhere: either the fcache,
* the kernel (WHERE_TRAMPOLINE), or the app itself via our start/stop API.
* N.B.: set whereami to WHERE_APP iff this is the first dispatch() entry
* for this thread!
*/
where_am_i_t wherewasi = dcontext->whereami;
#ifdef LINUX
if (!(wherewasi == WHERE_FCACHE || wherewasi == WHERE_TRAMPOLINE ||
wherewasi == WHERE_APP
IF_LINUX_KERNEL(|| wherewasi == WHERE_USERMODE))) {
/* This is probably our own syscalls hitting our own sysenter
* hook (PR 212570), since we're not completely user library
* independent (PR 206369).
* The primary calls I'm worried about are dl{open,close}.
* Note that we can't go jump to vsyscall_syscall_end_pc here b/c
* fcache_return cleared the dstack, so we can't really recover.
* We could put in a custom exit stub and return routine and recover,
* but we need to get library independent anyway so it's not worth it.
*/
ASSERT(get_syscall_method() == SYSCALL_METHOD_SYSENTER);
IF_X64(ASSERT_NOT_REACHED()); /* no sysenter support on x64 */
/* PR 356503: clients using libraries that make syscalls can end up here */
IF_CLIENT_INTERFACE(found_client_sysenter());
ASSERT_BUG_NUM(206369, false &&
"DR's own syscall (via user library) hit the sysenter hook");
}
#endif
ASSERT(wherewasi == WHERE_FCACHE || wherewasi == WHERE_TRAMPOLINE ||
wherewasi == WHERE_APP
IF_LINUX_KERNEL(|| wherewasi == WHERE_USERMODE));
dcontext->whereami = WHERE_DISPATCH;
ASSERT_LOCAL_HEAP_UNPROTECTED(dcontext);
ASSERT(check_should_be_protected(DATASEC_RARELY_PROT));
/* CANNOT hold any locks across cache execution, as our thread synch
* assumes none are held
*/
ASSERT_OWN_NO_LOCKS();
#if defined(LINUX) && defined(DEBUG) && !defined(LINUX_KERNEL)
/* i#238/PR 499179: check that libc errno hasn't changed */
dcontext->libc_errno = get_libc_errno();
#endif
DOLOG(2, LOG_INTERP, {
if (wherewasi == WHERE_APP) {
LOG(THREAD, LOG_INTERP, 2, "\ninitial dispatch: target = "PFX"\n",
dcontext->next_tag);
dump_mcontext_callstack(dcontext);
dump_mcontext(get_mcontext(dcontext), THREAD, DUMP_NOT_XML);
}
});
/* We have to perform some tasks with last_exit early, before we
* become couldbelinking -- the rest are done in dispatch_exit_fcache().
* It's ok to de-reference last_exit since even though deleter may assume
* no one has ptrs to it, cannot delete until we're officially out of the
* cache, which doesn't happen until enter_couldbelinking -- still kind of
* messy that we're violating assumption of no ptrs...
*/
if (wherewasi == WHERE_APP) { /* first entrance */
ASSERT(dcontext->last_exit == get_starting_linkstub()
/* new thread */
|| IF_WINDOWS_ELSE_0(dcontext->last_exit == get_asynch_linkstub())
#ifdef LINUX_KERNEL
/* We returned to native inside of the kernel because of an int3
* then we re-entered through a system call or an interrupt. */
|| IS_KERNEL_ENTRY_LINKSTUB(dcontext->last_exit)
#endif
);
} else {
ASSERT(dcontext->last_exit != NULL); /* MUST be set, if only to a fake linkstub_t */
/* cache last_exit's fragment */
dcontext->last_fragment = linkstub_fragment(dcontext, dcontext->last_exit);
/* If we exited from an indirect branch then dcontext->next_tag
* already has the next tag value; otherwise we must set it here,
* before we might dive back into the cache for a system call.
*/
if (LINKSTUB_DIRECT(dcontext->last_exit->flags)) {
if (INTERNAL_OPTION(cbr_single_stub)) {
linkstub_t *nxt =
linkstub_shares_next_stub(dcontext, dcontext->last_fragment,
dcontext->last_exit);
if (nxt != NULL) {
/* must distinguish the two based on eflags */
dcontext->last_exit =
linkstub_cbr_disambiguate(dcontext, dcontext->last_fragment,
dcontext->last_exit, nxt);
ASSERT(dcontext->last_fragment ==
linkstub_fragment(dcontext, dcontext->last_exit));
STATS_INC(cbr_disambiguations);
}
}
dcontext->next_tag = EXIT_TARGET_TAG(dcontext, dcontext->last_fragment,
dcontext->last_exit);
} else if (dcontext->last_exit == get_ibl_unlinked_found_linkstub()) {
fragment_t *ibl_target, wrapper;
ASSERT(in_fcache(dcontext->next_tag));
ibl_target = fragment_pclookup(dcontext, dcontext->next_tag,
&wrapper);
ASSERT(ibl_target != NULL);
dcontext->next_tag = ibl_target->tag;
} else {
/* get src info from coarse ibl exit into the right place */
if (DYNAMO_OPTION(coarse_units) &&
is_ibl_sourceless_linkstub((const linkstub_t*)dcontext->last_exit))
set_coarse_ibl_exit(dcontext);
}
dispatch_exit_fcache_stats(dcontext);
KSTOP_NOT_MATCHING(dispatch_num_exits);
/* Update the total measured time. This is a convenient place to do this
* because thread_measured is at the top of the kstack.
*/
DOKSTATS({
update_lifetime_kstats(dcontext);
});
}
KSTART(dispatch_num_exits); /* KSWITCHed next time around for a better explanation */
if (wherewasi != WHERE_APP) { /* if not first entrance */
if (get_at_syscall(dcontext))
handle_post_system_call(dcontext);
#ifndef LINUX_KERNEL
/* A non-ignorable syscall or cb return ending a bb must be acted on
* We do it here to avoid becoming couldbelinking twice.
*
*/
if (TESTANY(LINK_NI_SYSCALL_ALL, dcontext->last_exit->flags)
IF_CLIENT_INTERFACE(|| instrument_invoke_another_syscall(dcontext))) {
handle_system_call(dcontext);
/* will return here if decided to skip the syscall; else, back to dispatch() */
}
#endif
#ifdef WINDOWS
else if (TEST(LINK_CALLBACK_RETURN, dcontext->last_exit->flags)) {
handle_callback_return(dcontext);
ASSERT_NOT_REACHED();
}
#endif
/* Case 8177: If we have a flushed fragment hit a self-write, we cannot
* delete it in our self-write handler (b/c of case 3559's incoming links
* union). But, our self-write handler needs to be nolinking and needs to
* check sandbox2ro_threshold. So, we do our self-write check first, but we
* don't actually delete there for FRAG_WAS_DELETED fragments.
*/
if (TEST(LINK_SELFMOD_EXIT, dcontext->last_exit->flags)) {
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
/* this fragment overwrote its original memory image */
fragment_self_write(dcontext);
/* FIXME: optimize this to stay writable if we're going to
* be exiting dispatch as well -- no very quick check though
*/
SELF_PROTECT_LOCAL(dcontext, READONLY);
}
}
/* make sure to tell flushers that we are now going to be mucking
* with link info
*/
if (!enter_couldbelinking(dcontext, dcontext->last_fragment, true)) {
LOG(THREAD, LOG_DISPATCH, 2, "Just flushed last_fragment\n");
/* last_fragment flushed, but cannot access here to copy it
* to fake linkstub_t, so assert that callee did (either when freeing or
* when noticing pending deletion flag)
*/
ASSERT(LINKSTUB_FAKE(dcontext->last_exit));
}
if (wherewasi != WHERE_APP) { /* if not first entrance */
/* now fully process the last cache exit as couldbelinking */
dispatch_exit_fcache(dcontext);
}
}
/* Processing of the last exit from the cache.
* Invariant: dcontext->last_exit != NULL, though it may be a sentinel (see below).
*
* Note that the last exit and its owning fragment may be _fake_, i.e., just
* a copy of the key fields we typically check, for the following cases:
* - last fragment was flushed: fully deleted at cache exit synch point
* - last fragment was deleted since it overwrote itself (selfmod)
* - last fragment was deleted since it was a private trace building copy
* - last fragment was deleted for other reasons?!?
* - briefly during trace emitting, nobody should care though
* - coarse grain fragment exits, for which we have no linkstub_t or other
* extraneous bookkeeping
*
* For some cases we do not currently keep the key fields at all:
* - last fragment was flushed: detected at write fault
* And some times we are unable to keep the key fields:
* - last fragment was flushed: targeted in ibl via target_deleted path
* These last two cases are the only exits from fragment for which we
* do not know the key fields. For the former, we exit in the middle of
* a fragment that was already created, so not knowing does not affect
* security policies or other checks much. The latter is the most problematic,
* as we have a number of checks depending on knowing the last exit when indirect.
*
* We have other types of exits from the cache that never involved a real
* fragment, for which we also use fake linkstubs:
* - no real last fragment: system call
* - no real last fragment: sigreturn
* - no real last fragment: native_exec return
* - callbacks clear last_exit, but should come out of the cache at a syscall
* (bug 2464 was back when tried to carry last_exit through syscall)
* so this will end up looking like the system call case
*/
static void
dispatch_exit_fcache(dcontext_t *dcontext)
{
/* case 7966: no distinction of islinking-ness for hotp_only & thin_client */
ASSERT(RUNNING_WITHOUT_CODE_CACHE() || is_couldbelinking(dcontext));
#if defined(WINDOWS) && defined (CLIENT_INTERFACE)
ASSERT(!is_dynamo_address(dcontext->app_fls_data));
ASSERT(dcontext->app_fls_data == NULL ||
dcontext->app_fls_data != dcontext->priv_fls_data);
ASSERT(!is_dynamo_address(dcontext->app_nt_rpc));
ASSERT(dcontext->app_nt_rpc == NULL ||
dcontext->app_nt_rpc != dcontext->priv_nt_rpc);
#endif
#ifdef NATIVE_RETURN
if (in_fcache(dcontext->next_tag)) {
/* when we unlink a ret, it ends up coming back here
* with the code cache target as next_tag.
* we translate that to an app pc here.
*/
app_pc tgt_app_pc = ret_tgt_cache_to_app(dcontext,
(cache_pc)dcontext->next_tag);
LOG(THREAD, LOG_DISPATCH, 3, "next_tag is in cache: "PFX"\n",
dcontext->next_tag);
LOG(THREAD, LOG_DISPATCH, 3, "next_tag "PFX" -> app ret addr "PFX"\n",
dcontext->next_tag, tgt_app_pc);
/* set last_retaddr for fixup_last_cti, if building trace */
dcontext->last_retaddr = dcontext->next_tag;
dcontext->next_tag = tgt_app_pc;
ASSERT(dcontext->last_exit->ret_pc != NULL);
}
#endif
if (LINKSTUB_INDIRECT(dcontext->last_exit->flags)) {
/* indirect branch exit processing */
#if defined(RETURN_AFTER_CALL) || defined(RCT_IND_BRANCH)
/* PR 204770: use trace component bb tag for RCT source address */
app_pc src_tag = dcontext->last_fragment->tag;
if (!LINKSTUB_FAKE(dcontext->last_exit) &&
TEST(FRAG_IS_TRACE, dcontext->last_fragment->flags)) {
/* FIXME: should we call this for direct exits as well, up front? */
src_tag = get_trace_exit_component_tag
(dcontext, dcontext->last_fragment, dcontext->last_exit);
}
#endif
#ifdef RETURN_AFTER_CALL
/* This is the permission check for any new return target, it
* also double checks the findings of the indirect lookup
* routine
*/
if (dynamo_options.ret_after_call && TEST(LINK_RETURN, dcontext->last_exit->flags)) {
/* ret_after_call will raise a security violation on failure */
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
ret_after_call_check(dcontext, dcontext->next_tag, src_tag);
SELF_PROTECT_LOCAL(dcontext, READONLY);
}
#endif /* RETURN_AFTER_CALL */
#ifdef RCT_IND_BRANCH
/* permission check for any new indirect call or jump target */
/* we care to detect violations only if blocking or at least
* reporting the corresponding branch types
*/
if (TESTANY(OPTION_REPORT|OPTION_BLOCK, DYNAMO_OPTION(rct_ind_call)) ||
TESTANY(OPTION_REPORT|OPTION_BLOCK, DYNAMO_OPTION(rct_ind_jump))) {
if ((TEST(LINK_CALL, dcontext->last_exit->flags)
&& TESTANY(OPTION_REPORT|OPTION_BLOCK, DYNAMO_OPTION(rct_ind_call))) ||
(TEST(LINK_JMP, dcontext->last_exit->flags)
&& TESTANY(OPTION_REPORT|OPTION_BLOCK, DYNAMO_OPTION(rct_ind_jump)))
) {
/* case 4995: current shared syscalls implementation
* reuses the indirect jump table and marks its
* fake linkstub as such.
*/
if (LINKSTUB_FAKE(dcontext->last_exit) /* quick check */ &&
IS_SHARED_SYSCALLS_LINKSTUB(dcontext->last_exit)) {
ASSERT(IF_WINDOWS_ELSE(DYNAMO_OPTION(shared_syscalls), false));
ASSERT(TEST(LINK_JMP, dcontext->last_exit->flags));
} else {
/* rct_ind_branch_check will raise a security violation on failure */
rct_ind_branch_check(dcontext, dcontext->next_tag, src_tag);
}
}
}
#endif /* RCT_IND_BRANCH */
/* update IBL target tables for any indirect branch exit */
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
/* update IBL target table if target is a valid IBT */
/* FIXME: This is good for modularity but adds
* extra lookups in the fragment table. If it is
* performance problem can we do it better?
* Probably best to get bb2bb to work better and
* not worry about optimizing DR code.
*/
fragment_add_ibl_target(dcontext, dcontext->next_tag,
extract_branchtype(dcontext->last_exit->flags));
/* FIXME: optimize this to stay writable if we're going to
* be building a bb as well -- no very quick check though
*/
SELF_PROTECT_LOCAL(dcontext, READONLY);
} /* LINKSTUB_INDIRECT */
/* ref bug 2323, we need monitor to restore last fragment now,
* before we break out of the loop to build a new fragment
* ASSUMPTION: all unusual cache exits (asynch events) abort the current
* trace, so this is the only place we need to restore anything.
* monitor_cache_enter() asserts that for us.
* NOTE : we wait till after the cache exit stats and logs to call
* monitor_cache_exit since it might change the flags of the last
* fragment and screw up the stats
*/
monitor_cache_exit(dcontext);
#ifdef SIDELINE
/* sideline synchronization */
if (dynamo_options.sideline) {
thread_id_t tid = get_thread_id();
if (pause_for_sideline == tid) {
mutex_lock(&sideline_lock);
if (pause_for_sideline == tid) {
LOG(THREAD, LOG_DISPATCH|LOG_THREADS|LOG_SIDELINE, 2,
"Thread %d waiting for sideline thread\n", tid);
signal_event(paused_for_sideline_event);
STATS_INC(num_wait_sideline);
wait_for_event(resume_from_sideline_event);
mutex_unlock(&sideline_lock);
LOG(THREAD, LOG_DISPATCH|LOG_THREADS|LOG_SIDELINE, 2,
"Thread %d resuming after sideline thread\n", tid);
sideline_cleanup_replacement(dcontext);
} else
mutex_unlock(&sideline_lock);
}
}
#endif
#if defined(LINUX) && !defined(LINUX_KERNEL)
if (dcontext->signals_pending) {
/* FIXME: can overflow app stack if stack up too many signals
* by interrupting prev handlers -- exacerbated by RAC lack of
* caching (case 1858), which causes a cache exit prior to
* executing every single sigreturn!
*/
receive_pending_signal(dcontext);
}
#endif
#ifdef LINUX_KERNEL
if (has_pending_interrupt(dcontext)) {
receive_pending_interrupt(dcontext);
}
#endif
#ifdef CLIENT_INTERFACE
/* is ok to put the lock after the null check, this is only
* place they can be deleted
*/
if (dcontext->client_data != NULL && dcontext->client_data->to_do != NULL) {
client_todo_list_t *todo;
/* FIXME PR 200409: we're removing all API routines that use this
* todo list so we should never get here
*/
if (SHARED_FRAGMENTS_ENABLED()) {
USAGE_ERROR("CLIENT_INTERFACE incompatible with -shared_{bbs,traces}"
" at this time");
}
# ifdef CLIENT_SIDELINE
mutex_lock(&(dcontext->client_data->sideline_mutex));
# endif
todo = dcontext->client_data->to_do;
while (todo != NULL) {
client_todo_list_t *next_todo = todo->next;
fragment_t *f = fragment_lookup(dcontext, todo->tag);
if (f != NULL) {
if (todo->ilist != NULL) {
/* doing a replacement */
fragment_t * new_f;
uint orig_flags = f->flags;
void *vmlist = NULL;
DEBUG_DECLARE(bool ok;)
LOG(THREAD, LOG_INTERP, 3,
"Going to do a client fragment replacement at "PFX" F%d\n",
f->tag, f->id);
/* prevent emit from deleting f, we still need it */
/* FIXME: if f is shared we must hold change_linking_lock
* for the flags and vm area operations here
*/
ASSERT(!TEST(FRAG_SHARED, f->flags));
f->flags |= FRAG_CANNOT_DELETE;
DEBUG_DECLARE(ok =)
vm_area_add_to_list(dcontext, f->tag, &vmlist, orig_flags, f,
false/*no locks*/);
ASSERT(ok); /* should never fail for private fragments */
mangle(dcontext, todo->ilist, f->flags, true, true);
new_f = emit_invisible_fragment(dcontext, todo->tag, todo->ilist,
orig_flags, vmlist);
f->flags = orig_flags; /* FIXME: ditto about change_linking_lock */
instrlist_clear_and_destroy(dcontext, todo->ilist);
fragment_copy_data_fields(dcontext, f, new_f);
shift_links_to_new_fragment(dcontext, f, new_f);
fragment_replace(dcontext, f, new_f);
DOLOG(2, LOG_INTERP, {
LOG(THREAD, LOG_INTERP, 3,
"Finished emitting replacement fragment %d\n", new_f->id);
disassemble_fragment(dcontext, new_f, stats->loglevel < 3);
});
}
/* delete [old] fragment */
if ((f->flags & FRAG_CANNOT_DELETE) == 0) {
uint actions;
LOG(THREAD, LOG_INTERP, 3, "Client deleting old F%d\n", f->id);
if (todo->ilist != NULL) {
/* for the fragment replacement case, the fragment should
* already be unlinked and removed from the hash table.
*/
actions = FRAGDEL_NO_UNLINK | FRAGDEL_NO_HTABLE;
}
else {
actions = FRAGDEL_ALL;
}
fragment_delete(dcontext, f, actions);
STATS_INC(num_fragments_deleted_client);
} else {
LOG(THREAD, LOG_INTERP, 2, "Couldn't let client delete F%d\n",
f->id);
}
} else {
LOG(THREAD, LOG_INTERP, 2,
"Failed to delete/replace fragment at tag "PFX" because was already deleted",
todo->tag);
}
HEAP_TYPE_FREE(dcontext, todo, client_todo_list_t, ACCT_CLIENT, UNPROTECTED);
todo = next_todo;
}
dcontext->client_data->to_do = NULL;
# ifdef CLIENT_SIDELINE
mutex_unlock(&(dcontext->client_data->sideline_mutex));
# endif
}
#endif /* CLIENT_INTERFACE */
}
/* stats and logs on why we exited the code cache */
static void
dispatch_exit_fcache_stats(dcontext_t *dcontext)
{
#if defined(DEBUG) || defined(KSTATS)
fragment_t *next_f;
fragment_t *last_f;
fragment_t coarse_f;
#endif
#ifdef DEBUG
DOKSTATS({
/* According to comment where fcache_default or fcache_trace_trace is
* pushed, it can be switched to fcache_bb_bb or fcache_bb_trace,
* however these switches never happen. I'm putting this assertion in
* to verify that claim.
*/
kstat_stack_t *ks = &dcontext->thread_kstats->stack_kstats;
kstat_variable_t *var = ks->node[ks->depth - 1].var;
kstat_variables_t *vars = &dcontext->thread_kstats->vars_kstats;
ASSERT(var == &vars->fcache_default ||
var == &vars->fcache_trace_trace
IF_LINUX_KERNEL(|| var == &vars->usermode
/* Happens when dr_redirect_execution is called
* within a clean callee and there's a pending
* interrupt. */
|| var == &vars->kernel_interrupt_handling
|| var == &vars->kernel_interrupt_fcache_enter
|| var == &vars->kernel_interrupt_fcache_return
|| var == &vars->kernel_interrupt_ibl
|| var == &vars->kernel_interrupt_frag_success_page_fault
|| var == &vars->kernel_interrupt_frag_success_other_sync
|| var == &vars->kernel_interrupt_frag_success_async
|| var == &vars->kernel_interrupt_frag_delay_dispatch
|| var == &vars->kernel_interrupt_frag_delay_pc
|| var == &vars->delaying_patched_interrupt
|| var == &vars->kernel_interrupt_handling
|| var == &vars->user_interrupt_handling));
#ifdef LINUX_KERNEL
if (var == &vars->delaying_patched_interrupt) {
ASSERT(dcontext->last_exit == get_client_linkstub());
}
#endif
});
#endif
#ifdef PROFILE_RDTSC
if (dynamo_options.profile_times) {
int i,j;
uint64 end_time, total_time;
profile_fragment_dispatch(dcontext);
/* top ten cache times */
end_time = get_time();
total_time = end_time - dcontext->cache_enter_time;
for (i=0; i<10; i++) {
if (total_time > dcontext->cache_time[i]) {
/* insert */
for (j=9; j>i; j--) {
dcontext->cache_time[j] = dcontext->cache_time[j-1];
dcontext->cache_count[j] = dcontext->cache_count[j-1];
}
dcontext->cache_time[i] = total_time;
dcontext->cache_count[i] = dcontext->cache_frag_count;
break;
}
}
}
#endif
#if defined(DEBUG) || defined(KSTATS)
STATS_INC(num_exits);
ASSERT(dcontext->last_exit != NULL);
/* special exits that aren't from real fragments */
if (dcontext->last_exit == get_syscall_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from system call\n");
STATS_INC(num_exits_syscalls);
# ifdef CLIENT_INTERFACE
# ifdef KSTATS
/* PR 356503: clients using libraries that make syscalls, invoked from
* a clean call, will not trigger the whereami check below: so we
* locate here via mismatching kstat top-of-stack.
*/
KSTAT_THREAD(fcache_default, {
if (ks->node[ks->depth - 1].var == pv) {
found_client_sysenter();
}
});
# endif
# endif
KSTOP_NOT_PROPAGATED(syscall_fcache);
return;
}
else if (dcontext->last_exit == get_selfmod_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from fragment that self-flushed via code mod\n");
STATS_INC(num_exits_code_mod_flush);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
else if (dcontext->last_exit == get_ibl_deleted_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from fragment deleted but hit in ibl\n");
STATS_INC(num_exits_ibl_deleted);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
else if (dcontext->last_exit == get_ibl_unlinked_found_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from interrupt in ibl hit in ibl\n");
STATS_INC(num_exits_ibl_unlinked_found);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
# ifdef LINUX
else if (dcontext->last_exit == get_sigreturn_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from sigreturn, or os_forge_exception\n");
STATS_INC(num_exits_sigreturn);
KSTOP_NOT_MATCHING_NOT_PROPAGATED(syscall_fcache);
return;
}
# else /* WINDOWS */
else if (dcontext->last_exit == get_asynch_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from asynch event\n");
STATS_INC(num_exits_asynch);
/* w/ -shared_syscalls can also be a fragment kstart */
KSTOP_NOT_MATCHING_NOT_PROPAGATED(syscall_fcache);
return;
}
# endif
else if (dcontext->last_exit == get_native_exec_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from native_exec execution\n");
STATS_INC(num_exits_native_exec);
/* may be a quite large kstat count */
KSWITCH_STOP_NOT_PROPAGATED(native_exec_fcache);
return;
}
else if (dcontext->last_exit == get_native_exec_syscall_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from native_exec syscall trampoline\n");
STATS_INC(num_exits_native_exec_syscall);
/* may be a quite large kstat count */
KSWITCH_STOP_NOT_PROPAGATED(native_exec_fcache);
return;
}
else if (dcontext->last_exit == get_reset_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit due to proactive reset\n");
STATS_INC(num_exits_reset);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
# ifdef WINDOWS
else if (IS_SHARED_SYSCALLS_UNLINKED_LINKSTUB(dcontext->last_exit)) {
LOG(THREAD, LOG_DISPATCH, 2,
"Exit from unlinked shared syscall\n");
STATS_INC(num_unlinked_shared_syscalls_exits);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
else if (IS_SHARED_SYSCALLS_LINKSTUB(dcontext->last_exit)) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from shared syscall (%s)\n",
IS_SHARED_SYSCALLS_TRACE_LINKSTUB(dcontext->last_exit) ?
"trace" : "bb");
DOSTATS({
if (IS_SHARED_SYSCALLS_TRACE_LINKSTUB(dcontext->last_exit))
STATS_INC(num_shared_syscalls_trace_exits);
else
STATS_INC(num_shared_syscalls_bb_exits);
});
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
# endif
# ifdef HOT_PATCHING_INTERFACE
else if (dcontext->last_exit == get_hot_patch_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from hot patch routine\n");
STATS_INC(num_exits_hot_patch);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
# endif
# ifdef CLIENT_INTERFACE
else if (dcontext->last_exit == get_client_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from client redirection\n");
STATS_INC(num_exits_client_redirect);
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
return;
}
# endif
#ifdef LINUX_KERNEL
else if (dcontext->last_exit == get_syscall_entry_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2,
"Returning to kernel via syscall (i.e., exit from usermode)\n");
STATS_INC(num_syscalls);
if (DYNAMO_OPTION(optimize_sys_call_ret)) {
KSTOP_NOT_PROPAGATED(fcache_default);
} else {
KSTOP_NOT_PROPAGATED(usermode);
}
return;
}
else if (dcontext->last_exit == get_user_interrupt_entry_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2,
"Entry from userspace through an interrupt\n");
STATS_INC(num_exits_interrupts);
KSTOP_NOT_PROPAGATED(user_interrupt_handling);
return;
} else if (dcontext->last_exit == get_kernel_interrupt_entry_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2,
"Entry from kernel through an interrupt\n");
STATS_INC(num_exits_interrupts);
KSTOP_NOT_MATCHING_NOT_PROPAGATED(kernel_interrupt_handling);
return;
}
#endif
/* normal exits from real fragments, though the last_fragment may
* be deleted and we are working off a copy of its important fields
*/
/* FIXME: this lookup is needed for KSTATS and STATS_*. STATS_* are only
* printed at loglevel 1, but maintained at loglevel 0, and if
* we want an external agent to examine them at 0 we will want
* to keep this...leaving for now
*/
next_f = fragment_lookup_fine_and_coarse(dcontext, dcontext->next_tag,
&coarse_f, dcontext->last_exit);
last_f = dcontext->last_fragment;
DOKSTATS({
/* FIXME (case 4988): read top of kstats stack to get src
* type, and then split by last_fragment type as well
*/
KSWITCH_STOP_NOT_PROPAGATED(fcache_default);
});
if (is_ibl_sourceless_linkstub((const linkstub_t*)dcontext->last_exit)) {
if (DYNAMO_OPTION(coarse_units)) {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from coarse ibl from tag "PFX": %s %s",
dcontext->coarse_exit.src_tag,
TEST(FRAG_IS_TRACE, last_f->flags) ? "trace" : "bb",
TEST(LINK_RETURN, dcontext->last_exit->flags) ? "ret" :
TEST(LINK_CALL, dcontext->last_exit->flags) ? "call*" : "jmp*");
} else {
ASSERT(!DYNAMO_OPTION(indirect_stubs));
LOG(THREAD, LOG_DISPATCH, 2, "Exit from sourceless ibl: %s %s",
TEST(FRAG_IS_TRACE, last_f->flags) ? "trace" : "bb",
TEST(LINK_RETURN, dcontext->last_exit->flags) ? "ret" :
TEST(LINK_CALL, dcontext->last_exit->flags) ? "call*" : "jmp*");
}
} else if (dcontext->last_exit == get_coarse_exit_linkstub()) {
DOLOG(2, LOG_DISPATCH, {
coarse_info_t *info = dcontext->coarse_exit.dir_exit;
cache_pc stub;
ASSERT(info != NULL); /* though not initialized to NULL... */
stub = coarse_stub_lookup_by_target(dcontext, info, dcontext->next_tag);
LOG(THREAD, LOG_DISPATCH, 2,
"Exit from sourceless coarse-grain fragment via stub "PFX"\n", stub);
});
/* FIXME: this stat is not mutually exclusive of reason-for-exit stats */
STATS_INC(num_exits_coarse);
}
else if (dcontext->last_exit == get_coarse_trace_head_exit_linkstub()) {
LOG(THREAD, LOG_DISPATCH, 2,
"Exit from sourceless coarse-grain fragment targeting trace head");
/* FIXME: this stat is not mutually exclusive of reason-for-exit stats */
STATS_INC(num_exits_coarse_trace_head);
} else {
LOG(THREAD, LOG_DISPATCH, 2, "Exit from F%d("PFX")."PFX,
last_f->id, last_f->tag, EXIT_CTI_PC(dcontext->last_fragment,
dcontext->last_exit));
}
DOSTATS({
if (TEST(FRAG_IS_TRACE, last_f->flags))
STATS_INC(num_trace_exits);
else
STATS_INC(num_bb_exits);
});
LOG(THREAD, LOG_DISPATCH, 2, "%s",
TEST(FRAG_SHARED, last_f->flags) ? " (shared)":"");
DOLOG(2, LOG_SYMBOLS, {
char symbuf[MAXIMUM_SYMBOL_LENGTH];
print_symbolic_address(last_f->tag, symbuf, sizeof(symbuf), true);
LOG(THREAD, LOG_SYMBOLS, 2, "\t%s\n", symbuf);
});
# if defined(DEBUG) && defined(DGC_DIAGNOSTICS)
if (TEST(FRAG_DYNGEN, last_f->flags) && !is_dyngen_vsyscall(last_f->tag)) {
char buf[MAXIMUM_SYMBOL_LENGTH];
bool stack = is_address_on_stack(dcontext, last_f->tag);
app_pc translated_pc;
print_symbolic_address(dcontext->next_tag, buf, sizeof(buf), false);
LOG(THREAD, LOG_DISPATCH, 1,
"Exit from dyngen F%d("PFX"%s%s) w/ %s targeting "PFX" %s:",
last_f->id, last_f->tag, stack ? " stack":"",
(last_f->flags & FRAG_DYNGEN_RESTRICTED) != 0 ? " BAD":"",
LINKSTUB_DIRECT(dcontext->last_exit->flags) ? "db":"ib",
dcontext->next_tag, buf);
/* FIXME: risky if last fragment is deleted -- should check for that
* here and instead just print type from last_exit, since recreate
* may fail
*/
translated_pc = recreate_app_pc(dcontext, EXIT_CTI_PC(dcontext->last_fragment,
dcontext->last_exit),
dcontext->last_fragment);
if (translated_pc != NULL) {
disassemble(dcontext, translated_pc, THREAD);
LOG(THREAD, LOG_DISPATCH, 1, "\n");
}
DOLOG(stack ? 1U : 2U, LOG_DISPATCH, {
LOG(THREAD, LOG_DISPATCH, 1, "DGC bb:\n");
disassemble_app_bb(dcontext, last_f->tag, THREAD);
});
}
# endif /* defined(DEBUG) && defined(DGC_DIAGNOSTICS) */
if (LINKSTUB_INDIRECT(dcontext->last_exit->flags)) {
#ifdef RETURN_AFTER_CALL
bool ok = false;
#endif
STATS_INC(num_exits_ind_total);
if (next_f == NULL) {
LOG(THREAD, LOG_DISPATCH, 2, " (target "PFX" not in cache)",
dcontext->next_tag);
STATS_INC(num_exits_ind_good_miss);
KSWITCH(num_exits_ind_good_miss);
} else if (is_building_trace(dcontext) &&
!TEST(LINK_LINKED, dcontext->last_exit->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (in trace-building mode)");
STATS_INC(num_exits_ind_trace_build);
} else if (TEST(FRAG_WAS_DELETED, last_f->flags) ||
!INTERNAL_OPTION(link_ibl)) {
LOG(THREAD, LOG_DISPATCH, 2, " (src unlinked)");
STATS_INC(num_exits_ind_src_unlinked);
} else {
LOG(THREAD, LOG_DISPATCH, 2, " (target "PFX" in cache but not lookup table)",
dcontext->next_tag);
STATS_INC(num_exits_ind_bad_miss);
if (TEST(FRAG_IS_TRACE, last_f->flags)) {
STATS_INC(num_exits_ind_bad_miss_trace);
if (next_f && TEST(FRAG_IS_TRACE, next_f->flags)) {
STATS_INC(num_exits_ind_bad_miss_trace2trace);
KSWITCH(num_exits_ind_bad_miss_trace2trace);
} else if (next_f &&
!TEST(FRAG_IS_TRACE, next_f->flags)) {
if (!TEST(FRAG_IS_TRACE_HEAD, next_f->flags)) {
STATS_INC(num_exits_ind_bad_miss_trace2bb_nth);
KSWITCH(num_exits_ind_bad_miss_trace2bb_nth);
} else {
STATS_INC(num_exits_ind_bad_miss_trace2bb_th);
KSWITCH(num_exits_ind_bad_miss_trace2bb_th);
}
}
}
else {
STATS_INC(num_exits_ind_bad_miss_bb);
if (next_f && TEST(FRAG_IS_TRACE, next_f->flags)) {
STATS_INC(num_exits_ind_bad_miss_bb2trace);
KSWITCH(num_exits_ind_bad_miss_bb2trace);
} else if (next_f &&
!TEST(FRAG_IS_TRACE, next_f->flags)) {
DOSTATS({
if (TEST(FRAG_IS_TRACE_HEAD, next_f->flags))
STATS_INC(num_exits_ind_bad_miss_bb2bb_th);
});
STATS_INC(num_exits_ind_bad_miss_bb2bb);
KSWITCH(num_exits_ind_bad_miss_bb2bb);
}
}
}
DOSTATS({
if (!TEST(FRAG_IS_TRACE, last_f->flags))
STATS_INC(num_exits_ind_non_trace);
});
# ifdef RETURN_AFTER_CALL
/* split by ind branch type */
if (TEST(LINK_RETURN, dcontext->last_exit->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (return from "PFX" non-trace tgt "PFX")",
EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit),
dcontext->next_tag);
STATS_INC(num_exits_ret);
DOSTATS({
if (TEST(FRAG_IS_TRACE, last_f->flags))
STATS_INC(num_exits_ret_trace);
});
}
else if (TESTANY(LINK_CALL|LINK_JMP, dcontext->last_exit->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (ind %s from "PFX" non-trace tgt "PFX")",
TEST(LINK_CALL, dcontext->last_exit->flags) ? "call" : "jmp",
EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit),
dcontext->next_tag);
DOSTATS({
if (TEST(LINK_CALL, dcontext->last_exit->flags)) {
STATS_INC(num_exits_ind_call);
} else if (TEST(LINK_JMP, dcontext->last_exit->flags)) {
STATS_INC(num_exits_ind_jmp);
} else
ASSERT_NOT_REACHED();
});
} else if (!ok) {
LOG(THREAD, LOG_DISPATCH, 2,
"WARNING: unknown indirect exit from "PFX", in %s fragment "PFX,
EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit),
(TEST(FRAG_IS_TRACE, last_f->flags)) ? "trace" : "bb",
last_f);
STATS_INC(num_exits_ind_unknown);
ASSERT_NOT_REACHED();
}
# endif /* RETURN_AFTER_CALL */
} else { /* DIRECT LINK */
ASSERT(LINKSTUB_DIRECT(dcontext->last_exit->flags) ||
IS_COARSE_LINKSTUB(dcontext->last_exit));
if (IF_LINUX_KERNEL_ELSE(false,
TESTANY(LINK_NI_SYSCALL_ALL, dcontext->last_exit->flags))) {
LOG(THREAD, LOG_DISPATCH, 2, " (block ends with syscall)");
STATS_INC(num_exits_dir_syscall);
/* FIXME: it doesn't matter whether next_f exists or not we're still in a syscall */
KSWITCH(num_exits_dir_syscall);
}
# ifdef WINDOWS
else if (TEST(LINK_CALLBACK_RETURN, dcontext->last_exit->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (block ends with callback return)");
STATS_INC(num_exits_dir_cbret);
}
# endif
else if (next_f == NULL) {
LOG(THREAD, LOG_DISPATCH, 2, " (target "PFX" not in cache)",
dcontext->next_tag);
STATS_INC(num_exits_dir_miss);
KSWITCH(num_exits_dir_miss);
}
/* for SHARED_FRAGMENTS_ENABLED(), we do not grab the change_linking_lock
* for our is_linkable call since that leads to a lot of
* contention (and we don't want to go to a read-write model
* when most uses, and all non-debug uses, are writes!).
* instead, since we don't want to change state, we have no synch
* at all, which is ok since the state could have changed anyway
* (see comment at end of cases below)
*/
# ifdef DEBUG
else if (IS_COARSE_LINKSTUB(dcontext->last_exit)) {
LOG(THREAD, LOG_DISPATCH, 2, " (not lazily linked yet)");
}
else if (!is_linkable(dcontext, dcontext->last_fragment,
dcontext->last_exit, next_f,
false/*don't own link lock*/,
false/*do not change trace head state*/)) {
STATS_INC(num_exits_dir_nolink);
LOG(THREAD, LOG_DISPATCH, 2, " (cannot link F%d->F%d)",
last_f->id, next_f->id);
if (is_building_trace(dcontext) &&
!TEST(LINK_LINKED, dcontext->last_exit->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (in trace-building mode)");
STATS_INC(num_exits_dir_trace_build);
}
# ifndef TRACE_HEAD_CACHE_INCR
else if (TEST(FRAG_IS_TRACE_HEAD, next_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (target F%d is trace head)",
next_f->id);
STATS_INC(num_exits_dir_trace_head);
}
# endif
else if ((last_f->flags & FRAG_SHARED) != (next_f->flags & FRAG_SHARED)) {
LOG(THREAD, LOG_DISPATCH, 2, " (cannot link shared to private)",
last_f->id, next_f->id);
STATS_INC(num_exits_dir_nolink_sharing);
}
# ifdef DGC_DIAGNOSTICS
else if ((next_f->flags & FRAG_DYNGEN) != (last_f->flags & FRAG_DYNGEN)) {
LOG(THREAD, LOG_DISPATCH, 2, " (cannot link DGC to non-DGC)",
last_f->id, next_f->id);
}
# endif
else if (INTERNAL_OPTION(nolink)) {
LOG(THREAD, LOG_DISPATCH, 2, " (nolink option is on)");
}
else if (!TEST(FRAG_LINKED_OUTGOING, last_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (F%d is unlinked-out)", last_f->id);
}
else if (!TEST(FRAG_LINKED_INCOMING, next_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (F%d is unlinked-in)", next_f->id);
}
else {
LOG(THREAD, LOG_DISPATCH, 2, " (unknown reason)");
/* link info could have changed after we exited cache so
* this is probably not a problem, not much we can do
* to distinguish race from real problem, so no assertion.
* race can happen even w/ single_thread_in_DR.
*/
STATS_INC(num_exits_dir_race);
}
}
# ifdef TRACE_HEAD_CACHE_INCR
else if (TEST(FRAG_IS_TRACE_HEAD, next_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (trace head F%d now hot!)", next_f->id);
STATS_INC(num_exits_dir_trace_hot);
}
# endif
else if (TEST(FRAG_IS_TRACE, next_f->flags) && TEST(FRAG_SHARED, last_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2,
" (shared trace head shadowed by private trace F%d)", next_f->id);
STATS_INC(num_exits_dir_nolink_sharing);
}
else if (dcontext->next_tag == last_f->tag && next_f != last_f) {
/* invisible emission and replacement */
LOG(THREAD, LOG_DISPATCH, 2, " (self-loop in F%d, replaced by F%d)",
last_f->id, next_f->id);
STATS_INC(num_exits_dir_self_replacement);
}
# ifdef LINUX
else if (dcontext->signals_pending) {
/* this may not always be the reason...the interrupted fragment
* field is modularly hidden in linux/signal.c though
*/
LOG(THREAD, LOG_DISPATCH, 2, " (interrupted by delayable signal)");
STATS_INC(num_exits_dir_signal);
}
# endif
# ifdef NATIVE_RETURN
else if (TEST(FRAG_IS_TRACE_HEAD, next_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (returned to old trace head)");
}
# endif
else if (TEST(FRAG_COARSE_GRAIN, next_f->flags) &&
!TEST(FRAG_COARSE_GRAIN, last_f->flags)) {
LOG(THREAD, LOG_DISPATCH, 2, " (fine fragment targeting coarse trace head)");
/* FIXME: We would assert that FRAG_IS_TRACE_HEAD is set, but
* we have no way of setting that up for fine to coarse links
*/
/* stats are done in monitor_cache_enter() */
}
else {
LOG(THREAD, LOG_DISPATCH, 2,
" (UNKNOWN DIRECT EXIT F%d."PFX"->F%d)",
last_f->id, EXIT_CTI_PC(dcontext->last_fragment, dcontext->last_exit),
next_f->id);
/* link info could have changed after we exited cache so
* this is probably not a problem, not much we can do
* to distinguish race from real problem, so no assertion.
* race can happen even w/ single_thread_in_DR.
*/
STATS_INC(num_exits_dir_race);
}
# endif /* DEBUG */
}
if (dcontext->last_exit == get_deleted_linkstub(dcontext)) {
LOG(THREAD, LOG_DISPATCH, 2, " (fragment was flushed)");
}
LOG(THREAD, LOG_DISPATCH, 2, "\n");
DOLOG(5, LOG_DISPATCH, {
dump_mcontext(get_mcontext(dcontext), THREAD, DUMP_NOT_XML); });
DOLOG(6, LOG_DISPATCH, { dump_mcontext_callstack(dcontext); });
DOKSTATS({ DOLOG(6, LOG_DISPATCH, { kstats_dump_stack(dcontext); }); });
# ifdef RETURN_STACK
if (stats->loglevel > 2 && (stats->logmask & LOG_DISPATCH) != 0)
print_return_stack(dcontext);
# endif
# ifdef NATIVE_RETURN_CALLDEPTH
LOG(THREAD, LOG_DISPATCH, 3, "\tCall depth is %d\n",
dcontext->call_depth);
# endif
#endif /* defined(DEBUG) || defined(KSTATS) */
}
/***************************************************************************
* SYSTEM CALLS
*/
#ifdef LINUX
static void
adjust_syscall_continuation(dcontext_t *dcontext)
{
/* PR 212570: for linux sysenter, we hooked the sysenter return-to-user-mode
* point to go to post-do-vsyscall. So we end up here w/o any extra
* work pre-syscall; and since we put the hook-displaced code in the nop
* space immediately after the sysenter instr, which is our normal
* continuation pc, we have no work to do here either!
*/
if (get_syscall_method() == SYSCALL_METHOD_SYSENTER) {
/* we still see some int syscalls (for SYS_clone in particular) */
ASSERT(dcontext->sys_was_int ||
dcontext->asynch_target == vsyscall_syscall_end_pc);
} else if (vsyscall_syscall_end_pc != NULL &&
/* PR 341469: 32-bit apps (LOL64) on AMD hardware have
* OP_syscall in a vsyscall page
*/
get_syscall_method() != SYSCALL_METHOD_SYSCALL) {
/* If we fail to hook we currently bail out to int; but we then
* need to manually jump to the sysenter return point.
* Once we have PR 288330 we can remove this.
*/
if (dcontext->asynch_target == vsyscall_syscall_end_pc) {
ASSERT(vsyscall_sysenter_return_pc != NULL);
dcontext->asynch_target = vsyscall_sysenter_return_pc;
}
}
}
#endif
#ifndef LINUX_KERNEL
/* used to execute a system call instruction in the code cache
* dcontext->next_tag is store elsewhere and restored after the system call
* for resumption of execution post-syscall
*/
void
handle_system_call(dcontext_t *dcontext)
{
fcache_enter_func_t fcache_enter = get_fcache_enter_private_routine(dcontext);
app_pc do_syscall = (app_pc) get_do_syscall_entry(dcontext);
#ifdef CLIENT_INTERFACE
dr_mcontext_t *mc = get_mcontext(dcontext);
bool execute_syscall = true;
#endif
#ifdef WINDOWS
/* make sure to ask about syscall before pre_syscall, which will swap new mc in! */
bool use_prev_dcontext = is_cb_return_syscall(dcontext);
#else
if (TEST(LINK_NI_SYSCALL_INT, dcontext->last_exit->flags)) {
LOG(THREAD, LOG_SYSCALLS, 2, "Using do_int_syscall\n");
do_syscall = (app_pc) get_do_int_syscall_entry(dcontext);
/* last_exit will be for the syscall so set a flag (could alternatively
* set up a separate exit stub but this is simpler) */
dcontext->sys_was_int = true;
# ifdef VMX86_SERVER
if (is_vmkuw_sysnum(mc->xax)) {
/* Even w/ syscall # shift int80 => ENOSYS */
do_syscall = get_do_vmkuw_syscall_entry(dcontext);
LOG(THREAD, LOG_SYSCALLS, 2, "Using do_vmkuw_syscall\n");
}
# endif
} else {
dcontext->sys_was_int = false;
IF_NOT_X64(IF_VMX86(ASSERT(!is_vmkuw_sysnum(mc->xax))));
}
#endif
#ifdef CLIENT_INTERFACE
/* We invoke here rather than inside pre_syscall() primarily so we can
* set use_prev_dcontext(), but also b/c the windows and linux uses
* are identical. We do want this prior to xbp-param changes for linux
* sysenter-to-int (PR 313715) since to client this should
* look like the original sysenter. For Windows we could put this
* after sysenter handling but it's not clear which is better: we'll
* assert if client changes xsp/xdx but that's fine.
*/
/* i#202: ignore native syscalls in early_inject_init() */
if (IF_WINDOWS(dynamo_initialized &&)
!instrument_pre_syscall(dcontext, (int) mc->xax)) {
/* we won't execute post-syscall so we do not need to store
* dcontext->sys_*
*/
execute_syscall = false;
LOG(THREAD, LOG_SYSCALLS, 2, "skipping syscall %d on client request\n",
mc->xax);
}
# ifdef WINDOWS
/* re-set in case client changed the number */
use_prev_dcontext = is_cb_return_syscall(dcontext);
# endif
#endif
/* some syscalls require modifying local memory
* FIXME: move this unprot down to those syscalls to avoid unprot-prot-unprot-prot
* with the new clean dstack design -- though w/ shared_syscalls perhaps most
* syscalls coming through here will need this
*/
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
KSWITCH(num_exits_dir_syscall); /* encapsulates syscall overhead */
LOG(THREAD, LOG_SYSCALLS, 2,
"Entry into do_syscall to execute a non-ignorable system call\n");
#ifdef SIDELINE
/* clear cur-trace field so we don't think cur trace is still running */
sideline_trace = NULL;
#endif
/* our flushing design assumes our syscall handlers are nolinking,
* to avoid multiple-flusher deadlocks
*/
ASSERT(!is_couldbelinking(dcontext));
/* we need to store the next pc since entering the fcache will clobber it
* with the do_syscall entry point.
* we store in a dcontext slot since some syscalls need to view or modify it
* (the asynch ones: sigreturn, ntcontinue, etc., hence the name asynch_target).
* Yes this works with an NtContinue being interrupted in the kernel for an APC --
* we want to know the NtContinue target, there is no other target to remember.
* The only problem is if a syscall that modifies asynch_target fails -- then we
* want the old value, so we store it here.
*/
dcontext->asynch_target = get_fcache_target(dcontext);
#ifdef WINDOWS
if (get_syscall_method() == SYSCALL_METHOD_SYSENTER) {
/* kernel sends control directly to 0x7ffe0304 so we need
* to mangle the return address
*/
/* Ref case 5461 - edx will become top of stack post-syscall */
ASSERT(get_mcontext(dcontext)->xsp == get_mcontext(dcontext)->xdx);
#ifdef HOT_PATCHING_INTERFACE
/* For hotp_only, vsyscall_syscall_end_pc can be NULL as dr will never
* interp a system call. Also, for hotp_only, control can came here
* from native only to do a syscall that was hooked.
*/
ASSERT(!DYNAMO_OPTION(hotp_only) ||
(DYNAMO_OPTION(hotp_only) &&
dcontext->next_tag == BACK_TO_NATIVE_AFTER_SYSCALL));
#else
ASSERT(vsyscall_syscall_end_pc != NULL);
#endif
/* NOTE - the stack mangling must match that of intercept_nt_continue()
* and shared_syscall as not all routines looking at the stack
* differentiate. */
if (dcontext->asynch_target == vsyscall_syscall_end_pc) {
#ifdef HOT_PATCHING_INTERFACE
/* Don't expect to be here for -hotp_only */
ASSERT_CURIOSITY(!DYNAMO_OPTION(hotp_only));
#endif
/* currently pc is the ret after sysenter, we need it to be the return point
* (the ret after the call to the vsyscall sysenter)
* we do not need to keep the old asynch_target -- if we decide not to do
* the syscall we just have to pop the retaddr
*/
dcontext->asynch_target = *((app_pc *)get_mcontext(dcontext)->xsp);
ASSERT(dcontext->thread_record->under_dynamo_control);
} else {
/* else, special case like native_exec_syscall */
LOG(THREAD, LOG_ALL, 2, "post-sysenter target is non-vsyscall "PFX"\n",
dcontext->asynch_target);
ASSERT(DYNAMO_OPTION(native_exec_syscalls) &&
!dcontext->thread_record->under_dynamo_control);
}
/* FIXME A lack of write access to %esp will generate an exception
* originating from DR though it's really an app problem (unless we
* screwed up wildly). Should we call is_writeable(%esp) and force
* a new UNWRITEABLE_MEMORY_EXECUTION_EXCEPTION so that we don't take
* the blame?
*/
if (DYNAMO_OPTION(sygate_sysenter)) {
/* So stack looks like
* esp +0 app_ret_addr
* +4 app_val1
* for the case 5441 Sygate hack the sysenter needs to have a ret
* address that's in ntdll.dll, but we also need to redirect
* control back to do_syscall. So we mangle to
* esp +0 sysenter_ret_address (ret in ntdll)
* +4 after_do_syscall
* dc->sysenter_storage app_val1
* dc->asynch_target app_ret_addr
* After do_syscall we push app_val1 (since stack is popped twice)
* and send control to asynch_target (implicitly doing the
* post_sysenter ret instr).
*/
dcontext->sysenter_storage =
*((app_pc *)(get_mcontext(dcontext)->xsp+XSP_SZ));
*((app_pc *)get_mcontext(dcontext)->xsp) = sysenter_ret_address;
*((app_pc *)(get_mcontext(dcontext)->xsp+XSP_SZ)) =
after_do_syscall_code(dcontext);
} else {
*((app_pc *)get_mcontext(dcontext)->xsp) =
after_do_syscall_code(dcontext);
}
}
#endif
/* first do the pre-system-call */
if (IF_CLIENT_INTERFACE(execute_syscall &&) pre_system_call(dcontext)) {
/* now do the actual syscall instruction */
#ifdef LINUX
/* FIXME: move into some routine inside linux/?
* if so, move #include of sys/syscall.h too
*/
if (is_clone_thread_syscall(dcontext)) {
/* Code for after clone is in generated code do_clone_syscall. */
do_syscall = (app_pc) get_do_clone_syscall_entry(dcontext);
} else if (is_sigreturn_syscall(dcontext)) {
/* HACK: sigreturn goes straight to fcache_return, which expects
* app eax to already be in mcontext. pre-syscall cannot do that since
* do_syscall needs the syscall num in eax!
* so we have to do it here (alternative is to be like NtContinue handling
* with a special entry point, ends up being same sort of thing as here)
*/
/* pre-sigreturn handler put dest eax in next_tag
* save it in sys_param1, which is not used already in pre/post
*/
/* for CLIENT_INTERFACE, pre-sigreturn handler took eax after
* client had chance to change it, so we have the proper value here.
*/
dcontext->sys_param1 = (reg_t) dcontext->next_tag;
}
#else
if (use_prev_dcontext) {
/* get the current, but now swapped out, dcontext */
dcontext_t *tmp_dcontext = dcontext;
LOG(THREAD, LOG_SYSCALLS, 1, "handling a callback return\n");
dcontext = get_prev_swapped_dcontext(tmp_dcontext);
LOG(THREAD, LOG_SYSCALLS, 1, "swapped dcontext from "PFX" to "PFX"\n",
tmp_dcontext, dcontext);
/* we have special fcache_enter that uses different dcontext,
* FIXME: but what if syscall fails? need to unswap dcontexts!
*/
fcache_enter = get_fcache_enter_indirect_routine(dcontext);
/* avoid synch errors with dispatch -- since enter_fcache will set
* whereami for prev dcontext, not real one!
*/
tmp_dcontext->whereami = WHERE_FCACHE;
}
#endif
SELF_PROTECT_LOCAL(dcontext, READONLY);
set_at_syscall(dcontext, true);
KSTART(syscall_fcache); /* stopped in dispatch_exit_fcache_stats */
enter_fcache(dcontext, fcache_enter, do_syscall);
/* will handle post processing in handle_post_system_call */
ASSERT_NOT_REACHED();
}
else {
#ifdef CLIENT_INTERFACE
/* give the client its post-syscall event since we won't be calling
* post_system_call(), unless the client itself was the one who skipped.
*/
if (execute_syscall) {
instrument_post_syscall(dcontext, dcontext->sys_num);
}
#endif
#ifdef WINDOWS
if (get_syscall_method() == SYSCALL_METHOD_SYSENTER) {
/* decided to skip syscall -- pop retaddr, restore sysenter storage
* (if applicable) and set next target */
get_mcontext(dcontext)->xsp += XSP_SZ;
if (DYNAMO_OPTION(sygate_sysenter)) {
*((app_pc *)get_mcontext(dcontext)->xsp) =
dcontext->sysenter_storage;
}
set_fcache_target(dcontext, dcontext->asynch_target);
} else if (get_syscall_method() == SYSCALL_METHOD_WOW64 &&
get_os_version() >= WINDOWS_VERSION_7) {
/* win7 has an add 4,esp after the call* in the syscall wrapper,
* so we need to negate it since not making the call*
*/
get_mcontext(dcontext)->xsp -= XSP_SZ;
}
#else
adjust_syscall_continuation(dcontext);
set_fcache_target(dcontext, dcontext->asynch_target);
#endif
}
SELF_PROTECT_LOCAL(dcontext, READONLY);
}
#endif
static void
handle_post_system_call(dcontext_t *dcontext)
{
dr_mcontext_t *mc = get_mcontext(dcontext);
ASSERT(!is_couldbelinking(dcontext));
ASSERT(get_at_syscall(dcontext));
set_at_syscall(dcontext, false);
/* some syscalls require modifying local memory */
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
#ifdef LINUX
/* restore mcontext values prior to invoking instrument_post_syscall() */
if (was_sigreturn_syscall(dcontext)) {
/* restore app xax */
mc->xax = dcontext->sys_param1;
}
#endif
post_system_call(dcontext);
/* restore state for continuation in instruction after syscall */
/* FIXME: need to handle syscall failure -- those that clobbered asynch_target
* need to restore it to its previous value, which has to be stored somewhere!
*/
#ifdef WINDOWS
if (DYNAMO_OPTION(sygate_sysenter) &&
get_syscall_method() == SYSCALL_METHOD_SYSENTER) {
/* restore sysenter_storage, note stack was popped twice for
* syscall so need to push the value */
get_mcontext(dcontext)->xsp -= XSP_SZ;
*((app_pc *)get_mcontext(dcontext)->xsp) = dcontext->sysenter_storage;
}
#else
adjust_syscall_continuation(dcontext);
#endif
set_fcache_target(dcontext, dcontext->asynch_target);
#ifdef WINDOWS
/* We no longer need asynch_target so zero it out. Other pieces of DR
* -- callback & APC handling, detach -- test asynch_target to determine
* where the next app pc to execute is stored. If asynch_target != 0,
* it holds the value, else it's in the esi slot.
*/
dcontext->asynch_target = 0;
#endif
LOG(THREAD, LOG_SYSCALLS, 3, "finished handling system call\n");
SELF_PROTECT_LOCAL(dcontext, READONLY);
/* caller will go back to couldbelinking status */
}
#ifdef WINDOWS
/* in callback.c */
extern void callback_start_return(int app_errno, dr_mcontext_t *mc);
/* used to execute an int 2b instruction in code cache */
static void
handle_callback_return(dcontext_t *dcontext)
{
dcontext_t *prev_dcontext;
dr_mcontext_t *mc = get_mcontext(dcontext);
fcache_enter_func_t fcache_enter = get_fcache_enter_indirect_routine(dcontext);
LOG(THREAD, LOG_ASYNCH, 3, "handling a callback return\n");
/* may have to abort trace -> local heap */
SELF_PROTECT_LOCAL(dcontext, WRITABLE);
KSWITCH(num_exits_dir_cbret);
callback_start_return(dcontext->app_errno, mc);
/* get the current, but now swapped out, dcontext */
prev_dcontext = get_prev_swapped_dcontext(dcontext);
SELF_PROTECT_LOCAL(dcontext, READONLY);
/* obey flushing protocol, plus set whereami (both using real dcontext) */
dcontext->whereami = WHERE_FCACHE;
set_at_syscall(dcontext, true); /* will be set to false on other end's post-syscall */
ASSERT(!is_couldbelinking(dcontext));
/* if we get an APC it should be after returning to prev cxt, so don't need
* to worry about asynch_target
*/
/* make sure set the next_tag of prev_dcontext, not dcontext! */
set_fcache_target(prev_dcontext, (app_pc) get_do_callback_return_entry(prev_dcontext));
DOLOG(4, LOG_ASYNCH, {
LOG(THREAD, LOG_ASYNCH, 3, "passing prev dcontext "PFX", next_tag "PFX":\n",
prev_dcontext, prev_dcontext->next_tag);
dump_mcontext(get_mcontext(prev_dcontext), THREAD, DUMP_NOT_XML);
});
/* make sure to pass prev_dcontext, this is a special fcache enter routine
* that indirects through the dcontext passed to it (so ignores the switch-to
* dcontext that callback_start_return swapped into the main dcontext)
*/
KSTART(syscall_fcache); /* continue the interrupted syscall handling */
(*fcache_enter)(prev_dcontext);
/* callback return does not return to here! */
DOLOG(1, LOG_ASYNCH, {
LOG(THREAD, LOG_SYSCALLS, 1, "ERROR: int 2b returned!\n");
dump_mcontext(get_mcontext(dcontext), THREAD, DUMP_NOT_XML);
});
ASSERT_NOT_REACHED();
}
#endif /* WINDOWS */
/* used to execute a system call instruction in code cache
* not expected to return
* caller must set up mcontext with proper system call number and arguments
*/
void
issue_last_system_call_from_app(dcontext_t *dcontext)
{
LOG(THREAD, LOG_SYSCALLS, 2, "issue_last_system_call_from_app("PIFX")\n",
get_mcontext(dcontext)->xax);
/* it's up to the caller to let go of the bb building lock if it was held
* on this path, since not all paths to here hold it
*/
if (is_couldbelinking(dcontext))
enter_nolinking(dcontext, NULL, true);
KSTART(syscall_fcache); /* stopped in dispatch_exit_fcache_stats */
enter_fcache(dcontext, get_fcache_enter_private_routine(dcontext),
(app_pc) get_global_do_syscall_entry());
ASSERT_NOT_REACHED();
}
/* Stores the register parameters into the mcontext and calls dispatch.
* Checks whether currently on initstack and if so clears the initstack_mutex.
* Does not return.
*/
void
transfer_to_dispatch(dcontext_t *dcontext, int app_errno, dr_mcontext_t *mc)
{
app_pc cur_xsp;
int using_initstack = 0;
copy_mcontext(mc, get_mcontext(dcontext));
dcontext->app_errno = app_errno;
GET_STACK_PTR(cur_xsp);
if (is_on_initstack(cur_xsp))
using_initstack = 1;
#if defined(WINDOWS) && defined(CLIENT_INTERFACE)
/* i#249: swap PEB pointers */
if (INTERNAL_OPTION(private_peb) && should_swap_peb_pointer())
swap_peb_pointer(dcontext, true/*to priv*/);
#endif
LOG(THREAD, LOG_ASYNCH, 2,
"transfer_to_dispatch: pc=0x%08x, xsp="PFX", initstack=%d\n",
dcontext->next_tag, mc->xsp, using_initstack);
/* next, want to switch to dstack, and if using initstack, free mutex.
* finally, call dispatch(dcontext).
* note that we switch to the base of dstack, deliberately squashing
* what may have been there before, for both new dcontext and reuse dcontext
* options.
*/
call_switch_stack(dcontext, dcontext->dstack, dispatch, using_initstack,
false/*do not return on error*/);
ASSERT_NOT_REACHED();
}
| DynamoRIO/drk | core/dispatch.c | C | bsd-3-clause | 93,977 |
#!/usr/bin/env python3
import logging
from . import SubprocessHook
logger = logging.getLogger("barython")
class PulseAudioHook(SubprocessHook):
"""
Listen on pulseaudio events with pactl
"""
def __init__(self, cmd=["pactl", "subscribe", "-n", "barython"],
*args, **kwargs):
super().__init__(*args, **kwargs, cmd=cmd)
| Anthony25/barython | barython/hooks/audio.py | Python | bsd-3-clause | 363 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef MEDIA_GPU_V4L2_V4L2_VP8_ACCELERATOR_H_
#define MEDIA_GPU_V4L2_V4L2_VP8_ACCELERATOR_H_
#include <vector>
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "media/gpu/vp8_decoder.h"
namespace media {
class V4L2Device;
class V4L2DecodeSurface;
class V4L2DecodeSurfaceHandler;
class V4L2VP8Accelerator : public VP8Decoder::VP8Accelerator {
public:
explicit V4L2VP8Accelerator(V4L2DecodeSurfaceHandler* surface_handler,
V4L2Device* device);
~V4L2VP8Accelerator() override;
// VP8Decoder::VP8Accelerator implementation.
scoped_refptr<VP8Picture> CreateVP8Picture() override;
bool SubmitDecode(scoped_refptr<VP8Picture> pic,
const Vp8ReferenceFrameVector& reference_frames) override;
bool OutputPicture(scoped_refptr<VP8Picture> pic) override;
private:
scoped_refptr<V4L2DecodeSurface> VP8PictureToV4L2DecodeSurface(
VP8Picture* pic);
V4L2DecodeSurfaceHandler* const surface_handler_;
V4L2Device* const device_;
DISALLOW_COPY_AND_ASSIGN(V4L2VP8Accelerator);
};
} // namespace media
#endif // MEDIA_GPU_V4L2_V4L2_VP8_ACCELERATOR_H_
| endlessm/chromium-browser | media/gpu/v4l2/v4l2_vp8_accelerator.h | C | bsd-3-clause | 1,312 |
#include "memcache_client_base.h"
#include "vbucket_config.h"
#include "evpp/event_loop_thread_pool.h"
#include "likely.h"
#include <mutex>
namespace evmc {
MemcacheClientBase::~MemcacheClientBase() {
delete load_loop_;
delete load_thread_;
delete vbconf_1_;
delete vbconf_2_;
}
void MemcacheClientBase::Stop() {
if (load_loop_) {
load_loop_->Stop();
}
if (load_thread_) {
load_thread_->join();
}
}
void MemcacheClientBase::DoReloadConf() {
MultiModeVbucketConfig* vbconf = nullptr;
if (vbconf_cur_ == vbconf_1_) {
vbconf = vbconf_2_;
vbconf_2_->clear();
} else {
vbconf = vbconf_1_;
vbconf_1_->clear();
}
bool success = vbconf->Load(vbucket_conf_.c_str());
if (success) {
std::lock_guard<std::mutex> lck(vbucket_config_mutex_);
vbconf_cur_ = vbconf;
LOG_DEBUG << "DoReloadConf load ok, file=" << vbucket_conf_;
} else {
LOG_WARN << "DoReloadConf load err, file=" << vbucket_conf_;
}
return;
}
MultiModeVbucketConfig* MemcacheClientBase::vbucket_config() {
std::lock_guard<std::mutex> lck(vbucket_config_mutex_);
auto ret = vbconf_cur_;
return ret;
}
void MemcacheClientBase::LoadThread() {
load_loop_->Run();
LOG_ERROR << "load thread exit...";
}
void MemcacheClientBase::BuilderMemClient(evpp::EventLoop* loop, std::string& server, std::map<std::string, MemcacheClientPtr>& client_map, const int timeout_ms) {
evpp::TCPClient* tcp_client = new evpp::TCPClient(loop, server, "evmc");
MemcacheClientPtr memc_client = std::make_shared<MemcacheClient>(loop, tcp_client, this, timeout_ms);
LOG_INFO << "Start new tcp_client=" << tcp_client << " server=" << server << " timeout=" << timeout_ms;
tcp_client->SetConnectionCallback(std::bind(&MemcacheClientBase::OnClientConnection, this,
std::placeholders::_1, memc_client));
tcp_client->SetMessageCallback(std::bind(&MemcacheClient::OnResponseData, memc_client,
std::placeholders::_1, std::placeholders::_2));
tcp_client->Connect();
client_map.emplace(server, memc_client);
}
MemcacheClientBase::MemcacheClientBase(const char* vbucket_conf): vbucket_conf_(vbucket_conf), load_loop_(nullptr)
, load_thread_(nullptr), vbconf_cur_(nullptr), vbconf_1_(new MultiModeVbucketConfig()), vbconf_2_(new MultiModeVbucketConfig()) {
assert(vbconf_1_);
assert(vbconf_2_);
}
bool MemcacheClientBase::Start(bool is_reload) {
if (is_reload) {
load_loop_ = new evpp::EventLoop();
assert(load_loop_);
if (!vbconf_2_->Load(vbucket_conf_.c_str())) {
LOG_ERROR << "load error .file=" << vbucket_conf_;
delete load_loop_;
return false;
}
vbconf_cur_ = vbconf_2_;
/*load_thread_ = new std::thread(MemcacheClientBase::LoadThread, this);
assert(load_thread_);
evpp::Duration reload_delay(120.0);
while(!load_loop_->running()) {
usleep(1000);
}
load_loop_->RunEvery(reload_delay, std::bind(&MemcacheClientBase::DoReloadConf, this));*/
}
return true;
}
void MemcacheClientBase::OnClientConnection(const evpp::TCPConnPtr& conn, MemcacheClientPtr memc_client) {
LOG_INFO << "OnClientConnection conn=" << conn.get() << " memc_conn=" << memc_client->conn().get();
if (conn && conn->IsConnected()) {
LOG_INFO << "OnClientConnection connect ok";
CommandPtr command;
while (command = memc_client->PopWaitingCommand()) {
memc_client->PushRunningCommand(command);
command->Launch(memc_client);
}
} else {
if (conn) {
LOG_INFO << "Disconnected from " << conn->remote_addr();
} else {
LOG_INFO << "Connect init error";
}
CommandPtr command;
while (command = memc_client->PopRunningCommand()) {
if (command->ShouldRetry()) {
command->set_id(0);
command->set_server_id(command->server_id());
memc_client->exec_loop()->RunInLoop(std::bind(&MemcacheClientBase::LaunchCommand, this, command));
} else {
command->OnError(ERR_CODE_NETWORK);
}
}
while (command = memc_client->PopWaitingCommand()) {
if (command->ShouldRetry()) {
command->set_id(0);
command->set_server_id(command->server_id());
memc_client->exec_loop()->RunInLoop(std::bind(&MemcacheClientBase::LaunchCommand, this, command));
} else {
command->OnError(ERR_CODE_NETWORK);
}
}
}
}
}
| Qihoo360/evpp | apps/evmc/memcache_client_base.cc | C++ | bsd-3-clause | 4,782 |
//
// NotificationsTestSuite.cpp
//
// $Id$
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#include "NotificationsTestSuite.h"
#include "NotificationCenterTest.h"
#include "NotificationQueueTest.h"
#include "PriorityNotificationQueueTest.h"
#include "TimedNotificationQueueTest.h"
CppUnit::Test* NotificationsTestSuite::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("NotificationsTestSuite");
pSuite->addTest(NotificationCenterTest::suite());
pSuite->addTest(NotificationQueueTest::suite());
pSuite->addTest(PriorityNotificationQueueTest::suite());
pSuite->addTest(TimedNotificationQueueTest::suite());
return pSuite;
}
| nocnokneo/MITK | Utilities/Poco/Foundation/testsuite/src/NotificationsTestSuite.cpp | C++ | bsd-3-clause | 2,049 |
// Copyright 2012 Google, gopacket.LayerTypeMetadata{Inc. All rights reserved}.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
package layers
import (
"github.com/google/gopacket"
)
var (
LayerTypeARP = gopacket.RegisterLayerType(10, gopacket.LayerTypeMetadata{"ARP", gopacket.DecodeFunc(decodeARP)})
LayerTypeCiscoDiscovery = gopacket.RegisterLayerType(11, gopacket.LayerTypeMetadata{"CiscoDiscovery", gopacket.DecodeFunc(decodeCiscoDiscovery)})
LayerTypeEthernetCTP = gopacket.RegisterLayerType(12, gopacket.LayerTypeMetadata{"EthernetCTP", gopacket.DecodeFunc(decodeEthernetCTP)})
LayerTypeEthernetCTPForwardData = gopacket.RegisterLayerType(13, gopacket.LayerTypeMetadata{"EthernetCTPForwardData", nil})
LayerTypeEthernetCTPReply = gopacket.RegisterLayerType(14, gopacket.LayerTypeMetadata{"EthernetCTPReply", nil})
LayerTypeDot1Q = gopacket.RegisterLayerType(15, gopacket.LayerTypeMetadata{"Dot1Q", gopacket.DecodeFunc(decodeDot1Q)})
LayerTypeEtherIP = gopacket.RegisterLayerType(16, gopacket.LayerTypeMetadata{"EtherIP", gopacket.DecodeFunc(decodeEtherIP)})
LayerTypeEthernet = gopacket.RegisterLayerType(17, gopacket.LayerTypeMetadata{"Ethernet", gopacket.DecodeFunc(decodeEthernet)})
LayerTypeGRE = gopacket.RegisterLayerType(18, gopacket.LayerTypeMetadata{"GRE", gopacket.DecodeFunc(decodeGRE)})
LayerTypeICMPv4 = gopacket.RegisterLayerType(19, gopacket.LayerTypeMetadata{"ICMPv4", gopacket.DecodeFunc(decodeICMPv4)})
LayerTypeIPv4 = gopacket.RegisterLayerType(20, gopacket.LayerTypeMetadata{"IPv4", gopacket.DecodeFunc(decodeIPv4)})
LayerTypeIPv6 = gopacket.RegisterLayerType(21, gopacket.LayerTypeMetadata{"IPv6", gopacket.DecodeFunc(decodeIPv6)})
LayerTypeLLC = gopacket.RegisterLayerType(22, gopacket.LayerTypeMetadata{"LLC", gopacket.DecodeFunc(decodeLLC)})
LayerTypeSNAP = gopacket.RegisterLayerType(23, gopacket.LayerTypeMetadata{"SNAP", gopacket.DecodeFunc(decodeSNAP)})
LayerTypeMPLS = gopacket.RegisterLayerType(24, gopacket.LayerTypeMetadata{"MPLS", gopacket.DecodeFunc(decodeMPLS)})
LayerTypePPP = gopacket.RegisterLayerType(25, gopacket.LayerTypeMetadata{"PPP", gopacket.DecodeFunc(decodePPP)})
LayerTypePPPoE = gopacket.RegisterLayerType(26, gopacket.LayerTypeMetadata{"PPPoE", gopacket.DecodeFunc(decodePPPoE)})
LayerTypeRUDP = gopacket.RegisterLayerType(27, gopacket.LayerTypeMetadata{"RUDP", gopacket.DecodeFunc(decodeRUDP)})
LayerTypeSCTP = gopacket.RegisterLayerType(28, gopacket.LayerTypeMetadata{"SCTP", gopacket.DecodeFunc(decodeSCTP)})
LayerTypeSCTPUnknownChunkType = gopacket.RegisterLayerType(29, gopacket.LayerTypeMetadata{"SCTPUnknownChunkType", nil})
LayerTypeSCTPData = gopacket.RegisterLayerType(30, gopacket.LayerTypeMetadata{"SCTPData", nil})
LayerTypeSCTPInit = gopacket.RegisterLayerType(31, gopacket.LayerTypeMetadata{"SCTPInit", nil})
LayerTypeSCTPSack = gopacket.RegisterLayerType(32, gopacket.LayerTypeMetadata{"SCTPSack", nil})
LayerTypeSCTPHeartbeat = gopacket.RegisterLayerType(33, gopacket.LayerTypeMetadata{"SCTPHeartbeat", nil})
LayerTypeSCTPError = gopacket.RegisterLayerType(34, gopacket.LayerTypeMetadata{"SCTPError", nil})
LayerTypeSCTPShutdown = gopacket.RegisterLayerType(35, gopacket.LayerTypeMetadata{"SCTPShutdown", nil})
LayerTypeSCTPShutdownAck = gopacket.RegisterLayerType(36, gopacket.LayerTypeMetadata{"SCTPShutdownAck", nil})
LayerTypeSCTPCookieEcho = gopacket.RegisterLayerType(37, gopacket.LayerTypeMetadata{"SCTPCookieEcho", nil})
LayerTypeSCTPEmptyLayer = gopacket.RegisterLayerType(38, gopacket.LayerTypeMetadata{"SCTPEmptyLayer", nil})
LayerTypeSCTPInitAck = gopacket.RegisterLayerType(39, gopacket.LayerTypeMetadata{"SCTPInitAck", nil})
LayerTypeSCTPHeartbeatAck = gopacket.RegisterLayerType(40, gopacket.LayerTypeMetadata{"SCTPHeartbeatAck", nil})
LayerTypeSCTPAbort = gopacket.RegisterLayerType(41, gopacket.LayerTypeMetadata{"SCTPAbort", nil})
LayerTypeSCTPShutdownComplete = gopacket.RegisterLayerType(42, gopacket.LayerTypeMetadata{"SCTPShutdownComplete", nil})
LayerTypeSCTPCookieAck = gopacket.RegisterLayerType(43, gopacket.LayerTypeMetadata{"SCTPCookieAck", nil})
LayerTypeTCP = gopacket.RegisterLayerType(44, gopacket.LayerTypeMetadata{"TCP", gopacket.DecodeFunc(decodeTCP)})
LayerTypeUDP = gopacket.RegisterLayerType(45, gopacket.LayerTypeMetadata{"UDP", gopacket.DecodeFunc(decodeUDP)})
LayerTypeIPv6HopByHop = gopacket.RegisterLayerType(46, gopacket.LayerTypeMetadata{"IPv6HopByHop", gopacket.DecodeFunc(decodeIPv6HopByHop)})
LayerTypeIPv6Routing = gopacket.RegisterLayerType(47, gopacket.LayerTypeMetadata{"IPv6Routing", gopacket.DecodeFunc(decodeIPv6Routing)})
LayerTypeIPv6Fragment = gopacket.RegisterLayerType(48, gopacket.LayerTypeMetadata{"IPv6Fragment", gopacket.DecodeFunc(decodeIPv6Fragment)})
LayerTypeIPv6Destination = gopacket.RegisterLayerType(49, gopacket.LayerTypeMetadata{"IPv6Destination", gopacket.DecodeFunc(decodeIPv6Destination)})
LayerTypeIPSecAH = gopacket.RegisterLayerType(50, gopacket.LayerTypeMetadata{"IPSecAH", gopacket.DecodeFunc(decodeIPSecAH)})
LayerTypeIPSecESP = gopacket.RegisterLayerType(51, gopacket.LayerTypeMetadata{"IPSecESP", gopacket.DecodeFunc(decodeIPSecESP)})
LayerTypeUDPLite = gopacket.RegisterLayerType(52, gopacket.LayerTypeMetadata{"UDPLite", gopacket.DecodeFunc(decodeUDPLite)})
LayerTypeFDDI = gopacket.RegisterLayerType(53, gopacket.LayerTypeMetadata{"FDDI", gopacket.DecodeFunc(decodeFDDI)})
LayerTypeLoopback = gopacket.RegisterLayerType(54, gopacket.LayerTypeMetadata{"Loopback", gopacket.DecodeFunc(decodeLoopback)})
LayerTypeEAP = gopacket.RegisterLayerType(55, gopacket.LayerTypeMetadata{"EAP", gopacket.DecodeFunc(decodeEAP)})
LayerTypeEAPOL = gopacket.RegisterLayerType(56, gopacket.LayerTypeMetadata{"EAPOL", gopacket.DecodeFunc(decodeEAPOL)})
LayerTypeICMPv6 = gopacket.RegisterLayerType(57, gopacket.LayerTypeMetadata{"ICMPv6", gopacket.DecodeFunc(decodeICMPv6)})
LayerTypeLinkLayerDiscovery = gopacket.RegisterLayerType(58, gopacket.LayerTypeMetadata{"LinkLayerDiscovery", gopacket.DecodeFunc(decodeLinkLayerDiscovery)})
LayerTypeCiscoDiscoveryInfo = gopacket.RegisterLayerType(59, gopacket.LayerTypeMetadata{"CiscoDiscoveryInfo", gopacket.DecodeFunc(decodeCiscoDiscoveryInfo)})
LayerTypeLinkLayerDiscoveryInfo = gopacket.RegisterLayerType(60, gopacket.LayerTypeMetadata{"LinkLayerDiscoveryInfo", nil})
LayerTypeNortelDiscovery = gopacket.RegisterLayerType(61, gopacket.LayerTypeMetadata{"NortelDiscovery", gopacket.DecodeFunc(decodeNortelDiscovery)})
LayerTypeIGMP = gopacket.RegisterLayerType(62, gopacket.LayerTypeMetadata{"IGMP", gopacket.DecodeFunc(decodeIGMP)})
LayerTypePFLog = gopacket.RegisterLayerType(63, gopacket.LayerTypeMetadata{"PFLog", gopacket.DecodeFunc(decodePFLog)})
LayerTypeRadioTap = gopacket.RegisterLayerType(64, gopacket.LayerTypeMetadata{"RadioTap", gopacket.DecodeFunc(decodeRadioTap)})
LayerTypeDot11 = gopacket.RegisterLayerType(65, gopacket.LayerTypeMetadata{"Dot11", gopacket.DecodeFunc(decodeDot11)})
LayerTypeDot11Ctrl = gopacket.RegisterLayerType(66, gopacket.LayerTypeMetadata{"Dot11Ctrl", gopacket.DecodeFunc(decodeDot11Ctrl)})
LayerTypeDot11Data = gopacket.RegisterLayerType(67, gopacket.LayerTypeMetadata{"Dot11Data", gopacket.DecodeFunc(decodeDot11Data)})
LayerTypeDot11DataCFAck = gopacket.RegisterLayerType(68, gopacket.LayerTypeMetadata{"Dot11DataCFAck", gopacket.DecodeFunc(decodeDot11DataCFAck)})
LayerTypeDot11DataCFPoll = gopacket.RegisterLayerType(69, gopacket.LayerTypeMetadata{"Dot11DataCFPoll", gopacket.DecodeFunc(decodeDot11DataCFPoll)})
LayerTypeDot11DataCFAckPoll = gopacket.RegisterLayerType(70, gopacket.LayerTypeMetadata{"Dot11DataCFAckPoll", gopacket.DecodeFunc(decodeDot11DataCFAckPoll)})
LayerTypeDot11DataNull = gopacket.RegisterLayerType(71, gopacket.LayerTypeMetadata{"Dot11DataNull", gopacket.DecodeFunc(decodeDot11DataNull)})
LayerTypeDot11DataCFAckNoData = gopacket.RegisterLayerType(72, gopacket.LayerTypeMetadata{"Dot11DataCFAck", gopacket.DecodeFunc(decodeDot11DataCFAck)})
LayerTypeDot11DataCFPollNoData = gopacket.RegisterLayerType(73, gopacket.LayerTypeMetadata{"Dot11DataCFPoll", gopacket.DecodeFunc(decodeDot11DataCFPoll)})
LayerTypeDot11DataCFAckPollNoData = gopacket.RegisterLayerType(74, gopacket.LayerTypeMetadata{"Dot11DataCFAckPoll", gopacket.DecodeFunc(decodeDot11DataCFAckPoll)})
LayerTypeDot11DataQOSData = gopacket.RegisterLayerType(75, gopacket.LayerTypeMetadata{"Dot11DataQOSData", gopacket.DecodeFunc(decodeDot11DataQOSData)})
LayerTypeDot11DataQOSDataCFAck = gopacket.RegisterLayerType(76, gopacket.LayerTypeMetadata{"Dot11DataQOSDataCFAck", gopacket.DecodeFunc(decodeDot11DataQOSDataCFAck)})
LayerTypeDot11DataQOSDataCFPoll = gopacket.RegisterLayerType(77, gopacket.LayerTypeMetadata{"Dot11DataQOSDataCFPoll", gopacket.DecodeFunc(decodeDot11DataQOSDataCFPoll)})
LayerTypeDot11DataQOSDataCFAckPoll = gopacket.RegisterLayerType(78, gopacket.LayerTypeMetadata{"Dot11DataQOSDataCFAckPoll", gopacket.DecodeFunc(decodeDot11DataQOSDataCFAckPoll)})
LayerTypeDot11DataQOSNull = gopacket.RegisterLayerType(79, gopacket.LayerTypeMetadata{"Dot11DataQOSNull", gopacket.DecodeFunc(decodeDot11DataQOSNull)})
LayerTypeDot11DataQOSCFPollNoData = gopacket.RegisterLayerType(80, gopacket.LayerTypeMetadata{"Dot11DataQOSCFPoll", gopacket.DecodeFunc(decodeDot11DataQOSCFPollNoData)})
LayerTypeDot11DataQOSCFAckPollNoData = gopacket.RegisterLayerType(81, gopacket.LayerTypeMetadata{"Dot11DataQOSCFAckPoll", gopacket.DecodeFunc(decodeDot11DataQOSCFAckPollNoData)})
LayerTypeDot11InformationElement = gopacket.RegisterLayerType(82, gopacket.LayerTypeMetadata{"Dot11InformationElement", gopacket.DecodeFunc(decodeDot11InformationElement)})
LayerTypeDot11CtrlCTS = gopacket.RegisterLayerType(83, gopacket.LayerTypeMetadata{"Dot11CtrlCTS", gopacket.DecodeFunc(decodeDot11CtrlCTS)})
LayerTypeDot11CtrlRTS = gopacket.RegisterLayerType(84, gopacket.LayerTypeMetadata{"Dot11CtrlRTS", gopacket.DecodeFunc(decodeDot11CtrlRTS)})
LayerTypeDot11CtrlBlockAckReq = gopacket.RegisterLayerType(85, gopacket.LayerTypeMetadata{"Dot11CtrlBlockAckReq", gopacket.DecodeFunc(decodeDot11CtrlBlockAckReq)})
LayerTypeDot11CtrlBlockAck = gopacket.RegisterLayerType(86, gopacket.LayerTypeMetadata{"Dot11CtrlBlockAck", gopacket.DecodeFunc(decodeDot11CtrlBlockAck)})
LayerTypeDot11CtrlPowersavePoll = gopacket.RegisterLayerType(87, gopacket.LayerTypeMetadata{"Dot11CtrlPowersavePoll", gopacket.DecodeFunc(decodeDot11CtrlPowersavePoll)})
LayerTypeDot11CtrlAck = gopacket.RegisterLayerType(88, gopacket.LayerTypeMetadata{"Dot11CtrlAck", gopacket.DecodeFunc(decodeDot11CtrlAck)})
LayerTypeDot11CtrlCFEnd = gopacket.RegisterLayerType(89, gopacket.LayerTypeMetadata{"Dot11CtrlCFEnd", gopacket.DecodeFunc(decodeDot11CtrlCFEnd)})
LayerTypeDot11CtrlCFEndAck = gopacket.RegisterLayerType(90, gopacket.LayerTypeMetadata{"Dot11CtrlCFEndAck", gopacket.DecodeFunc(decodeDot11CtrlCFEndAck)})
LayerTypeDot11MgmtAssociationReq = gopacket.RegisterLayerType(91, gopacket.LayerTypeMetadata{"Dot11MgmtAssociationReq", gopacket.DecodeFunc(decodeDot11MgmtAssociationReq)})
LayerTypeDot11MgmtAssociationResp = gopacket.RegisterLayerType(92, gopacket.LayerTypeMetadata{"Dot11MgmtAssociationResp", gopacket.DecodeFunc(decodeDot11MgmtAssociationResp)})
LayerTypeDot11MgmtReassociationReq = gopacket.RegisterLayerType(93, gopacket.LayerTypeMetadata{"Dot11MgmtReassociationReq", gopacket.DecodeFunc(decodeDot11MgmtReassociationReq)})
LayerTypeDot11MgmtReassociationResp = gopacket.RegisterLayerType(94, gopacket.LayerTypeMetadata{"Dot11MgmtReassociationResp", gopacket.DecodeFunc(decodeDot11MgmtReassociationResp)})
LayerTypeDot11MgmtProbeReq = gopacket.RegisterLayerType(95, gopacket.LayerTypeMetadata{"Dot11MgmtProbeReq", gopacket.DecodeFunc(decodeDot11MgmtProbeReq)})
LayerTypeDot11MgmtProbeResp = gopacket.RegisterLayerType(96, gopacket.LayerTypeMetadata{"Dot11MgmtProbeResp", gopacket.DecodeFunc(decodeDot11MgmtProbeResp)})
LayerTypeDot11MgmtMeasurementPilot = gopacket.RegisterLayerType(97, gopacket.LayerTypeMetadata{"Dot11MgmtMeasurementPilot", gopacket.DecodeFunc(decodeDot11MgmtMeasurementPilot)})
LayerTypeDot11MgmtBeacon = gopacket.RegisterLayerType(98, gopacket.LayerTypeMetadata{"Dot11MgmtBeacon", gopacket.DecodeFunc(decodeDot11MgmtBeacon)})
LayerTypeDot11MgmtATIM = gopacket.RegisterLayerType(99, gopacket.LayerTypeMetadata{"Dot11MgmtATIM", gopacket.DecodeFunc(decodeDot11MgmtATIM)})
LayerTypeDot11MgmtDisassociation = gopacket.RegisterLayerType(100, gopacket.LayerTypeMetadata{"Dot11MgmtDisassociation", gopacket.DecodeFunc(decodeDot11MgmtDisassociation)})
LayerTypeDot11MgmtAuthentication = gopacket.RegisterLayerType(101, gopacket.LayerTypeMetadata{"Dot11MgmtAuthentication", gopacket.DecodeFunc(decodeDot11MgmtAuthentication)})
LayerTypeDot11MgmtDeauthentication = gopacket.RegisterLayerType(102, gopacket.LayerTypeMetadata{"Dot11MgmtDeauthentication", gopacket.DecodeFunc(decodeDot11MgmtDeauthentication)})
LayerTypeDot11MgmtAction = gopacket.RegisterLayerType(103, gopacket.LayerTypeMetadata{"Dot11MgmtAction", gopacket.DecodeFunc(decodeDot11MgmtAction)})
LayerTypeDot11MgmtActionNoAck = gopacket.RegisterLayerType(104, gopacket.LayerTypeMetadata{"Dot11MgmtActionNoAck", gopacket.DecodeFunc(decodeDot11MgmtActionNoAck)})
LayerTypeDot11MgmtArubaWLAN = gopacket.RegisterLayerType(105, gopacket.LayerTypeMetadata{"Dot11MgmtArubaWLAN", gopacket.DecodeFunc(decodeDot11MgmtArubaWLAN)})
LayerTypeDot11WEP = gopacket.RegisterLayerType(106, gopacket.LayerTypeMetadata{"Dot11WEP", gopacket.DecodeFunc(decodeDot11WEP)})
LayerTypeDNS = gopacket.RegisterLayerType(107, gopacket.LayerTypeMetadata{"DNS", gopacket.DecodeFunc(decodeDNS)})
LayerTypeUSB = gopacket.RegisterLayerType(108, gopacket.LayerTypeMetadata{"USB", gopacket.DecodeFunc(decodeUSB)})
LayerTypeUSBRequestBlockSetup = gopacket.RegisterLayerType(109, gopacket.LayerTypeMetadata{"USBRequestBlockSetup", gopacket.DecodeFunc(decodeUSBRequestBlockSetup)})
LayerTypeUSBControl = gopacket.RegisterLayerType(110, gopacket.LayerTypeMetadata{"USBControl", gopacket.DecodeFunc(decodeUSBControl)})
LayerTypeUSBInterrupt = gopacket.RegisterLayerType(111, gopacket.LayerTypeMetadata{"USBInterrupt", gopacket.DecodeFunc(decodeUSBInterrupt)})
LayerTypeUSBBulk = gopacket.RegisterLayerType(112, gopacket.LayerTypeMetadata{"USBBulk", gopacket.DecodeFunc(decodeUSBBulk)})
LayerTypeLinuxSLL = gopacket.RegisterLayerType(113, gopacket.LayerTypeMetadata{"Linux SLL", gopacket.DecodeFunc(decodeLinuxSLL)})
LayerTypeSFlow = gopacket.RegisterLayerType(114, gopacket.LayerTypeMetadata{"SFlow", gopacket.DecodeFunc(decodeSFlow)})
LayerTypePrismHeader = gopacket.RegisterLayerType(115, gopacket.LayerTypeMetadata{"Prism monitor mode header", gopacket.DecodeFunc(decodePrismHeader)})
LayerTypeSlowProtocol = gopacket.RegisterLayerType(116, gopacket.LayerTypeMetadata{"Slow Protocol", gopacket.DecodeFunc(decodeSlowProtocol)})
LayerTypeLACP = gopacket.RegisterLayerType(117, gopacket.LayerTypeMetadata{"LACP", gopacket.DecodeFunc(decodeLACP)})
LayerTypeLAMP = gopacket.RegisterLayerType(118, gopacket.LayerTypeMetadata{"LAMP", gopacket.DecodeFunc(decodeLAMP)})
//LayerTypeSlowProtocolOAM = gopacket.RegisterLayerType(119, gopacket.LayerTypeMetadata{"OAM", gopacket.DecodeFunc(decodeSlowProtocolOAM)})
//LayerTypeSlowProtocolOSSP = gopacket.RegisterLayerType(120, gopacket.LayerTypeMetadata{"OSSP", gopacket.DecodeFunc(decodeSlowProtocolOSSP)})
LayerTypeBPDU = gopacket.RegisterLayerType(121, gopacket.LayerTypeMetadata{"STP", gopacket.DecodeFunc(decodeBPDU)})
LayerTypePVST = gopacket.RegisterLayerType(122, gopacket.LayerTypeMetadata{"PVST", gopacket.DecodeFunc(decodePVST)})
LayerTypeVxlan = gopacket.RegisterLayerType(123, gopacket.LayerTypeMetadata{"VXLAN", gopacket.DecodeFunc(decodeVxlan)})
LayerTypeDRCP = gopacket.RegisterLayerType(124, gopacket.LayerTypeMetadata{"DRCP", gopacket.DecodeFunc(decodeDRCP)})
)
var (
// LayerClassIPNetwork contains TCP/IP network layer types.
LayerClassIPNetwork = gopacket.NewLayerClass([]gopacket.LayerType{
LayerTypeIPv4,
LayerTypeIPv6,
})
// LayerClassIPTransport contains TCP/IP transport layer types.
LayerClassIPTransport = gopacket.NewLayerClass([]gopacket.LayerType{
LayerTypeTCP,
LayerTypeUDP,
LayerTypeSCTP,
})
// LayerClassIPControl contains TCP/IP control protocols.
LayerClassIPControl = gopacket.NewLayerClass([]gopacket.LayerType{
LayerTypeICMPv4,
LayerTypeICMPv6,
})
// LayerClassSCTPChunk contains SCTP chunk types (not the top-level SCTP
// layer).
LayerClassSCTPChunk = gopacket.NewLayerClass([]gopacket.LayerType{
LayerTypeSCTPUnknownChunkType,
LayerTypeSCTPData,
LayerTypeSCTPInit,
LayerTypeSCTPSack,
LayerTypeSCTPHeartbeat,
LayerTypeSCTPError,
LayerTypeSCTPShutdown,
LayerTypeSCTPShutdownAck,
LayerTypeSCTPCookieEcho,
LayerTypeSCTPEmptyLayer,
LayerTypeSCTPInitAck,
LayerTypeSCTPHeartbeatAck,
LayerTypeSCTPAbort,
LayerTypeSCTPShutdownComplete,
LayerTypeSCTPCookieAck,
})
// LayerClassIPv6Extension contains IPv6 extension headers.
LayerClassIPv6Extension = gopacket.NewLayerClass([]gopacket.LayerType{
LayerTypeIPv6HopByHop,
LayerTypeIPv6Routing,
LayerTypeIPv6Fragment,
LayerTypeIPv6Destination,
})
LayerClassIPSec = gopacket.NewLayerClass([]gopacket.LayerType{
LayerTypeIPSecAH,
LayerTypeIPSecESP,
})
)
| ccordes-snaproute/gopacket | layers/layertypes.go | GO | bsd-3-clause | 18,948 |
module Validations.Types
( module Validations.Types.Checker
) where
import Validations.Types.Checker
| mavenraven/validations | src/Validations/Types.hs | Haskell | bsd-3-clause | 106 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2021 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Common filesystem operations """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import stat
import time
import errno
import ntpath
import shutil
import tempfile
import warnings
import posixpath
import contextlib
import subprocess
from qisys import ui
try:
from xdg.BaseDirectory import xdg_cache_home, xdg_config_home, xdg_data_home
except ImportError:
xdg_config_home = os.path.expanduser("~/.config")
xdg_cache_home = os.path.expanduser("~/.cache")
xdg_data_home = os.path.expanduser("~/.local/share")
CONFIG_PATH = xdg_config_home
CACHE_PATH = xdg_cache_home
SHARE_PATH = xdg_data_home
def set_home(home):
""" Set Home """
# This module should be refactored into object to avoid the anti-pattern global statement
global CONFIG_PATH, CACHE_PATH, SHARE_PATH
CONFIG_PATH = os.path.join(home, "config")
CACHE_PATH = os.path.join(home, "cache")
SHARE_PATH = os.path.join(home, "share")
def get_config_path(*args):
"""
Get a config path to read or write some configuration.
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CONFIG_PATH, *args)
def get_cache_path(*args):
"""
Get a config path to read or write some cached data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(CACHE_PATH, *args)
def get_share_path(*args):
"""
Get a config path to read or write some persistent data
:param args: a list of subfolders. Those will be created when needed
"""
return get_path(SHARE_PATH, *args)
def get_path(*args):
""" Helper for get_*_path methods """
full_path = os.path.join(*args)
to_make = os.path.dirname(full_path)
mkdir(to_make, recursive=True)
full_path = to_native_path(full_path)
return full_path
def username():
""" Get the current user name """
if os.name != 'nt':
import pwd
uid = os.getuid() # pylint:disable=no-member
pw_info = pwd.getpwuid(uid)
if pw_info:
return pw_info.pw_name
_username = os.environ.get("USERNAME")
if _username:
return _username
return None
def mkdir(dest_dir, recursive=False):
""" Recursive mkdir (do not fail if file exists) """
try:
if recursive:
os.makedirs(dest_dir)
else:
os.mkdir(dest_dir)
except OSError as exc:
if exc.errno != 17:
raise
# Directory already exists -> no exception
def ln(src, dst, symlink=True):
""" ln (do not fail if file exists) """
try:
if symlink:
os.symlink(src, dst) # pylint:disable=no-member
else:
raise NotImplementedError
except OSError as exc:
if exc.errno != 17:
raise
def write_file_if_different(data, out_path, mode="w"):
""" Write the data to out_path if the content is different """
try:
with open(out_path, "r") as outr:
out_prev = outr.read()
if out_prev == data:
ui.debug("skipping write to %s: same content" % (out_path))
return
except Exception:
pass
with open(out_path, mode) as out_file:
out_file.write(data)
def configure_file__legacy(in_path, out_path, copy_only=False,
*args, **kwargs): # pylint:disable=keyword-arg-before-vararg
"""
Configure a file.
:param in_path: input file
:param out_path: output file
The out_path needs not to exist, missing leading directories will
be created if necessary.
If copy_only is True, the contents will be copied "as is".
If not, we will use the args and kwargs parameter as in::
in_content.format(*args, **kwargs)
"""
# This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)
# If nobody complains, remove this function in the next release
warnings.warn(
"Deprecated function: "
"This function seems to be never called, and has been renamed with __legacy suffix (2020-02-07)\n"
"If nobody complains, remove this function in the next release, else, deals with its bad args/kwargs signature",
DeprecationWarning)
mkdir(os.path.dirname(os.path.abspath(out_path)), recursive=True)
with open(in_path, "r") as in_file:
in_content = in_file.read()
if copy_only:
out_content = in_content
else:
out_content = in_content.format(*args, **kwargs)
write_file_if_different(out_content, out_path)
def _copy_link(src, dest, quiet):
""" Copy Link """
if not os.path.islink(src):
raise Exception("%s is not a link!" % src)
target = os.readlink(src) # pylint:disable=no-member
# remove existing stuff
if os.path.lexists(dest):
rm(dest)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s -> %s" % (dest, target))
to_make = os.path.dirname(dest)
mkdir(to_make, recursive=True)
os.symlink(target, dest) # pylint:disable=no-member
def _handle_dirs(src, dest, root, directories, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
# To avoid filering './' stuff
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for directory in directories:
to_filter = os.path.join(rel_root, directory)
if not filter_fun(to_filter):
continue
dsrc = os.path.join(root, directory)
ddest = os.path.join(new_root, directory)
if os.path.islink(dsrc):
_copy_link(dsrc, ddest, quiet)
installed.append(directory)
else:
if os.path.lexists(ddest) and not os.path.isdir(ddest):
raise Exception("Expecting a directory but found a file: %s" % ddest)
mkdir(ddest, recursive=True)
return installed
def _handle_files(src, dest, root, files, filter_fun, quiet):
""" Helper function used by install() """
installed = list()
rel_root = os.path.relpath(root, src)
if rel_root == ".":
rel_root = ""
new_root = os.path.join(dest, rel_root)
for f in files:
if not filter_fun(os.path.join(rel_root, f)):
continue
fsrc = os.path.join(root, f)
fdest = os.path.join(new_root, f)
rel_path = os.path.join(rel_root, f)
if os.path.islink(fsrc):
mkdir(new_root, recursive=True)
_copy_link(fsrc, fdest, quiet)
installed.append(rel_path)
else:
if os.path.lexists(fdest) and os.path.isdir(fdest):
raise Exception("Expecting a file but found a directory: %s" % fdest)
if not quiet:
print("-- Installing %s" % fdest.encode('ascii', "ignore"))
mkdir(new_root, recursive=True)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(fdest)
shutil.copy(fsrc, fdest)
installed.append(rel_path)
return installed
def install(src, dest, filter_fun=None, quiet=False):
"""
Install a directory or a file to a destination.
If filter_fun is not None, then the file will only be
installed if filter_fun(relative/path/to/file) returns True.
If ``dest`` does not exist, it will be created first.
When installing files, if the destination already exists,
it will be removed first, then overwritten by the new file.
This function will preserve relative symlinks between directories,
used for instance in Mac frameworks::
|__ Versions
|__ Current -> 4.0
|__ 4 -> 4.0
|__ 4.0
Return the list of files installed (with relative paths)
"""
installed = list()
# FIXME: add a `safe mode` ala install?
if not os.path.exists(src):
mess = "Could not install '%s' to '%s'\n" % (src, dest)
mess += '%s does not exist' % src
raise Exception(mess)
src = to_native_path(src, normcase=False)
dest = to_native_path(dest, normcase=False)
ui.debug("Installing", src, "->", dest)
if filter_fun is None:
def no_filter_fun(_unused):
""" Filter Function Always True """
return True
filter_fun = no_filter_fun
if os.path.isdir(src):
if src == dest:
raise Exception("source and destination are the same directory")
for (root, dirs, files) in os.walk(src):
dirs = _handle_dirs(src, dest, root, dirs, filter_fun, quiet)
files = _handle_files(src, dest, root, files, filter_fun, quiet)
installed.extend(files)
else:
# Emulate posix `install' behavior:
# if dest is a dir, install in the directory, else
# simply copy the file.
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if src == dest:
raise Exception("source and destination are the same file")
mkdir(os.path.dirname(dest), recursive=True)
if sys.stdout.isatty() and not quiet:
print("-- Installing %s" % dest)
# We do not want to fail if dest exists but is read only
# (following what `install` does, but not what `cp` does)
rm(dest)
shutil.copy(src, dest)
installed.append(os.path.basename(src))
return installed
def safe_copy(src, dest):
"""
Copy a source file to a destination but
do not overwrite dest if it is more recent than src
Create any missing directories when necessary
If dest is a directory, src will be copied inside dest.
"""
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if not up_to_date(dest, src):
shutil.copy(src, dest)
def up_to_date(output_path, input_path):
"""" Return True if output_path exists and is more recent than input_path """
if not os.path.exists(output_path):
return False
out_mtime = os.stat(output_path).st_mtime
in_mtime = os.stat(input_path).st_mtime
return out_mtime > in_mtime
def copy_git_src(src, dest):
"""
Copy a source to a destination but only copy the files under version control.
Assumes that ``src`` is inside a git worktree
"""
process = subprocess.Popen(["git", "ls-files", "."], cwd=src,
stdout=subprocess.PIPE)
(out, _) = process.communicate()
for filename in out.splitlines():
src_file = os.path.join(src, filename.decode('ascii'))
dest_file = os.path.join(dest, filename.decode('ascii'))
install(src_file, dest_file, quiet=True)
def rm(name):
"""
This one can take a file or a directory.
Contrary to shutil.remove or os.remove, it:
* won't fail if the directory does not exist
* won't fail if the directory contains read-only files
* won't fail if the file does not exist
Please avoid using shutil.rmtree ...
"""
if not os.path.lexists(name):
return
if os.path.isdir(name) and not os.path.islink(name):
ui.debug("Removing directory:", name)
rmtree(name.encode('ascii', "ignore"))
else:
ui.debug("Removing", name)
os.remove(name)
def rmtree(path):
"""
shutil.rmtree() on steroids.
Taken from gclient source code (BSD license)
Recursively removes a directory, even if it's marked read-only.
shutil.rmtree() doesn't work on Windows if any of the files or directories
are read-only, which svn repositories and some .svn files are. We need to
be able to force the files to be writable (i.e., deletable) as we traverse
the tree.
Even with all this, Windows still sometimes fails to delete a file, citing
a permission error (maybe something to do with antivirus scans or disk
indexing). The best suggestion any of the user forums had was to wait a
bit and try again, so we do that too. It's hand-waving, but sometimes it
works. :/
On POSIX systems, things are a little bit simpler. The modes of the files
to be deleted doesn't matter, only the modes of the directories containing
them are significant. As the directory tree is traversed, each directory
has its mode set appropriately before descending into it. This should
result in the entire tree being removed, with the possible exception of
``path`` itself, because nothing attempts to change the mode of its parent.
Doing so would be hazardous, as it's not a directory slated for removal.
In the ordinary case, this is not a problem: for our purposes, the user
will never lack write permission on ``path``'s parent.
"""
if not os.path.exists(path):
return
if os.path.islink(path) or not os.path.isdir(path):
raise Exception('Called rmtree(%s) in non-directory' % path)
if sys.platform == 'win32':
# Some people don't have the APIs installed. In that case we'll do without.
win32api = None
win32con = None
try:
import win32api
import win32con
except ImportError:
pass
else:
# On POSIX systems, we need the x-bit set on the directory to access it,
# the r-bit to see its contents, and the w-bit to remove files from it.
# The actual modes of the files within the directory is irrelevant.
os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def remove(func, subpath):
""" Remove """
if sys.platform == 'win32':
os.chmod(subpath, stat.S_IWRITE)
if win32api and win32con:
win32api.SetFileAttributes(subpath, win32con.FILE_ATTRIBUTE_NORMAL)
try:
func(subpath)
except OSError as e:
if e.errno != errno.EACCES or sys.platform != 'win32':
raise
# Failed to delete, try again after a 100ms sleep.
time.sleep(0.1)
func(subpath)
for fn in os.listdir(path):
# If fullpath is a symbolic link that points to a directory, isdir will
# be True, but we don't want to descend into that as a directory, we just
# want to remove the link. Check islink and treat links as ordinary files
# would be treated regardless of what they reference.
fullpath = os.path.join(path, fn)
if os.path.islink(fullpath) or not os.path.isdir(fullpath):
remove(os.remove, fullpath)
else:
# Recurse.
rmtree(fullpath)
remove(os.rmdir, path)
def mv(src, dest):
""" Move a file into a directory, but do not crash if dest/src exists """
if src == dest:
return
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
if os.path.exists(dest):
rm(dest)
ui.debug(src, "->", dest)
shutil.move(src, dest)
def ls_r(directory):
"""
Returns a sorted list of all the files present in a directory,
relative to this directory.
For instance, with::
foo
|__ eggs
| |__ c
| |__ d
|__ empty
|__ spam
|__a
|__b
ls_r(foo) returns:
["eggs/c", "eggs/d", "empty/", "spam/a", "spam/b"]
"""
res = list()
for root, dirs, files in os.walk(directory):
new_root = os.path.relpath(root, directory)
if new_root == "." and not files:
continue
if new_root == "." and files:
res.extend(files)
continue
if not files and not dirs:
res.append(new_root + os.path.sep)
continue
for f in files:
res.append(os.path.join(new_root, f))
return sorted(res)
def which(program):
"""
find program in the environment PATH
:return: path to program if found, None otherwise
"""
warnings.warn("qisys.sh.which is deprecated, "
"use qisys.command.find_program instead")
from qisys.command import find_program
return find_program(program)
def to_posix_path(path, fix_drive=False):
"""
Returns a POSIX path from a DOS path
:param fix_drive: if True, will replace c: by /c/ (ala mingw)
"""
res = os.path.expanduser(path)
res = os.path.abspath(res)
res = path.replace(ntpath.sep, posixpath.sep)
if fix_drive:
(drive, rest) = os.path.splitdrive(res)
letter = drive[0]
return "/" + letter + rest
return res
def to_dos_path(path):
"""
Return a DOS path from a "windows with /" path.
Useful because people sometimes use forward slash in
environment variable, for instance
"""
res = path.replace(posixpath.sep, ntpath.sep)
return res
def to_native_path(path, normcase=True):
"""
Return an absolute, native path from a path,
:param normcase: make sure the path is all lower-case on
case-insensitive filesystems
"""
path = os.path.expanduser(path)
if normcase:
path = os.path.normcase(path)
path = os.path.normpath(path)
path = os.path.abspath(path)
path = os.path.realpath(path)
if sys.platform.startswith("win"):
path = to_dos_path(path)
return path
def is_path_inside(a, b):
"""
Returns True if a is inside b
>>> is_path_inside("foo/bar", "foo")
True
>>> is_path_inside("gui/bar/libfoo", "lib")
False
"""
a = to_native_path(a)
b = to_native_path(b)
a_split = a.split(os.path.sep)
b_split = b.split(os.path.sep)
if len(a_split) < len(b_split):
return False
for (a_part, b_part) in zip(a_split, b_split):
if a_part != b_part:
return False
return True
def is_empty(path):
""" Check if a path is empty """
return os.listdir(path) == list()
class TempDir(object):
"""
This is a nice wrapper around tempfile module.
Usage::
with TempDir("foo-bar") as temp_dir:
subdir = os.path.join(temp_dir, "subdir")
do_foo(subdir)
This piece of code makes sure that:
* a temporary directory named temp_dir has been
created (guaranteed to exist, be empty, and writeable)
* the directory will be removed when the scope of
temp_dir has ended unless an exception has occurred
and DEBUG environment variable is set.
"""
def __init__(self, name="tmp"):
""" TempDir Init """
self._temp_dir = tempfile.mkdtemp(prefix=name + "-")
def __enter__(self):
""" Enter """
return self._temp_dir
def __exit__(self, _type, value, tb):
""" Exit """
if os.environ.get("DEBUG"):
if tb is not None:
print("==")
print("Not removing ", self._temp_dir)
print("==")
return
rm(self._temp_dir)
@contextlib.contextmanager
def change_cwd(directory):
""" Change the current working dir """
if not os.path.exists(directory):
mess = "Cannot change working dir to '%s'\n" % directory
mess += "This path does not exist"
raise Exception(mess)
previous_cwd = os.getcwd()
os.chdir(directory)
yield
os.chdir(previous_cwd)
def is_runtime(filename):
""" Filter function to only install runtime components of packages """
# FIXME: this looks like a hack.
# Maybe a user-generated MANIFEST at the root of the package path
# would be better?
basedir = filename.split(os.path.sep)[0]
if filename.startswith("bin") and sys.platform.startswith("win"):
return filename.endswith(".exe") or filename.endswith(".dll")
if filename.startswith("lib"):
is_lib_prefixed_runtime = not filename.endswith((".a", ".lib", ".la", ".pc"))
return is_lib_prefixed_runtime
if filename.startswith(os.path.join("share", "cmake")) or \
filename.startswith(os.path.join("share", "man")):
return False
if basedir == "include":
# Usually runtime dir names aren't include, but there is an exception for python:
return filename.endswith("pyconfig.h")
# True by default: better have too much stuff than not enough
# That includes these known cases:
# * filename.startswith("bin") but not sys.platform.startswith("win")
# * basedir == "share"
# * basedir.endswith(".framework")
return True
def broken_symlink(file_path):
""" Returns True if the file is a broken symlink """
return os.path.lexists(file_path) and not os.path.exists(file_path)
def is_binary(file_path):
""" Returns True if the file is binary """
with open(file_path, 'rb') as fp:
data = fp.read(1024)
if not data:
return False
if b'\0' in data:
return True
return False
def is_executable_binary(file_path):
"""
Returns true if the file:
* is executable
* is a binary (i.e not a script)
"""
if not os.path.isfile(file_path):
return False
if not os.access(file_path, os.X_OK):
return False
return is_binary(file_path)
class PreserveFileMetadata(object):
""" Preserve file metadata (permissions and times) """
def __init__(self, path):
""" Preserve file metadata of 'path' """
self.path = path
self.time = None
self.mode = None
def __enter__(self):
""" Enter method saving metadata """
st = os.stat(self.path)
self.time = (st.st_atime, st.st_mtime)
self.mode = st.st_mode
def __exit__(self, _type, value, tb):
""" Exit method restoring metadata """
os.chmod(self.path, self.mode)
os.utime(self.path, self.time)
| aldebaran/qibuild | python/qisys/sh.py | Python | bsd-3-clause | 22,082 |
catissue_audit_event_details;select ELEMENT_NAME,CURRENT_VALUE from catissue_audit_event_details where ELEMENT_NAME='EMBEDDING_MEDIUM'
catissue_audit_event;select EVENT_TYPE from catissue_audit_event | NCIP/catissue-core | software/caTissue/modules/tests/struts/CaTissue_TestCases/SQLForActualDataSets/dbunit_embeddedEvent.sql | SQL | bsd-3-clause | 200 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace GenIpCpp
{
class Program
{
public static UInt32 IpToInt(string ip)
{
char[] separator = new char[] { '.' };
string[] items = ip.Split(separator);
return UInt32.Parse(items[0]) << 24
| UInt32.Parse(items[1]) << 16
| UInt32.Parse(items[2]) << 8
| UInt32.Parse(items[3]);
}
static void Main(string[] args)
{
StringBuilder sb=new StringBuilder(64*1024*1024);
sb.AppendLine("#include \"items.h\"");
sb.AppendLine("IpItem items[]=");
sb.AppendLine("{");
int ncount = 0;
using (var sr = new StreamReader(@"F:\network\ipwry\ipfile.txt",System.Text.Encoding.GetEncoding(936)))
{
var curline = sr.ReadLine();
while (curline.Length>0)
{
if (curline.Length < 33)
{
System.Console.WriteLine("Error:{0}",curline);
continue;
}
string strfromip = curline.Substring(0, 16).Trim();
string strtoip = curline.Substring(16, 16).Trim();
string straddr = curline.Substring(32).Replace("\\","\\\\").Replace("\"","");
var fromip = IpToInt(strfromip);
var toip = IpToInt(strtoip);
sb.AppendFormat(" {{{0},{1},\"{2}\"}},\r\n", fromip, toip, straddr);
ncount++;
//System.Console.WriteLine("{0},{1},{2}", fromip, toip, straddr);
curline = sr.ReadLine();
if (curline == null)
break;
}
}
sb.AppendLine("};");
sb.AppendFormat("int itemslen={0};\n",ncount);
System.Console.WriteLine(sb.ToString());
}
}
}
| sevencat/ipwry | GenIpCpp/Program.cs | C# | bsd-3-clause | 2,249 |
/*
* Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
* Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
* Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <features.h>
#ifdef HAVE_STDBOOL_H
# include <stdbool.h>
#endif
#include <stdint.h>
#include <inttypes.h>
#include <sys/types.h>
#ifdef STDC_HEADERS
# include <stddef.h>
#endif
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
/* Open-coding isprint(ch) et al proved more efficient than calling
* generalized libc interface. We don't *want* to do non-ASCII anyway.
*/
/* #include <ctype.h> */
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <sys/syscall.h>
#include "mpers_type.h"
#ifndef HAVE_STRERROR
const char *strerror(int);
#endif
#ifndef HAVE_STPCPY
/* Some libc have stpcpy, some don't. Sigh...
* Roll our private implementation...
*/
#undef stpcpy
#define stpcpy strace_stpcpy
extern char *stpcpy(char *dst, const char *src);
#endif
#if defined __GNUC__ && defined __GNUC_MINOR__
# define GNUC_PREREQ(maj, min) \
((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
#else
# define __attribute__(x) /* empty */
# define GNUC_PREREQ(maj, min) 0
#endif
#if GNUC_PREREQ(2, 5)
# define ATTRIBUTE_NORETURN __attribute__((__noreturn__))
#else
# define ATTRIBUTE_NORETURN /* empty */
#endif
#if GNUC_PREREQ(2, 7)
# define ATTRIBUTE_FORMAT(args) __attribute__((__format__ args))
# define ATTRIBUTE_ALIGNED(arg) __attribute__((__aligned__(arg)))
# define ATTRIBUTE_PACKED __attribute__((__packed__))
#else
# define ATTRIBUTE_FORMAT(args) /* empty */
# define ATTRIBUTE_ALIGNED(arg) /* empty */
# define ATTRIBUTE_PACKED /* empty */
#endif
#if GNUC_PREREQ(3, 0)
# define ATTRIBUTE_MALLOC __attribute__((__malloc__))
#else
# define ATTRIBUTE_MALLOC /* empty */
#endif
#if GNUC_PREREQ(3, 1)
# define ATTRIBUTE_NOINLINE __attribute__((__noinline__))
#else
# define ATTRIBUTE_NOINLINE /* empty */
#endif
#if GNUC_PREREQ(4, 3)
# define ATTRIBUTE_ALLOC_SIZE(args) __attribute__((__alloc_size__ args))
#else
# define ATTRIBUTE_ALLOC_SIZE(args) /* empty */
#endif
#ifndef offsetof
# define offsetof(type, member) \
(((char *) &(((type *) NULL)->member)) - ((char *) (type *) NULL))
#endif
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
/* macros */
#ifndef MAX
# define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef MIN
# define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#define CLAMP(val, min, max) MIN(MAX(min, val), max)
/* Glibc has an efficient macro for sigemptyset
* (it just does one or two assignments of 0 to internal vector of longs).
*/
#if defined(__GLIBC__) && defined(__sigemptyset) && !defined(sigemptyset)
# define sigemptyset __sigemptyset
#endif
/* Configuration section */
#ifndef DEFAULT_STRLEN
/* default maximum # of bytes printed in `printstr', change with -s switch */
# define DEFAULT_STRLEN 32
#endif
#ifndef DEFAULT_ACOLUMN
# define DEFAULT_ACOLUMN 40 /* default alignment column for results */
#endif
/*
* Maximum number of args to a syscall.
*
* Make sure that all entries in all syscallent.h files have nargs <= MAX_ARGS!
* linux/<ARCH>/syscallent*.h:
* all have nargs <= 6 except mips o32 which has nargs <= 7.
*/
#ifndef MAX_ARGS
# ifdef LINUX_MIPSO32
# define MAX_ARGS 7
# else
# define MAX_ARGS 6
# endif
#endif
/* default sorting method for call profiling */
#ifndef DEFAULT_SORTBY
# define DEFAULT_SORTBY "time"
#endif
/*
* Experimental code using PTRACE_SEIZE can be enabled here.
* This needs Linux kernel 3.4.x or later to work.
*/
#define USE_SEIZE 1
/* To force NOMMU build, set to 1 */
#define NOMMU_SYSTEM 0
/*
* Set to 1 to use speed-optimized vfprintf implementation.
* It results in strace using about 5% less CPU in user space
* (compared to glibc version).
* But strace spends a lot of time in kernel space,
* so overall it does not appear to be a significant win.
* Thus disabled by default.
*/
#define USE_CUSTOM_PRINTF 0
#ifndef ERESTARTSYS
# define ERESTARTSYS 512
#endif
#ifndef ERESTARTNOINTR
# define ERESTARTNOINTR 513
#endif
#ifndef ERESTARTNOHAND
# define ERESTARTNOHAND 514
#endif
#ifndef ERESTART_RESTARTBLOCK
# define ERESTART_RESTARTBLOCK 516
#endif
#if defined(SPARC) || defined(SPARC64)
# define PERSONALITY0_WORDSIZE 4
# if defined(SPARC64)
# define SUPPORTED_PERSONALITIES 2
# define PERSONALITY1_WORDSIZE 8
# ifdef HAVE_M32_MPERS
# define PERSONALITY1_INCLUDE_FUNCS "m32_funcs.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "m32_printer_decls.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "m32_printer_defs.h"
# endif
# endif
#endif
#ifdef X86_64
# define SUPPORTED_PERSONALITIES 3
# define PERSONALITY0_WORDSIZE 8
# define PERSONALITY1_WORDSIZE 4
# define PERSONALITY2_WORDSIZE 4
# ifdef HAVE_M32_MPERS
# define PERSONALITY1_INCLUDE_FUNCS "m32_funcs.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "m32_printer_decls.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "m32_printer_defs.h"
# endif
# ifdef HAVE_MX32_MPERS
# define PERSONALITY2_INCLUDE_FUNCS "mx32_funcs.h"
# define PERSONALITY2_INCLUDE_PRINTERS_DECLS "mx32_printer_decls.h"
# define PERSONALITY2_INCLUDE_PRINTERS_DEFS "mx32_printer_defs.h"
# endif
#endif
#ifdef X32
# define SUPPORTED_PERSONALITIES 2
# define PERSONALITY0_WORDSIZE 4
# define PERSONALITY1_WORDSIZE 4
# ifdef HAVE_M32_MPERS
# define PERSONALITY1_INCLUDE_FUNCS "m32_funcs.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "m32_printer_decls.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "m32_printer_defs.h"
# endif
#endif
#ifdef ARM
/* one personality */
#endif
#ifdef AARCH64
/* The existing ARM personality, then AArch64 */
# define SUPPORTED_PERSONALITIES 2
# define PERSONALITY0_WORDSIZE 8
# define PERSONALITY1_WORDSIZE 4
# ifdef HAVE_M32_MPERS
# define PERSONALITY1_INCLUDE_FUNCS "m32_funcs.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "m32_printer_decls.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "m32_printer_defs.h"
# endif
#endif
#ifdef POWERPC64
# define SUPPORTED_PERSONALITIES 2
# define PERSONALITY0_WORDSIZE 8
# define PERSONALITY1_WORDSIZE 4
# ifdef HAVE_M32_MPERS
# define PERSONALITY1_INCLUDE_FUNCS "m32_funcs.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "m32_printer_decls.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "m32_printer_defs.h"
# endif
#endif
#ifdef TILE
# define SUPPORTED_PERSONALITIES 2
# define PERSONALITY0_WORDSIZE 8
# define PERSONALITY1_WORDSIZE 4
# ifdef __tilepro__
# define DEFAULT_PERSONALITY 1
# endif
# ifdef HAVE_M32_MPERS
# define PERSONALITY1_INCLUDE_FUNCS "m32_funcs.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "m32_printer_decls.h"
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "m32_printer_defs.h"
# endif
#endif
#ifndef SUPPORTED_PERSONALITIES
# define SUPPORTED_PERSONALITIES 1
#endif
#ifndef DEFAULT_PERSONALITY
# define DEFAULT_PERSONALITY 0
#endif
#ifndef PERSONALITY0_WORDSIZE
# define PERSONALITY0_WORDSIZE SIZEOF_LONG
#endif
#ifndef PERSONALITY0_INCLUDE_PRINTERS_DECLS
# define PERSONALITY0_INCLUDE_PRINTERS_DECLS "native_printer_decls.h"
#endif
#ifndef PERSONALITY0_INCLUDE_PRINTERS_DEFS
# define PERSONALITY0_INCLUDE_PRINTERS_DEFS "native_printer_defs.h"
#endif
#ifndef PERSONALITY1_INCLUDE_PRINTERS_DECLS
# define PERSONALITY1_INCLUDE_PRINTERS_DECLS "native_printer_decls.h"
#endif
#ifndef PERSONALITY1_INCLUDE_PRINTERS_DEFS
# define PERSONALITY1_INCLUDE_PRINTERS_DEFS "native_printer_defs.h"
#endif
#ifndef PERSONALITY2_INCLUDE_PRINTERS_DECLS
# define PERSONALITY2_INCLUDE_PRINTERS_DECLS "native_printer_decls.h"
#endif
#ifndef PERSONALITY2_INCLUDE_PRINTERS_DEFS
# define PERSONALITY2_INCLUDE_PRINTERS_DEFS "native_printer_defs.h"
#endif
#ifndef PERSONALITY1_INCLUDE_FUNCS
# define PERSONALITY1_INCLUDE_FUNCS "empty.h"
#endif
#ifndef PERSONALITY2_INCLUDE_FUNCS
# define PERSONALITY2_INCLUDE_FUNCS "empty.h"
#endif
typedef struct sysent {
unsigned nargs;
int sys_flags;
int sen;
int (*sys_func)();
const char *sys_name;
} struct_sysent;
typedef struct ioctlent {
const char *symbol;
unsigned int code;
} struct_ioctlent;
/* Trace Control Block */
struct tcb {
int flags; /* See below for TCB_ values */
int pid; /* If 0, this tcb is free */
int qual_flg; /* qual_flags[scno] or DEFAULT_QUAL_FLAGS + RAW */
int u_error; /* Error code */
long scno; /* System call number */
long u_arg[MAX_ARGS]; /* System call arguments */
#if defined(LINUX_MIPSN32) || defined(X32)
long long ext_arg[MAX_ARGS];
long long u_lrval; /* long long return value */
#endif
long u_rval; /* Return value */
#if SUPPORTED_PERSONALITIES > 1
unsigned int currpers; /* Personality at the time of scno update */
#endif
int sys_func_rval; /* Syscall entry parser's return value */
int curcol; /* Output column for this process */
FILE *outf; /* Output file for this process */
const char *auxstr; /* Auxiliary info from syscall (see RVAL_STR) */
const struct_sysent *s_ent; /* sysent[scno] or dummy struct for bad scno */
const struct_sysent *s_prev_ent; /* for "resuming interrupted SYSCALL" msg */
struct timeval stime; /* System time usage as of last process wait */
struct timeval dtime; /* Delta for system time usage */
struct timeval etime; /* Syscall entry time */
#ifdef USE_LIBUNWIND
struct UPT_info* libunwind_ui;
struct mmap_cache_t* mmap_cache;
unsigned int mmap_cache_size;
unsigned int mmap_cache_generation;
struct queue_t* queue;
#endif
};
/* TCB flags */
/* We have attached to this process, but did not see it stopping yet */
#define TCB_STARTUP 0x01
#define TCB_IGNORE_ONE_SIGSTOP 0x02 /* Next SIGSTOP is to be ignored */
/*
* Are we in system call entry or in syscall exit?
*
* This bit is set after all syscall entry processing is done.
* Therefore, this bit will be set when next ptrace stop occurs,
* which should be syscall exit stop. Other stops which are possible
* directly after syscall entry (death, ptrace event stop)
* are simpler and handled without calling trace_syscall(), therefore
* the places where TCB_INSYSCALL can be set but we aren't in syscall stop
* are limited to trace(), this condition is never observed in trace_syscall()
* and below.
* The bit is cleared after all syscall exit processing is done.
*
* Use entering(tcp) / exiting(tcp) to check this bit to make code more readable.
*/
#define TCB_INSYSCALL 0x04
#define TCB_ATTACHED 0x08 /* We attached to it already */
#define TCB_REPRINT 0x10 /* We should reprint this syscall on exit */
#define TCB_FILTERED 0x20 /* This system call has been filtered out */
/* qualifier flags */
#define QUAL_TRACE 0x001 /* this system call should be traced */
#define QUAL_ABBREV 0x002 /* abbreviate the structures of this syscall */
#define QUAL_VERBOSE 0x004 /* decode the structures of this syscall */
#define QUAL_RAW 0x008 /* print all args in hex for this syscall */
#define QUAL_SIGNAL 0x010 /* report events with this signal */
#define QUAL_READ 0x020 /* dump data read on this file descriptor */
#define QUAL_WRITE 0x040 /* dump data written to this file descriptor */
typedef uint8_t qualbits_t;
#define UNDEFINED_SCNO 0x100 /* Used only in tcp->qual_flg */
#define DEFAULT_QUAL_FLAGS (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
#define entering(tcp) (!((tcp)->flags & TCB_INSYSCALL))
#define exiting(tcp) ((tcp)->flags & TCB_INSYSCALL)
#define syserror(tcp) ((tcp)->u_error != 0)
#define verbose(tcp) ((tcp)->qual_flg & QUAL_VERBOSE)
#define abbrev(tcp) ((tcp)->qual_flg & QUAL_ABBREV)
#define filtered(tcp) ((tcp)->flags & TCB_FILTERED)
struct xlat {
unsigned int val;
const char *str;
};
#define XLAT(x) { x, #x }
#define XLAT_END { 0, NULL }
extern const struct xlat addrfams[];
extern const struct xlat at_flags[];
extern const struct xlat dirent_types[];
extern const struct xlat open_access_modes[];
extern const struct xlat open_mode_flags[];
extern const struct xlat resource_flags[];
extern const struct xlat whence_codes[];
/* Format of syscall return values */
#define RVAL_DECIMAL 000 /* decimal format */
#define RVAL_HEX 001 /* hex format */
#define RVAL_OCTAL 002 /* octal format */
#define RVAL_UDECIMAL 003 /* unsigned decimal format */
#if defined(LINUX_MIPSN32) || defined(X32)
# if 0 /* unused so far */
# define RVAL_LDECIMAL 004 /* long decimal format */
# define RVAL_LHEX 005 /* long hex format */
# define RVAL_LOCTAL 006 /* long octal format */
# endif
# define RVAL_LUDECIMAL 007 /* long unsigned decimal format */
#endif
#define RVAL_FD 010 /* file descriptor */
#define RVAL_MASK 017 /* mask for these values */
#define RVAL_STR 020 /* Print `auxstr' field after return val */
#define RVAL_NONE 040 /* Print nothing */
#define RVAL_DECODED 0100 /* syscall decoding finished */
#define TRACE_FILE 001 /* Trace file-related syscalls. */
#define TRACE_IPC 002 /* Trace IPC-related syscalls. */
#define TRACE_NETWORK 004 /* Trace network-related syscalls. */
#define TRACE_PROCESS 010 /* Trace process-related syscalls. */
#define TRACE_SIGNAL 020 /* Trace signal-related syscalls. */
#define TRACE_DESC 040 /* Trace file descriptor-related syscalls. */
#define TRACE_MEMORY 0100 /* Trace memory mapping-related syscalls. */
#define SYSCALL_NEVER_FAILS 0200 /* Syscall is always successful. */
#define STACKTRACE_INVALIDATE_CACHE 0400 /* Trigger proc/maps cache updating */
#define STACKTRACE_CAPTURE_ON_ENTER 01000 /* Capture stacktrace on "entering" stage */
#define TRACE_INDIRECT_SUBCALL 02000 /* Syscall is an indirect socket/ipc subcall. */
#define IOCTL_NUMBER_UNKNOWN 0
#define IOCTL_NUMBER_HANDLED 1
#define IOCTL_NUMBER_STOP_LOOKUP 010
#define indirect_ipccall(tcp) (tcp->s_ent->sys_flags & TRACE_INDIRECT_SUBCALL)
#if defined(ARM) || defined(AARCH64) \
|| defined(I386) || defined(X32) || defined(X86_64) \
|| defined(IA64) \
|| defined(BFIN) \
|| defined(M68K) \
|| defined(MICROBLAZE) \
|| defined(S390) \
|| defined(SH) || defined(SH64) \
|| defined(SPARC) || defined(SPARC64) \
/**/
# define NEED_UID16_PARSERS 1
#else
# define NEED_UID16_PARSERS 0
#endif
typedef enum {
CFLAG_NONE = 0,
CFLAG_ONLY_STATS,
CFLAG_BOTH
} cflag_t;
extern cflag_t cflag;
extern bool debug_flag;
extern bool Tflag;
extern bool iflag;
extern bool count_wallclock;
extern unsigned int qflag;
extern bool not_failing_only;
extern unsigned int show_fd_path;
extern bool hide_log_until_execve;
/* are we filtering traces based on paths? */
extern const char **paths_selected;
#define tracing_paths (paths_selected != NULL)
extern unsigned xflag;
extern unsigned followfork;
#ifdef USE_LIBUNWIND
/* if this is true do the stack trace for every system call */
extern bool stack_trace_enabled;
#endif
extern unsigned ptrace_setoptions;
extern unsigned max_strlen;
extern unsigned os_release;
#undef KERNEL_VERSION
#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
void error_msg(const char *fmt, ...) ATTRIBUTE_FORMAT((printf, 1, 2));
void perror_msg(const char *fmt, ...) ATTRIBUTE_FORMAT((printf, 1, 2));
void error_msg_and_die(const char *fmt, ...)
ATTRIBUTE_FORMAT((printf, 1, 2)) ATTRIBUTE_NORETURN;
void error_msg_and_help(const char *fmt, ...)
ATTRIBUTE_FORMAT((printf, 1, 2)) ATTRIBUTE_NORETURN;
void perror_msg_and_die(const char *fmt, ...)
ATTRIBUTE_FORMAT((printf, 1, 2)) ATTRIBUTE_NORETURN;
void die_out_of_memory(void) ATTRIBUTE_NORETURN;
void *xmalloc(size_t size) ATTRIBUTE_MALLOC ATTRIBUTE_ALLOC_SIZE((1));
void *xcalloc(size_t nmemb, size_t size)
ATTRIBUTE_MALLOC ATTRIBUTE_ALLOC_SIZE((1, 2));
void *xreallocarray(void *ptr, size_t nmemb, size_t size)
ATTRIBUTE_ALLOC_SIZE((2, 3));
char *xstrdup(const char *str) ATTRIBUTE_MALLOC;
#if USE_CUSTOM_PRINTF
/*
* See comment in vsprintf.c for allowed formats.
* Short version: %h[h]u, %zu, %tu are not allowed, use %[l[l]]u.
*/
int strace_vfprintf(FILE *fp, const char *fmt, va_list args);
#else
# define strace_vfprintf vfprintf
#endif
extern void set_sortby(const char *);
extern void set_overhead(int);
extern void qualify(const char *);
extern void print_pc(struct tcb *);
extern int trace_syscall(struct tcb *);
extern void count_syscall(struct tcb *, const struct timeval *);
extern void call_summary(FILE *);
extern void clear_regs(void);
extern void get_regs(pid_t pid);
extern int get_scno(struct tcb *tcp);
extern const char *syscall_name(long scno);
extern bool is_erestart(struct tcb *);
extern void temporarily_clear_syserror(struct tcb *);
extern void restore_cleared_syserror(struct tcb *);
extern int umoven(struct tcb *, long, unsigned int, void *);
#define umove(pid, addr, objp) \
umoven((pid), (addr), sizeof(*(objp)), (void *) (objp))
extern int umoven_or_printaddr(struct tcb *, long, unsigned int, void *);
#define umove_or_printaddr(pid, addr, objp) \
umoven_or_printaddr((pid), (addr), sizeof(*(objp)), (void *) (objp))
extern int umove_ulong_or_printaddr(struct tcb *, long, unsigned long *);
extern int umove_ulong_array_or_printaddr(struct tcb *, long, unsigned long *, size_t);
extern int umovestr(struct tcb *, long, unsigned int, char *);
extern int upeek(int pid, long, long *);
#if defined ALPHA || defined IA64 || defined MIPS \
|| defined SH || defined SPARC || defined SPARC64
# define HAVE_GETRVAL2
extern long getrval2(struct tcb *);
#else
# undef HAVE_GETRVAL2
#endif
extern const char *signame(const int);
extern void pathtrace_select(const char *);
extern int pathtrace_match(struct tcb *);
extern int getfdpath(struct tcb *, int, char *, unsigned);
extern const char *xlookup(const struct xlat *, const unsigned int);
extern const char *xlat_search(const struct xlat *, const size_t, const unsigned int);
extern unsigned long get_pagesize(void);
extern int string_to_uint(const char *str);
extern int next_set_bit(const void *bit_array, unsigned cur_bit, unsigned size_bits);
#define QUOTE_0_TERMINATED 0x01
#define QUOTE_OMIT_LEADING_TRAILING_QUOTES 0x02
extern int print_quoted_string(const char *, unsigned int, unsigned int);
/* a refers to the lower numbered u_arg,
* b refers to the higher numbered u_arg
*/
#ifdef HAVE_LITTLE_ENDIAN_LONG_LONG
# define LONG_LONG(a,b) \
((long long)((unsigned long long)(unsigned)(a) | ((unsigned long long)(b)<<32)))
#else
# define LONG_LONG(a,b) \
((long long)((unsigned long long)(unsigned)(b) | ((unsigned long long)(a)<<32)))
#endif
extern int getllval(struct tcb *, unsigned long long *, int);
extern int printllval(struct tcb *, const char *, int)
ATTRIBUTE_FORMAT((printf, 2, 0));
extern void printaddr(long);
extern void printxvals(const unsigned int, const char *, const struct xlat *, ...);
#define printxval(xlat, val, dflt) printxvals(val, dflt, xlat, NULL)
extern int printargs(struct tcb *);
extern int printargs_lu(struct tcb *);
extern int printargs_ld(struct tcb *);
extern void addflags(const struct xlat *, int);
extern int printflags(const struct xlat *, int, const char *);
extern const char *sprintflags(const char *, const struct xlat *, int);
extern const char *sprintmode(int);
extern const char *sprinttime(time_t);
extern void dumpiov_in_msghdr(struct tcb *, long);
extern void dumpiov_in_mmsghdr(struct tcb *, long);
extern void dumpiov(struct tcb *, int, long);
extern void dumpstr(struct tcb *, long, int);
extern void printstr(struct tcb *, long, long);
extern bool printnum_short(struct tcb *, long, const char *)
ATTRIBUTE_FORMAT((printf, 3, 0));
extern bool printnum_int(struct tcb *, long, const char *)
ATTRIBUTE_FORMAT((printf, 3, 0));
extern bool printnum_int64(struct tcb *, long, const char *)
ATTRIBUTE_FORMAT((printf, 3, 0));
#if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4
extern bool printnum_long_int(struct tcb *, long, const char *, const char *)
ATTRIBUTE_FORMAT((printf, 3, 0))
ATTRIBUTE_FORMAT((printf, 4, 0));
# define printnum_slong(tcp, addr) \
printnum_long_int((tcp), (addr), "%" PRId64, "%d")
# define printnum_ulong(tcp, addr) \
printnum_long_int((tcp), (addr), "%" PRIu64, "%u")
# define printnum_ptr(tcp, addr) \
printnum_long_int((tcp), (addr), "%#" PRIx64, "%#x")
#elif SIZEOF_LONG > 4
# define printnum_slong(tcp, addr) \
printnum_int64((tcp), (addr), "%" PRId64)
# define printnum_ulong(tcp, addr) \
printnum_int64((tcp), (addr), "%" PRIu64)
# define printnum_ptr(tcp, addr) \
printnum_int64((tcp), (addr), "%#" PRIx64)
#else
# define printnum_slong(tcp, addr) \
printnum_int((tcp), (addr), "%d")
# define printnum_ulong(tcp, addr) \
printnum_int((tcp), (addr), "%u")
# define printnum_ptr(tcp, addr) \
printnum_int((tcp), (addr), "%#x")
#endif
extern bool printpair_int(struct tcb *, long, const char *)
ATTRIBUTE_FORMAT((printf, 3, 0));
extern bool printpair_int64(struct tcb *, long, const char *)
ATTRIBUTE_FORMAT((printf, 3, 0));
extern void printpath(struct tcb *, long);
extern void printpathn(struct tcb *, long, unsigned int);
#define TIMESPEC_TEXT_BUFSIZE \
(sizeof(intmax_t)*3 * 2 + sizeof("{tv_sec=%jd, tv_nsec=%jd}"))
extern void printfd(struct tcb *, int);
extern bool print_sockaddr_by_inode(const unsigned long, const char *);
extern void print_dirfd(struct tcb *, int);
extern void printsock(struct tcb *, long, int);
extern void print_sock_optmgmt(struct tcb *, long, int);
#ifdef ALPHA
extern void printrusage32(struct tcb *, long);
extern const char *sprint_timeval32(struct tcb *tcp, long);
extern void print_timeval32(struct tcb *tcp, long);
extern void print_timeval32_pair(struct tcb *tcp, long);
extern void print_itimerval32(struct tcb *tcp, long);
#endif
extern void printuid(const char *, const unsigned int);
extern void print_sigset_addr_len(struct tcb *, long, long);
extern const char *sprintsigmask_n(const char *, const void *, unsigned int);
#define tprintsigmask_addr(prefix, mask) \
tprints(sprintsigmask_n((prefix), (mask), sizeof(mask)))
extern void printsignal(int);
extern void tprint_iov(struct tcb *, unsigned long, unsigned long, int decode_iov);
extern void tprint_iov_upto(struct tcb *, unsigned long, unsigned long, int decode_iov, unsigned long);
extern void tprint_open_modes(int);
extern const char *sprint_open_modes(int);
extern void print_seccomp_filter(struct tcb *tcp, unsigned long);
extern int block_ioctl(struct tcb *, const unsigned int, long);
extern int evdev_ioctl(struct tcb *, const unsigned int, long);
extern int loop_ioctl(struct tcb *, const unsigned int, long);
extern int mtd_ioctl(struct tcb *, const unsigned int, long);
extern int ptp_ioctl(struct tcb *, const unsigned int, long);
extern int rtc_ioctl(struct tcb *, const unsigned int, long);
extern int scsi_ioctl(struct tcb *, const unsigned int, long);
extern int sock_ioctl(struct tcb *, const unsigned int, long);
extern int term_ioctl(struct tcb *, const unsigned int, long);
extern int ubi_ioctl(struct tcb *, const unsigned int, long);
extern int v4l2_ioctl(struct tcb *, const unsigned int, long);
extern int tv_nz(const struct timeval *);
extern int tv_cmp(const struct timeval *, const struct timeval *);
extern double tv_float(const struct timeval *);
extern void tv_add(struct timeval *, const struct timeval *, const struct timeval *);
extern void tv_sub(struct timeval *, const struct timeval *, const struct timeval *);
extern void tv_mul(struct timeval *, const struct timeval *, int);
extern void tv_div(struct timeval *, const struct timeval *, int);
#ifdef USE_LIBUNWIND
extern void unwind_init(void);
extern void unwind_tcb_init(struct tcb *tcp);
extern void unwind_tcb_fin(struct tcb *tcp);
extern void unwind_cache_invalidate(struct tcb* tcp);
extern void unwind_print_stacktrace(struct tcb* tcp);
extern void unwind_capture_stacktrace(struct tcb* tcp);
#endif
/* Strace log generation machinery.
*
* printing_tcp: tcb which has incomplete line being printed right now.
* NULL if last line has been completed ('\n'-terminated).
* printleader(tcp) examines it, finishes incomplete line if needed,
* the sets it to tcp.
* line_ended() clears printing_tcp and resets ->curcol = 0.
* tcp->curcol == 0 check is also used to detect completeness
* of last line, since in -ff mode just checking printing_tcp for NULL
* is not enough.
*
* If you change this code, test log generation in both -f and -ff modes
* using:
* strace -oLOG -f[f] test/threaded_execve
* strace -oLOG -f[f] test/sigkill_rain
* strace -oLOG -f[f] -p "`pidof web_browser`"
*/
extern struct tcb *printing_tcp;
extern void printleader(struct tcb *);
extern void line_ended(void);
extern void tabto(void);
extern void tprintf(const char *fmt, ...) ATTRIBUTE_FORMAT((printf, 1, 2));
extern void tprints(const char *str);
#if SUPPORTED_PERSONALITIES > 1
extern void set_personality(int personality);
extern unsigned current_personality;
#else
# define set_personality(personality) ((void)0)
# define current_personality 0
#endif
#if SUPPORTED_PERSONALITIES == 1
# define current_wordsize PERSONALITY0_WORDSIZE
#else
# if SUPPORTED_PERSONALITIES == 2 && PERSONALITY0_WORDSIZE == PERSONALITY1_WORDSIZE
# define current_wordsize PERSONALITY0_WORDSIZE
# else
extern unsigned current_wordsize;
# endif
#endif
/* In many, many places we play fast and loose and use
* tprintf("%d", (int) tcp->u_arg[N]) to print fds, pids etc.
* We probably need to use widen_to_long() instead:
*/
#if SUPPORTED_PERSONALITIES > 1 && SIZEOF_LONG > 4
# define widen_to_long(v) (current_wordsize == 4 ? (long)(int32_t)(v) : (long)(v))
#else
# define widen_to_long(v) ((long)(v))
#endif
extern const struct_sysent sysent0[];
extern const char *const errnoent0[];
extern const char *const signalent0[];
extern const struct_ioctlent ioctlent0[];
extern qualbits_t *qual_vec[SUPPORTED_PERSONALITIES];
#define qual_flags (qual_vec[current_personality])
#if SUPPORTED_PERSONALITIES > 1
extern const struct_sysent *sysent;
extern const char *const *errnoent;
extern const char *const *signalent;
extern const struct_ioctlent *ioctlent;
#else
# define sysent sysent0
# define errnoent errnoent0
# define signalent signalent0
# define ioctlent ioctlent0
#endif
extern unsigned nsyscalls;
extern unsigned nerrnos;
extern unsigned nsignals;
extern unsigned nioctlents;
extern unsigned num_quals;
#if SUPPORTED_PERSONALITIES > 1
# include "printers.h"
#else
# include "native_printer_decls.h"
#endif
/*
* If you need non-NULL sysent[scno].sys_func and sysent[scno].sys_name
*/
#define SCNO_IS_VALID(scno) \
((unsigned long)(scno) < nsyscalls && sysent[scno].sys_func)
/* Only ensures that sysent[scno] isn't out of range */
#define SCNO_IN_RANGE(scno) \
((unsigned long)(scno) < nsyscalls)
#define MPERS_FUNC_NAME__(prefix, name) prefix ## name
#define MPERS_FUNC_NAME_(prefix, name) MPERS_FUNC_NAME__(prefix, name)
#define MPERS_FUNC_NAME(name) MPERS_FUNC_NAME_(MPERS_PREFIX, name)
#define SYS_FUNC_NAME(syscall_name) MPERS_FUNC_NAME(sys_ ## syscall_name)
#define SYS_FUNC(syscall_name) int SYS_FUNC_NAME(syscall_name)(struct tcb *tcp)
#define MPERS_PRINTER_DECL(type, name) type MPERS_FUNC_NAME(name)
| kapdop/android_external_strace | defs.h | C | bsd-3-clause | 28,264 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_NAVIGATION_CONSOLE_LOGGER_H_
#define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_NAVIGATION_CONSOLE_LOGGER_H_
#include <string>
#include <utility>
#include <vector>
#include "content/public/browser/navigation_handle_user_data.h"
#include "content/public/browser/web_contents_observer.h"
#include "third_party/blink/public/mojom/devtools/console_message.mojom.h"
namespace content {
class NavigationHandle;
} // namespace content
namespace subresource_filter {
// This class provides a static API to log console messages when an ongoing
// navigation successfully commits.
// - This class only supports main frame navigations.
// - This class should be replaced with a class scoped to the NavigationHandle
// if it ever starts supporting user data.
class NavigationConsoleLogger
: public content::WebContentsObserver,
public content::NavigationHandleUserData<NavigationConsoleLogger> {
public:
// Creates a NavigationConsoleLogger object if it does not already exist for
// |handle|. It will be scoped until the current main frame navigation commits
// its next navigation. If |handle| has already committed, logs the message
// immediately.
static void LogMessageOnCommit(content::NavigationHandle* handle,
blink::mojom::ConsoleMessageLevel level,
const std::string& message);
NavigationConsoleLogger(const NavigationConsoleLogger&) = delete;
NavigationConsoleLogger& operator=(const NavigationConsoleLogger&) = delete;
~NavigationConsoleLogger() override;
private:
friend class content::NavigationHandleUserData<NavigationConsoleLogger>;
explicit NavigationConsoleLogger(content::NavigationHandle& handle);
// Creates a new NavigationConsoleLogger scoped to |handle| if one doesn't
// exist. Returns the NavigationConsoleLogger associated with |handle|.
//
// Note: |handle| must be associated with a main frame navigation.
static NavigationConsoleLogger* CreateIfNeededForNavigation(
content::NavigationHandle* handle);
// content::WebContentsObserver:
void DidFinishNavigation(content::NavigationHandle* handle) override;
using Message = std::pair<blink::mojom::ConsoleMessageLevel, std::string>;
std::vector<Message> commit_messages_;
// |handle_| must outlive this class. This is guaranteed because the object
// tears itself down with |handle_|'s navigation finishes.
const content::NavigationHandle* handle_;
NAVIGATION_HANDLE_USER_DATA_KEY_DECL();
};
} // namespace subresource_filter
#endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_NAVIGATION_CONSOLE_LOGGER_H_
| scheib/chromium | components/subresource_filter/content/browser/navigation_console_logger.h | C | bsd-3-clause | 2,850 |
from sklearn2sql_heroku.tests.regression import generic as reg_gen
reg_gen.test_model("SVR_rbf" , "freidman1" , "db2")
| antoinecarme/sklearn2sql_heroku | tests/regression/freidman1/ws_freidman1_SVR_rbf_db2_code_gen.py | Python | bsd-3-clause | 121 |
/*
Copyright (c) 2016, Shanghai YUEWEN Information Technology Co., Ltd.
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 Shanghai YUEWEN Information Technology Co., Ltd.
* 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 SHANGHAI YUEWEN INFORMATION TECHNOLOGY CO., LTD.
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 REGENTS AND 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.
Copyright (c) 2016 著作权由上海阅文信息技术有限公司所有。著作权人保留一切权利。
这份授权条款,在使用者符合以下三条件的情形下,授予使用者使用及再散播本软件包装原始码及二进位可执行形式的权利,无论此包装是否经改作皆然:
* 对于本软件源代码的再散播,必须保留上述的版权宣告、此三条件表列,以及下述的免责声明。
* 对于本套件二进位可执行形式的再散播,必须连带以文件以及/或者其他附于散播包装中的媒介方式,重制上述之版权宣告、此三条件表列,以及下述的免责声明。
* 未获事前取得书面许可,不得使用柏克莱加州大学或本软件贡献者之名称,来为本软件之衍生物做任何表示支持、认可或推广、促销之行为。
免责声明:本软件是由上海阅文信息技术有限公司及本软件之贡献者以现状提供,本软件包装不负任何明示或默示之担保责任,
包括但不限于就适售性以及特定目的的适用性为默示性担保。加州大学董事会及本软件之贡献者,无论任何条件、无论成因或任何责任主义、
无论此责任为因合约关系、无过失责任主义或因非违约之侵权(包括过失或其他原因等)而起,对于任何因使用本软件包装所产生的任何直接性、间接性、
偶发性、特殊性、惩罚性或任何结果的损害(包括但不限于替代商品或劳务之购用、使用损失、资料损失、利益损失、业务中断等等),
不负任何责任,即在该种使用已获事前告知可能会造成此类损害的情形下亦然。
*/
package org.albianj.text;
import org.albianj.verify.Validate;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.text.StrSubstitutor;
import java.util.Arrays;
import java.util.Map;
public class StringHelper extends StringUtils {
/*
* Turns a hex encoded string into a byte array. It is specifically meant to
* "reverse" the toHex(byte[]) method.
*
* @param hex a hex encoded String to transform into a byte array.
*
* @return a byte array representing the hex String[
*/
public static final byte[] decodeHex(String hex) {
char[] chars = hex.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int byteCount = 0;
for (int i = 0; i < chars.length; i += 2) {
int newByte = 0x00;
newByte |= hexCharToByte(chars[i]);
newByte <<= 4;
newByte |= hexCharToByte(chars[i + 1]);
bytes[byteCount] = (byte) newByte;
byteCount++;
}
return bytes;
}
/**
* Returns the the byte value of a hexadecmical char (0-f). It's assumed
* that the hexidecimal chars are lower case as appropriate.
*
* @param ch a hexedicmal character (0-f)
* @return the byte value of the character (0x00-0x0F)
*/
private static final byte hexCharToByte(char ch) {
switch (ch) {
case '0':
return 0x00;
case '1':
return 0x01;
case '2':
return 0x02;
case '3':
return 0x03;
case '4':
return 0x04;
case '5':
return 0x05;
case '6':
return 0x06;
case '7':
return 0x07;
case '8':
return 0x08;
case '9':
return 0x09;
case 'a':
return 0x0A;
case 'b':
return 0x0B;
case 'c':
return 0x0C;
case 'd':
return 0x0D;
case 'e':
return 0x0E;
case 'f':
return 0x0F;
}
return 0x00;
}
public static String padLeft(String s, int length) {
if (null == s) {
return null;
}
if (s.length() > length) {
return s.substring(0, length);
}
byte[] bs = new byte[length];
byte[] ss = s.getBytes();
Arrays.fill(bs, (byte) (48 & 0xff));
System.arraycopy(ss, 0, bs, length - ss.length, ss.length);
return new String(bs);
}
public static String censoredZero(String s) {
if (Validate.isNullOrEmptyOrAllSpace(s)) {
return null;
}
int idx = s.lastIndexOf("0");
if (-1 == idx) {
return s;
} else {
return s.substring(idx);
}
}
public static String captureName(String name) {
char[] cs = name.toCharArray();
if ('a' <= cs[0] && 'z' >= cs[0])
cs[0] -= 32;
return String.valueOf(cs);
}
public static String uppercasingFirstLetter(String name) {
char[] cs = name.toCharArray();
if ('a' <= cs[0] && 'z' >= cs[0])
cs[0] -= 32;
return String.valueOf(cs);
}
public static String lowercasingFirstLetter(String txt) {
char[] cs = txt.toCharArray();
if ('A' <= cs[0] && 'Z' >= cs[0])
cs[0] += 32;
return String.valueOf(cs);
}
/**
* 通过具名参数的方式来格式化
* @param template
* @param values
* @code
* String template = "Welcome to {theWorld}. My name is {myName}.";
* Map<String, String> values = new HashMap<>();
* values.put("theWorld", "Stackoverflow");
* values.put("myName", "Thanos");
* @return
*/
public static String formatTemplate(String template, Map<String, Object> values) {
return StrSubstitutor.replace(template, values, "{", "}");
}
// public static String join(Object... args){
// if(null == args || 0 == args.length) {
// return "";
// }
// StringBuilder sb = new StringBuilder();
// for(Object arg : args){
// sb.append(arg);
// }
// return sb.toString();
// }
}
| crosg/Albianj2 | Albianj.Commons/src/main/java/org/albianj/text/StringHelper.java | Java | bsd-3-clause | 7,685 |
/*-
* Copyright (c) 2013, 2014 Jason Lingle
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the author 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 AUTHOR ``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 AUTHOR 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 MICROMP_H_
#define MICROMP_H_
/**
* @file
*
* This file defines the interface for "microMP" (ump), which we use as a
* replacement for OpenMP. The interface obviously isn't as nice as OpenMP, but
* there's a number of reasons not to use the latter:
*
* - This is more portable. We don't need a compiler that supports OMP.
*
* - We're not at the mercy of whatever OMP implementation hapens to live with
* us; we can rely on particular performance characteristics.
*
* - Even good OMP implementations like GNU's are built more with throughput
* than latency in mind. For example, on FreeBSD, delays of up to 250ms are
* occasionally seen, which rather detracts from the graphical experience.
*
* - OMP isn't hugely efficient with micro-tasks we usually get when
* parallelising graphics code with simple OMP directives; making larger
* tasks would generally require surrounding too much code with parallel
* sections, and peppering everything with master-only sections.
*/
/**
* The size of the cache lines on the host system. It is important for
* performance that this is not underestimated, as this may cause false sharing
* between the workers.
*/
#define UMP_CACHE_LINE_SZ 64
/**
* The maximum supported number of threads.
*/
#define UMP_MAX_THREADS 64
/**
* Describes the parameters for executing uMP tasks. This struct may be
* modified at run-time by uMP.
*/
typedef struct {
/**
* The function to execute on each worker. It is up to the calling code to
* arrange some means of communicating parameters to the workers.
*
* @param ix The index of the division the function is to perform.
* @param n The total number of divisions the into which the work is divided
*/
void (*exec)(unsigned ix, unsigned n);
/**
* The maximum number of divisions into which to split any given task.
*/
unsigned num_divisions;
/**
* For async tasks, indicates the number of divisions that are assigned to
* the master thread, which it performs before the async call returns. The
* initial value is a hint to the scheduler. The scheduler will adjust it at
* run-time so as to minimise the time between the work actually being
* completed and ump_join() being called.
*
* This value has no effect for sync calls.
*/
unsigned divisions_for_master;
} ump_task;
/**
* Starts the given number of background worker threads and otherwise
* initialises uMP. If anything goes wrong, the program exits.
*/
void ump_init(unsigned num_threads);
/**
* Executes the given task synchronously. The calling thread will perform a
* share of work equal to the other workers. When this call returns, the task
* is guaranteed to be entirely done.
*
* ump_join() is called implicitly at the start of this function.
*/
void ump_run_sync(ump_task*);
/**
* Executes the given task semi-asynchronously. The calling thread will usually
* perform some work on the task itself before this call returns, though that
* amount is always less than the other workers.
*
* ump_join() is called implicitly at the start of this function.
*/
void ump_run_async(ump_task*);
/**
* Blocks the calling thread until the current task, if any, has completed.
*/
void ump_join(void);
/**
* Checks whether the most recently assigned task is still in-progress. If it
* is, returns 0. If it has completed, returns 1, and it is safe to call other
* ump_ functions again.
*/
int ump_is_finished(void);
/**
* Returns the number of background worker threads are running in uMP.
*/
unsigned ump_num_workers(void);
/**
* Returns a pointer such that:
* ret >= input
* ret < input + UMP_CACHE_LINE_SZ
* ret &~ (UMP_CACHE_LINE_SZ-1) == 0
*
* ie, the input is advanced less than one cache line forward, as necessary to
* ensure that it is aligned to the start of a cache line.
*/
void* align_to_cache_line(void* input);
#endif /* MICROMP_H_ */
| AltSysrq/mantigraphia | src/micromp.h | C | bsd-3-clause | 5,440 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-04 05:22
from __future__ import unicode_literals
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Policy',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('news_duration_date_start', models.DateTimeField(blank=True, null=True)),
('news_duration_date_end', models.DateTimeField(blank=True, null=True)),
('contests_duration_date_start', models.DateTimeField(blank=True, null=True)),
('contests_duration_date_end', models.DateTimeField(blank=True, null=True)),
('max_answers_per_question', models.PositiveSmallIntegerField(default=1, validators=[django.core.validators.MinValueValidator(1)])),
('map_radius', models.PositiveSmallIntegerField(default=500, validators=[django.core.validators.MinValueValidator(1)])),
('admin_email', models.CharField(default='heroku@risingtide.ph', max_length=100)),
('messages_new_account', models.TextField(blank=True, null=True)),
('messages_new_contest', models.TextField(blank=True, null=True)),
('messages_new_loyalty_item', models.TextField(blank=True, null=True)),
('messages_winner', models.TextField(blank=True, null=True)),
('last_update_datetime', models.DateTimeField(blank=True, null=True)),
('claiming_method', models.CharField(blank=True, max_length=200, null=True)),
('country', models.CharField(blank=True, choices=[('indonesia', 'Indonesia'), ('malaysia', 'Malaysia'), ('philippines', 'Philippines'), ('singapore', 'Singapore')], default='Philippines', max_length=15)),
('salesrep_no', models.CharField(blank=True, max_length=200, null=True)),
('last_update_by_author', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'cms_policy',
'verbose_name_plural': 'Policies',
},
),
]
| acercado/jd-ph-cms | jd-ph-cms/policies/migrations/0001_initial.py | Python | bsd-3-clause | 2,519 |
<?php
/* @var $this yii\web\View */
?>
<h1>region/delete</h1>
<p>
You may change the content of this page by modifying
the file <code><?= __FILE__; ?></code>.
</p>
| romaten1/yii2-vk-mongodb | modules/vk/views/region/delete.php | PHP | bsd-3-clause | 173 |
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/snapshot/partial-serializer.h"
#include "src/snapshot/startup-serializer.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
PartialSerializer::PartialSerializer(
Isolate* isolate, StartupSerializer* startup_serializer,
v8::SerializeEmbedderFieldsCallback callback)
: Serializer(isolate),
startup_serializer_(startup_serializer),
serialize_embedder_fields_(callback) {
InitializeCodeAddressMap();
}
PartialSerializer::~PartialSerializer() {
OutputStatistics("PartialSerializer");
}
void PartialSerializer::Serialize(Object** o, bool include_global_proxy) {
if ((*o)->IsContext()) {
Context* context = Context::cast(*o);
reference_map()->AddAttachedReference(context->global_proxy());
// The bootstrap snapshot has a code-stub context. When serializing the
// partial snapshot, it is chained into the weak context list on the isolate
// and it's next context pointer may point to the code-stub context. Clear
// it before serializing, it will get re-added to the context list
// explicitly when it's loaded.
if (context->IsNativeContext()) {
context->set(Context::NEXT_CONTEXT_LINK,
isolate_->heap()->undefined_value());
DCHECK(!context->global_object()->IsUndefined(context->GetIsolate()));
// Reset math random cache to get fresh random numbers.
context->set_math_random_index(Smi::kZero);
context->set_math_random_cache(isolate_->heap()->undefined_value());
}
}
VisitPointer(o);
SerializeDeferredObjects();
SerializeEmbedderFields();
Pad();
}
void PartialSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
WhereToPoint where_to_point, int skip) {
if (obj->IsMap()) {
// The code-caches link to context-specific code objects, which
// the startup and context serializes cannot currently handle.
DCHECK(Map::cast(obj)->code_cache() == obj->GetHeap()->empty_fixed_array());
}
// Replace typed arrays by undefined.
if (obj->IsJSTypedArray()) obj = isolate_->heap()->undefined_value();
if (SerializeHotObject(obj, how_to_code, where_to_point, skip)) return;
int root_index = root_index_map_.Lookup(obj);
if (root_index != RootIndexMap::kInvalidRootIndex) {
PutRoot(root_index, obj, how_to_code, where_to_point, skip);
return;
}
if (SerializeBackReference(obj, how_to_code, where_to_point, skip)) return;
if (ShouldBeInThePartialSnapshotCache(obj)) {
FlushSkip(skip);
int cache_index = startup_serializer_->PartialSnapshotCacheIndex(obj);
sink_.Put(kPartialSnapshotCache + how_to_code + where_to_point,
"PartialSnapshotCache");
sink_.PutInt(cache_index, "partial_snapshot_cache_index");
return;
}
// Pointers from the partial snapshot to the objects in the startup snapshot
// should go through the root array or through the partial snapshot cache.
// If this is not the case you may have to add something to the root array.
DCHECK(!startup_serializer_->reference_map()->Lookup(obj).is_valid());
// All the internalized strings that the partial snapshot needs should be
// either in the root table or in the partial snapshot cache.
DCHECK(!obj->IsInternalizedString());
// Function and object templates are not context specific.
DCHECK(!obj->IsTemplateInfo());
FlushSkip(skip);
// Clear literal boilerplates.
if (obj->IsJSFunction()) {
JSFunction* function = JSFunction::cast(obj);
function->ClearTypeFeedbackInfo();
}
if (obj->IsJSObject()) {
JSObject* jsobj = JSObject::cast(obj);
if (jsobj->GetEmbedderFieldCount() > 0) {
DCHECK_NOT_NULL(serialize_embedder_fields_.callback);
embedder_field_holders_.Add(jsobj);
}
}
// Object has not yet been serialized. Serialize it here.
ObjectSerializer serializer(this, obj, &sink_, how_to_code, where_to_point);
serializer.Serialize();
}
bool PartialSerializer::ShouldBeInThePartialSnapshotCache(HeapObject* o) {
// Scripts should be referred only through shared function infos. We can't
// allow them to be part of the partial snapshot because they contain a
// unique ID, and deserializing several partial snapshots containing script
// would cause dupes.
DCHECK(!o->IsScript());
return o->IsName() || o->IsSharedFunctionInfo() || o->IsHeapNumber() ||
o->IsCode() || o->IsScopeInfo() || o->IsAccessorInfo() ||
o->IsTemplateInfo() ||
o->map() ==
startup_serializer_->isolate()->heap()->fixed_cow_array_map();
}
void PartialSerializer::SerializeEmbedderFields() {
int count = embedder_field_holders_.length();
if (count == 0) return;
DisallowHeapAllocation no_gc;
DisallowJavascriptExecution no_js(isolate());
DisallowCompilation no_compile(isolate());
DCHECK_NOT_NULL(serialize_embedder_fields_.callback);
sink_.Put(kEmbedderFieldsData, "embedder fields data");
while (embedder_field_holders_.length() > 0) {
HandleScope scope(isolate());
Handle<JSObject> obj(embedder_field_holders_.RemoveLast(), isolate());
SerializerReference reference = reference_map_.Lookup(*obj);
DCHECK(reference.is_back_reference());
int embedder_fields_count = obj->GetEmbedderFieldCount();
for (int i = 0; i < embedder_fields_count; i++) {
if (obj->GetEmbedderField(i)->IsHeapObject()) continue;
StartupData data = serialize_embedder_fields_.callback(
v8::Utils::ToLocal(obj), i, serialize_embedder_fields_.data);
sink_.Put(kNewObject + reference.space(), "embedder field holder");
PutBackReference(*obj, reference);
sink_.PutInt(i, "embedder field index");
sink_.PutInt(data.raw_size, "embedder fields data size");
sink_.PutRaw(reinterpret_cast<const byte*>(data.data), data.raw_size,
"embedder fields data");
delete[] data.data;
}
}
sink_.Put(kSynchronize, "Finished with embedder fields data");
}
} // namespace internal
} // namespace v8
| RPGOne/Skynet | node-master/deps/v8/src/snapshot/partial-serializer.cc | C++ | bsd-3-clause | 6,185 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.