code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
package com.snail.webgame.game.protocal.relation.getRequest;
import org.epilot.ccf.config.Resource;
import org.epilot.ccf.core.processor.ProtocolProcessor;
import org.epilot.ccf.core.processor.Request;
import org.epilot.ccf.core.processor.Response;
import org.epilot.ccf.core.protocol.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.snail.webgame.game.common.GameMessageHead;
import com.snail.webgame.game.common.util.Command;
import com.snail.webgame.game.protocal.relation.service.RoleRelationMgtService;
public class GetAddRequestProcessor extends ProtocolProcessor{
private static Logger logger = LoggerFactory.getLogger("logs");
private RoleRelationMgtService roleRelationMgtService;
public void setRoleRelationMgtService(RoleRelationMgtService roleRelationMgtService) {
this.roleRelationMgtService = roleRelationMgtService;
}
@Override
public void execute(Request request, Response response) {
Message msg = request.getMessage();
GameMessageHead header = (GameMessageHead) msg.getHeader();
header.setMsgType(Command.GET_ADD_REQUEST_RESP);
int roleId = header.getUserID0();
GetAddRequestReq req = (GetAddRequestReq) msg.getBody();
GetAddRequestResp resp = roleRelationMgtService.getAddFriendRequestList(roleId, req);
msg.setHeader(header);
msg.setBody(resp);
response.write(msg);
if(logger.isInfoEnabled()){
logger.info(Resource.getMessage("game", "GAME_ROLE_RELATION_INFO_4") + ": result=" + resp.getResult() + ",roleId="
+ roleId);
}
}
}
| bozhbo12/demo-spring-server | spring-game/src/main/java/com/spring/game/game/protocal/relation/getRequest/GetAddRequestProcessor.java | Java | gpl-3.0 | 1,541 |
'use strict';
var ParameterDef = function(object) {
this.id = object.id;
this.summary = object.summary;
this.description = object.description;
this.type = object.type;
this.mandatory = object.mandatory;
this.defaultValue = object.defaultValue;
};
module.exports = ParameterDef;
| linagora/mupee | backend/rules/parameter-definition.js | JavaScript | gpl-3.0 | 292 |
/*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.core;
import java.util.ArrayList;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IModuleDescription;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
/**
* @see IJavaElementRequestor
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class JavaElementRequestor implements IJavaElementRequestor {
/**
* True if this requestor no longer wants to receive
* results from its <code>IRequestorNameLookup</code>.
*/
protected boolean canceled= false;
/**
* A collection of the resulting fields, or <code>null</code>
* if no field results have been received.
*/
protected ArrayList fields= null;
/**
* A collection of the resulting initializers, or <code>null</code>
* if no initializer results have been received.
*/
protected ArrayList initializers= null;
/**
* A collection of the resulting member types, or <code>null</code>
* if no member type results have been received.
*/
protected ArrayList memberTypes= null;
/**
* A collection of the resulting methods, or <code>null</code>
* if no method results have been received.
*/
protected ArrayList methods= null;
/**
* A collection of the resulting package fragments, or <code>null</code>
* if no package fragment results have been received.
*/
protected ArrayList packageFragments= null;
/**
* A collection of the resulting types, or <code>null</code>
* if no type results have been received.
*/
protected ArrayList types= null;
/**
* A collection of the resulting modules, or <code>null</code>
* if no module results have been received
*/
protected ArrayList<IModuleDescription> modules = null;
/**
* Empty arrays used for efficiency
*/
protected static final IField[] EMPTY_FIELD_ARRAY= new IField[0];
protected static final IInitializer[] EMPTY_INITIALIZER_ARRAY= new IInitializer[0];
protected static final IType[] EMPTY_TYPE_ARRAY= new IType[0];
protected static final IPackageFragment[] EMPTY_PACKAGE_FRAGMENT_ARRAY= new IPackageFragment[0];
protected static final IMethod[] EMPTY_METHOD_ARRAY= new IMethod[0];
protected static final IModuleDescription[] EMPTY_MODULE_ARRAY= new IModuleDescription[0];
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptField(IField field) {
if (this.fields == null) {
this.fields= new ArrayList();
}
this.fields.add(field);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptInitializer(IInitializer initializer) {
if (this.initializers == null) {
this.initializers= new ArrayList();
}
this.initializers.add(initializer);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptMemberType(IType type) {
if (this.memberTypes == null) {
this.memberTypes= new ArrayList();
}
this.memberTypes.add(type);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptMethod(IMethod method) {
if (this.methods == null) {
this.methods = new ArrayList();
}
this.methods.add(method);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptPackageFragment(IPackageFragment packageFragment) {
if (this.packageFragments== null) {
this.packageFragments= new ArrayList();
}
this.packageFragments.add(packageFragment);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptType(IType type) {
if (this.types == null) {
this.types= new ArrayList();
}
this.types.add(type);
}
/**
* @see IJavaElementRequestor
*/
@Override
public void acceptModule(IModuleDescription module) {
if (this.modules == null) {
this.modules= new ArrayList();
}
this.modules.add(module);
}
/**
* @see IJavaElementRequestor
*/
public IField[] getFields() {
if (this.fields == null) {
return EMPTY_FIELD_ARRAY;
}
int size = this.fields.size();
IField[] results = new IField[size];
this.fields.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IInitializer[] getInitializers() {
if (this.initializers == null) {
return EMPTY_INITIALIZER_ARRAY;
}
int size = this.initializers.size();
IInitializer[] results = new IInitializer[size];
this.initializers.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IType[] getMemberTypes() {
if (this.memberTypes == null) {
return EMPTY_TYPE_ARRAY;
}
int size = this.memberTypes.size();
IType[] results = new IType[size];
this.memberTypes.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IMethod[] getMethods() {
if (this.methods == null) {
return EMPTY_METHOD_ARRAY;
}
int size = this.methods.size();
IMethod[] results = new IMethod[size];
this.methods.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IPackageFragment[] getPackageFragments() {
if (this.packageFragments== null) {
return EMPTY_PACKAGE_FRAGMENT_ARRAY;
}
int size = this.packageFragments.size();
IPackageFragment[] results = new IPackageFragment[size];
this.packageFragments.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IType[] getTypes() {
if (this.types== null) {
return EMPTY_TYPE_ARRAY;
}
int size = this.types.size();
IType[] results = new IType[size];
this.types.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
public IModuleDescription[] getModules() {
if (this.modules == null) {
return EMPTY_MODULE_ARRAY;
}
int size = this.modules.size();
IModuleDescription[] results = new IModuleDescription[size];
this.modules.toArray(results);
return results;
}
/**
* @see IJavaElementRequestor
*/
@Override
public boolean isCanceled() {
return this.canceled;
}
/**
* Reset the state of this requestor.
*/
public void reset() {
this.canceled = false;
this.fields = null;
this.initializers = null;
this.memberTypes = null;
this.methods = null;
this.packageFragments = null;
this.types = null;
}
/**
* Sets the #isCanceled state of this requestor to true or false.
*/
public void setCanceled(boolean b) {
this.canceled= b;
}
}
| Niky4000/UsefulUtils | projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/JavaElementRequestor.java | Java | gpl-3.0 | 6,654 |
import string
import ast
from state_machine import PSM, Source
class SpecialPattern:
individual_chars = ('t', 'n', 'v', 'f', 'r', '0')
range_chars = ('d', 'D', 'w', 'W', 's', 'S')
special_chars = ('^', '$', '[', ']', '(', ')', '{', '}', '\\', '.', '*',
'?', '+', '|', '.')
restrict_special_chars = ('\\', '[', ']')
posix_classes = ("alnum", "alpha", "blank", "cntrl", "digit", "graph",
"lower", "print", "punct", "space", "upper", "xdigit",
"d", "w", "s")
min_len_posix_class = 1
#-------------------------------------
# Group
class WrappedGroup:
def __init__(self):
self.group = ast.Group()
self.is_alt = False
def add(self, other):
if self.is_alt:
last_alt = self.alt.parts[-1] + (other,)
self.alt.parts = self.alt.parts[:-1] + (last_alt,)
else:
self.group.seq = self.group.seq + (other,)
@property
def alt(self) -> ast.Alternative:
assert self.is_alt
return self.group.seq[0]
def collapse_alt(self):
if self.is_alt:
self.alt.parts = self.alt.parts + ((),)
else:
self.is_alt = True
first_alt_elems = self.group.seq
self.group.seq = (ast.Alternative(),)
self.alt.parts = (first_alt_elems,())
class OpeningOfGroup:
def __init__(self, parent: None, initial: bool=False):
self.is_initial = initial
self.parent = parent # OpeningOfGroup or ContentOfGroup
self.g = WrappedGroup()
self.content_of_initial = None
# forward of function
self.add = self.g.add
# if this group is the initial, their is no parent but we must refer
# to itself as the returning state
# but if it is a nested group, it must be added into its global group
if self.is_initial:
self.content_of_initial = ContentOfGroup(self, initial)
else:
self.parent.add(self.g.group)
def next(self, psm: PSM):
if not self.is_initial and psm.char == "?":
return FirstOptionOfGroup(self)
elif psm.char == ")":
if self.is_initial:
psm.error = 'unexpected ")"'
else:
return self.parent
elif psm.char == "(":
return OpeningOfGroup(self)
elif self.is_initial:
return self.content_of_initial.next(psm)
else:
t = ContentOfGroup(self)
return t.next(psm)
class FirstOptionOfGroup:
def __init__(self, parent: OpeningOfGroup):
self.parent = parent
def next(self, psm: PSM):
if psm.char == ":":
self.parent.g.group.ignored = True
return ContentOfGroup(self.parent)
elif psm.char == "!":
self.parent.g.group.lookhead = ast.Group.NegativeLookhead
return ContentOfGroup(self.parent)
elif psm.char == "=":
self.parent.g.group.lookhead = ast.Group.PositiveLookhead
return ContentOfGroup(self.parent)
elif psm.char == "<":
self.parent.g.group.name = ""
return NameOfGroup(self.parent)
else:
psm.error = 'expected ":", "!", "<" or "="'
class NameOfGroup:
def __init__(self, parent: OpeningOfGroup):
self.parent = parent
def next(self, psm: PSM):
if psm.char.isalpha() or psm.char == "_":
self.parent.g.group.name += psm.char
return self
elif psm.char == ">":
return self.parent
else:
psm.error = 'expected a letter, "_" or ">"'
class ContentOfGroup:
NotQuantified = 0
Quantified = 1
UngreedyQuantified = 2
def __init__(self, parent: OpeningOfGroup, initial: bool=False):
self.parent = parent
self.is_initial = initial
self.limited_prev = parent if initial else self
self.quantified = ContentOfGroup.NotQuantified
# forward of function
self.add = self.parent.add
def next(self, psm: PSM):
quantified = self.quantified
self.quantified = ContentOfGroup.NotQuantified
if psm.char == ")":
if self.is_initial:
psm.error = "unbalanced parenthesis"
else:
return self.parent.parent
elif psm.char == "(":
return OpeningOfGroup(self.limited_prev)
elif psm.char == "^":
self.add(ast.MatchBegin())
return self.limited_prev
elif psm.char == "$":
self.add(ast.MatchEnd())
return self.limited_prev
elif psm.char == ".":
t = ast.PatternChar()
t.pattern = psm.char
self.add(t)
return self.limited_prev
elif psm.char == "\\":
return EscapedChar(self.limited_prev,
as_single_chars=SpecialPattern.special_chars)
elif psm.char == "[":
return CharClass(self.limited_prev)
elif psm.char == "|":
self.parent.g.collapse_alt()
return self.limited_prev
# >>> Quantifiers
elif psm.char == "?" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
last = self._last_or_fail(psm)
if last:
last.quantifier = ast.NoneOrOnce()
return self.limited_prev
elif psm.char == "*" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
last = self._last_or_fail(psm)
if last:
last.quantifier = ast.NoneOrMore()
return self.limited_prev
elif psm.char == "+" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
last = self._last_or_fail(psm)
if last:
last.quantifier = ast.OneOrMore()
return self.limited_prev
elif psm.char == "{" and quantified == ContentOfGroup.NotQuantified:
self.quantified = ContentOfGroup.Quantified
t = MinimumOfRepetition(self.limited_prev)
last = self._last_or_fail(psm)
if last:
last.quantifier = t.between
return t
elif psm.char == "?" and quantified == ContentOfGroup.Quantified:
self.quantified = ContentOfGroup.UngreedyQuantified
last = self._last_or_fail(psm)
if last:
last.quantifier.greedy = False
return self.limited_prev
elif quantified == ContentOfGroup.Quantified:
psm.error = "unexpected quantifier"
elif quantified == ContentOfGroup.UngreedyQuantified:
psm.error = "quantifier repeated"
# <<< Quantifier
else:
t = ast.SingleChar()
t.char = psm.char
self.add(t)
return self.limited_prev
def _last_or_fail(self, psm: PSM):
if self.parent.g.group.seq:
return self.parent.g.group.seq[-1]
else:
psm.error = "nothing to repeat"
class MinimumOfRepetition:
def __init__(self, parent: ContentOfGroup):
self.parent = parent
self.between = ast.Between()
self.min = []
def next(self, psm: PSM):
if psm.char.isdigit():
self.min.append(psm.char)
return self
elif psm.char == ",":
self._interpret()
return MaximumOfRepetition(self)
elif psm.char == "}":
self._interpret()
return self.parent
else:
psm.error = 'expected digit, "," or "}"'
def _interpret(self):
if not self.min:
return
try:
count = int("".join(self.min))
except ValueError:
assert False, "internal error: cannot convert to number minimum of repetition"
self.between.min = count
class MaximumOfRepetition:
def __init__(self, repeat: MinimumOfRepetition):
self.repeat = repeat
self.max = []
def next(self, psm: PSM):
if psm.char.isdigit():
self.max.append(psm.char)
return self
elif psm.char == "}":
self._interpret()
return self.repeat.parent
else:
psm.error = 'expected digit, "," or "}"'
def _interpret(self):
if not self.max:
return
try:
count = int("".join(self.max))
except ValueError:
assert False, "internal error: cannot convert to number maximum of repetition"
self.repeat.between.max = count
#--------------------------------------
# Escaping
class EscapedChar:
def __init__(self, prev, as_single_chars=(), as_pattern_chars=()):
self.prev = prev # ContentOfGroup or CharClass
self.single_chars = as_single_chars
self.pattern_chars = as_pattern_chars
def next(self, psm: PSM):
if psm.char in SpecialPattern.individual_chars \
or psm.char in SpecialPattern.range_chars \
or psm.char in self.pattern_chars:
t = ast.PatternChar()
t.pattern = psm.char
self.prev.add(t)
return self.prev
elif psm.char in self.single_chars:
t = ast.SingleChar()
t.char = psm.char
self.prev.add(t)
return self.prev
elif psm.char == "x":
return AsciiChar(self.prev)
elif psm.char == "u":
return UnicodeChar(self.prev)
else:
psm.error = "unauthorized escape of {}".format(psm.char)
class AsciiChar:
def __init__(self, prev):
self.prev = prev # ContentOfGroup or CharClass
self.pattern = ast.PatternChar()
self.pattern.type = ast.PatternChar.Ascii
self.prev.add(self.pattern)
def next(self, psm: PSM):
if psm.char in string.hexdigits:
self.pattern.pattern += psm.char
count = len(self.pattern.pattern)
return self.prev if count >= 2 else self
else:
psm.error = "expected ASCII hexadecimal character"
class UnicodeChar:
def __init__(self, prev):
self.prev = prev # ContentOfGroup or CharClass
self.pattern = ast.PatternChar()
self.pattern.type = ast.PatternChar.Unicode
self.prev.add(self.pattern)
def next(self, psm: PSM):
if psm.char in string.hexdigits:
self.pattern.pattern += psm.char
count = len(self.pattern.pattern)
return self.prev if count >= 4 else self
else:
psm.error = "expected ASCII hexadecimal character"
#-------------------------------------
# Character class
class WrappedCharClass:
def __init__(self):
# ast is CharClass or may be changed to PatternClass in one case
self.ast = ast.CharClass()
def add(self, other):
assert isinstance(self.ast, ast.CharClass)
self.ast.elems = self.ast.elems + (other,)
def pop(self):
assert isinstance(self.ast, ast.CharClass)
last = self.ast.elems[-1]
self.ast.elems = self.ast.elems[:-1]
return last
class CharClass:
def __init__(self, prev):
self.prev = prev # ContentOfGroup or CharClass
self.q = WrappedCharClass()
# forward function
self.add = self.q.add
self.next_is_range = False
self.empty = True
self.can_mutate = True
def next(self, psm: PSM):
this_should_be_range = self.next_is_range
self.next_is_range = False
this_is_empty = self.empty
self.empty = False
if psm.char == "\\":
self.can_mutate = False
self.next_is_range = this_should_be_range
return EscapedChar(self,
as_single_chars=SpecialPattern.restrict_special_chars)
elif this_should_be_range and psm.char != "]":
assert isinstance(self.q.ast, ast.CharClass)
assert len(self.q.ast.elems) >= 1
self.next_is_range = False
t = ast.Range()
t.begin = self.q.pop()
t.end = ast.SingleChar()
t.end.char = psm.char
self.q.add(t)
return self
elif psm.char == "^":
# if at the begining, it has a special meaning
if this_is_empty:
self.can_mutate = False
self.q.ast.negate = True
else:
t = ast.SingleChar()
t.char = psm.char
self.q.add(t)
return self
elif psm.char == "]":
if this_should_be_range:
t = ast.SingleChar()
t.char = "-"
self.q.add(t)
else:
self.mutate_if_posix_like()
self.prev.add(self.q.ast)
return self.prev
elif psm.char == "[":
return CharClass(self)
elif psm.char == "-" and len(self.q.ast.elems) >= 1:
self.next_is_range = True
return self
else:
t = ast.SingleChar()
t.char = psm.char
self.q.add(t)
return self
def mutate_if_posix_like(self):
"""
Change from character class to pattern char if the content is matching
POSIX-like classe.
"""
assert isinstance(self.q.ast, ast.CharClass)
# put in this variable everything that had happen but not saved into
# the single char object
# because mutation is only possible if the exact string of the content
# match a pre-definied list, so if an unlogged char is consumed, it
# must prevent mutation
if not self.can_mutate:
return
if len(self.q.ast.elems) < SpecialPattern.min_len_posix_class + 2:
return
opening = self.q.ast.elems[0]
if not isinstance(opening, ast.SingleChar) or opening.char != ":":
return
closing = self.q.ast.elems[-1]
if not isinstance(closing, ast.SingleChar) or closing.char != ":":
return
is_only_ascii = lambda x: (isinstance(x, ast.SingleChar)
and len(x.char) == 1
and x.char.isalpha())
class_may_be_a_word = not any(
not is_only_ascii(x) for x in self.q.ast.elems[1:-1])
if not class_may_be_a_word:
return
word = "".join(s.char for s in self.q.ast.elems[1:-1])
if word not in SpecialPattern.posix_classes:
return
t = ast.PatternChar()
t.pattern = word
t.type = ast.PatternChar.Posix
self.q.ast = t
#-------------------------------------
def parse(expr, **kw):
sm = PSM()
sm.source = Source(expr)
sm.starts_with(OpeningOfGroup(parent=None, initial=True))
sm.pre_action = kw.get("pre_action", None)
sm.post_action = kw.get("post_action", None)
sm.parse()
return sm.state.g.group
| VaysseB/id_generator | src/parser.py | Python | gpl-3.0 | 15,217 |
{
am_pm_abbreviated => [
"Munkyo",
"Eigulo"
],
available_formats => {
E => "ccc",
EHm => "E HH:mm",
EHms => "E HH:mm:ss",
Ed => "d, E",
Ehm => "E h:mm a",
Ehms => "E h:mm:ss a",
Gy => "G y",
GyMMM => "G y MMM",
GyMMMEd => "G y MMM d, E",
GyMMMd => "G y MMM d",
H => "HH",
Hm => "HH:mm",
Hms => "HH:mm:ss",
Hmsv => "HH:mm:ss v",
Hmv => "HH:mm v",
M => "L",
MEd => "E, M/d",
MMM => "LLL",
MMMEd => "E, MMM d",
MMMMEd => "E, MMMM d",
"MMMMW-count-other" => "'week' W 'of' MMMM",
MMMMd => "MMMM d",
MMMd => "MMM d",
Md => "M/d",
d => "d",
h => "h a",
hm => "h:mm a",
hms => "h:mm:ss a",
hmsv => "h:mm:ss a v",
hmv => "h:mm a v",
ms => "mm:ss",
y => "y",
yM => "M/y",
yMEd => "E, M/d/y",
yMMM => "MMM y",
yMMMEd => "E, MMM d, y",
yMMMM => "MMMM y",
yMMMd => "y MMM d",
yMd => "y-MM-dd",
yQQQ => "QQQ y",
yQQQQ => "QQQQ y",
"yw-count-other" => "'week' w 'of' y"
},
code => "xog",
date_format_full => "EEEE, d MMMM y",
date_format_long => "d MMMM y",
date_format_medium => "d MMM y",
date_format_short => "dd/MM/y",
datetime_format_full => "{1} {0}",
datetime_format_long => "{1} {0}",
datetime_format_medium => "{1} {0}",
datetime_format_short => "{1} {0}",
day_format_abbreviated => [
"Bala",
"Kubi",
"Kusa",
"Kuna",
"Kuta",
"Muka",
"Sabi"
],
day_format_narrow => [
"B",
"B",
"S",
"K",
"K",
"M",
"S"
],
day_format_wide => [
"Balaza",
"Owokubili",
"Owokusatu",
"Olokuna",
"Olokutaanu",
"Olomukaaga",
"Sabiiti"
],
day_stand_alone_abbreviated => [
"Bala",
"Kubi",
"Kusa",
"Kuna",
"Kuta",
"Muka",
"Sabi"
],
day_stand_alone_narrow => [
"B",
"B",
"S",
"K",
"K",
"M",
"S"
],
day_stand_alone_wide => [
"Balaza",
"Owokubili",
"Owokusatu",
"Olokuna",
"Olokutaanu",
"Olomukaaga",
"Sabiiti"
],
era_abbreviated => [
"AZ",
"AF"
],
era_narrow => [
"AZ",
"AF"
],
era_wide => [
"Kulisto nga azilawo",
"Kulisto nga affile"
],
first_day_of_week => 1,
glibc_date_1_format => "%a %b %e %H:%M:%S %Z %Y",
glibc_date_format => "%m/%d/%y",
glibc_datetime_format => "%a %b %e %H:%M:%S %Y",
glibc_time_12_format => "%I:%M:%S %p",
glibc_time_format => "%H:%M:%S",
language => "Soga",
month_format_abbreviated => [
"Jan",
"Feb",
"Mar",
"Apu",
"Maa",
"Juu",
"Jul",
"Agu",
"Seb",
"Oki",
"Nov",
"Des"
],
month_format_narrow => [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
month_format_wide => [
"Janwaliyo",
"Febwaliyo",
"Marisi",
"Apuli",
"Maayi",
"Juuni",
"Julaayi",
"Agusito",
"Sebuttemba",
"Okitobba",
"Novemba",
"Desemba"
],
month_stand_alone_abbreviated => [
"Jan",
"Feb",
"Mar",
"Apu",
"Maa",
"Juu",
"Jul",
"Agu",
"Seb",
"Oki",
"Nov",
"Des"
],
month_stand_alone_narrow => [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
month_stand_alone_wide => [
"Janwaliyo",
"Febwaliyo",
"Marisi",
"Apuli",
"Maayi",
"Juuni",
"Julaayi",
"Agusito",
"Sebuttemba",
"Okitobba",
"Novemba",
"Desemba"
],
name => "Soga",
native_language => "Olusoga",
native_name => "Olusoga",
native_script => undef,
native_territory => undef,
native_variant => undef,
quarter_format_abbreviated => [
"Q1",
"Q2",
"Q3",
"Q4"
],
quarter_format_narrow => [
1,
2,
3,
4
],
quarter_format_wide => [
"Ebisera ebyomwaka ebisoka",
"Ebisera ebyomwaka ebyokubiri",
"Ebisera ebyomwaka ebyokusatu",
"Ebisera ebyomwaka ebyokuna"
],
quarter_stand_alone_abbreviated => [
"Q1",
"Q2",
"Q3",
"Q4"
],
quarter_stand_alone_narrow => [
1,
2,
3,
4
],
quarter_stand_alone_wide => [
"Ebisera ebyomwaka ebisoka",
"Ebisera ebyomwaka ebyokubiri",
"Ebisera ebyomwaka ebyokusatu",
"Ebisera ebyomwaka ebyokuna"
],
script => undef,
territory => undef,
time_format_full => "HH:mm:ss zzzz",
time_format_long => "HH:mm:ss z",
time_format_medium => "HH:mm:ss",
time_format_short => "HH:mm",
variant => undef,
version => 31
}
| mgood7123/UPM | Files/Code/perl/lib/site_perl/5.26.1/auto/share/dist/DateTime-Locale/xog.pl | Perl | gpl-3.0 | 4,559 |
/*
* eGov suite of products aim to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) <2015> eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at [email protected].
*/
package org.egov.search.service;
import org.egov.search.domain.entities.Address;
import org.egov.search.domain.entities.Person;
import org.json.simple.JSONObject;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import static com.jayway.jsonassert.JsonAssert.with;
public class SimpleFieldsResourceGeneratorTest {
private String json;
@Before
public void before() {
Person person = Person.newInstance();
ResourceGenerator<Person> resourceGenerator = new ResourceGenerator<>(Person.class, person);
JSONObject resource = resourceGenerator.generate();
json = resource.toJSONString();
}
@Test
public void withMultipleFields() {
with(json).assertEquals("$.searchable.citizen", true);
with(json).assertEquals("$.searchable.age", 37);
with(json).assertEquals("$.clauses.status", "ACTIVE");
with(json).assertNotDefined("$.searchable.role");
}
@Test
public void withMultipleFields_WithGivenName() {
with(json).assertEquals("$.searchable.citizen_name", "Elzan");
}
@Test
public void withAListField() {
with(json).assertEquals("$.searchable.jobs", Arrays.asList("Job One", "Job Two"));
}
@Test
public void withAMapField() {
with(json).assertEquals("$.searchable.serviceHistory.company1", "Job One");
with(json).assertEquals("$.searchable.serviceHistory.company2", "Job Two");
}
@Test
public void shouldGroupFields() {
Address address = new Address("street1", "560001");
ResourceGenerator<Address> resourceGenerator = new ResourceGenerator<>(Address.class, address);
JSONObject resource = resourceGenerator.generate();
String json = resource.toJSONString();
with(json).assertEquals("$.searchable.street", "street1");
with(json).assertEquals("$.searchable.pincode", "560001");
with(json).assertNotDefined("$.clauses");
with(json).assertNotDefined("$.common");
}
}
| egovernments/eGov-Search | src/test/java/org/egov/search/service/SimpleFieldsResourceGeneratorTest.java | Java | gpl-3.0 | 3,937 |
Fox.define('views/email/fields/from-email-address', 'views/fields/link', function (Dep) {
return Dep.extend({
listTemplate: 'email/fields/from-email-address/detail',
detailTemplate: 'email/fields/from-email-address/detail',
});
});
| ilovefox8/zhcrm | client/src/views/email/fields/from-email-address.js | JavaScript | gpl-3.0 | 261 |
package com.mx.fic.inventory.business.builder;
import com.mx.fic.inventory.business.builder.config.AbstractDTOBuilder;
import com.mx.fic.inventory.business.builder.config.BuilderConfiguration;
import com.mx.fic.inventory.dto.BaseDTO;
import com.mx.fic.inventory.dto.UserDetailDTO;
import com.mx.fic.inventory.persistent.BaseEntity;
import com.mx.fic.inventory.persistent.UserDetail;
@BuilderConfiguration (dtoClass = UserDetailDTO.class, entityClass= UserDetail.class)
public class UserDetailBuilder extends AbstractDTOBuilder {
public BaseDTO createDTO(BaseEntity entity) {
UserDetailDTO userDetailDTO = new UserDetailDTO();
UserDetail userDetail = (UserDetail) entity;
userDetailDTO.setAddress(userDetail.getAddress());
userDetailDTO.setCurp(userDetail.getCurp());
userDetailDTO.setEmail(userDetail.getEmail());
userDetailDTO.setId(userDetail.getId());
userDetailDTO.setLastAccess(userDetail.getLastAccess());
userDetailDTO.setLastName(userDetail.getLastName());
userDetailDTO.setName(userDetail.getName());
userDetailDTO.setRfc(userDetail.getRfc());
userDetailDTO.setShortName(userDetail.getShortName());
userDetailDTO.setSurName(userDetail.getSurName());
return userDetailDTO;
}
}
| modemm3/fic | fic-inventory/fic-inventory-business/src/main/java/com/mx/fic/inventory/business/builder/UserDetailBuilder.java | Java | gpl-3.0 | 1,223 |
export function Bounds(width, height) {
this.width = width;
this.height = height;
}
Bounds.prototype.equals = function(o) {
return ((o != null) && (this.width == o.width) && (this.height == o.height));
};
| elkonurbaev/nine-e | src/utils/Bounds.js | JavaScript | gpl-3.0 | 219 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- qsqlquerymodel.cpp -->
<title>List of All Members for QSqlQueryModel | Qt SQL 5.7</title>
<link rel="stylesheet" type="text/css" href="style/offline-simple.css" />
<script type="text/javascript">
window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");};
</script>
</head>
<body>
<div class="header" id="qtdocheader">
<div class="main">
<div class="main-rounded">
<div class="navigationbar">
<table><tr>
<td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtsql-index.html">Qt SQL</a></td><td ><a href="qtsql-module.html">C++ Classes</a></td><td >QSqlQueryModel</td></tr></table><table class="buildversion"><tr>
<td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td>
</tr></table>
</div>
</div>
<div class="content">
<div class="line">
<div class="content mainContent">
<div class="sidebar"><div class="sidebar-content" id="sidebar-content"></div></div>
<h1 class="title">List of All Members for QSqlQueryModel</h1>
<p>This is the complete list of members for <a href="qsqlquerymodel.html">QSqlQueryModel</a>, including inherited members.</p>
<div class="table"><table class="propsummary">
<tr><td class="topAlign"><ul>
<li class="fn">enum <span class="name"><b><a href="../qtcore/qabstractitemmodel.html#LayoutChangeHint-enum">LayoutChangeHint</a></b></span></li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#QSqlQueryModel">QSqlQueryModel</a></b></span>(QObject *)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#dtor.QSqlQueryModel">~QSqlQueryModel</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginInsertColumns">beginInsertColumns</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginInsertRows">beginInsertRows</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginMoveColumns">beginMoveColumns</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginMoveRows">beginMoveRows</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginRemoveColumns">beginRemoveColumns</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginRemoveRows">beginRemoveRows</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#beginResetModel">beginResetModel</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#blockSignals">blockSignals</a></b></span>(bool )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#buddy">buddy</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#canDropMimeData">canDropMimeData</a></b></span>(const QMimeData *, Qt::DropAction , int , int , const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#canFetchMore">canFetchMore</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#canFetchMore">canFetchMore</a></b></span>(const QModelIndex &) const : bool</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#changePersistentIndex">changePersistentIndex</a></b></span>(const QModelIndex &, const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#changePersistentIndexList">changePersistentIndexList</a></b></span>(const QModelIndexList &, const QModelIndexList &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#childEvent">childEvent</a></b></span>(QChildEvent *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#children">children</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#clear">clear</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnCount">columnCount</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#columnCount">columnCount</a></b></span>(const QModelIndex &) const : int</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsAboutToBeInserted">columnsAboutToBeInserted</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsAboutToBeMoved">columnsAboutToBeMoved</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsAboutToBeRemoved">columnsAboutToBeRemoved</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsInserted">columnsInserted</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsMoved">columnsMoved</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#columnsRemoved">columnsRemoved</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect">connect</a></b></span>(const QObject *, const char *, const QObject *, const char *, Qt::ConnectionType )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-1">connect</a></b></span>(const QObject *, const QMetaMethod &, const QObject *, const QMetaMethod &, Qt::ConnectionType )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-2">connect</a></b></span>(const QObject *, const char *, const char *, Qt::ConnectionType ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-3">connect</a></b></span>(const QObject *, PointerToMemberFunction , const QObject *, PointerToMemberFunction , Qt::ConnectionType )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-4">connect</a></b></span>(const QObject *, PointerToMemberFunction , Functor )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connect-5">connect</a></b></span>(const QObject *, PointerToMemberFunction , const QObject *, Functor , Qt::ConnectionType )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#connectNotify">connectNotify</a></b></span>(const QMetaMethod &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#createIndex">createIndex</a></b></span>(int , int , void *) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#createIndex-1">createIndex</a></b></span>(int , int , quintptr ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#customEvent">customEvent</a></b></span>(QEvent *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#d_ptr-var">d_ptr</a></b></span> : </li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#data">data</a></b></span>(const QModelIndex &, int ) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#data">data</a></b></span>(const QModelIndex &, int ) const : QVariant</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#dataChanged">dataChanged</a></b></span>(const QModelIndex &, const QModelIndex &, const QVector<int> &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#deleteLater">deleteLater</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#destroyed">destroyed</a></b></span>(QObject *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect">disconnect</a></b></span>(const QObject *, const char *, const QObject *, const char *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-1">disconnect</a></b></span>(const QObject *, const QMetaMethod &, const QObject *, const QMetaMethod &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-4">disconnect</a></b></span>(const QMetaObject::Connection &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-2">disconnect</a></b></span>(const char *, const QObject *, const char *) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-3">disconnect</a></b></span>(const QObject *, const char *) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnect-5">disconnect</a></b></span>(const QObject *, PointerToMemberFunction , const QObject *, PointerToMemberFunction )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#disconnectNotify">disconnectNotify</a></b></span>(const QMetaMethod &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#dropMimeData">dropMimeData</a></b></span>(const QMimeData *, Qt::DropAction , int , int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#dropMimeData">dropMimeData</a></b></span>(const QMimeData *, Qt::DropAction , int , int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#dumpObjectInfo">dumpObjectInfo</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#dumpObjectTree">dumpObjectTree</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#dynamicPropertyNames">dynamicPropertyNames</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endInsertColumns">endInsertColumns</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endInsertRows">endInsertRows</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endMoveColumns">endMoveColumns</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endMoveRows">endMoveRows</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endRemoveColumns">endRemoveColumns</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endRemoveRows">endRemoveRows</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#endResetModel">endResetModel</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#event">event</a></b></span>(QEvent *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#eventFilter">eventFilter</a></b></span>(QObject *, QEvent *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#fetchMore">fetchMore</a></b></span>(const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#fetchMore">fetchMore</a></b></span>(const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChild">findChild</a></b></span>(const QString &, Qt::FindChildOptions ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChildren">findChildren</a></b></span>(const QString &, Qt::FindChildOptions ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChildren-1">findChildren</a></b></span>(const QRegExp &, Qt::FindChildOptions ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#findChildren-2">findChildren</a></b></span>(const QRegularExpression &, Qt::FindChildOptions ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#flags">flags</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#flags">flags</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#hasChildren">hasChildren</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#hasIndex">hasIndex</a></b></span>(int , int , const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#headerData">headerData</a></b></span>(int , Qt::Orientation , int ) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#headerData">headerData</a></b></span>(int , Qt::Orientation , int ) const : QVariant</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#headerDataChanged">headerDataChanged</a></b></span>(Qt::Orientation , int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#index">index</a></b></span>(int , int , const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#index">index</a></b></span>(int , int , const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#indexInQuery">indexInQuery</a></b></span>(const QModelIndex &) const : QModelIndex</li>
</ul></td><td class="topAlign"><ul>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#inherits">inherits</a></b></span>(const char *) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertColumn">insertColumn</a></b></span>(int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertColumns">insertColumns</a></b></span>(int , int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#insertColumns">insertColumns</a></b></span>(int , int , const QModelIndex &) : bool</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertRow">insertRow</a></b></span>(int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#insertRows">insertRows</a></b></span>(int , int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#installEventFilter">installEventFilter</a></b></span>(QObject *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#isSignalConnected">isSignalConnected</a></b></span>(const QMetaMethod &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#isWidgetType">isWidgetType</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#isWindowType">isWindowType</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#itemData">itemData</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#killTimer">killTimer</a></b></span>(int )</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#lastError">lastError</a></b></span>() const : QSqlError</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#layoutAboutToBeChanged">layoutAboutToBeChanged</a></b></span>(const QList<QPersistentModelIndex> &, QAbstractItemModel::LayoutChangeHint )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#layoutChanged">layoutChanged</a></b></span>(const QList<QPersistentModelIndex> &, QAbstractItemModel::LayoutChangeHint )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#match">match</a></b></span>(const QModelIndex &, int , const QVariant &, int , Qt::MatchFlags ) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#metaObject">metaObject</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#mimeData">mimeData</a></b></span>(const QModelIndexList &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#mimeTypes">mimeTypes</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#modelAboutToBeReset">modelAboutToBeReset</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#modelReset">modelReset</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveColumn">moveColumn</a></b></span>(const QModelIndex &, int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveColumns">moveColumns</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveRow">moveRow</a></b></span>(const QModelIndex &, int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#moveRows">moveRows</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#moveToThread">moveToThread</a></b></span>(QThread *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#objectName-prop">objectName</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#objectNameChanged">objectNameChanged</a></b></span>(const QString &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#parent">parent</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#parent">parent</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#persistentIndexList">persistentIndexList</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#property">property</a></b></span>(const char *) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#query">query</a></b></span>() const : QSqlQuery</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#queryChange">queryChange</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#receivers">receivers</a></b></span>(const char *) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#record">record</a></b></span>(int ) const : QSqlRecord</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#record-1">record</a></b></span>() const : QSqlRecord</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeColumn">removeColumn</a></b></span>(int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeColumns">removeColumns</a></b></span>(int , int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#removeColumns">removeColumns</a></b></span>(int , int , const QModelIndex &) : bool</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#removeEventFilter">removeEventFilter</a></b></span>(QObject *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeRow">removeRow</a></b></span>(int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#removeRows">removeRows</a></b></span>(int , int , const QModelIndex &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#resetInternalData">resetInternalData</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#revert">revert</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#roleNames">roleNames</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowCount">rowCount</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#rowCount">rowCount</a></b></span>(const QModelIndex &) const : int</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsAboutToBeInserted">rowsAboutToBeInserted</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsAboutToBeMoved">rowsAboutToBeMoved</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsAboutToBeRemoved">rowsAboutToBeRemoved</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsInserted">rowsInserted</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsMoved">rowsMoved</a></b></span>(const QModelIndex &, int , int , const QModelIndex &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#rowsRemoved">rowsRemoved</a></b></span>(const QModelIndex &, int , int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#sender">sender</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#senderSignalIndex">senderSignalIndex</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#setData">setData</a></b></span>(const QModelIndex &, const QVariant &, int )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#setHeaderData">setHeaderData</a></b></span>(int , Qt::Orientation , const QVariant &, int )</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setHeaderData">setHeaderData</a></b></span>(int , Qt::Orientation , const QVariant &, int ) : bool</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#setItemData">setItemData</a></b></span>(const QModelIndex &, const QMap<int, QVariant> &)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setLastError">setLastError</a></b></span>(const QSqlError &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#objectName-prop">setObjectName</a></b></span>(const QString &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#setParent">setParent</a></b></span>(QObject *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#setProperty">setProperty</a></b></span>(const char *, const QVariant &)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setQuery">setQuery</a></b></span>(const QSqlQuery &)</li>
<li class="fn"><span class="name"><b><a href="qsqlquerymodel.html#setQuery-1">setQuery</a></b></span>(const QString &, const QSqlDatabase &)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#sibling">sibling</a></b></span>(int , int , const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstracttablemodel.html#sibling">sibling</a></b></span>(int , int , const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#signalsBlocked">signalsBlocked</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#sort">sort</a></b></span>(int , Qt::SortOrder )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#span">span</a></b></span>(const QModelIndex &) const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#startTimer">startTimer</a></b></span>(int , Qt::TimerType )</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#staticMetaObject-var">staticMetaObject</a></b></span> : </li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#staticQtMetaObject-var">staticQtMetaObject</a></b></span> : </li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#submit">submit</a></b></span>()</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#supportedDragActions">supportedDragActions</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qabstractitemmodel.html#supportedDropActions">supportedDropActions</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#thread">thread</a></b></span>() const</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#timerEvent">timerEvent</a></b></span>(QTimerEvent *)</li>
<li class="fn"><span class="name"><b><a href="../qtcore/qobject.html#tr">tr</a></b></span>(const char *, const char *, int )</li>
</ul>
</td></tr>
</table></div>
</div>
</div>
</div>
</div>
</div>
<div class="footer">
<p>
<acronym title="Copyright">©</acronym> 2016 The Qt Company Ltd.
Documentation contributions included herein are the copyrights of
their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property
of their respective owners. </p>
</div>
</body>
</html>
| angeloprudentino/QtNets | Doc/qtsql/qsqlquerymodel-members.html | HTML | gpl-3.0 | 26,906 |
import {
ATTENDANCE_STATUS_CONFIG_ID,
AttendanceStatusType,
NullAttendanceStatusType,
} from "./attendance-status";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
/**
* Simple relationship object to represent an individual child's status at an event including context information.
*/
export class EventAttendance {
private _status: AttendanceStatusType;
@DatabaseField({
dataType: "configurable-enum",
innerDataType: ATTENDANCE_STATUS_CONFIG_ID,
})
get status(): AttendanceStatusType {
return this._status;
}
set status(value) {
if (typeof value === "object") {
this._status = value;
} else {
this._status = NullAttendanceStatusType;
}
}
@DatabaseField() remarks: string;
constructor(
status: AttendanceStatusType = NullAttendanceStatusType,
remarks: string = ""
) {
this.status = status;
this.remarks = remarks;
}
}
| NGO-DB/ndb-core | src/app/child-dev-project/attendance/model/event-attendance.ts | TypeScript | gpl-3.0 | 934 |
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue';
import BootstrapVue from 'bootstrap-vue';
import 'bootstrap-vue/dist/bootstrap-vue.css';
import 'bootstrap/dist/css/bootstrap.css';
import { mapActions } from 'vuex';
import App from './App';
import websock from './websock';
import * as mtype from './store/mutation-types';
import store from './store';
Vue.config.productionTip = false;
Vue.use(BootstrapVue);
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
store,
components: { App },
created() {
websock.connect(message => this.newMessage(message));
setInterval(() => { store.commit(mtype.UPDATE_CALLS_DUR); }, 1000);
},
methods: mapActions(['newMessage']),
});
| staskobzar/amiws | web_root_vue/src/main.js | JavaScript | gpl-3.0 | 826 |
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Surname - RAINSFORD</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li class = "CurrentSection"><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="SurnameDetail">
<h3>RAINSFORD</h3>
<p id="description">
This page contains an index of all the individuals in the database with the surname of RAINSFORD. Selecting the person’s name will take you to that person’s individual page.
</p>
<table class="infolist primobjlist surname">
<thead>
<tr>
<th class="ColumnName">Given Name</th>
<th class="ColumnDate">Birth</th>
<th class="ColumnDate">Death</th>
<th class="ColumnPartner">Partner</th>
<th class="ColumnParents">Parents</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnName">
<a href="../../../ppl/b/1/d15f5fe0c5b127625ca75ac491b.html">Margaret<span class="grampsid"> [I3099]</span></a>
</td>
<td class="ColumnBirth"> </td>
<td class="ColumnDeath"> </td>
<td class="ColumnPartner">
<a href="../../../ppl/3/1/d15f5fe0c4a27430484a60d8013.html">GROVES, Henry<span class="grampsid"> [I3098]</span></a>
</td>
<td class="ColumnParents"> </td>
</tr>
</tbody>
</table>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:14<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
| RossGammon/the-gammons.net | RossFamilyTree/srn/f/3/95b01a5fdd342ebb10992a51c878ec3f.html | HTML | gpl-3.0 | 3,143 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<meta charset="utf-8"/>
<title> » Deprecated elements
</title>
<meta name="author" content=""/>
<meta name="description" content=""/>
<link href="../css/bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="../css/font-awesome.min.css" rel="stylesheet">
<link href="../css/prism.css" rel="stylesheet" media="all"/>
<link href="../css/template.css" rel="stylesheet" media="all"/>
<!--[if lt IE 9]>
<script src="../js/html5.js"></script>
<![endif]-->
<script src="../js/jquery-1.11.0.min.js"></script>
<script src="../js/ui/1.10.4/jquery-ui.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/jquery.smooth-scroll.js"></script>
<script src="../js/prism.min.js"></script>
<!-- TODO: Add http://jscrollpane.kelvinluck.com/ to style the scrollbars for browsers not using webkit-->
<link rel="shortcut icon" href="../images/favicon.ico"/>
<link rel="apple-touch-icon" href="../images/apple-touch-icon.png"/>
<link rel="apple-touch-icon" sizes="72x72" href="../images/apple-touch-icon-72x72.png"/>
<link rel="apple-touch-icon" sizes="114x114" href="../images/apple-touch-icon-114x114.png"/>
</head>
<body>
<div class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<i class="icon-ellipsis-vertical"></i>
</a>
<a class="brand" href="../index.html">DataUtilities</a>
<div class="nav-collapse">
<ul class="nav pull-right">
<li class="dropdown">
<a href="../index.html" class="dropdown-toggle" data-toggle="dropdown">
API Documentation <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="../namespaces/Battis.html">\Battis</a></li>
</ul>
</li>
<li class="dropdown" id="charts-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Charts <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="../graphs/class.html">
<i class="icon-list-alt"></i> Class hierarchy diagram
</a>
</li>
</ul>
</li>
<li class="dropdown" id="reports-menu">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="../reports/errors.html">
<i class="icon-list-alt"></i> Errors <span class="label label-info pull-right">0</span>
</a>
</li>
<li>
<a href="../reports/markers.html">
<i class="icon-list-alt"></i> Markers <span class="label label-info pull-right">2</span>
</a>
</li>
<li>
<a href="../reports/deprecated.html">
<i class="icon-list-alt"></i> Deprecated <span class="label label-info pull-right">0</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<!--<div class="go_to_top">-->
<!--<a href="#___" style="color: inherit">Back to top  <i class="icon-upload icon-white"></i></a>-->
<!--</div>-->
</div>
<div id="___" class="container-fluid">
<div class="row-fluid">
<div class="span2 sidebar">
<ul class="side-nav nav nav-list">
<li class="nav-header">Navigation</li>
</ul>
</div>
<div class="span10 offset2">
<ul class="breadcrumb">
<li><a href="../"><i class="icon-remove-sign"></i></a><span class="divider">\</span></li>
<li>Deprecated elements</li>
</ul>
<div id="marker-accordion">
<div class="alert alert-info">No deprecated elements have been found in this project.</div>
</table>
</div>
</div>
</div>
</div>
<footer class="row-fluid">
<section class="span10 offset2">
<section class="row-fluid">
<section class="span10 offset1">
<section class="row-fluid footer-sections">
<section class="span4">
<h1><i class="icon-code"></i></h1>
<div>
<ul>
<li><a href="../namespaces/Battis.html">\Battis</a></li>
</ul>
</div>
</section>
<section class="span4">
<h1><i class="icon-bar-chart"></i></h1>
<div>
<ul>
<li><a href="../graphs/class.html">Class Hierarchy Diagram</a></li>
</ul>
</div>
</section>
<section class="span4">
<h1><i class="icon-pushpin"></i></h1>
<div>
<ul>
<li><a href="../reports/errors.html">Errors</a></li>
<li><a href="../reports/markers.html">Markers</a></li>
</ul>
</div>
</section>
</section>
</section>
</section>
<section class="row-fluid">
<section class="span10 offset1">
<hr />
Documentation is powered by <a href="http://www.phpdoc.org/">phpDocumentor </a> and authored
on May 29th, 2017 at 14:17.
</section>
</section>
</section>
</footer>
</div>
</body>
</html>
| battis/data-utilities | doc/reports/deprecated.html | HTML | gpl-3.0 | 7,685 |
#include "hal/time/time.hpp"
namespace hal
{
namespace time
{
static u64 currentTime = 0;
u64 milliseconds()
{
return currentTime;
}
} // namespace time
} // namespace hal
namespace stub
{
namespace time
{
void setCurrentTime(u64 milliseconds)
{
hal::time::currentTime = milliseconds;
}
void forwardTime(u64 milliseconds)
{
hal::time::currentTime += milliseconds;
}
} // namespace time
} // namespace stub
| matgla/AquaLampWiFiModule | test/UT/src/stub/timeStub.cpp | C++ | gpl-3.0 | 464 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_utils.php';
require_once 'cc_version_base.php';
require_once 'cc_organization.php';
/**
* Version 1 class of Common Cartridge
*
*/
class cc_version1 extends cc_version_base {
const webcontent = 'webcontent';
const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p0/question-bank';
const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p0/assessment';
const associatedcontent = 'associatedcontent/imscc_xmlv1p0/learning-application-resource';
const discussiontopic = 'imsdt_xmlv1p0';
const weblink = 'imswl_xmlv1p0';
public static $checker = array(self::webcontent,
self::assessment,
self::associatedcontent,
self::discussiontopic,
self::questionbank,
self::weblink);
/**
* Validate if the type are valid or not
*
* @param string $type
* @return bool
*/
public function valid($type) {
return in_array($type, self::$checker);
}
public function __construct() {
$this->ccnamespaces = array('imscc' => 'http://www.imsglobal.org/xsd/imscc/imscp_v1p1',
'lomimscc' => 'http://ltsc.ieee.org/xsd/imscc/LOM',
'lom' => 'http://ltsc.ieee.org/xsd/LOM',
'voc' => 'http://ltsc.ieee.org/xsd/LOM/vocab',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
);
$this->ccnsnames = array('imscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/imscp_v1p2_localised.xsd' ,
'lom' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/lomLoose_localised.xsd' ,
'lomimscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_1/lomLoose_localised.xsd',
'voc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/vocab/loose.xsd'
);
$this->ccversion = '1.0.0';
$this->camversion = '1.0.0';
$this->_generator = 'Moodle 2 Common Cartridge generator';
}
protected function on_create(DOMDocument &$doc, $rootmanifestnode=null,$nmanifestID=null) {
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$this->manifestID = is_null($nmanifestID) ? cc_helpers::uuidgen('M_') : $nmanifestID;
$mUUID = $doc->createAttribute('identifier');
$mUUID->nodeValue = $this->manifestID;
if (is_null($rootmanifestnode)) {
if (!empty($this->_generator)) {
$comment = $doc->createComment($this->_generator);
$doc->appendChild($comment);
}
$rootel = $doc->createElementNS($this->ccnamespaces['imscc'],'manifest');
$rootel->appendChild($mUUID);
$doc->appendChild($rootel);
//add all namespaces
foreach ($this->ccnamespaces as $key => $value) {
if ($key != 'lom' ){
$dummy_attr = $key.":dummy";
$doc->createAttributeNS($value,$dummy_attr);
}
}
// add location of schemas
$schemaLocation='';
foreach ($this->ccnsnames as $key => $value) {
$vt = empty($schemaLocation) ? '' : ' ';
$schemaLocation .= $vt.$this->ccnamespaces[$key].' '.$value;
}
$aSchemaLoc = $doc->createAttributeNS($this->ccnamespaces['xsi'],'xsi:schemaLocation');
$aSchemaLoc->nodeValue=$schemaLocation;
$rootel->appendChild($aSchemaLoc);
} else {
$rootel = $doc->createElementNS($this->ccnamespaces['imscc'],'imscc:manifest');
$rootel->appendChild($mUUID);
}
$metadata = $doc->createElementNS($this->ccnamespaces['imscc'],'metadata');
$schema = $doc->createElementNS($this->ccnamespaces['imscc'],'schema','IMS Common Cartridge');
$schemaversion = $doc->createElementNS($this->ccnamespaces['imscc'],'schemaversion',$this->ccversion);
$metadata->appendChild($schema);
$metadata->appendChild($schemaversion);
$rootel->appendChild($metadata);
if (!is_null($rootmanifestnode)) {
$rootmanifestnode->appendChild($rootel);
}
$organizations = $doc->createElementNS($this->ccnamespaces['imscc'],'organizations');
$rootel->appendChild($organizations);
$resources = $doc->createElementNS($this->ccnamespaces['imscc'],'resources');
$rootel->appendChild($resources);
return true;
}
protected function update_attribute(DOMDocument &$doc, $attrname, $attrvalue, DOMElement &$node) {
$busenew = (is_object($node) && $node->hasAttribute($attrname));
$nResult = null;
if (!$busenew && is_null($attrvalue)) {
$node->removeAttribute($attrname);
} else {
$nResult = $busenew ? $node->getAttributeNode($attrname) : $doc->createAttribute($attrname);
$nResult->nodeValue = $attrvalue;
if (!$busenew) {
$node->appendChild($nResult);
}
}
return $nResult;
}
protected function update_attribute_ns(DOMDocument &$doc, $attrname, $attrnamespace,$attrvalue, DOMElement &$node) {
$busenew = (is_object($node) && $node->hasAttributeNS($attrnamespace, $attrname));
$nResult = null;
if (!$busenew && is_null($attrvalue)) {
$node->removeAttributeNS($attrnamespace, $attrname);
} else {
$nResult = $busenew ? $node->getAttributeNodeNS($attrnamespace, $attrname) : $doc->createAttributeNS($attrnamespace, $attrname);
$nResult->nodeValue = $attrvalue;
if (!$busenew) {
$node->appendChild($nResult);
}
}
return $nResult;
}
protected function get_child_node(DOMDocument &$doc, $itemname, DOMElement &$node) {
$nlist = $node->getElementsByTagName($itemname);
$item = is_object($nlist) && ($nlist->length > 0) ? $nlist->item(0) : null;
return $item;
}
protected function update_child_item(DOMDocument &$doc, $itemname, $itemvalue, DOMElement &$node, $attrtostore=null) {
$tnode = $this->get_child_node($doc,'title',$node);
$usenew = is_null($tnode);
$tnode = $usenew ? $doc->createElementNS($this->ccnamespaces['imscc'], $itemname) : $tnode;
if (!is_null($attrtostore)) {
foreach ($attrtostore as $key => $value) {
$this->update_attribute($doc,$key,$value,$tnode);
}
}
$tnode->nodeValue = $itemvalue;
if ($usenew) {
$node->appendChild($tnode);
}
}
protected function update_items($items, DOMDocument &$doc, DOMElement &$xmlnode) {
foreach ($items as $key => $item) {
$itemnode = $doc->createElementNS($this->ccnamespaces['imscc'], 'item');
$this->update_attribute($doc, 'identifier' , $key , $itemnode);
$this->update_attribute($doc, 'identifierref', $item->identifierref, $itemnode);
$this->update_attribute($doc, 'parameters' , $item->parameters , $itemnode);
if (!empty($item->title)) {
$titlenode = $doc->createElementNS($this->ccnamespaces['imscc'],
'title',
$item->title);
$itemnode->appendChild($titlenode);
}
if ($item->has_child_items()) {
$this->update_items($item->childitems, $doc, $itemnode);
}
$xmlnode->appendChild($itemnode);
}
}
/**
* Create a Resource (How to)
*
* @param cc_i_resource $res
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_resource(cc_i_resource &$res, DOMDocument &$doc, $xmlnode=null) {
$usenew = is_object($xmlnode);
$dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "resource");
$this->update_attribute($doc,'identifier',$res->identifier,$dnode);
$this->update_attribute($doc,'type' ,$res->type ,$dnode);
!is_null($res->href) ? $this->update_attribute($doc,'href',$res->href,$dnode): null;
$this->update_attribute($doc,'base' ,$res->base ,$dnode);
foreach ($res->files as $file) {
$nd = $doc->createElementNS($this->ccnamespaces['imscc'],'file');
$ndatt = $doc->createAttribute('href');
$ndatt->nodeValue = $file;
$nd->appendChild($ndatt);
$dnode->appendChild($nd);
}
$this->resources[$res->identifier] = $res;
foreach ($res->dependency as $dependency){
$nd = $doc->createElementNS($this->ccnamespaces['imscc'],'dependency');
$ndatt = $doc->createAttribute('identifierref');
$ndatt->nodeValue = $dependency;
$nd->appendChild($ndatt);
$dnode->appendChild($nd);
}
return $dnode;
}
/**
* Create an Item Folder (How To)
*
* @param cc_i_organization $org
* @param DOMDocument $doc
* @param DOMElement $xmlnode
*/
protected function create_item_folder (cc_i_organization &$org, DOMDocument &$doc, DOMElement &$xmlnode=null){
$itemfoldernode = $doc->createElementNS($this->ccnamespaces['imscc'],'item');
$this->update_attribute($doc,'identifier', "root", $itemfoldernode);
if ($org->has_items()) {
$this->update_items($org->itemlist, $doc, $itemfoldernode);
}
if (is_null($this->organizations)) {
$this->organizations = array();
}
$this->organizations[$org->identifier] = $org;
$xmlnode->appendChild($itemfoldernode);
}
/**
* Create an Organization (How To)
*
* @param cc_i_organization $org
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_organization (cc_i_organization &$org, DOMDocument &$doc, $xmlnode=null){
$usenew = is_object($xmlnode);
$dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "organization");
$this->update_attribute($doc,'identifier' ,$org->identifier,$dnode);
$this->update_attribute($doc,'structure' ,$org->structure ,$dnode);
$this->create_item_folder($org,$doc,$dnode);
return $dnode;
}
/**
* Create Metadata For Manifest (How To)
*
* @param cc_i_metadata_manifest $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_manifest (cc_i_metadata_manifest $met,DOMDocument &$doc,$xmlnode=null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lomimscc'], "lom");
if (!empty($xmlnode)) {
$xmlnode->appendChild($dnode);
}
$dnodegeneral = empty($met->arraygeneral ) ? null : $this->create_metadata_general ($met, $doc, $xmlnode);
$dnodetechnical = empty($met->arraytech ) ? null : $this->create_metadata_technical($met, $doc, $xmlnode);
$dnoderights = empty($met->arrayrights ) ? null : $this->create_metadata_rights ($met, $doc, $xmlnode);
$dnodelifecycle = empty($met->arraylifecycle) ? null : $this->create_metadata_lifecycle($met, $doc, $xmlnode);
!is_null($dnodegeneral)?$dnode->appendChild($dnodegeneral):null;
!is_null($dnodetechnical)?$dnode->appendChild($dnodetechnical):null;
!is_null($dnoderights)?$dnode->appendChild($dnoderights):null;
!is_null($dnodelifecycle)?$dnode->appendChild($dnodelifecycle):null;
return $dnode;
}
/**
* Create Metadata For Resource (How To)
*
* @param cc_i_metadata_resource $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_resource (cc_i_metadata_resource $met,DOMDocument &$doc,$xmlnode=null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom");
!empty($xmlnode)? $xmlnode->appendChild($dnode):null;
!empty($met->arrayeducational) ? $this->create_metadata_educational($met,$doc,$dnode):null;
return $dnode;
}
/**
* Create Metadata For File (How To)
*
* @param cc_i_metadata_file $met
* @param DOMDocument $doc
* @param Object $xmlnode
* @return DOMNode
*/
protected function create_metadata_file (cc_i_metadata_file $met,DOMDocument &$doc,$xmlnode=null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom");
!empty($xmlnode)? $xmlnode->appendChild($dnode):null;
!empty($met->arrayeducational) ? $this->create_metadata_educational($met,$doc,$dnode):null;
return $dnode;
}
/**
* Create General Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_general($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'general');
foreach ($met->arraygeneral as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
if ($name != 'language' && $name != 'catalog' && $name != 'entry'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'string',$v[1]);
$ndatt = $doc->createAttribute('language');
$ndatt->nodeValue = $v[0];
$nd3->appendChild($ndatt);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}else{
if ($name == 'language'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]);
$nd->appendChild($nd2);
}
}
}
}
if (!empty($met->arraygeneral['catalog']) || !empty($met->arraygeneral['entry'])){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'identifier');
$nd->appendChild($nd2);
if (!empty($met->arraygeneral['catalog'])){
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'catalog',$met->arraygeneral['catalog'][0][0]);
$nd2->appendChild($nd3);
}
if (!empty($met->arraygeneral['entry'])){
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'entry',$met->arraygeneral['entry'][0][0]);
$nd2->appendChild($nd4);
}
}
return $nd;
}
/**
* Create Technical Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_technical($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'technical');
$xmlnode->appendChild($nd);
foreach ($met->arraytech as $name => $value) {
($name);
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]);
$nd->appendChild($nd2);
}
}
return $nd;
}
/**
* Create Rights Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_rights($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'rights');
foreach ($met->arrayrights as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
if ($name == 'description'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'string',$v[1]);
$ndatt = $doc->createAttribute('language');
$ndatt->nodeValue = $v[0];
$nd3->appendChild($ndatt);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}elseif ($name == 'copyrightAndOtherRestrictions' || $name == 'cost'){
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'value',$v[0]);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}
}
}
return $nd;
}
/**
* Create LifeCyle Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_lifecycle($met,DOMDocument &$doc,$xmlnode){
($xmlnode);
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'],'lifeCycle');
$nd2= $doc->createElementNS($this->ccnamespaces['lomimscc'],'contribute');
$nd->appendChild ($nd2);
$xmlnode->appendChild ($nd);
foreach ($met->arraylifecycle as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
if ($name == 'role'){
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd2->appendChild($nd3);
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'value',$v[0]);
$nd3->appendChild($nd4);
}else{
if ($name == 'date'){
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name);
$nd2->appendChild($nd3);
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'],'dateTime',$v[0]);
$nd3->appendChild($nd4);
}else{
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'],$name,$v[0]);
$nd2->appendChild($nd3);
}
}
}
}
return $nd;
}
/**
* Create Education Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_educational ($met,DOMDocument &$doc, $xmlnode){
$nd = $doc->createElementNS($this->ccnamespaces['lom'],'educational');
$nd2 = $doc->createElementNS($this->ccnamespaces['lom'],'intendedEndUserRole');
$nd3 = $doc->createElementNS($this->ccnamespaces['voc'],'vocabulary');
$xmlnode->appendChild($nd);
$nd->appendChild($nd2);
$nd2->appendChild($nd3);
foreach ($met->arrayeducational as $name => $value) {
!is_array($value)?$value =array($value):null;
foreach ($value as $k => $v){
($k);
$nd4 = $doc->createElementNS($this->ccnamespaces['voc'],$name,$v[0]);
$nd3->appendChild($nd4);
}
}
return $nd;
}
} | ouyangyu/fdmoodle | backup/cc/cc_lib/cc_version1.php | PHP | gpl-3.0 | 21,798 |
package com.programandoapasitos.facturador.gui;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.programandoapasitos.facturador.gui.superclases.FramePadre;
import com.programandoapasitos.facturador.utiles.ManejadorProperties;
@SuppressWarnings("serial")
public class MenuPrincipal extends FramePadre {
// Propiedades
private JLabel lblIcono;
private JMenuBar menuBar;
private JMenu mnClientes;
private JMenu mnFacturas;
private JMenuItem mntmNuevaFactura;
private JMenuItem mntmNuevoCliente;
private JMenuItem mntmBuscarFactura;
private JMenuItem mntmBuscarCliente;
// Constructor
public MenuPrincipal(int ancho, int alto, String titulo) {
super(ancho, alto, titulo);
this.inicializar();
}
// Métodos
public void inicializar() {
this.inicializarMenuBar();
this.iniciarLabels();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sobrescribe setDefaultCloseOperation de FramePadre
setVisible(true);
}
public void inicializarMenuBar() {
menuBar = new JMenuBar();
menuBar.setBounds(0, 0, 900, 21);
this.panel.add(menuBar);
this.inicializarMenuFacturas();
this.inicializarMenuClientes();
}
/**
* Initialize submenu Bills
*/
public void inicializarMenuFacturas() {
mnFacturas = new JMenu(ManejadorProperties.verLiteral("MENU_FACTURAS"));
menuBar.add(mnFacturas);
mntmNuevaFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL"));
mntmNuevaFactura.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new FrameNuevaFactura(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_BILL"));
}
});
mnFacturas.add(mntmNuevaFactura);
mntmBuscarFactura = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL"));
mntmBuscarFactura.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new FrameBuscarFacturas(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_BILL"));
}
});
mnFacturas.add(mntmBuscarFactura);
}
public void inicializarMenuClientes() {
mnClientes = new JMenu(ManejadorProperties.verLiteral("MENU_CLIENTES"));
menuBar.add(mnClientes);
mntmNuevoCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT"));
mntmNuevoCliente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new FrameNuevoCliente(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_NEW_CLIENT"));
}
});
mnClientes.add(mntmNuevoCliente);
mntmBuscarCliente = new JMenuItem(ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT"));
mntmBuscarCliente.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new FrameBuscarClientes(ManejadorProperties.verGui("SUBFRAMES_WIDTH"), ManejadorProperties.verGui("SUBFRAMES_HEIGHT"), ManejadorProperties.verLiteral("MENU_ITEM_SEARCH_CLIENT"));
}
});
mnClientes.add(mntmBuscarCliente);
}
/**
* Initialize icon label
*/
public void iniciarLabels() {
lblIcono = new JLabel("");
lblIcono.setIcon(new ImageIcon(ManejadorProperties.verRuta("MENU_ITEM_SEARCH_CLIENT")));
lblIcono.setBounds(342, 240, 210, 124);
this.panel.add(lblIcono);
}
}
| inazense/java-generate-bills | src/main/java/com/programandoapasitos/facturador/gui/MenuPrincipal.java | Java | gpl-3.0 | 3,783 |
# Sweep with the pawns
This rule will have all pawns sweep the board, trying to defeat as many pieces as possible. We will assume we have all pawns in the front row.
The idea is to have them all stay in a row: first, they will all advance to row 2, then to row 3, and so on, without breaking formation.
```
(defrule EQUIPO-A::advance_pawns_f2
(declare (salience 60))
(tiempo ?t)
(ficha (equipo "A") (num ?n) (pos-y 2) (puntos 2))
=>
(assert (mueve (num ?n) (mov 3) (tiempo ?t)))
)
(defrule EQUIPO-A::advance_pawns_f3
(declare (salience 59))
(tiempo ?t)
(ficha (equipo "A") (num ?n) (pos-y 3) (puntos 2))
=>
(assert (mueve (num ?n) (mov 3) (tiempo ?t)))
)
(defrule EQUIPO-A::advance_pawns_f4
(declare (salience 58))
(tiempo ?t)
(ficha (equipo "A") (num ?n) (pos-y 4) (puntos 2))
=>
(assert (mueve (num ?n) (mov 3) (tiempo ?t)))
)
(defrule EQUIPO-A::advance_pawns_f5
(declare (salience 57))
(tiempo ?t)
(ficha (equipo "A") (num ?n) (pos-y 5) (puntos 2))
=>
(assert (mueve (num ?n) (mov 3) (tiempo ?t)))
)
(defrule EQUIPO-A::advance_pawns_f6
(declare (salience 56))
(tiempo ?t)
(ficha (equipo "A") (num ?n) (pos-y 6) (puntos 2))
=>
(assert (mueve (num ?n) (mov 3) (tiempo ?t)))
)
(defrule EQUIPO-A::advance_pawns_f7
(declare (salience 55))
(tiempo ?t)
(ficha (equipo "A") (num ?n) (pos-y 7) (puntos 2))
=>
(assert (mueve (num ?n) (mov 3) (tiempo ?t)))
)
```
There is a rule for each piece, since doing it in a more parametric form would increase the complexity significantly. This also allows for tweaking the priority, changing the order in which pawns advance to the next row.
| DrPantera/gsiege | docs/rule-sweeppawn.md | Markdown | gpl-3.0 | 1,701 |
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
#include "common.h"
#include "seafile-session.h"
#include "bloom-filter.h"
#include "gc-core.h"
#include "utils.h"
#define DEBUG_FLAG SEAFILE_DEBUG_OTHER
#include "log.h"
#define MAX_BF_SIZE (((size_t)1) << 29) /* 64 MB */
/* Total number of blocks to be scanned. */
static guint64 total_blocks;
static guint64 removed_blocks;
static guint64 reachable_blocks;
/*
* The number of bits in the bloom filter is 4 times the number of all blocks.
* Let m be the bits in the bf, n be the number of blocks to be added to the bf
* (the number of live blocks), and k = 3 (closed to optimal for m/n = 4),
* the probability of false-positive is
*
* p = (1 - e^(-kn/m))^k = 0.15
*
* Because m = 4 * total_blocks >= 4 * (live blocks) = 4n, we should have p <= 0.15.
* Put it another way, we'll clean up at least 85% dead blocks in each gc operation.
* See http://en.wikipedia.org/wiki/Bloom_filter.
*
* Supose we have 8TB space, and the avg block size is 1MB, we'll have 8M blocks, then
* the size of bf is (8M * 4)/8 = 4MB.
*
* If total_blocks is a small number (e.g. < 100), we should try to clean all dead blocks.
* So we set the minimal size of the bf to 1KB.
*/
static Bloom *
alloc_gc_index ()
{
size_t size;
size = (size_t) MAX(total_blocks << 2, 1 << 13);
size = MIN (size, MAX_BF_SIZE);
seaf_message ("GC index size is %u Byte.\n", (int)size >> 3);
return bloom_create (size, 3, 0);
}
typedef struct {
SeafRepo *repo;
Bloom *index;
GHashTable *visited;
/* > 0: keep a period of history;
* == 0: only keep data in head commit;
* < 0: keep all history data.
*/
gint64 truncate_time;
gboolean traversed_head;
int traversed_commits;
gint64 traversed_blocks;
gboolean ignore_errors;
} GCData;
static int
add_blocks_to_index (SeafFSManager *mgr, GCData *data, const char *file_id)
{
SeafRepo *repo = data->repo;
Bloom *index = data->index;
Seafile *seafile;
int i;
seafile = seaf_fs_manager_get_seafile (mgr, repo->store_id, repo->version, file_id);
if (!seafile) {
seaf_warning ("Failed to find file %s.\n", file_id);
return -1;
}
for (i = 0; i < seafile->n_blocks; ++i) {
bloom_add (index, seafile->blk_sha1s[i]);
++data->traversed_blocks;
}
seafile_unref (seafile);
return 0;
}
static gboolean
fs_callback (SeafFSManager *mgr,
const char *store_id,
int version,
const char *obj_id,
int type,
void *user_data,
gboolean *stop)
{
GCData *data = user_data;
if (data->visited != NULL) {
if (g_hash_table_lookup (data->visited, obj_id) != NULL) {
*stop = TRUE;
return TRUE;
}
char *key = g_strdup(obj_id);
g_hash_table_insert (data->visited, key, key);
}
if (type == SEAF_METADATA_TYPE_FILE &&
add_blocks_to_index (mgr, data, obj_id) < 0)
return FALSE;
return TRUE;
}
static gboolean
traverse_commit (SeafCommit *commit, void *vdata, gboolean *stop)
{
GCData *data = vdata;
int ret;
if (data->truncate_time == 0)
{
*stop = TRUE;
/* Stop after traversing the head commit. */
}
else if (data->truncate_time > 0 &&
(gint64)(commit->ctime) < data->truncate_time &&
data->traversed_head)
{
/* Still traverse the first commit older than truncate_time.
* If a file in the child commit of this commit is deleted,
* we need to access this commit in order to restore it
* from trash.
*/
*stop = TRUE;
}
if (!data->traversed_head)
data->traversed_head = TRUE;
seaf_debug ("Traversed commit %.8s.\n", commit->commit_id);
++data->traversed_commits;
ret = seaf_fs_manager_traverse_tree (seaf->fs_mgr,
data->repo->store_id, data->repo->version,
commit->root_id,
fs_callback,
data, data->ignore_errors);
if (ret < 0 && !data->ignore_errors)
return FALSE;
return TRUE;
}
static int
populate_gc_index_for_repo (SeafRepo *repo, Bloom *index, gboolean ignore_errors)
{
GList *branches, *ptr;
SeafBranch *branch;
GCData *data;
int ret = 0;
seaf_message ("Populating index for repo %.8s.\n", repo->id);
branches = seaf_branch_manager_get_branch_list (seaf->branch_mgr, repo->id);
if (branches == NULL) {
seaf_warning ("[GC] Failed to get branch list of repo %s.\n", repo->id);
return -1;
}
data = g_new0(GCData, 1);
data->repo = repo;
data->index = index;
data->visited = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
gint64 truncate_time = seaf_repo_manager_get_repo_truncate_time (repo->manager,
repo->id);
if (truncate_time > 0) {
seaf_repo_manager_set_repo_valid_since (repo->manager,
repo->id,
truncate_time);
} else if (truncate_time == 0) {
/* Only the head commit is valid after GC if no history is kept. */
SeafCommit *head = seaf_commit_manager_get_commit (seaf->commit_mgr,
repo->id, repo->version,
repo->head->commit_id);
if (head)
seaf_repo_manager_set_repo_valid_since (repo->manager,
repo->id,
head->ctime);
seaf_commit_unref (head);
}
data->truncate_time = truncate_time;
data->ignore_errors = ignore_errors;
for (ptr = branches; ptr != NULL; ptr = ptr->next) {
branch = ptr->data;
gboolean res = seaf_commit_manager_traverse_commit_tree (seaf->commit_mgr,
repo->id,
repo->version,
branch->commit_id,
traverse_commit,
data,
ignore_errors);
seaf_branch_unref (branch);
if (!res && !ignore_errors) {
ret = -1;
break;
}
}
seaf_message ("Traversed %d commits, %"G_GINT64_FORMAT" blocks.\n",
data->traversed_commits, data->traversed_blocks);
reachable_blocks += data->traversed_blocks;
g_list_free (branches);
g_hash_table_destroy (data->visited);
g_free (data);
return ret;
}
typedef struct {
Bloom *index;
int dry_run;
} CheckBlocksData;
static gboolean
check_block_liveness (const char *store_id, int version,
const char *block_id, void *vdata)
{
CheckBlocksData *data = vdata;
Bloom *index = data->index;
if (!bloom_test (index, block_id)) {
++removed_blocks;
if (!data->dry_run)
seaf_block_manager_remove_block (seaf->block_mgr,
store_id, version,
block_id);
}
return TRUE;
}
static int
populate_gc_index_for_virtual_repos (SeafRepo *repo, Bloom *index, int ignore_errors)
{
GList *vrepo_ids = NULL, *ptr;
char *repo_id;
SeafRepo *vrepo;
int ret = 0;
vrepo_ids = seaf_repo_manager_get_virtual_repo_ids_by_origin (seaf->repo_mgr,
repo->id);
for (ptr = vrepo_ids; ptr; ptr = ptr->next) {
repo_id = ptr->data;
vrepo = seaf_repo_manager_get_repo (seaf->repo_mgr, repo_id);
if (!vrepo) {
seaf_warning ("Failed to get repo %s.\n", repo_id);
if (!ignore_errors) {
ret = -1;
goto out;
} else
continue;
}
ret = populate_gc_index_for_repo (vrepo, index, ignore_errors);
seaf_repo_unref (vrepo);
if (ret < 0 && !ignore_errors)
goto out;
}
out:
string_list_free (vrepo_ids);
return ret;
}
int
gc_v1_repo (SeafRepo *repo, int dry_run, int ignore_errors)
{
Bloom *index;
int ret;
total_blocks = seaf_block_manager_get_block_number (seaf->block_mgr,
repo->store_id, repo->version);
removed_blocks = 0;
reachable_blocks = 0;
if (total_blocks == 0) {
seaf_message ("No blocks. Skip GC.\n");
return 0;
}
seaf_message ("GC started. Total block number is %"G_GUINT64_FORMAT".\n", total_blocks);
/*
* Store the index of live blocks in bloom filter to save memory.
* Since bloom filters only have false-positive, we
* may skip some garbage blocks, but we won't delete
* blocks that are still alive.
*/
index = alloc_gc_index ();
if (!index) {
seaf_warning ("GC: Failed to allocate index.\n");
return -1;
}
seaf_message ("Populating index.\n");
ret = populate_gc_index_for_repo (repo, index, ignore_errors);
if (ret < 0 && !ignore_errors)
goto out;
/* Since virtual repos share fs and block store with the origin repo,
* it's necessary to do GC for them together.
*/
ret = populate_gc_index_for_virtual_repos (repo, index, ignore_errors);
if (ret < 0 && !ignore_errors)
goto out;
if (!dry_run)
seaf_message ("Scanning and deleting unused blocks.\n");
else
seaf_message ("Scanning unused blocks.\n");
CheckBlocksData data;
data.index = index;
data.dry_run = dry_run;
ret = seaf_block_manager_foreach_block (seaf->block_mgr,
repo->store_id, repo->version,
check_block_liveness,
&data);
if (ret < 0) {
seaf_warning ("GC: Failed to clean dead blocks.\n");
goto out;
}
if (!dry_run)
seaf_message ("GC finished. %"G_GUINT64_FORMAT" blocks total, "
"about %"G_GUINT64_FORMAT" reachable blocks, "
"%"G_GUINT64_FORMAT" blocks are removed.\n",
total_blocks, reachable_blocks, removed_blocks);
else
seaf_message ("GC finished. %"G_GUINT64_FORMAT" blocks total, "
"about %"G_GUINT64_FORMAT" reachable blocks, "
"%"G_GUINT64_FORMAT" blocks can be removed.\n",
total_blocks, reachable_blocks, removed_blocks);
out:
bloom_destroy (index);
return ret;
}
int
gc_core_run (int dry_run)
{
GList *repos = NULL, *del_repos = NULL, *ptr;
SeafRepo *repo;
GList *corrupt_repos = NULL;
gboolean error = FALSE;
repos = seaf_repo_manager_get_repo_list (seaf->repo_mgr, -1, -1, &error);
if (error) {
seaf_warning ("Failed to load repo list.\n");
return -1;
}
for (ptr = repos; ptr; ptr = ptr->next) {
repo = ptr->data;
if (repo->is_corrupted) {
corrupt_repos = g_list_prepend (corrupt_repos, g_strdup(repo->id));
continue;
}
if (!repo->is_virtual) {
seaf_message ("GC version %d repo %s(%.8s)\n",
repo->version, repo->name, repo->id);
if (gc_v1_repo (repo, dry_run, FALSE) < 0)
corrupt_repos = g_list_prepend (corrupt_repos, g_strdup(repo->id));
}
seaf_repo_unref (repo);
}
g_list_free (repos);
seaf_message ("=== GC deleted repos ===\n");
del_repos = seaf_repo_manager_list_garbage_repos (seaf->repo_mgr);
for (ptr = del_repos; ptr; ptr = ptr->next) {
char *repo_id = ptr->data;
/* Confirm repo doesn't exist before removing blocks. */
if (!seaf_repo_manager_repo_exists (seaf->repo_mgr, repo_id)) {
if (!dry_run) {
seaf_message ("GC deleted repo %.8s.\n", repo_id);
seaf_block_manager_remove_store (seaf->block_mgr, repo_id);
} else {
seaf_message ("Repo %.8s can be GC'ed.\n", repo_id);
}
}
if (!dry_run)
seaf_repo_manager_remove_garbage_repo (seaf->repo_mgr, repo_id);
g_free (repo_id);
}
g_list_free (del_repos);
seaf_message ("=== GC is finished ===\n");
if (corrupt_repos) {
seaf_message ("The following repos are corrupted. "
"You can run seaf-fsck to fix them.\n");
for (ptr = corrupt_repos; ptr; ptr = ptr->next) {
char *repo_id = ptr->data;
seaf_message ("%s\n", repo_id);
g_free (repo_id);
}
g_list_free (corrupt_repos);
}
return 0;
}
| skmezanul/disk42 | server/gc/gc-core.c | C | gpl-3.0 | 13,299 |
\hypertarget{_factory_controller_8cpp}{\section{src/interfaces/\+Factory\+Controller.cpp File Reference}
\label{_factory_controller_8cpp}\index{src/interfaces/\+Factory\+Controller.\+cpp@{src/interfaces/\+Factory\+Controller.\+cpp}}
}
{\ttfamily \#include \char`\"{}I\+Controller.\+h\char`\"{}}\\*
{\ttfamily \#include $<$src/logic/controller/\+Controller.\+h$>$}\\*
Include dependency graph for Factory\+Controller.\+cpp\+:
| Tedlar/Mission-Impossible | doxygen/latex/_factory_controller_8cpp.tex | TeX | gpl-3.0 | 425 |
<?php
use Respect\Validation\Validator as DataValidator;
/**
* @api {post} /staff/search-tickets Search tickets
* @apiVersion 4.5.0
*
* @apiName Search tickets
*
* @apiGroup Staff
*
* @apiDescription This path search some tickets.
*
* @apiPermission staff1
*
* @apiParam {String} query Query string to search.
* @apiParam {Number} page The page number.
*
* @apiUse NO_PERMISSION
* @apiUse INVALID_QUERY
* @apiUse INVALID_PAGE
*
* @apiSuccess {Object} data Information about tickets
* @apiSuccess {[Ticket](#api-Data_Structures-ObjectTicket)[]} data.tickets Array of tickets found
* @apiSuccess {Number} data.pages Number of pages
*
*/
class SearchTicketStaffController extends Controller {
const PATH = '/search-tickets';
const METHOD = 'POST';
public function validations() {
return[
'permission' => 'staff_1',
'requestData' => [
'query' => [
'validation' => DataValidator::length(1),
'error' => ERRORS::INVALID_QUERY
],
'page' => [
'validation' => DataValidator::numeric(),
'error' => ERRORS::INVALID_PAGE
]
]
];
}
public function handler() {
Response::respondSuccess([
'tickets' => $this->getTicketList()->toArray(),
'pages' => $this->getTotalPages()
]);
}
private function getTicketList() {
$query = $this->getSearchQuery();
return Ticket::find($query, [
Controller::request('query') . '%',
'%' . Controller::request('query') . '%',
Controller::request('query') . '%'
]);
}
private function getSearchQuery() {
$page = Controller::request('page');
$query = " (title LIKE ? OR title LIKE ?) AND ";
$query .= $this->getStaffDepartmentsQueryFilter();
$query .= "ORDER BY CASE WHEN (title LIKE ?) THEN 1 ELSE 2 END ASC LIMIT 10 OFFSET " . (($page-1)*10);
return $query;
}
private function getTotalPages() {
$query = " (title LIKE ? OR title LIKE ?) AND ";
$query .= $this->getStaffDepartmentsQueryFilter();
$ticketQuantity = Ticket::count($query, [
Controller::request('query') . '%',
'%' . Controller::request('query') . '%'
]);
return ceil($ticketQuantity / 10);
}
private function getStaffDepartmentsQueryFilter() {
$user = Controller::getLoggedUser();
$query = ' (';
foreach ($user->sharedDepartmentList as $department) {
$query .= 'department_id=' . $department->id . ' OR ';
}
$query = substr($query, 0, -3);
$query .= ') ';
return $query;
}
} | ivandiazwm/opensupports | server/controllers/staff/search-tickets.php | PHP | gpl-3.0 | 2,810 |
/* radare - LGPL - Copyright 2008-2014 - pancake */
// TODO: implement a more inteligent way to store cached memory
// TODO: define limit of max mem to cache
#include "r_io.h"
static void cache_item_free(RIOCache *cache) {
if (!cache)
return;
if (cache->data)
free (cache->data);
free (cache);
}
R_API void r_io_cache_init(RIO *io) {
io->cache = r_list_new ();
io->cache->free = (RListFree)cache_item_free;
io->cached = R_FALSE; // cache write ops
io->cached_read = R_FALSE; // cached read ops
}
R_API void r_io_cache_enable(RIO *io, int read, int write) {
io->cached = read | write;
io->cached_read = read;
}
R_API void r_io_cache_commit(RIO *io) {
RListIter *iter;
RIOCache *c;
if (io->cached) {
io->cached = R_FALSE;
r_list_foreach (io->cache, iter, c) {
if (!r_io_write_at (io, c->from, c->data, c->size))
eprintf ("Error writing change at 0x%08"PFMT64x"\n", c->from);
}
io->cached = R_TRUE;
r_io_cache_reset (io, io->cached);
}
}
R_API void r_io_cache_reset(RIO *io, int set) {
io->cached = set;
r_list_purge (io->cache);
}
R_API int r_io_cache_invalidate(RIO *io, ut64 from, ut64 to) {
RListIter *iter, *iter_tmp;
RIOCache *c;
if (from>=to) return R_FALSE;
r_list_foreach_safe (io->cache, iter, iter_tmp, c) {
if (c->from >= from && c->to <= to) {
r_list_delete (io->cache, iter);
}
}
return R_FALSE;
}
R_API int r_io_cache_list(RIO *io, int rad) {
int i, j = 0;
RListIter *iter;
RIOCache *c;
r_list_foreach (io->cache, iter, c) {
if (rad) {
io->printf ("wx ");
for (i=0; i<c->size; i++)
io->printf ("%02x", c->data[i]);
io->printf (" @ 0x%08"PFMT64x"\n", c->from);
} else {
io->printf ("idx=%d addr=0x%08"PFMT64x" size=%d ",
j, c->from, c->size);
for (i=0; i<c->size; i++)
io->printf ("%02x", c->data[i]);
io->printf ("\n");
}
j++;
}
return R_FALSE;
}
R_API int r_io_cache_write(RIO *io, ut64 addr, const ut8 *buf, int len) {
RIOCache *ch = R_NEW (RIOCache);
ch->from = addr;
ch->to = addr + len;
ch->size = len;
ch->data = (ut8*)malloc (len);
memcpy (ch->data, buf, len);
r_list_append (io->cache, ch);
return len;
}
R_API int r_io_cache_read(RIO *io, ut64 addr, ut8 *buf, int len) {
int l, ret, da, db;
RListIter *iter;
RIOCache *c;
r_list_foreach (io->cache, iter, c) {
if (r_range_overlap (addr, addr+len-1, c->from, c->to, &ret)) {
if (ret>0) {
da = ret;
db = 0;
l = c->size-da;
} else if (ret<0) {
da = 0;
db = -ret;
l = c->size-db;
} else {
da = 0;
db = 0;
l = c->size;
}
if (l>len) l = len;
if (l<1) l = 1; // XXX: fail
else memcpy (buf+da, c->data+db, l);
}
}
return len;
}
| jpenalbae/radare2 | libr/io/cache.c | C | gpl-3.0 | 2,674 |
/*
* Lumeer: Modern Data Definition and Processing Platform
*
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {SharedModule} from '../../../../shared/shared.module';
import {SearchAllComponent} from './search-all.component';
import {SearchCollectionsModule} from '../search-collections/search-collections.module';
import {SearchViewsModule} from '../search-views/search-views.module';
import {SearchTasksModule} from '../search-tasks/search-tasks.module';
@NgModule({
imports: [CommonModule, SharedModule, SearchCollectionsModule, SearchViewsModule, SearchTasksModule],
declarations: [SearchAllComponent],
exports: [SearchAllComponent],
})
export class SearchAllModule {}
| Lumeer/web-ui | src/app/view/perspectives/dashboard/search-all/search-all.module.ts | TypeScript | gpl-3.0 | 1,450 |
/*
===========================================================================
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of Spearmint Source Code.
Spearmint Source Code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the License,
or (at your option) any later version.
Spearmint Source Code 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 Spearmint Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, Spearmint Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following
the terms and conditions of the GNU General Public License. If not, please
request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional
terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc.,
Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
/*****************************************************************************
* name: l_precomp.h
*
* desc: pre compiler
*
* $Archive: /source/code/botlib/l_precomp.h $
*
*****************************************************************************/
#ifndef MAX_PATH
#define MAX_PATH MAX_QPATH
#endif
#ifndef PATH_SEPERATORSTR
#if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
#define PATHSEPERATOR_STR "\\"
#else
#define PATHSEPERATOR_STR "/"
#endif
#endif
#ifndef PATH_SEPERATORCHAR
#if defined(WIN32)|defined(_WIN32)|defined(__NT__)|defined(__WINDOWS__)|defined(__WINDOWS_386__)
#define PATHSEPERATOR_CHAR '\\'
#else
#define PATHSEPERATOR_CHAR '/'
#endif
#endif
#if defined(BSPC) && !defined(QDECL)
#define QDECL
#endif
#define DEFINE_FIXED 0x0001
#define BUILTIN_LINE 1
#define BUILTIN_FILE 2
#define BUILTIN_DATE 3
#define BUILTIN_TIME 4
#define BUILTIN_STDC 5
#define INDENT_IF 0x0001
#define INDENT_ELSE 0x0002
#define INDENT_ELIF 0x0004
#define INDENT_IFDEF 0x0008
#define INDENT_IFNDEF 0x0010
//macro definitions
typedef struct define_s
{
char *name; //define name
int flags; //define flags
int builtin; // > 0 if builtin define
int numparms; //number of define parameters
token_t *parms; //define parameters
token_t *tokens; //macro tokens (possibly containing parm tokens)
struct define_s *next; //next defined macro in a list
struct define_s *hashnext; //next define in the hash chain
} define_t;
//indents
//used for conditional compilation directives:
//#if, #else, #elif, #ifdef, #ifndef
typedef struct indent_s
{
int type; //indent type
int skip; //true if skipping current indent
script_t *script; //script the indent was in
struct indent_s *next; //next indent on the indent stack
} indent_t;
//source file
typedef struct source_s
{
char filename[1024]; //file name of the script
char includepath[1024]; //path to include files
punctuation_t *punctuations; //punctuations to use
script_t *scriptstack; //stack with scripts of the source
token_t *tokens; //tokens to read first
define_t *defines; //list with macro definitions
define_t **definehash; //hash chain with defines
indent_t *indentstack; //stack with indents
int skip; // > 0 if skipping conditional code
token_t token; //last read token
} source_t;
//read a token from the source
int PC_ReadToken(source_t *source, token_t *token);
//expect a certain token
int PC_ExpectTokenString(source_t *source, char *string);
//expect a certain token type
int PC_ExpectTokenType(source_t *source, int type, int subtype, token_t *token);
//expect a token
int PC_ExpectAnyToken(source_t *source, token_t *token);
//returns true when the token is available
int PC_CheckTokenString(source_t *source, char *string);
//returns true and reads the token when a token with the given type is available
int PC_CheckTokenType(source_t *source, int type, int subtype, token_t *token);
//skip tokens until the given token string is read
int PC_SkipUntilString(source_t *source, char *string);
//unread the last token read from the script
void PC_UnreadLastToken(source_t *source);
//unread the given token
void PC_UnreadToken(source_t *source, token_t *token);
//read a token only if on the same line, lines are concatenated with a slash
int PC_ReadLine(source_t *source, token_t *token);
//returns true if there was a white space in front of the token
int PC_WhiteSpaceBeforeToken(token_t *token);
//add a define to the source
int PC_AddDefine(source_t *source, char *string);
//add a globals define that will be added to all opened sources
int PC_AddGlobalDefine(char *string);
//remove the given global define
int PC_RemoveGlobalDefine(char *name);
//remove all globals defines
void PC_RemoveAllGlobalDefines(void);
//add builtin defines
void PC_AddBuiltinDefines(source_t *source);
//set the source include path
void PC_SetIncludePath(source_t *source, char *path);
//set the punction set
void PC_SetPunctuations(source_t *source, punctuation_t *p);
//set the base folder to load files from
void PC_SetBaseFolder(const char *path);
//load a source file
source_t *LoadSourceFile(const char *filename);
//load a source from memory
source_t *LoadSourceMemory(char *ptr, int length, char *name);
//free the given source
void FreeSource(source_t *source);
//print a source error
void QDECL SourceError(source_t *source, char *str, ...) __attribute__ ((format (printf, 2, 3)));
//print a source warning
void QDECL SourceWarning(source_t *source, char *str, ...) __attribute__ ((format (printf, 2, 3)));
#ifdef BSPC
// some of BSPC source does include qcommon/q_shared.h and some does not
// we define pc_token_s pc_token_t if needed (yes, it's ugly)
#ifndef __Q_SHARED_H
#define MAX_TOKENLENGTH 1024
typedef struct pc_token_s
{
int type;
int subtype;
int intvalue;
float floatvalue;
char string[MAX_TOKENLENGTH];
} pc_token_t;
#endif //!_Q_SHARED_H
#endif //BSPC
//
int PC_LoadSourceHandle(const char *filename, const char *basepath);
int PC_FreeSourceHandle(int handle);
int PC_ReadTokenHandle(int handle, pc_token_t *pc_token);
void PC_UnreadLastTokenHandle( int handle );
int PC_SourceFileAndLine(int handle, char *filename, int *line);
void PC_CheckOpenSourceHandles(void);
| mecwerks/spearmint-ios | code/botlib/l_precomp.h | C | gpl-3.0 | 6,785 |
// you can call this function to create a window to tweak a float value
// if it is called multiple times, it will add more tweakable bars to that window
void tweak(float *var);
| DomNomNom/anisotropic | tweaker.h | C | gpl-3.0 | 179 |
/*-
* Copyright (c) 2003-2017 Lev Walkin <[email protected]>. All rights reserved.
* Redistribution and modifications are permitted subject to BSD license.
*/
#ifndef ASN_TYPE_NULL_H
#define ASN_TYPE_NULL_H
#include <asn_application.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* The value of the NULL type is meaningless.
* Use the BOOLEAN type if you need to carry true/false semantics.
*/
typedef int NULL_t;
extern asn_TYPE_descriptor_t asn_DEF_NULL;
extern asn_TYPE_operation_t asn_OP_NULL;
asn_struct_free_f NULL_free;
asn_struct_print_f NULL_print;
asn_struct_compare_f NULL_compare;
ber_type_decoder_f NULL_decode_ber;
der_type_encoder_f NULL_encode_der;
xer_type_decoder_f NULL_decode_xer;
xer_type_encoder_f NULL_encode_xer;
oer_type_decoder_f NULL_decode_oer;
oer_type_encoder_f NULL_encode_oer;
per_type_decoder_f NULL_decode_uper;
per_type_encoder_f NULL_encode_uper;
per_type_decoder_f NULL_decode_aper;
per_type_encoder_f NULL_encode_aper;
asn_random_fill_f NULL_random_fill;
#define NULL_constraint asn_generic_no_constraint
#ifdef __cplusplus
}
#endif
#endif /* NULL_H */
| acetcom/cellwire | lib/asn1c/common/NULL.h | C | gpl-3.0 | 1,102 |
package com.diggime.modules.email.model.impl;
import com.diggime.modules.email.model.EMail;
import com.diggime.modules.email.model.MailContact;
import org.json.JSONObject;
import java.time.LocalDateTime;
import java.util.List;
import static org.foilage.utils.checkers.NullChecker.notNull;
public class PostmarkEMail implements EMail {
private final int id;
private final String messageId;
private final LocalDateTime sentDate;
private final MailContact sender;
private final List<MailContact> receivers;
private final List<MailContact> carbonCopies;
private final List<MailContact> blindCarbonCopies;
private final String subject;
private final String tag;
private final String htmlBody;
private final String textBody;
public PostmarkEMail(LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) {
this.id = 0;
this.messageId = "";
this.sentDate = notNull(sentDate);
this.sender = notNull(sender);
this.receivers = notNull(receivers);
this.carbonCopies = notNull(carbonCopies);
this.blindCarbonCopies = notNull(blindCarbonCopies);
this.subject = notNull(subject);
this.tag = notNull(tag);
this.htmlBody = notNull(htmlBody);
this.textBody = notNull(textBody);
}
public PostmarkEMail(String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) {
this.id = 0;
this.messageId = notNull(messageId);
this.sentDate = notNull(sentDate);
this.sender = notNull(sender);
this.receivers = notNull(receivers);
this.carbonCopies = notNull(carbonCopies);
this.blindCarbonCopies = notNull(blindCarbonCopies);
this.subject = notNull(subject);
this.tag = notNull(tag);
this.htmlBody = notNull(htmlBody);
this.textBody = notNull(textBody);
}
public PostmarkEMail(EMail mail, String messageId) {
this.id = mail.getId();
this.messageId = notNull(messageId);
this.sentDate = mail.getSentDate();
this.sender = mail.getSender();
this.receivers = mail.getReceivers();
this.carbonCopies = mail.getCarbonCopies();
this.blindCarbonCopies = mail.getBlindCarbonCopies();
this.subject = mail.getSubject();
this.tag = mail.getTag();
this.htmlBody = mail.getHtmlBody();
this.textBody = mail.getTextBody();
}
public PostmarkEMail(int id, String messageId, LocalDateTime sentDate, MailContact sender, List<MailContact> receivers, List<MailContact> carbonCopies, List<MailContact> blindCarbonCopies, String subject, String tag, String htmlBody, String textBody) {
this.id = id;
this.messageId = notNull(messageId);
this.sentDate = notNull(sentDate);
this.sender = notNull(sender);
this.receivers = notNull(receivers);
this.carbonCopies = notNull(carbonCopies);
this.blindCarbonCopies = notNull(blindCarbonCopies);
this.subject = notNull(subject);
this.tag = notNull(tag);
this.htmlBody = notNull(htmlBody);
this.textBody = notNull(textBody);
}
@Override
public int getId() {
return id;
}
@Override
public String getMessageId() {
return messageId;
}
@Override
public LocalDateTime getSentDate() {
return sentDate;
}
@Override
public MailContact getSender() {
return sender;
}
@Override
public List<MailContact> getReceivers() {
return receivers;
}
@Override
public List<MailContact> getCarbonCopies() {
return carbonCopies;
}
@Override
public List<MailContact> getBlindCarbonCopies() {
return blindCarbonCopies;
}
@Override
public String getSubject() {
return subject;
}
@Override
public String getTag() {
return tag;
}
@Override
public String getHtmlBody() {
return htmlBody;
}
@Override
public String getTextBody() {
return textBody;
}
@Override
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
obj.put("From", sender.getName()+" <"+sender.getAddress()+">");
addReceivers(obj, receivers, "To");
addReceivers(obj, carbonCopies, "Cc");
addReceivers(obj, blindCarbonCopies, "Bcc");
obj.put("Subject", subject);
if(tag.length()>0) {
obj.put("Tag", tag);
}
if(htmlBody.length()>0) {
obj.put("HtmlBody", htmlBody);
} else {
obj.put("HtmlBody", textBody);
}
if(textBody.length()>0) {
obj.put("TextBody", textBody);
}
return obj;
}
private void addReceivers(JSONObject obj, List<MailContact> sendList, String jsonType) {
boolean first = true;
StringBuilder sb = new StringBuilder();
for(MailContact contact: sendList) {
if(first) {
first = false;
} else {
sb.append(", ");
}
sb.append(contact.getName());
sb.append(" <");
sb.append(contact.getAddress());
sb.append(">");
}
if(sendList.size()>0) {
obj.put(jsonType, sb.toString());
}
}
}
| drbizzaro/diggime | base/main/src/com/diggime/modules/email/model/impl/PostmarkEMail.java | Java | gpl-3.0 | 5,687 |
/*
* Copyright (C) 2014 Hector Espert Pardo
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.blackleg.libdam.geometry;
import es.blackleg.libdam.utilities.Calculadora;
/**
*
* @author Hector Espert Pardo
*/
public class Circulo extends Figura {
private double radio;
public Circulo() {
}
public Circulo(double radio) {
this.radio = radio;
}
public void setRadio(double radio) {
this.radio = radio;
}
public double getRadio() {
return radio;
}
public double getDiametro() {
return 2 * radio;
}
@Override
public double calculaArea() {
return Calculadora.areaCirculo(radio);
}
@Override
public double calculaPerimetro() {
return Calculadora.perimetroCirculo(radio);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Circulo other = (Circulo) obj;
return Double.doubleToLongBits(this.radio) == Double.doubleToLongBits(other.radio);
}
@Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + (int) (Double.doubleToLongBits(this.radio) ^ (Double.doubleToLongBits(this.radio) >>> 32));
return hash;
}
@Override
public String toString() {
return String.format("Circulo: x=%d, y=%d, R=%.2f.", super.getCentro().getX(), super.getCentro().getY(), radio);
}
}
| blackleg/libdam | src/main/java/es/blackleg/libdam/geometry/Circulo.java | Java | gpl-3.0 | 2,177 |
<?php
return [
'facebook' => [
'appId' => '', //application api id for facebook
'appSecret' => '', //application api secret for facebook
'scope' => 'email, user_birthday, publish_actions' //facebook scopes
],
'twitter' => [
'appId' => '', //twitter application consumer key
'appSecret' => '' //twitter application consumer secret
//Twitter scopes must be defined in dev.twitter.com
]
]; | jlorente/social-abstract-client | config/config.php | PHP | gpl-3.0 | 450 |
/**
* Cerberus Copyright (C) 2013 - 2017 cerberustesting
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of Cerberus.
*
* Cerberus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Cerberus 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 Cerberus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cerberus.service.groovy.impl;
import groovy.lang.GroovyShell;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.cerberus.service.groovy.IGroovyService;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.kohsuke.groovy.sandbox.SandboxTransformer;
import org.springframework.stereotype.Service;
/**
* {@link IGroovyService} default implementation
*
* @author Aurelien Bourdon
*/
@Service
public class GroovyService implements IGroovyService {
/**
* Groovy specific compilation customizer in order to avoid code injection
*/
private static final CompilerConfiguration GROOVY_COMPILER_CONFIGURATION = new CompilerConfiguration().addCompilationCustomizers(new SandboxTransformer());
/**
* Each Groovy execution is ran inside a dedicated {@link Thread},
* especially to register our Groovy interceptor
*/
private ExecutorService executorService;
@PostConstruct
private void init() {
executorService = Executors.newCachedThreadPool();
}
@PreDestroy
private void shutdown() {
if (executorService != null && !executorService.isShutdown()) {
executorService.shutdownNow();
}
}
@Override
public String eval(final String script) throws IGroovyServiceException {
try {
Future<String> expression = executorService.submit(() -> {
RestrictiveGroovyInterceptor interceptor = new RestrictiveGroovyInterceptor(
Collections.<Class<?>>emptySet(),
Collections.<Class<?>>emptySet(),
Collections.<RestrictiveGroovyInterceptor.AllowedPrefix>emptyList()
);
try {
interceptor.register();
GroovyShell shell = new GroovyShell(GROOVY_COMPILER_CONFIGURATION);
return shell.evaluate(script).toString();
} finally {
interceptor.unregister();
}
});
String eval = expression.get();
if (eval == null) {
throw new IGroovyServiceException("Groovy evaluation returns null result");
}
return eval;
} catch (Exception e) {
throw new IGroovyServiceException(e);
}
}
}
| cerberustesting/cerberus-source | source/src/main/java/org/cerberus/service/groovy/impl/GroovyService.java | Java | gpl-3.0 | 3,363 |
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Engine;
using Micropolis.Common;
using Microsoft.ApplicationInsights;
namespace Micropolis.ViewModels
{
public class EvaluationPaneViewModel : BindableBase, Engine.IListener
{
private Engine.Micropolis _engine;
private MainGamePageViewModel _mainPageViewModel;
/// <summary>
/// Sets the engine.
/// </summary>
/// <param name="newEngine">The new engine.</param>
public void SetEngine(Engine.Micropolis newEngine)
{
if (_engine != null)
{
//old engine
_engine.RemoveListener(this);
}
_engine = newEngine;
if (_engine != null)
{
//new engine
_engine.AddListener(this);
LoadEvaluation();
}
}
public EvaluationPaneViewModel()
{
DismissCommand = new DelegateCommand(OnDismissClicked);
try
{
_telemetry = new TelemetryClient();
}
catch (Exception)
{
}
}
/// <summary>
/// Called when user clicked the dismiss button to close the window.
/// </summary>
private void OnDismissClicked()
{
try {
_telemetry.TrackEvent("EvaluationPaneDismissClicked");
}
catch (Exception) { }
_mainPageViewModel.HideEvaluationPane();
}
private string _headerPublicOpinionTextBlockText;
public string HeaderPublicOpinionTextBlockText
{
get
{
return this._headerPublicOpinionTextBlockText;
}
set
{
this.SetProperty(ref this._headerPublicOpinionTextBlockText, value);
}
}
private string _pubOpTextBlockText;
public string PubOpTextBlockText
{
get
{
return this._pubOpTextBlockText;
}
set
{
this.SetProperty(ref this._pubOpTextBlockText, value);
}
}
private string _pubOp2TextBlockText;
public string PubOp2TextBlockText
{
get
{
return this._pubOp2TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp2TextBlockText, value);
}
}
private string _pubOp3TextBlockText;
public string PubOp3TextBlockText
{
get
{
return this._pubOp3TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp3TextBlockText, value);
}
}
private string _pubOp4TextBlockText;
public string PubOp4TextBlockText
{
get
{
return this._pubOp4TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp4TextBlockText, value);
}
}
/// <summary>
/// Makes the public opinion pane.
/// </summary>
/// <returns></returns>
private void MakePublicOpinionPane()
{
HeaderPublicOpinionTextBlockText = Strings.GetString("public-opinion");
PubOpTextBlockText = Strings.GetString("public-opinion-1");
PubOp2TextBlockText = Strings.GetString("public-opinion-2");
PubOp3TextBlockText = Strings.GetString("public-opinion-yes");
PubOp4TextBlockText = Strings.GetString("public-opinion-no");
VoterProblem1TextBlockText = "";
VoterCount1TextBlockText = "";
VoterProblem2TextBlockText = "";
VoterCount2TextBlockText = "";
VoterProblem3TextBlockText = "";
VoterCount3TextBlockText = "";
VoterProblem4TextBlockText = "";
VoterCount4TextBlockText = "";
}
private string _voterProblem4TextBlockText;
public string VoterProblem4TextBlockText
{
get
{
return this._voterProblem4TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem4TextBlockText, value);
}
}
private string _voterProblem3TextBlockText;
public string VoterProblem3TextBlockText
{
get
{
return this._voterProblem3TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem3TextBlockText, value);
}
}
private string _voterProblem2TextBlockText;
public string VoterProblem2TextBlockText
{
get
{
return this._voterProblem2TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem2TextBlockText, value);
}
}
private string _voterProblem1TextBlockText;
public string VoterProblem1TextBlockText
{
get
{
return this._voterProblem1TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem1TextBlockText, value);
}
}
private string _voterCount1TextBlockText;
public string VoterCount1TextBlockText
{
get
{
return this._voterCount1TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount1TextBlockText, value);
}
}
private string _voterCount2TextBlockText;
public string VoterCount2TextBlockText
{
get
{
return this._voterCount2TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount2TextBlockText, value);
}
}
private string _voterCount3TextBlockText;
public string VoterCount3TextBlockText
{
get
{
return this._voterCount3TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount3TextBlockText, value);
}
}
private string _voterCount4TextBlockText;
public string VoterCount4TextBlockText
{
get
{
return this._voterCount4TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount4TextBlockText, value);
}
}
/// <summary>
/// Makes the statistics pane.
/// </summary>
/// <returns></returns>
private void MakeStatisticsPane()
{
HeaderStatisticsTextBlockText = Strings.GetString("statistics-head");
CityScoreHeaderTextBlockText = Strings.GetString("city-score-head");
StatPopTextBlockText = Strings.GetString("stats-population");
StatMigTextBlockText = Strings.GetString("stats-net-migration");
StatsLastYearTextBlockText = Strings.GetString("stats-last-year");
StatsAssessedValueTextBlockText = Strings.GetString("stats-assessed-value");
StatsCategoryTextBlockText = Strings.GetString("stats-category");
StatsGameLevelTextBlockText = Strings.GetString("stats-game-level");
CityScoreCurrentTextBlockText = Strings.GetString("city-score-current");
CityScoreChangeTextBlockText = Strings.GetString("city-score-change");
}
private string _headerStatisticsTextBlockText;
public string HeaderStatisticsTextBlockText
{
get
{
return this._headerStatisticsTextBlockText;
}
set
{
this.SetProperty(ref this._headerStatisticsTextBlockText, value);
}
}
private string _cityScoreHeaderTextBlockText;
public string CityScoreHeaderTextBlockText
{
get
{
return this._cityScoreHeaderTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreHeaderTextBlockText, value);
}
}
private string _statPopTextBlockText;
public string StatPopTextBlockText
{
get
{
return this._statPopTextBlockText;
}
set
{
this.SetProperty(ref this._statPopTextBlockText, value);
}
}
private string _statMigTextBlockText;
public string StatMigTextBlockText
{
get
{
return this._statMigTextBlockText;
}
set
{
this.SetProperty(ref this._statMigTextBlockText, value);
}
}
private string _statsLastYearTextBlockText;
public string StatsLastYearTextBlockText
{
get
{
return this._statsLastYearTextBlockText;
}
set
{
this.SetProperty(ref this._statsLastYearTextBlockText, value);
}
}
private string _statsAssessedValueTextBlockText;
public string StatsAssessedValueTextBlockText
{
get
{
return this._statsAssessedValueTextBlockText;
}
set
{
this.SetProperty(ref this._statsAssessedValueTextBlockText, value);
}
}
private string _statsCategoryTextBlockText;
public string StatsCategoryTextBlockText
{
get
{
return this._statsCategoryTextBlockText;
}
set
{
this.SetProperty(ref this._statsCategoryTextBlockText, value);
}
}
private string _statsGameLevelTextBlockText;
public string StatsGameLevelTextBlockText
{
get
{
return this._statsGameLevelTextBlockText;
}
set
{
this.SetProperty(ref this._statsGameLevelTextBlockText, value);
}
}
private string _cityScoreCurrentTextBlockText;
public string CityScoreCurrentTextBlockText
{
get
{
return this._cityScoreCurrentTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreCurrentTextBlockText, value);
}
}
private string _cityScoreChangeTextBlockText;
public string CityScoreChangeTextBlockText
{
get
{
return this._cityScoreChangeTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreChangeTextBlockText, value);
}
}
private string _yesTextBlockText;
public string YesTextBlockText
{
get
{
return this._yesTextBlockText;
}
set
{
this.SetProperty(ref this._yesTextBlockText, value);
}
}
private string _noTextBlockText;
public string NoTextBlockText
{
get
{
return this._noTextBlockText;
}
set
{
this.SetProperty(ref this._noTextBlockText, value);
}
}
/// <summary>
/// Loads the evaluation.
/// </summary>
private void LoadEvaluation()
{
YesTextBlockText = ((_engine.Evaluation.CityYes).ToString()+"%");
NoTextBlockText = ((_engine.Evaluation.CityNo).ToString()+"%");
CityProblem p;
int numVotes;
p = 0 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[0]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem1TextBlockText = ("problem." + p); //name
VoterCount1TextBlockText = (0.01*numVotes).ToString();
VoterProblem1IsVisible = true;
VoterCount1IsVisible = true;
}
else
{
VoterProblem1IsVisible = false;
VoterCount1IsVisible = false;
}
p = 1 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[1]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem2TextBlockText = ("problem." + p); //name
VoterCount2TextBlockText = (0.01 * numVotes).ToString();
VoterProblem2IsVisible = true;
VoterCount2IsVisible = true;
}
else
{
VoterProblem2IsVisible = false;
VoterCount2IsVisible = false;
}
p = 2 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[2]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem3TextBlockText = ("problem." + p); //name
VoterCount3TextBlockText = (0.01 * numVotes).ToString();
VoterProblem3IsVisible = true;
VoterCount3IsVisible = true;
}
else
{
VoterProblem3IsVisible = false;
VoterCount3IsVisible = false;
}
p = 3 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[3]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem4TextBlockText = ("problem." + p); //name
VoterCount4TextBlockText = (0.01 * numVotes).ToString();
VoterProblem4IsVisible = true;
VoterCount4IsVisible = true;
}
else
{
VoterProblem4IsVisible = false;
VoterCount4IsVisible = false;
}
PopTextBlockText = (_engine.Evaluation.CityPop).ToString();
DeltaTextBlockText = (_engine.Evaluation.DeltaCityPop).ToString();
AssessTextBlockText = (_engine.Evaluation.CityAssValue).ToString();
CityClassTextBlockText = (GetCityClassName(_engine.Evaluation.CityClass));
GameLevelTextBlockText = (GetGameLevelName(_engine.GameLevel));
ScoreTextBlockText = (_engine.Evaluation.CityScore).ToString();
ScoreDeltaTextBlockText = (_engine.Evaluation.DeltaCityScore).ToString();
}
private bool _voterCount4IsVisible;
public bool VoterCount4IsVisible
{
get
{
return this._voterCount4IsVisible;
}
set
{
this.SetProperty(ref this._voterCount4IsVisible, value);
}
}
private bool _voterCount3IsVisible;
public bool VoterCount3IsVisible
{
get
{
return this._voterCount3IsVisible;
}
set
{
this.SetProperty(ref this._voterCount3IsVisible, value);
}
}
private bool _voterCount2IsVisible;
public bool VoterCount2IsVisible
{
get
{
return this._voterCount2IsVisible;
}
set
{
this.SetProperty(ref this._voterCount2IsVisible, value);
}
}
private bool _voterCount1IsVisible;
public bool VoterCount1IsVisible
{
get
{
return this._voterCount1IsVisible;
}
set
{
this.SetProperty(ref this._voterCount1IsVisible, value);
}
}
private bool _voterProblem4IsVisible;
public bool VoterProblem4IsVisible
{
get
{
return this._voterProblem4IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem4IsVisible, value);
}
}
private bool _voterProblem3IsVisible;
public bool VoterProblem3IsVisible
{
get
{
return this._voterProblem3IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem3IsVisible, value);
}
}
private bool _voterProblem2IsVisible;
public bool VoterProblem2IsVisible
{
get
{
return this._voterProblem2IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem2IsVisible, value);
}
}
private bool _voterProblem1IsVisible;
public bool VoterProblem1IsVisible
{
get
{
return this._voterProblem1IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem1IsVisible, value);
}
}
private string _scoreDeltaTextBlockText;
public string ScoreDeltaTextBlockText
{
get
{
return this._scoreDeltaTextBlockText;
}
set
{
this.SetProperty(ref this._scoreDeltaTextBlockText, value);
}
}
private string _scoreTextBlockText;
public string ScoreTextBlockText
{
get
{
return this._scoreTextBlockText;
}
set
{
this.SetProperty(ref this._scoreTextBlockText, value);
}
}
private string _gameLevelTextBlockText;
public string GameLevelTextBlockText
{
get
{
return this._gameLevelTextBlockText;
}
set
{
this.SetProperty(ref this._gameLevelTextBlockText, value);
}
}
private string _cityClassTextBlockText;
public string CityClassTextBlockText
{
get
{
return this._cityClassTextBlockText;
}
set
{
this.SetProperty(ref this._cityClassTextBlockText, value);
}
}
private string _assessTextBlockText;
public string AssessTextBlockText
{
get
{
return this._assessTextBlockText;
}
set
{
this.SetProperty(ref this._assessTextBlockText, value);
}
}
private string _deltaTextBlockText;
public string DeltaTextBlockText
{
get
{
return this._deltaTextBlockText;
}
set
{
this.SetProperty(ref this._deltaTextBlockText, value);
}
}
private string _popTextBlockText;
public string PopTextBlockText
{
get
{
return this._popTextBlockText;
}
set
{
this.SetProperty(ref this._popTextBlockText, value);
}
}
/// <summary>
/// Gets the name of the city class.
/// </summary>
/// <param name="cityClass">The city class.</param>
/// <returns></returns>
private static String GetCityClassName(int cityClass)
{
return Strings.GetString("class." + cityClass);
}
/// <summary>
/// Gets the name of the game level.
/// </summary>
/// <param name="gameLevel">The game level.</param>
/// <returns></returns>
private static String GetGameLevelName(int gameLevel)
{
return Strings.GetString("level." + gameLevel);
}
public DelegateCommand DismissCommand { get; private set; }
private string _dismissButtonText;
private TelemetryClient _telemetry;
public string DismissButtonText
{
get
{
return this._dismissButtonText;
}
set
{
this.SetProperty(ref this._dismissButtonText, value);
}
}
internal void SetupAfterBasicInit(MainGamePageViewModel mainPageViewModel, Engine.Micropolis engine)
{
_mainPageViewModel = mainPageViewModel;
DismissButtonText = Strings.GetString("dismiss-evaluation");
MakePublicOpinionPane();
MakeStatisticsPane();
SetEngine(engine);
LoadEvaluation();
}
#region implements Micropolis.IListener
/// <summary>
/// Cities the message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="loc">The loc.</param>
public void CityMessage(MicropolisMessage message, CityLocation loc)
{
}
/// <summary>
/// Cities the sound.
/// </summary>
/// <param name="sound">The sound.</param>
/// <param name="loc">The loc.</param>
public void CitySound(Sound sound, CityLocation loc)
{
}
/// <summary>
/// Fired whenever the "census" is taken, and the various historical counters have been updated. (Once a month in
/// game.)
/// </summary>
public void CensusChanged()
{
}
/// <summary>
/// Fired whenever resValve, comValve, or indValve changes. (Twice a month in game.)
/// </summary>
public void DemandChanged()
{
}
/// <summary>
/// Fired whenever the mayor's money changes.
/// </summary>
public void FundsChanged()
{
}
/// <summary>
/// Fired whenever autoBulldoze, autoBudget, noDisasters, or simSpeed change.
/// </summary>
public void OptionsChanged()
{
}
#endregion
#region implements Engine.IListener
/// <summary>
/// Fired whenever the city evaluation is recalculated. (Once a year.)
/// </summary>
public void EvaluationChanged()
{
LoadEvaluation();
}
#endregion
}
}
| andreasbalzer/MicropolisForWindows | Micropolis.W10/ViewModels/EvaluationPaneViewModel.cs | C# | gpl-3.0 | 24,009 |
<?php
/**
* KR_Custom_Posts
*/
class KR_Custom_Posts extends Odin_Post_Type {
private $_labels = array();
private $_arguments = array();
private $_dashicon = 'dashicons-';
private $_supports = array( 'title', 'editor', 'thumbnail' );
private $_slug;
private $_singular;
private $_plural;
private $_rewrite;
private $_exclude_search;
public function __construct( $post_slug = null, $singular = null, $plural = null, $supports = array(), $dashicon = 'admin-post', $rewrite = null, $exclude_search = false ) {
if(empty($post_slug)) {
echo '<pre>' . print_r( __('The Parameter <code>$post_slug</code> is required!!'), true ) . '</pre>';
die();
}
$this->_slug = $post_slug;
$this->_dashicon = $this->_dashicon . $dashicon;
$this->_singular = (!empty($singular)) ? $singular : $this->_slug;
$this->_plural = (!empty($plural)) ? $plural : $this->_slug;
$this->_supports = (count($supports) > 0) ? $supports : $this->_supports;
$this->_rewrite = (!empty($rewrite)) ? array('slug' => $rewrite) : array('slug' => $this->_slug);
$this->_exclude_search = $exclude_search;
$this->kr_init();
}
private function kr_init() {
parent::__construct( $this->_slug, $this->_slug );
$this->kr_set_labels();
$this->kr_set_arguments();
$this->set_labels($this->_labels); # odin method set_labels
$this->set_arguments($this->_arguments); # odin method set_arguments
$this->kr_cleaner();
}
private function kr_set_labels() {
$this->_labels = array(
'name' => $this->_plural,
'singular_name' => $this->_singular,
'menu_name' => $this->_plural,
'all_items' => $this->_plural,
'add_new' => 'Adicionar Novo',
'add_new_item' => 'Adicionar Novo',
'search_items' => 'Buscar',
'not_found' => 'Nada encontrado',
'not_found_in_trash' => 'Nada encontrado na lixeira',
);
}
private function kr_set_arguments() {
$this->_arguments = array(
'supports' => $this->_supports,
'menu_icon' => $this->_dashicon,
'rewrite' => $this->_rewrite,
'exclude_from_search' => $this->_exclude_search,
// 'menu_position' => '1.36',
'capability_type' => 'page',
);
}
private function kr_cleaner() {
unset($this->_slug);
unset($this->_dashicon);
unset($this->_singular);
unset($this->_plural);
unset($this->_supports);
unset($this->_exclude_search);
unset($this->_rewrite);
unset($this->_labels);
unset($this->_arguments);
}
} # End Class KR_Custom_Posts
| abracce/theme-abracce.org.br | app/class/custom-posts.php | PHP | gpl-3.0 | 2,596 |
<?php
/* core/modules/system/templates/block--system-branding-block.html.twig */
class __TwigTemplate_f1b301a70237e4e176f4b41c2721030700b3dd2e5c3f618f2513416e3a699971 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
$this->parent = $this->loadTemplate("block.html.twig", "core/modules/system/templates/block--system-branding-block.html.twig", 1);
$this->blocks = array(
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "block.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$tags = array("if" => 19);
$filters = array("t" => 20);
$functions = array("path" => 20);
try {
$this->env->getExtension('sandbox')->checkSecurity(
array('if'),
array('t'),
array('path')
);
} catch (Twig_Sandbox_SecurityError $e) {
$e->setTemplateFile($this->getTemplateName());
if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) {
$e->setTemplateLine($tags[$e->getTagName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) {
$e->setTemplateLine($filters[$e->getFilterName()]);
} elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) {
$e->setTemplateLine($functions[$e->getFunctionName()]);
}
throw $e;
}
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 18
public function block_content($context, array $blocks = array())
{
// line 19
echo " ";
if ((isset($context["site_logo"]) ? $context["site_logo"] : null)) {
// line 20
echo " <a href=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->getPath("<front>")));
echo "\" title=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home")));
echo "\" rel=\"home\">
<img src=\"";
// line 21
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_logo"]) ? $context["site_logo"] : null), "html", null, true));
echo "\" alt=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home")));
echo "\" />
</a>
";
}
// line 24
echo " ";
if ((isset($context["site_name"]) ? $context["site_name"] : null)) {
// line 25
echo " <a href=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar($this->env->getExtension('drupal_core')->getPath("<front>")));
echo "\" title=\"";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->renderVar(t("Home")));
echo "\" rel=\"home\">";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_name"]) ? $context["site_name"] : null), "html", null, true));
echo "</a>
";
}
// line 27
echo " ";
echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["site_slogan"]) ? $context["site_slogan"] : null), "html", null, true));
echo "
";
}
public function getTemplateName()
{
return "core/modules/system/templates/block--system-branding-block.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 86 => 27, 76 => 25, 73 => 24, 65 => 21, 58 => 20, 55 => 19, 52 => 18, 11 => 1,);
}
}
/* {% extends "block.html.twig" %}*/
/* {#*/
/* /***/
/* * @file*/
/* * Default theme implementation for a branding block.*/
/* **/
/* * Each branding element variable (logo, name, slogan) is only available if*/
/* * enabled in the block configuration.*/
/* **/
/* * Available variables:*/
/* * - site_logo: Logo for site as defined in Appearance or theme settings.*/
/* * - site_name: Name for site as defined in Site information settings.*/
/* * - site_slogan: Slogan for site as defined in Site information settings.*/
/* **/
/* * @ingroup themeable*/
/* *//* */
/* #}*/
/* {% block content %}*/
/* {% if site_logo %}*/
/* <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">*/
/* <img src="{{ site_logo }}" alt="{{ 'Home'|t }}" />*/
/* </a>*/
/* {% endif %}*/
/* {% if site_name %}*/
/* <a href="{{ path('<front>') }}" title="{{ 'Home'|t }}" rel="home">{{ site_name }}</a>*/
/* {% endif %}*/
/* {{ site_slogan }}*/
/* {% endblock %}*/
/* */
| acastellon/smtcc | sites/default/files/php/twig/42a2597a_block--system-branding-block.html.twig_c69e55da788ed29c4c90e83e1c7f08c4006237988dbbe9f913bdfe4f6f661444/498169c485adefe3bb313999225832f5bbdd2ab6ac9b397903eae1c54b5b0ab3.php | PHP | gpl-3.0 | 5,470 |
#region using directives
using System;
using PoGo.PokeMobBot.Logic.Event;
using PoGo.PokeMobBot.Logic.Event.Egg;
using PoGo.PokeMobBot.Logic.Event.Fort;
using PoGo.PokeMobBot.Logic.Event.Global;
using PoGo.PokeMobBot.Logic.Event.GUI;
using PoGo.PokeMobBot.Logic.Event.Item;
using PoGo.PokeMobBot.Logic.Event.Logic;
using PoGo.PokeMobBot.Logic.Event.Obsolete;
using PoGo.PokeMobBot.Logic.Event.Player;
using PoGo.PokeMobBot.Logic.Event.Pokemon;
using PoGo.PokeMobBot.Logic.State;
using PoGo.PokeMobBot.Logic.Utils;
using POGOProtos.Networking.Responses;
#endregion
namespace PoGo.PokeMobBot.Logic
{
public class StatisticsAggregator
{
public void HandleEvent(ProfileEvent evt, ISession session)
{
session.Stats.SetUsername(evt.Profile);
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(ErrorEvent evt, ISession session)
{
}
public void HandleEvent(NoticeEvent evt, ISession session)
{
}
public void HandleEvent(FortLureStartedEvent evt, ISession session)
{
}
public void HandleEvent(ItemUsedEvent evt, ISession session)
{
}
public void HandleEvent(WarnEvent evt, ISession session)
{
}
public void HandleEvent(UseLuckyEggEvent evt, ISession session)
{
}
public void HandleEvent(PokemonEvolveEvent evt, ISession session)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(TransferPokemonEvent evt, ISession session)
{
session.Stats.TotalPokemonsTransfered++;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(EggHatchedEvent evt, ISession session)
{
session.Stats.TotalPokemons++;
session.Stats.HatchedNow++;
session.Stats.RefreshStatAndCheckLevelup(session);
session.Stats.RefreshPokeDex(session);
}
public void HandleEvent(VerifyChallengeEvent evt, ISession session)
{
}
public void HandleEvent(CheckChallengeEvent evt, ISession session)
{
}
public void HandleEvent(BuddySetEvent evt, ISession session)
{
}
public void HandleEvent(BuddyWalkedEvent evt, ISession session)
{
}
public void HandleEvent(ItemRecycledEvent evt, ISession session)
{
session.Stats.TotalItemsRemoved += evt.Count;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(FortUsedEvent evt, ISession session)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.TotalPokestops++;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(FortTargetEvent evt, ISession session)
{
}
public void HandleEvent(PokemonActionDoneEvent evt, ISession session)
{
}
public void HandleEvent(PokemonCaptureEvent evt, ISession session)
{
if (evt.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.TotalPokemons++;
session.Stats.TotalStardust = evt.Stardust;
session.Stats.RefreshStatAndCheckLevelup(session);
session.Stats.RefreshPokeDex(session);
}
session.Stats.PokeBalls++;
}
public void HandleEvent(NoPokeballEvent evt, ISession session)
{
}
public void HandleEvent(UseBerryEvent evt, ISession session)
{
}
public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session)
{
}
public void HandleEvent(UpdatePositionEvent evt, ISession session)
{
}
public void HandleEvent(NewVersionEvent evt, ISession session)
{
}
public void HandleEvent(UpdateEvent evt, ISession session)
{
}
public void HandleEvent(BotCompleteFailureEvent evt, ISession session)
{
}
public void HandleEvent(DebugEvent evt, ISession session)
{
}
public void HandleEvent(EggIncubatorStatusEvent evt, ISession session)
{
}
public void HandleEvent(EggsListEvent evt, ISession session)
{
}
public void HandleEvent(ForceMoveDoneEvent evt, ISession session)
{
}
public void HandleEvent(FortFailedEvent evt, ISession session)
{
}
public void HandleEvent(InvalidKeepAmountEvent evt, ISession session)
{
}
public void HandleEvent(InventoryListEvent evt, ISession session)
{
}
public void HandleEvent(InventoryNewItemsEvent evt, ISession session)
{
}
public void HandleEvent(EggFoundEvent evt, ISession session)
{
}
public void HandleEvent(NextRouteEvent evt, ISession session)
{
}
public void HandleEvent(PlayerLevelUpEvent evt, ISession session)
{
}
public void HandleEvent(PlayerStatsEvent evt, ISession session)
{
}
public void HandleEvent(PokemonDisappearEvent evt, ISession session)
{
session.Stats.EncountersNow++;
}
public void HandleEvent(PokemonEvolveDoneEvent evt, ISession session)
{
session.Stats.TotalEvolves++;
session.Stats.RefreshPokeDex(session);
}
public void HandleEvent(PokemonFavoriteEvent evt, ISession session)
{
}
public void HandleEvent(PokemonSettingsEvent evt, ISession session)
{
}
public void HandleEvent(PokemonsFoundEvent evt, ISession session)
{
}
public void HandleEvent(PokemonsWildFoundEvent evt, ISession session)
{
}
public void HandleEvent(PokemonStatsChangedEvent evt, ISession session)
{
}
public void HandleEvent(PokeStopListEvent evt, ISession session)
{
}
public void HandleEvent(SnipeEvent evt, ISession session)
{
}
public void HandleEvent(SnipeModeEvent evt, ISession session)
{
}
public void HandleEvent(UseLuckyEggMinPokemonEvent evt, ISession session)
{
}
public void HandleEvent(PokemonListEvent evt, ISession session)
{
}
public void HandleEvent(GymPokeEvent evt, ISession session)
{
}
public void HandleEvent(PokestopsOptimalPathEvent evt, ISession session)
{
}
public void HandleEvent(TeamSetEvent evt, ISession session)
{
}
public void HandleEvent(ItemLostEvent evt, ISession session)
{
}
public void Listen(IEvent evt, ISession session)
{
try
{
dynamic eve = evt;
HandleEvent(eve, session);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
}
}
}
} | Lunat1q/Catchem-PoGo | Source/PoGo.PokeMobBot.Logic/StatisticsAggregator.cs | C# | gpl-3.0 | 7,499 |
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member (no intention to document this file)
namespace RobinHood70.WallE.Base
{
public class AllCategoriesItem
{
#region Constructors
internal AllCategoriesItem(string category, int files, bool hidden, int pages, int size, int subcats)
{
this.Category = category;
this.Files = files;
this.Hidden = hidden;
this.Pages = pages;
this.Size = size;
this.Subcategories = subcats;
}
#endregion
#region Public Properties
public string Category { get; }
public int Files { get; }
public bool Hidden { get; }
public int Pages { get; }
public int Size { get; }
public int Subcategories { get; }
#endregion
#region Public Override Methods
public override string ToString() => this.Category;
#endregion
}
}
| RobinHood70/HoodBot | WallE/Base/Outputs/AllCategoriesItem.cs | C# | gpl-3.0 | 839 |
module libxc_funcs_m
implicit none
public
integer, parameter :: XC_LDA_X = 1 ! Exchange
integer, parameter :: XC_LDA_C_WIGNER = 2 ! Wigner parametrization
integer, parameter :: XC_LDA_C_RPA = 3 ! Random Phase Approximation
integer, parameter :: XC_LDA_C_HL = 4 ! Hedin & Lundqvist
integer, parameter :: XC_LDA_C_GL = 5 ! Gunnarson & Lundqvist
integer, parameter :: XC_LDA_C_XALPHA = 6 ! Slater's Xalpha
integer, parameter :: XC_LDA_C_VWN = 7 ! Vosko, Wilk, & Nussair
integer, parameter :: XC_LDA_C_VWN_RPA = 8 ! Vosko, Wilk, & Nussair (RPA)
integer, parameter :: XC_LDA_C_PZ = 9 ! Perdew & Zunger
integer, parameter :: XC_LDA_C_PZ_MOD = 10 ! Perdew & Zunger (Modified)
integer, parameter :: XC_LDA_C_OB_PZ = 11 ! Ortiz & Ballone (PZ)
integer, parameter :: XC_LDA_C_PW = 12 ! Perdew & Wang
integer, parameter :: XC_LDA_C_PW_MOD = 13 ! Perdew & Wang (Modified)
integer, parameter :: XC_LDA_C_OB_PW = 14 ! Ortiz & Ballone (PW)
integer, parameter :: XC_LDA_C_AMGB = 15 ! Attacalite et al
integer, parameter :: XC_LDA_XC_TETER93 = 20 ! Teter 93 parametrization
integer, parameter :: XC_GGA_X_PBE = 101 ! Perdew, Burke & Ernzerhof exchange
integer, parameter :: XC_GGA_X_PBE_R = 102 ! Perdew, Burke & Ernzerhof exchange (revised)
integer, parameter :: XC_GGA_X_B86 = 103 ! Becke 86 Xalfa,beta,gamma
integer, parameter :: XC_GGA_X_B86_R = 104 ! Becke 86 Xalfa,beta,gamma (reoptimized)
integer, parameter :: XC_GGA_X_B86_MGC = 105 ! Becke 86 Xalfa,beta,gamma (with mod. grad. correction)
integer, parameter :: XC_GGA_X_B88 = 106 ! Becke 88
integer, parameter :: XC_GGA_X_G96 = 107 ! Gill 96
integer, parameter :: XC_GGA_X_PW86 = 108 ! Perdew & Wang 86
integer, parameter :: XC_GGA_X_PW91 = 109 ! Perdew & Wang 91
integer, parameter :: XC_GGA_X_OPTX = 110 ! Handy & Cohen OPTX 01
integer, parameter :: XC_GGA_X_DK87_R1 = 111 ! dePristo & Kress 87 (version R1)
integer, parameter :: XC_GGA_X_DK87_R2 = 112 ! dePristo & Kress 87 (version R2)
integer, parameter :: XC_GGA_X_LG93 = 113 ! Lacks & Gordon 93
integer, parameter :: XC_GGA_X_FT97_A = 114 ! Filatov & Thiel 97 (version A)
integer, parameter :: XC_GGA_X_FT97_B = 115 ! Filatov & Thiel 97 (version B)
integer, parameter :: XC_GGA_X_PBE_SOL = 116 ! Perdew, Burke & Ernzerhof exchange (solids)
integer, parameter :: XC_GGA_X_RPBE = 117 ! Hammer, Hansen & Norskov (PBE-like)
integer, parameter :: XC_GGA_X_WC = 118 ! Wu & Cohen
integer, parameter :: XC_GGA_X_mPW91 = 119 ! Modified form of PW91 by Adamo & Barone
integer, parameter :: XC_GGA_X_AM05 = 120 ! Armiento & Mattsson 05 exchange
integer, parameter :: XC_GGA_X_PBEA = 121 ! Madsen (PBE-like)
integer, parameter :: XC_GGA_X_MPBE = 122 ! Adamo & Barone modification to PBE
integer, parameter :: XC_GGA_X_XPBE = 123 ! xPBE reparametrization by Xu & Goddard
integer, parameter :: XC_GGA_X_OPTPBE = 124 ! optPBE reparametrization for optPBE-vdW
integer, parameter :: XC_GGA_X_OPTB88 = 125 ! optB88 reparametrization for optB88-vdW
integer, parameter :: XC_GGA_X_C09 = 126 ! Cooper exchange for C09-vdW
integer, parameter :: XC_GGA_C_PBE = 130 ! Perdew, Burke & Ernzerhof correlation
integer, parameter :: XC_GGA_C_LYP = 131 ! Lee, Yang & Parr
integer, parameter :: XC_GGA_C_P86 = 132 ! Perdew 86
integer, parameter :: XC_GGA_C_PBE_SOL = 133 ! Perdew, Burke & Ernzerhof correlation SOL
integer, parameter :: XC_GGA_C_PW91 = 134 ! Perdew & Wang 91
integer, parameter :: XC_GGA_C_AM05 = 135 ! Armiento & Mattsson 05 correlation
integer, parameter :: XC_GGA_C_XPBE = 136 ! xPBE reparametrization by Xu & Goddard
integer, parameter :: XC_GGA_C_PBE_REVTPSS = 137 ! PBE correlation for TPSS
integer, parameter :: XC_GGA_XC_LB = 160 ! van Leeuwen & Baerends
integer, parameter :: XC_GGA_XC_HCTH_93 = 161 ! HCTH functional fitted to 93 molecules
integer, parameter :: XC_GGA_XC_HCTH_120 = 162 ! HCTH functional fitted to 120 molecules
integer, parameter :: XC_GGA_XC_HCTH_147 = 163 ! HCTH functional fitted to 147 molecules
integer, parameter :: XC_GGA_XC_HCTH_407 = 164 ! HCTH functional fitted to 147 molecules
integer, parameter :: XC_GGA_XC_EDF1 = 165 ! Empirical functionals from Adamson, Gill, and Pople
integer, parameter :: XC_GGA_XC_XLYP = 166 ! XLYP functional
integer, parameter :: XC_HYB_GGA_XC_B3PW91 = 401 ! The original hybrid proposed by Becke
integer, parameter :: XC_HYB_GGA_XC_B3LYP = 402 ! The (in)famous B3LYP
integer, parameter :: XC_HYB_GGA_XC_B3P86 = 403 ! Perdew 86 hybrid similar to B3PW91
integer, parameter :: XC_HYB_GGA_XC_O3LYP = 404 ! hybrid using the optx functional
integer, parameter :: XC_HYB_GGA_XC_PBEH = 406 ! aka PBE0 or PBE1PBE
integer, parameter :: XC_HYB_GGA_XC_X3LYP = 411 ! maybe the best hybrid
integer, parameter :: XC_HYB_GGA_XC_B1WC = 412 ! Becke 1-parameter mixture of WC and EXX
integer, parameter :: XC_MGGA_X_TPSS = 201 ! Perdew, Tao, Staroverov & Scuseria exchange
integer, parameter :: XC_MGGA_C_TPSS = 202 ! Perdew, Tao, Staroverov & Scuseria correlation
integer, parameter :: XC_MGGA_X_M06L = 203 ! Zhao, Truhlar exchange
integer, parameter :: XC_MGGA_C_M06L = 204 ! Zhao, Truhlar correlation
integer, parameter :: XC_MGGA_X_REVTPSS = 205 ! Perdew, Ruzsinszky, Csonka, Constantin and Sun Exchange
integer, parameter :: XC_MGGA_C_REVTPSS = 206 ! Perdew, Ruzsinszky, Csonka, Constantin and Sun Correlation
integer, parameter :: XC_LCA_OMC = 301 ! Orestes, Marcasso & Capelle
integer, parameter :: XC_LCA_LCH = 302 ! Lee, Colwell & Handy
end module libxc_funcs_m
| ajylee/gpaw-rtxs | c/libxc/src/libxc_funcs.f90 | FORTRAN | gpl-3.0 | 6,568 |
# brasillivre 
Segundo o [Ministério do Trabalho](http://www.mtps.gov.br/fiscalizacao-combate-trabalho-escravo)
>Considera-se trabalho realizado em condição análoga à de escravo a que resulte das seguintes situações, quer em conjunto, quer isoladamente: a submissão de trabalhador a trabalhos forçados; a submissão de trabalhador a jornada exaustiva; a sujeição de trabalhador a condições degradantes de trabalho; a restrição da locomoção do trabalhador, seja em razão de dívida contraída, seja por meio do cerceamento do uso de qualquer meio de transporte por parte do trabalhador, ou por qualquer outro meio com o fim de retê-lo no local de trabalho; a vigilância ostensiva no local de trabalho por parte do empregador ou seu preposto, com o fim de retê-lo no local de trabalho; a posse de documentos ou objetos pessoais do trabalhador, por parte do empregador ou seu preposto, com o fim de retê-lo no local de trabalho.
### Fontes
A Lista de Transparência sobre Trabalho Escravo Contemporâneo no Brasil pode ser obtida através do seguinte link
[http://reporterbrasil.org.br/wp-content/uploads/2016/06/listadetransparencia4.pdf](http://reporterbrasil.org.br/wp-content/uploads/2016/06/listadetransparencia4.pdf)
### Objetivos do Projeto
...
### O porquê
[STF proíbe Ministério do Trabalho de divulgar lista suja do trabalho escravo](http://oglobo.globo.com/economia/negocios/stf-proibe-ministerio-do-trabalho-de-divulgar-lista-suja-do-trabalho-escravo-14944492)
[STF libera divulgação de lista suja do trabalho escravo]
(http://exame.abril.com.br/brasil/noticias/stf-libera-divulgacao-de-lista-de-empresas-autuadas-por-trabalho-escravo)
...não consigo compreender o judiciário
[http://www.bbc.com/portuguese/noticias/2014/11/141117_escravidao_brasil_mundo_pai](http://www.bbc.com/portuguese/noticias/2014/11/141117_escravidao_brasil_mundo_pai)
### [Roadmap](https://github.com/devmessias/brasillivre/labels/roadmap)
Se você deseja contribuir para o projeto eu coloquei em
[brasillivre/labels/roadmap](https://github.com/devmessias/brasillivre/labels/roadmap) todos os issues que considero mais importantes no momento, pull requests são sempre bem-vindos, assim como novas sugestões de features.
| devmessias/brasillivre | README.md | Markdown | gpl-3.0 | 2,273 |
'''WARCAT: Web ARChive (WARC) Archiving Tool
Tool and library for handling Web ARChive (WARC) files.
'''
from .version import *
| chfoo/warcat | warcat/__init__.py | Python | gpl-3.0 | 130 |
#ifndef __TARGET_CORE_USER_H
#define __TARGET_CORE_USER_H
/* This header will be used by application too */
#include <linux/types.h>
#include <linux/uio.h>
#define TCMU_VERSION "2.0"
/*
* Ring Design
* -----------
*
* The mmaped area is divided into three parts:
* 1) The mailbox (struct tcmu_mailbox, below)
* 2) The command ring
* 3) Everything beyond the command ring (data)
*
* The mailbox tells userspace the offset of the command ring from the
* start of the shared memory region, and how big the command ring is.
*
* The kernel passes SCSI commands to userspace by putting a struct
* tcmu_cmd_entry in the ring, updating mailbox->cmd_head, and poking
* userspace via uio's interrupt mechanism.
*
* tcmu_cmd_entry contains a header. If the header type is PAD,
* userspace should skip hdr->length bytes (mod cmdr_size) to find the
* next cmd_entry.
*
* Otherwise, the entry will contain offsets into the mmaped area that
* contain the cdb and data buffers -- the latter accessible via the
* iov array. iov addresses are also offsets into the shared area.
*
* When userspace is completed handling the command, set
* entry->rsp.scsi_status, fill in rsp.sense_buffer if appropriate,
* and also set mailbox->cmd_tail equal to the old cmd_tail plus
* hdr->length, mod cmdr_size. If cmd_tail doesn't equal cmd_head, it
* should process the next packet the same way, and so on.
*/
#define TCMU_MAILBOX_VERSION 2
#define ALIGN_SIZE 64 /* Should be enough for most CPUs */
#define TCMU_MAILBOX_FLAG_CAP_OOOC (1 << 0) /* Out-of-order completions */
struct tcmu_mailbox
{
__u16 version;
__u16 flags;
__u32 cmdr_off;
__u32 cmdr_size;
__u32 cmd_head;
/* Updated by user. On its own cacheline */
__u32 cmd_tail __attribute__((__aligned__(ALIGN_SIZE)));
} __packed;
enum tcmu_opcode
{
TCMU_OP_PAD = 0,
TCMU_OP_CMD,
};
/*
* Only a few opcodes, and length is 8-byte aligned, so use low bits for opcode.
*/
struct tcmu_cmd_entry_hdr
{
__u32 len_op;
__u16 cmd_id;
__u8 kflags;
#define TCMU_UFLAG_UNKNOWN_OP 0x1
__u8 uflags;
} __packed;
#define TCMU_OP_MASK 0x7
static inline enum tcmu_opcode tcmu_hdr_get_op(__u32 len_op)
{
return len_op & TCMU_OP_MASK;
}
static inline void tcmu_hdr_set_op(__u32 *len_op, enum tcmu_opcode op)
{
*len_op &= ~TCMU_OP_MASK;
*len_op |= (op & TCMU_OP_MASK);
}
static inline __u32 tcmu_hdr_get_len(__u32 len_op)
{
return len_op & ~TCMU_OP_MASK;
}
static inline void tcmu_hdr_set_len(__u32 *len_op, __u32 len)
{
*len_op &= TCMU_OP_MASK;
*len_op |= len;
}
/* Currently the same as SCSI_SENSE_BUFFERSIZE */
#define TCMU_SENSE_BUFFERSIZE 96
struct tcmu_cmd_entry
{
struct tcmu_cmd_entry_hdr hdr;
union
{
struct
{
uint32_t iov_cnt;
uint32_t iov_bidi_cnt;
uint32_t iov_dif_cnt;
uint64_t cdb_off;
uint64_t __pad1;
uint64_t __pad2;
struct iovec iov[0];
} req;
struct
{
uint8_t scsi_status;
uint8_t __pad1;
uint16_t __pad2;
uint32_t __pad3;
char sense_buffer[TCMU_SENSE_BUFFERSIZE];
} rsp;
};
} __packed;
#define TCMU_OP_ALIGN_SIZE sizeof(uint64_t)
enum tcmu_genl_cmd
{
TCMU_CMD_UNSPEC,
TCMU_CMD_ADDED_DEVICE,
TCMU_CMD_REMOVED_DEVICE,
__TCMU_CMD_MAX,
};
#define TCMU_CMD_MAX (__TCMU_CMD_MAX - 1)
enum tcmu_genl_attr
{
TCMU_ATTR_UNSPEC,
TCMU_ATTR_DEVICE,
TCMU_ATTR_MINOR,
__TCMU_ATTR_MAX,
};
#define TCMU_ATTR_MAX (__TCMU_ATTR_MAX - 1)
#endif
| williamfdevine/PrettyLinux | include/uapi/linux/target_core_user.h | C | gpl-3.0 | 3,382 |
/*
* Symphony - A modern community (forum/SNS/blog) platform written in Java.
* Copyright (C) 2012-2017, b3log.org & hacpai.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.b3log.symphony.processor;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.ioc.inject.Inject;
import org.b3log.latke.logging.Level;
import org.b3log.latke.logging.Logger;
import org.b3log.latke.model.Pagination;
import org.b3log.latke.service.LangPropsService;
import org.b3log.latke.servlet.HTTPRequestContext;
import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.After;
import org.b3log.latke.servlet.annotation.Before;
import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.Locales;
import org.b3log.latke.util.Stopwatchs;
import org.b3log.latke.util.Strings;
import org.b3log.symphony.model.Article;
import org.b3log.symphony.model.Common;
import org.b3log.symphony.model.UserExt;
import org.b3log.symphony.processor.advice.AnonymousViewCheck;
import org.b3log.symphony.processor.advice.PermissionGrant;
import org.b3log.symphony.processor.advice.stopwatch.StopwatchEndAdvice;
import org.b3log.symphony.processor.advice.stopwatch.StopwatchStartAdvice;
import org.b3log.symphony.service.*;
import org.b3log.symphony.util.Emotions;
import org.b3log.symphony.util.Markdowns;
import org.b3log.symphony.util.Symphonys;
import org.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
/**
* Index processor.
* <p>
* <ul>
* <li>Shows index (/), GET</li>
* <li>Shows recent articles (/recent), GET</li>
* <li>Shows hot articles (/hot), GET</li>
* <li>Shows perfect articles (/perfect), GET</li>
* <li>Shows about (/about), GET</li>
* <li>Shows b3log (/b3log), GET</li>
* <li>Shows SymHub (/symhub), GET</li>
* <li>Shows kill browser (/kill-browser), GET</li>
* </ul>
* </p>
*
* @author <a href="http://88250.b3log.org">Liang Ding</a>
* @author <a href="http://vanessa.b3log.org">Liyuan Li</a>
* @version 1.12.3.24, Dec 26, 2016
* @since 0.2.0
*/
@RequestProcessor
public class IndexProcessor {
/**
* Logger.
*/
private static final Logger LOGGER = Logger.getLogger(IndexProcessor.class.getName());
/**
* Article query service.
*/
@Inject
private ArticleQueryService articleQueryService;
/**
* User query service.
*/
@Inject
private UserQueryService userQueryService;
/**
* User management service.
*/
@Inject
private UserMgmtService userMgmtService;
/**
* Data model service.
*/
@Inject
private DataModelService dataModelService;
/**
* Language service.
*/
@Inject
private LangPropsService langPropsService;
/**
* Timeline management service.
*/
@Inject
private TimelineMgmtService timelineMgmtService;
/**
* Shows md guide.
*
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/guide/markdown", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showMDGuide(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("other/md-guide.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
InputStream inputStream = null;
try {
inputStream = IndexProcessor.class.getResourceAsStream("/md_guide.md");
final String md = IOUtils.toString(inputStream, "UTF-8");
String html = Emotions.convert(md);
html = Markdowns.toHTML(html);
dataModel.put("md", md);
dataModel.put("html", html);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Loads markdown guide failed", e);
} finally {
IOUtils.closeQuietly(inputStream);
}
dataModelService.fillHeaderAndFooter(request, response, dataModel);
}
/**
* Shows index.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = {"", "/"}, method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showIndex(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("index.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final List<JSONObject> recentArticles = articleQueryService.getIndexRecentArticles(avatarViewMode);
dataModel.put(Common.RECENT_ARTICLES, recentArticles);
JSONObject currentUser = userQueryService.getCurrentUser(request);
if (null == currentUser) {
userMgmtService.tryLogInWithCookie(request, context.getResponse());
}
currentUser = userQueryService.getCurrentUser(request);
if (null != currentUser) {
if (!UserExt.finshedGuide(currentUser)) {
response.sendRedirect(Latkes.getServePath() + "/guide");
return;
}
final String userId = currentUser.optString(Keys.OBJECT_ID);
final int pageSize = Symphonys.getInt("indexArticlesCnt");
final List<JSONObject> followingTagArticles = articleQueryService.getFollowingTagArticles(
avatarViewMode, userId, 1, pageSize);
dataModel.put(Common.FOLLOWING_TAG_ARTICLES, followingTagArticles);
final List<JSONObject> followingUserArticles = articleQueryService.getFollowingUserArticles(
avatarViewMode, userId, 1, pageSize);
dataModel.put(Common.FOLLOWING_USER_ARTICLES, followingUserArticles);
} else {
dataModel.put(Common.FOLLOWING_TAG_ARTICLES, Collections.emptyList());
dataModel.put(Common.FOLLOWING_USER_ARTICLES, Collections.emptyList());
}
final List<JSONObject> perfectArticles = articleQueryService.getIndexPerfectArticles(avatarViewMode);
dataModel.put(Common.PERFECT_ARTICLES, perfectArticles);
final List<JSONObject> timelines = timelineMgmtService.getTimelines();
dataModel.put(Common.TIMELINES, timelines);
dataModel.put(Common.SELECTED, Common.INDEX);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
dataModelService.fillIndexTags(dataModel);
}
/**
* Shows recent articles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = {"/recent", "/recent/hot", "/recent/good", "/recent/reply"}, method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showRecent(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response)
throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("recent.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
int pageSize = Symphonys.getInt("indexArticlesCnt");
final JSONObject user = userQueryService.getCurrentUser(request);
if (null != user) {
pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
if (!UserExt.finshedGuide(user)) {
response.sendRedirect(Latkes.getServePath() + "/guide");
return;
}
}
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
String sortModeStr = StringUtils.substringAfter(request.getRequestURI(), "/recent");
int sortMode;
switch (sortModeStr) {
case "":
sortMode = 0;
break;
case "/hot":
sortMode = 1;
break;
case "/good":
sortMode = 2;
break;
case "/reply":
sortMode = 3;
break;
default:
sortMode = 0;
}
final JSONObject result = articleQueryService.getRecentArticles(avatarViewMode, sortMode, pageNum, pageSize);
final List<JSONObject> allArticles = (List<JSONObject>) result.get(Article.ARTICLES);
dataModel.put(Common.SELECTED, Common.RECENT);
final List<JSONObject> stickArticles = new ArrayList<>();
final Iterator<JSONObject> iterator = allArticles.iterator();
while (iterator.hasNext()) {
final JSONObject article = iterator.next();
final boolean stick = article.optInt(Article.ARTICLE_T_STICK_REMAINS) > 0;
article.put(Article.ARTICLE_T_IS_STICK, stick);
if (stick) {
stickArticles.add(article);
iterator.remove();
}
}
dataModel.put(Common.STICK_ARTICLES, stickArticles);
dataModel.put(Common.LATEST_ARTICLES, allArticles);
final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION);
final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
dataModel.put(Common.CURRENT, StringUtils.substringAfter(request.getRequestURI(), "/recent"));
}
/**
* Shows hot articles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/hot", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showHotArticles(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("hot.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
int pageSize = Symphonys.getInt("indexArticlesCnt");
final JSONObject user = userQueryService.getCurrentUser(request);
if (null != user) {
pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
}
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final List<JSONObject> indexArticles = articleQueryService.getHotArticles(avatarViewMode, pageSize);
dataModel.put(Common.INDEX_ARTICLES, indexArticles);
dataModel.put(Common.SELECTED, Common.HOT);
Stopwatchs.start("Fills");
try {
dataModelService.fillHeaderAndFooter(request, response, dataModel);
if (!(Boolean) dataModel.get(Common.IS_MOBILE)) {
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
}
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
} finally {
Stopwatchs.end();
}
}
/**
* Shows SymHub page.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/symhub", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showSymHub(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("other/symhub.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
final List<JSONObject> syms = Symphonys.getSyms();
dataModel.put("syms", (Object) syms);
Stopwatchs.start("Fills");
try {
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
if (!(Boolean) dataModel.get(Common.IS_MOBILE)) {
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
}
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
} finally {
Stopwatchs.end();
}
}
/**
* Shows perfect articles.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/perfect", method = HTTPRequestMethod.GET)
@Before(adviceClass = {StopwatchStartAdvice.class, AnonymousViewCheck.class})
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showPerfectArticles(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("perfect.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
String pageNumStr = request.getParameter("p");
if (Strings.isEmptyOrNull(pageNumStr) || !Strings.isNumeric(pageNumStr)) {
pageNumStr = "1";
}
final int pageNum = Integer.valueOf(pageNumStr);
int pageSize = Symphonys.getInt("indexArticlesCnt");
final JSONObject user = userQueryService.getCurrentUser(request);
if (null != user) {
pageSize = user.optInt(UserExt.USER_LIST_PAGE_SIZE);
if (!UserExt.finshedGuide(user)) {
response.sendRedirect(Latkes.getServePath() + "/guide");
return;
}
}
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
final JSONObject result = articleQueryService.getPerfectArticles(avatarViewMode, pageNum, pageSize);
final List<JSONObject> perfectArticles = (List<JSONObject>) result.get(Article.ARTICLES);
dataModel.put(Common.PERFECT_ARTICLES, perfectArticles);
dataModel.put(Common.SELECTED, Common.PERFECT);
final JSONObject pagination = result.getJSONObject(Pagination.PAGINATION);
final int pageCount = pagination.optInt(Pagination.PAGINATION_PAGE_COUNT);
final List<Integer> pageNums = (List<Integer>) pagination.get(Pagination.PAGINATION_PAGE_NUMS);
if (!pageNums.isEmpty()) {
dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
}
dataModel.put(Pagination.PAGINATION_CURRENT_PAGE_NUM, pageNum);
dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
dataModelService.fillHeaderAndFooter(request, response, dataModel);
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
}
/**
* Shows about.
*
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/about", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void showAbout(final HttpServletResponse response) throws Exception {
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
response.setHeader("Location", "https://hacpai.com/article/1440573175609");
response.flushBuffer();
}
/**
* Shows b3log.
*
* @param context the specified context
* @param request the specified request
* @param response the specified response
* @throws Exception exception
*/
@RequestProcessing(value = "/b3log", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = {PermissionGrant.class, StopwatchEndAdvice.class})
public void showB3log(final HTTPRequestContext context,
final HttpServletRequest request, final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
context.setRenderer(renderer);
renderer.setTemplateName("other/b3log.ftl");
final Map<String, Object> dataModel = renderer.getDataModel();
dataModelService.fillHeaderAndFooter(request, response, dataModel);
final int avatarViewMode = (int) request.getAttribute(UserExt.USER_AVATAR_VIEW_MODE);
dataModelService.fillRandomArticles(avatarViewMode, dataModel);
dataModelService.fillSideHotArticles(avatarViewMode, dataModel);
dataModelService.fillSideTags(dataModel);
dataModelService.fillLatestCmts(dataModel);
}
/**
* Shows kill browser page with the specified context.
*
* @param context the specified context
* @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response
*/
@RequestProcessing(value = "/kill-browser", method = HTTPRequestMethod.GET)
@Before(adviceClass = StopwatchStartAdvice.class)
@After(adviceClass = StopwatchEndAdvice.class)
public void showKillBrowser(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) {
final AbstractFreeMarkerRenderer renderer = new SkinRenderer(request);
renderer.setTemplateName("other/kill-browser.ftl");
context.setRenderer(renderer);
final Map<String, Object> dataModel = renderer.getDataModel();
final Map<String, String> langs = langPropsService.getAll(Locales.getLocale());
dataModel.putAll(langs);
Keys.fillRuntime(dataModel);
dataModelService.fillMinified(dataModel);
}
}
| BrickCat/symphony | src/main/java/org/b3log/symphony/processor/IndexProcessor.java | Java | gpl-3.0 | 21,728 |
/*
Copyright 2011 MCForge
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.osedu.org/licenses/ECL-2.0
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.IO;
namespace MCForge
{
public class CmdMap : Command
{
public override string name { get { return "map"; } }
public override string shortcut { get { return ""; } }
public override string type { get { return "mod"; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public CmdMap() { }
public override void Use(Player p, string message)
{
if (message == "") message = p.level.name;
Level foundLevel;
if (message.IndexOf(' ') == -1)
{
foundLevel = Level.Find(message);
if (foundLevel == null)
{
if (p != null)
{
foundLevel = p.level;
}
}
else
{
Player.SendMessage(p, "MOTD: &b" + foundLevel.motd);
Player.SendMessage(p, "Finite mode: " + FoundCheck(foundLevel.finite));
Player.SendMessage(p, "Animal AI: " + FoundCheck(foundLevel.ai));
Player.SendMessage(p, "Edge water: " + FoundCheck(foundLevel.edgeWater));
Player.SendMessage(p, "Grass growing: " + FoundCheck(foundLevel.GrassGrow));
Player.SendMessage(p, "Physics speed: &b" + foundLevel.speedPhysics);
Player.SendMessage(p, "Physics overload: &b" + foundLevel.overload);
Player.SendMessage(p, "Survival death: " + FoundCheck(foundLevel.Death) + "(Fall: " + foundLevel.fall + ", Drown: " + foundLevel.drown + ")");
Player.SendMessage(p, "Killer blocks: " + FoundCheck(foundLevel.Killer));
Player.SendMessage(p, "Unload: " + FoundCheck(foundLevel.unload));
Player.SendMessage(p, "Auto physics: " + FoundCheck(foundLevel.rp));
Player.SendMessage(p, "Instant building: " + FoundCheck(foundLevel.Instant));
Player.SendMessage(p, "RP chat: " + FoundCheck(!foundLevel.worldChat));
return;
}
}
else
{
foundLevel = Level.Find(message.Split(' ')[0]);
if (foundLevel == null || message.Split(' ')[0].ToLower() == "ps" || message.Split(' ')[0].ToLower() == "rp") foundLevel = p.level;
else message = message.Substring(message.IndexOf(' ') + 1);
}
if (p != null)
if (p.group.Permission < LevelPermission.Operator) { Player.SendMessage(p, "Setting map options is reserved to OP+"); return; }
string foundStart;
if (message.IndexOf(' ') == -1) foundStart = message.ToLower();
else foundStart = message.Split(' ')[0].ToLower();
try
{
switch (foundStart)
{
case "theme": foundLevel.theme = message.Substring(message.IndexOf(' ') + 1); foundLevel.ChatLevel("Map theme: &b" + foundLevel.theme); break;
case "finite": foundLevel.finite = !foundLevel.finite; foundLevel.ChatLevel("Finite mode: " + FoundCheck(foundLevel.finite)); break;
case "ai": foundLevel.ai = !foundLevel.ai; foundLevel.ChatLevel("Animal AI: " + FoundCheck(foundLevel.ai)); break;
case "edge": foundLevel.edgeWater = !foundLevel.edgeWater; foundLevel.ChatLevel("Edge water: " + FoundCheck(foundLevel.edgeWater)); break;
case "grass": foundLevel.GrassGrow = !foundLevel.GrassGrow; foundLevel.ChatLevel("Growing grass: " + FoundCheck(foundLevel.GrassGrow)); break;
case "ps":
case "physicspeed":
if (int.Parse(message.Split(' ')[1]) < 10) { Player.SendMessage(p, "Cannot go below 10"); return; }
foundLevel.speedPhysics = int.Parse(message.Split(' ')[1]);
foundLevel.ChatLevel("Physics speed: &b" + foundLevel.speedPhysics);
break;
case "overload":
if (int.Parse(message.Split(' ')[1]) < 500) { Player.SendMessage(p, "Cannot go below 500 (default is 1500)"); return; }
if (p.group.Permission < LevelPermission.Admin && int.Parse(message.Split(' ')[1]) > 2500) { Player.SendMessage(p, "Only SuperOPs may set higher than 2500"); return; }
foundLevel.overload = int.Parse(message.Split(' ')[1]);
foundLevel.ChatLevel("Physics overload: &b" + foundLevel.overload);
break;
case "motd":
if (message.Split(' ').Length == 1) foundLevel.motd = "ignore";
else foundLevel.motd = message.Substring(message.IndexOf(' ') + 1);
foundLevel.ChatLevel("Map MOTD: &b" + foundLevel.motd);
break;
case "death": foundLevel.Death = !foundLevel.Death; foundLevel.ChatLevel("Survival death: " + FoundCheck(foundLevel.Death)); break;
case "killer": foundLevel.Killer = !foundLevel.Killer; foundLevel.ChatLevel("Killer blocks: " + FoundCheck(foundLevel.Killer)); break;
case "fall": foundLevel.fall = int.Parse(message.Split(' ')[1]); foundLevel.ChatLevel("Fall distance: &b" + foundLevel.fall); break;
case "drown": foundLevel.drown = int.Parse(message.Split(' ')[1]) * 10; foundLevel.ChatLevel("Drown time: &b" + (foundLevel.drown / 10)); break;
case "unload": foundLevel.unload = !foundLevel.unload; foundLevel.ChatLevel("Auto unload: " + FoundCheck(foundLevel.unload)); break;
case "rp":
case "restartphysics": foundLevel.rp = !foundLevel.rp; foundLevel.ChatLevel("Auto physics: " + FoundCheck(foundLevel.rp)); break;
case "instant":
if (p.group.Permission < LevelPermission.Admin) { Player.SendMessage(p, "This is reserved for Super+"); return; }
foundLevel.Instant = !foundLevel.Instant; foundLevel.ChatLevel("Instant building: " + FoundCheck(foundLevel.Instant)); break;
case "chat":
foundLevel.worldChat = !foundLevel.worldChat; foundLevel.ChatLevel("RP chat: " + FoundCheck(!foundLevel.worldChat)); break;
default:
Player.SendMessage(p, "Could not find option entered.");
return;
}
foundLevel.changed = true;
if (p.level != foundLevel) Player.SendMessage(p, "/map finished!");
}
catch { Player.SendMessage(p, "INVALID INPUT"); }
}
public string FoundCheck(bool check)
{
if (check) return "&aON";
else return "&cOFF";
}
public override void Help(Player p)
{
Player.SendMessage(p, "/map [level] [toggle] - Sets [toggle] on [map]");
Player.SendMessage(p, "Possible toggles: theme, finite, ai, edge, ps, overload, motd, death, fall, drown, unload, rp, instant, killer, chat");
Player.SendMessage(p, "Edge will cause edge water to flow.");
Player.SendMessage(p, "Grass will make grass not grow without physics");
Player.SendMessage(p, "Finite will cause all liquids to be finite.");
Player.SendMessage(p, "AI will make animals hunt or flee.");
Player.SendMessage(p, "PS will set the map's physics speed.");
Player.SendMessage(p, "Overload will change how easy/hard it is to kill physics.");
Player.SendMessage(p, "MOTD will set a custom motd for the map. (leave blank to reset)");
Player.SendMessage(p, "Death will allow survival-style dying (falling, drowning)");
Player.SendMessage(p, "Fall/drown set the distance/time before dying from each.");
Player.SendMessage(p, "Killer turns killer blocks on and off.");
Player.SendMessage(p, "Unload sets whether the map unloads when no one's there.");
Player.SendMessage(p, "RP sets whether the physics auto-start for the map");
Player.SendMessage(p, "Instant mode works by not updating everyone's screens");
Player.SendMessage(p, "Chat sets the map to recieve no messages from other maps");
}
}
} | colinodell/mcforge | Commands/CmdMap.cs | C# | gpl-3.0 | 9,301 |
require 'test/unit'
class FizzbuzzTest < Test::Unit::TestCase
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
# Do nothing
end
# Called after every test method runs. Can be used to tear
# down fixture information.
def teardown
# Do nothing
end
# Fake test
def test_fail
expected = 1
actual =1
assert_same expected, actual
# fail('Not implemented')
end
def test_fizzbuzz
require './fizzbuzz.d/rb-fizzbuzz'
res=[]
1.upto(100).each {|e|
next if fizbuz e, res
next if fiz e, res
next if buz e, res
res << e
}
assert_same 100, res.length
end
end | rogeraaut/rogeraaut.github.io | lang.ruby.d/tests/fizzbuzz_test.rb | Ruby | gpl-3.0 | 688 |
/*
Copyright 2013 Statoil ASA.
This file is part of the Open Porous Media project (OPM).
OPM is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>.
*/
#define BOOST_TEST_MODULE ParserIntegrationTests
#include <boost/test/unit_test.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/filesystem.hpp>
#include <ostream>
#include <fstream>
#include <opm/parser/eclipse/Deck/Deck.hpp>
#include <opm/parser/eclipse/Parser/Parser.hpp>
#include <opm/parser/eclipse/Parser/ParserRecord.hpp>
#include <opm/parser/eclipse/Parser/ParserEnums.hpp>
using namespace Opm;
using namespace boost::filesystem;
static void
createDeckWithInclude(path& datafile, std::string addEndKeyword)
{
path tmpdir = temp_directory_path();
path root = tmpdir / unique_path("%%%%-%%%%");
path absoluteInclude = root / "absolute.include";
path includePath1 = root / "include";
path includePath2 = root / "include2";
path pathIncludeFile = "path.file";
create_directories(root);
create_directories(includePath1);
create_directories(includePath2);
{
datafile = root / "TEST.DATA";
std::ofstream of(datafile.string().c_str());
of << "PATHS" << std::endl;
of << "PATH1 '" << includePath1.string() << "' /" << std::endl;
of << "PATH2 '" << includePath2.string() << "' /" << std::endl;
of << "/" << std::endl;
of << "INCLUDE" << std::endl;
of << " \'relative.include\' /" << std::endl;
of << std::endl;
of << "INCLUDE" << std::endl;
of << " \'" << absoluteInclude.string() << "\' /" << std::endl;
of << std::endl;
of << "INCLUDE" << std::endl;
of << " \'include/nested.include\' /" << std::endl;
of << std::endl;
of << std::endl;
of << "INCLUDE" << std::endl;
of << " \'$PATH1/" << pathIncludeFile.string() << "\' /" << std::endl;
of << std::endl;
of << "INCLUDE" << std::endl;
of << " \'$PATH2/" << pathIncludeFile.string() << "\' /" << std::endl;
of.close();
}
{
path relativeInclude = root / "relative.include";
std::ofstream of(relativeInclude.string().c_str());
of << "START" << std::endl;
of << " 10 'FEB' 2012 /" << std::endl;
of.close();
}
{
std::ofstream of(absoluteInclude.string().c_str());
if (addEndKeyword.length() > 0) {
of << addEndKeyword << std::endl;
}
of << "DIMENS" << std::endl;
of << " 10 20 30 /" << std::endl;
of.close();
}
{
path nestedInclude = includePath1 / "nested.include";
path gridInclude = includePath1 / "grid.include";
std::ofstream of(nestedInclude.string().c_str());
of << "INCLUDE" << std::endl;
of << " \'$PATH1/grid.include\' /" << std::endl;
of.close();
std::ofstream of2(gridInclude.string().c_str());
of2 << "GRIDUNIT" << std::endl;
of2 << "/" << std::endl;
of2.close();
}
{
path fullPathToPathIncludeFile1 = includePath1 / pathIncludeFile;
std::ofstream of1(fullPathToPathIncludeFile1.string().c_str());
of1 << "TITLE" << std::endl;
of1 << "This is the title /" << std::endl;
of1.close();
path fullPathToPathIncludeFile2 = includePath2 / pathIncludeFile;
std::ofstream of2(fullPathToPathIncludeFile2.string().c_str());
of2 << "BOX" << std::endl;
of2 << " 1 2 3 4 5 6 /" << std::endl;
of2.close();
}
std::cout << datafile << std::endl;
}
BOOST_AUTO_TEST_CASE(parse_fileWithWWCTKeyword_deckReturned) {
path datafile;
Parser parser;
createDeckWithInclude (datafile, "");
auto deck = parser.parseFile(datafile.string());
BOOST_CHECK( deck.hasKeyword("START"));
BOOST_CHECK( deck.hasKeyword("DIMENS"));
BOOST_CHECK( deck.hasKeyword("GRIDUNIT"));
}
BOOST_AUTO_TEST_CASE(parse_fileWithENDINCKeyword_deckReturned) {
path datafile;
Parser parser;
createDeckWithInclude (datafile, "ENDINC");
auto deck = parser.parseFile(datafile.string());
BOOST_CHECK( deck.hasKeyword("START"));
BOOST_CHECK( !deck.hasKeyword("DIMENS"));
BOOST_CHECK( deck.hasKeyword("GRIDUNIT"));
}
BOOST_AUTO_TEST_CASE(parse_fileWithENDKeyword_deckReturned) {
path datafile;
Parser parser;
createDeckWithInclude (datafile, "END");
auto deck = parser.parseFile(datafile.string());
BOOST_CHECK( deck.hasKeyword("START"));
BOOST_CHECK( !deck.hasKeyword("DIMENS"));
BOOST_CHECK( !deck.hasKeyword("GRIDUNIT"));
}
BOOST_AUTO_TEST_CASE(parse_fileWithPathsKeyword_IncludeExtendsPath) {
path datafile;
Parser parser;
createDeckWithInclude (datafile, "");
auto deck = parser.parseFile(datafile.string());
BOOST_CHECK( deck.hasKeyword("TITLE"));
BOOST_CHECK( deck.hasKeyword("BOX"));
}
| andlaus/opm-common | tests/parser/integration/IncludeTest.cpp | C++ | gpl-3.0 | 5,738 |
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Newegg.Oversea.Silverlight.ControlPanel.Core.Base;
using ECCentral.BizEntity.Enum;
using ECCentral.BizEntity.MKT;
using Newegg.Oversea.Silverlight.Utilities.Validation;
using ECCentral.BizEntity;
namespace ECCentral.Portal.UI.MKT.Models
{
public class AmbassadorNewsVM : ModelBase
{
public string CompanyCode { get; set; }
public int? SysNo { get; set; }
private int? _ReferenceSysNo;
public int? ReferenceSysNo
{
get { return _ReferenceSysNo; }
set { base.SetValue("ReferenceSysNo", ref _ReferenceSysNo, value); }
}
private string _Title;
[Validate(ValidateType.Required)]
[Validate(ValidateType.MaxLength,100)]
public string Title
{
get { return _Title; }
set { base.SetValue("Title", ref _Title, value); }
}
private string _Content;
[Validate(ValidateType.Required)]
public string Content
{
get { return _Content; }
set { base.SetValue("Content", ref _Content, value); }
}
private AmbassadorNewsStatus? status;
[Validate(ValidateType.Required)]
public AmbassadorNewsStatus? Status
{
get { return status; }
set { base.SetValue("Status", ref status, value); }
}
}
}
| ZeroOne71/ql | 02_ECCentral/02_Portal/UI/ECCentral.Portal.UI.MKT/NeweggCN/Models/AmbassadorNewsVM.cs | C# | gpl-3.0 | 1,650 |
using ServiceStack.OrmLite;
using System;
using System.Configuration;
using System.Data;
namespace Bm2s.Data.Utils
{
/// <summary>
/// Data access point
/// </summary>
public class Datas
{
/// <summary>
/// Database provider
/// </summary>
private IOrmLiteDialectProvider _dbProvider;
/// <summary>
/// Gets the database provider
/// </summary>
public IOrmLiteDialectProvider DbProvider
{
get
{
if (this._dbProvider == null)
{
switch (ConfigurationManager.AppSettings["DbProvider"].ToLower())
{
case "oracle":
this._dbProvider = OracleDialect.Provider;
break;
case "mysql" :
this._dbProvider = MySqlDialect.Provider;
break;
case "postgresql":
this._dbProvider = PostgreSqlDialect.Provider;
break;
case "mssqlserver":
this._dbProvider = SqlServerDialect.Provider;
break;
default:
this._dbProvider = null;
break;
}
}
return this._dbProvider;
}
}
/// <summary>
/// Database connection
/// </summary>
private IDbConnection _dbConnection;
/// <summary>
/// Gets the database connection
/// </summary>
public IDbConnection DbConnection
{
get
{
if (this._dbConnection == null)
{
this._dbConnection = this.DbConnectionFactory.OpenDbConnection();
}
return this._dbConnection;
}
}
/// <summary>
/// Database connection factory
/// </summary>
private IDbConnectionFactory _dbConnectionFactory;
/// <summary>
/// Gets the database connection factory
/// </summary>
public IDbConnectionFactory DbConnectionFactory
{
get
{
if (this._dbConnectionFactory == null)
{
this._dbConnectionFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["bm2s"].ConnectionString, this.DbProvider);
}
return this._dbConnectionFactory;
}
}
/// <summary>
/// Constructor for the singleton
/// </summary>
protected Datas()
{
this.CheckDatabaseSchema();
}
/// <summary>
/// Creation of the schemas
/// </summary>
public virtual void CheckDatabaseSchema()
{
}
/// <summary>
/// Create datas for the first use
/// </summary>
public virtual void CheckFirstUseDatas()
{
}
}
}
| Csluikidikilest/Bm2sServer | Bm2s.Data.Utils/Datas.cs | C# | gpl-3.0 | 2,584 |
/**
* Created by caimiao on 15-6-14.
*/
define(function(require, exports, module) {
exports.hello= function (echo) {
alert(echo);
};
}) | caimmy/prehistory | static/js/js_modules/archjs_tools.js | JavaScript | gpl-3.0 | 154 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_sciclubpadova
*
* @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
/**
* SciClubPadova Model
*
* @since 0.0.1
*/
class SciClubPadovaModelSciClubPadova extends JModelItem
{
/**
* @var object item
*/
protected $item;
/**
* Method to auto-populate the model state.
*
* This method should only be called once per instantiation and is designed
* to be called on the first call to the getState() method unless the model
* configuration flag to ignore the request is set.
*
* Note. Calling getState in this method will result in recursion.
*
* @return void
* @since 2.5
*/
protected function populateState()
{
// Get the message id
$jinput = JFactory::getApplication()->input;
$id = $jinput->get('id', 1, 'INT');
$this->setState('message.id', $id);
// Load the parameters.
$this->setState('params', JFactory::getApplication()->getParams());
parent::populateState();
}
/**
* Method to get a table object, load it if necessary.
*
* @param string $type The table name. Optional.
* @param string $prefix The class prefix. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return JTable A JTable object
*
* @since 1.6
*/
public function getTable($type = 'SciClubPadova', $prefix = 'SciClubPadovaTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
/**
* Get the message
* @return object The message to be displayed to the user
*/
public function getItem()
{
if (!isset($this->item))
{
$id = $this->getState('message.id');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('h.greeting, h.params, c.title as category')
->from('#__sciclubpadova as h')
->leftJoin('#__categories as c ON h.catid=c.id')
->where('h.id=' . (int)$id);
$db->setQuery((string)$query);
if ($this->item = $db->loadObject())
{
// Load the JSON string
$params = new JRegistry;
$params->loadString($this->item->params, 'JSON');
$this->item->params = $params;
// Merge global params with item params
$params = clone $this->getState('params');
$params->merge($this->item->params);
$this->item->params = $params;
}
}
return $this->item;
}
}
| lancillot72/JSCE | com_sciclubpadova/site/models/sciclubpadova.php | PHP | gpl-3.0 | 2,647 |
body {
word-wrap: break-word;
word-break: break-all;
padding: 2px 5px;
background-color: #FFFFFF;
color: #000000;
max-width: 1024px;
margin: 0px auto;
box-shadow: 0 0 15px #ccc;
tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; -webkit-tab-size: 4;
}
p, div {
overflow: hidden;
}
p {
margin: 0px;
padding: 2px 1px 2px 1px;
}
.tp {
margin: 0px;
background-color: #E6F3FF;
}
a {
text-decoration: none;
color: #08C;
}
form {
margin: 0px;
padding: 0px;
}
img, input, textarea {
max-width: 100%;
vertical-align: middle;
}
hr {
height: 1px;
border: 1px solid #BED8EA;
border-left: none;
border-right: none;
}
textarea {
width: 270px;
height: 55px;
overflow-y: visible;
}
pre, textarea {
white-space: pre-wrap;
word-wrap: break-word;
word-break: break-all;
}
ol, ul {
margin: 0px;
}
.success {
color: green;
}
.failure {
color: red;
}
.notice {
color: red;
}
img {
max-width: 100%;
}
.info-box {
text-align: center;
border: solid red 1px;
}
.video {
width: 600px;
height: 400px;
border: none;
max-width: 100%;
}
.audio {
width: 600px;
border: none;
max-width: 100%;
}
#content_title {
width: 270px;
max-width: 100%;
}
/* 针对电脑屏幕 */
@media screen and (min-width: 800px) {
img {
max-width: 800px;
max-height: 600px;
}
}
/* 小说阅读器 */
.topic-ul {
list-style-type: none;
padding: 0;
}
.topic-ul > li {
padding: 5px 10px 2px 10px;
border-bottom: 1px solid #EEE;
display: flex;
align-items: center;
justify-content: space-between;
}
.topic-ul > li .topic-meta {
margin: 0px;
}
.topic-ul > li .topic-reply-count {
width: 5%;
display: flex;
font-weight: 300;
font-size: 30px;
color: gray;
}
.topic-ul > li .topic-reply-count a {
color: gray;
}
.topic-ul > li .topic-forum-name {
width: 15%;
display: flex;
}
.topic-ul > li .topic-forum-name a {
color: gray;
}
.topic-ul > li .topic-anchor {
width: 20%;
display: flex;
flex-direction: column;
align-items: center;
word-break: break-all;
}
.topic-ul > li .topic-anchor > a {
color: gray;
}
.topic-ul > li .topic-title {
width: 60%;
display: flex;
flex-direction: column;
justify-content: center;
}
.topic-ul > li .topic-title > a {
font-size: 18px;
display: block;
}
.page-jumper {
overflow: hidden;
display: inline-flex;
flex-wrap: wrap;
align-content: center;
padding-left: 2px;
margin: 10px 0 0 20px;
}
.page-jumper > li {
display: inline-block;
}
.page-jumper > li > input {
height: 22px;
width: 38px;
position: relative;
margin-left: -1px;
display: block;
padding: 5px 10px;
border: 1px solid #ddd;
border-radius: 5px;
color: #337ab7;
}
.pagination {
overflow: hidden;
display: inline-flex;
flex-wrap: wrap;
align-content: center;
padding-left: 2px;
margin: 10px 0 0 20px;
}
.pagination > li {
display: inline-block;
}
.pagination > li:first-child > a {
border-radius: 5px 0 0 5px;
}
.pagination > li:last-child > a {
border-radius: 0 5px 5px 0;
}
.pagination > li > a {
position: relative;
margin-left: -1px;
display: block;
padding: 5px 10px;
border: 1px solid #ddd;
color: #337ab7;
}
.pagination > .disabled > a {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.pagination > .disabled > a:focus {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.pagination > .disabled > a:hover {
color: #777;
cursor: not-allowed;
background-color: #fff;
}
.pagination > .active > a {
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
.pagination > .active > a:focus {
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
.pagination > .active > a:hover {
color: #fff;
cursor: default;
background-color: #337ab7;
border-color: #337ab7;
}
@media screen and (max-width: 600px) {
.topic-ul > li .topic-reply-count {
display: block;
}
.topic-ul > li .topic-reply-count .number {
display: block;
font-size: 14px;
}
.topic-ul > li .topic-reply-count .spliter {
display: none;
}
.topic-ul > li .topic-reply-count .forum {
display: block;
font-size: 14px;
}
.topic-ul > li .topic-anchor > a {
font-size: 14px;
}
.topic-ul > li .topic-title > a {
font-size: 16px;
}
.topic-ul > li .topic-reply-count {
display: none;
}
.topic-ul > li .topic-forum-name {
display: none;
}
.topic-ul > li .topic-title {
width: 80%;
}
}
/* 关注与屏蔽列表样式 */
.relationship-wrapper .empty {
width: 100%;
text-align: center;
color: #999fa5;
font-size: 14px;
}
.relationship-wrapper .user-item {
height: 60px;
color: #333333;
display: block;
border-bottom: 1px solid #f5f5f5;
}
.relationship-wrapper .user-item a {
text-decoration: none;
}
.relationship-wrapper .user-item a:nth-child(1) {
display: inline-block;
width: calc(100% - 60px);
}
.relationship-wrapper .user-item .avatar {
float: left;
height: 50px;
width: 50px;
margin-left: 20px;
margin-top: 5px;
display: inline-block;
border-radius: 50px;
}
.relationship-wrapper .user-item .info {
margin-left: 15px;
margin-top: 10px;
display: inline-block;
width: calc(100% - 100px);
}
.relationship-wrapper .user-item .info .name {
font-size: 18px;
}
.relationship-wrapper .user-item .info .signature {
color: #999fa5;
font-size: 12px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.relationship-wrapper .user-item .remove {
float: right;
height: 100%;
width: 60px;
display: inline-block;
padding-top: 20px;
color: #ff0000;
text-align: center;
}
/*回复列表中的区块引用*/
.reply-box blockquote {
background: #f9f9f9;
border-left: 10px solid #ccc;
margin: 1.5em 10px;
padding: 0.5em 10px;
max-height: 500px;
overflow: hidden;
text-overflow: ellipsis;
}
.reply-box blockquote:before {
color: #ccc;
font-size: 4em;
line-height: 0.1em;
margin-right: 0.25em;
vertical-align: -0.4em;
}
#searchType-label {
display: inline-block;
}
.hu60_face, #face img {
width: 32px;
max-width: 32px;
}
/*代码高亮*/
.hu60_code code, .markdown-body pre code {
white-space: pre-wrap !important;
word-wrap: break-word !important;
word-break: break-all !important;
}
.hu60_code code {
background-color: #f7f7f7;
}
| boy404/hu60wap6 | src/tpl/classic/css/default.css | CSS | gpl-3.0 | 6,783 |
<?php
/** PHPExcel root directory */
if (!defined('PHPEXCEL_ROOT')) {
/**
* @ignore
*/
define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
}
/**
* PHPExcel_Reader_SYLK
*
* Copyright (c) 2006 - 2015 PHPExcel
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category PHPExcel
* @package PHPExcel_Reader
* @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
* @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
* @version ##VERSION##, ##DATE##
*/
class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader
{
/**
* Input encoding
*
* @var string
*/
private $inputEncoding = 'ANSI';
/**
* Sheet index to read
*
* @var int
*/
private $sheetIndex = 0;
/**
* Formats
*
* @var array
*/
private $formats = array();
/**
* Format Count
*
* @var int
*/
private $format = 0;
/**
* Create a new PHPExcel_Reader_SYLK
*/
public function __construct()
{
$this->readFilter = new PHPExcel_Reader_DefaultReadFilter();
}
/**
* Validate that the current file is a SYLK file
*
* @return boolean
*/
protected function isValidFormat()
{
// Read sample data (first 2 KB will do)
$data = fread($this->fileHandle, 2048);
// Count delimiters in file
$delimiterCount = substr_count($data, ';');
if ($delimiterCount < 1) {
return false;
}
// Analyze first line looking for ID; signature
$lines = explode("\n", $data);
if (substr($lines[0], 0, 4) != 'ID;P') {
return false;
}
return true;
}
/**
* Set input encoding
*
* @param string $pValue Input encoding
*/
public function setInputEncoding($pValue = 'ANSI')
{
$this->inputEncoding = $pValue;
return $this;
}
/**
* Get input encoding
*
* @return string
*/
public function getInputEncoding()
{
return $this->inputEncoding;
}
/**
* Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns)
*
* @param string $pFilename
* @throws PHPExcel_Reader_Exception
*/
public function listWorksheetInfo($pFilename)
{
// Open file
$this->openFile($pFilename);
if (!$this->isValidFormat()) {
fclose($this->fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->fileHandle;
rewind($fileHandle);
$worksheetInfo = array();
$worksheetInfo[0]['worksheetName'] = 'Worksheet';
$worksheetInfo[0]['lastColumnLetter'] = 'A';
$worksheetInfo[0]['lastColumnIndex'] = 0;
$worksheetInfo[0]['totalRows'] = 0;
$worksheetInfo[0]['totalColumns'] = 0;
// Loop through file
$rowData = array();
// loop through one row (line) at a time in the file
$rowIndex = 0;
while (($rowData = fgets($fileHandle)) !== false) {
$columnIndex = 0;
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
if ($dataType == 'C') {
// Read cell value data
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$columnIndex = substr($rowDatum, 1) - 1;
break;
case 'R':
case 'Y':
$rowIndex = substr($rowDatum, 1);
break;
}
$worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex);
$worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex);
}
}
}
$worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']);
$worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1;
// Close file
fclose($fileHandle);
return $worksheetInfo;
}
/**
* Loads PHPExcel from file
*
* @param string $pFilename
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function load($pFilename)
{
// Create new PHPExcel
$objPHPExcel = new PHPExcel();
// Load into this instance
return $this->loadIntoExisting($pFilename, $objPHPExcel);
}
/**
* Loads PHPExcel from file into PHPExcel instance
*
* @param string $pFilename
* @param PHPExcel $objPHPExcel
* @return PHPExcel
* @throws PHPExcel_Reader_Exception
*/
public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
{
// Open file
$this->openFile($pFilename);
if (!$this->isValidFormat()) {
fclose($this->fileHandle);
throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file.");
}
$fileHandle = $this->fileHandle;
rewind($fileHandle);
// Create new PHPExcel
while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) {
$objPHPExcel->createSheet();
}
$objPHPExcel->setActiveSheetIndex($this->sheetIndex);
$fromFormats = array('\-', '\ ');
$toFormats = array('-', ' ');
// Loop through file
$rowData = array();
$column = $row = '';
// loop through one row (line) at a time in the file
while (($rowData = fgets($fileHandle)) !== false) {
// convert SYLK encoded $rowData to UTF-8
$rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData);
// explode each row at semicolons while taking into account that literal semicolon (;)
// is escaped like this (;;)
$rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData)))));
$dataType = array_shift($rowData);
// Read shared styles
if ($dataType == 'P') {
$formatArray = array();
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'P':
$formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1));
break;
case 'E':
case 'F':
$formatArray['font']['name'] = substr($rowDatum, 1);
break;
case 'L':
$formatArray['font']['size'] = substr($rowDatum, 1);
break;
case 'S':
$styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) {
case 'I':
$formatArray['font']['italic'] = true;
break;
case 'D':
$formatArray['font']['bold'] = true;
break;
case 'T':
$formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B':
$formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L':
$formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R':
$formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
$this->formats['P'.$this->format++] = $formatArray;
// Read cell value data
} elseif ($dataType == 'C') {
$hasCalculatedValue = false;
$cellData = $cellDataFormula = '';
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'K':
$cellData = substr($rowDatum, 1);
break;
case 'E':
$cellDataFormula = '='.substr($rowDatum, 1);
// Convert R1C1 style references to A1 style references (but only when not quoted)
$temp = explode('"', $cellDataFormula);
$key = false;
foreach ($temp as &$value) {
// Only count/replace in alternate array entries
if ($key = !$key) {
preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER+PREG_OFFSET_CAPTURE);
// Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way
// through the formula from left to right. Reversing means that we work right to left.through
// the formula
$cellReferences = array_reverse($cellReferences);
// Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent,
// then modify the formula to use that new reference
foreach ($cellReferences as $cellReference) {
$rowReference = $cellReference[2][0];
// Empty R reference is the current row
if ($rowReference == '') {
$rowReference = $row;
}
// Bracketed R references are relative to the current row
if ($rowReference{0} == '[') {
$rowReference = $row + trim($rowReference, '[]');
}
$columnReference = $cellReference[4][0];
// Empty C reference is the current column
if ($columnReference == '') {
$columnReference = $column;
}
// Bracketed C references are relative to the current column
if ($columnReference{0} == '[') {
$columnReference = $column + trim($columnReference, '[]');
}
$A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference;
$value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0]));
}
}
}
unset($value);
// Then rebuild the formula string
$cellDataFormula = implode('"', $temp);
$hasCalculatedValue = true;
break;
}
}
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$cellData = PHPExcel_Calculation::unwrapResult($cellData);
// Set cell value
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData);
if ($hasCalculatedValue) {
$cellData = PHPExcel_Calculation::unwrapResult($cellData);
$objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData);
}
// Read cell formatting
} elseif ($dataType == 'F') {
$formatStyle = $columnWidth = $styleSettings = '';
$styleData = array();
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
case 'P':
$formatStyle = $rowDatum;
break;
case 'W':
list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1));
break;
case 'S':
$styleSettings = substr($rowDatum, 1);
for ($i=0; $i<strlen($styleSettings); ++$i) {
switch ($styleSettings{$i}) {
case 'I':
$styleData['font']['italic'] = true;
break;
case 'D':
$styleData['font']['bold'] = true;
break;
case 'T':
$styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'B':
$styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'L':
$styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
case 'R':
$styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN;
break;
}
}
break;
}
}
if (($formatStyle > '') && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
if (isset($this->formats[$formatStyle])) {
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->formats[$formatStyle]);
}
}
if ((!empty($styleData)) && ($column > '') && ($row > '')) {
$columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1);
$objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData);
}
if ($columnWidth > '') {
if ($startCol == $endCol) {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
} else {
$startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1);
$endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1);
$objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth);
do {
$objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth);
} while ($startCol != $endCol);
}
}
} else {
foreach ($rowData as $rowDatum) {
switch ($rowDatum{0}) {
case 'C':
case 'X':
$column = substr($rowDatum, 1);
break;
case 'R':
case 'Y':
$row = substr($rowDatum, 1);
break;
}
}
}
}
// Close file
fclose($fileHandle);
// Return
return $objPHPExcel;
}
/**
* Get sheet index
*
* @return int
*/
public function getSheetIndex()
{
return $this->sheetIndex;
}
/**
* Set sheet index
*
* @param int $pValue Sheet index
* @return PHPExcel_Reader_SYLK
*/
public function setSheetIndex($pValue = 0)
{
$this->sheetIndex = $pValue;
return $this;
}
}
| Aiwings/FNMNS_Formations | assets/PHPExcel/Classes/PHPExcel/Reader/SYLK.php | PHP | gpl-3.0 | 12,367 |
import math
from PyQt5.QtCore import Qt, pyqtSlot
from PyQt5.QtGui import QCloseEvent
from PyQt5.QtWidgets import QDialog, QInputDialog
from urh import settings
from urh.models.FuzzingTableModel import FuzzingTableModel
from urh.signalprocessing.ProtocoLabel import ProtocolLabel
from urh.signalprocessing.ProtocolAnalyzerContainer import ProtocolAnalyzerContainer
from urh.ui.ui_fuzzing import Ui_FuzzingDialog
class FuzzingDialog(QDialog):
def __init__(self, protocol: ProtocolAnalyzerContainer, label_index: int, msg_index: int, proto_view: int,
parent=None):
super().__init__(parent)
self.ui = Ui_FuzzingDialog()
self.ui.setupUi(self)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setWindowFlags(Qt.Window)
self.protocol = protocol
msg_index = msg_index if msg_index != -1 else 0
self.ui.spinBoxFuzzMessage.setValue(msg_index + 1)
self.ui.spinBoxFuzzMessage.setMinimum(1)
self.ui.spinBoxFuzzMessage.setMaximum(self.protocol.num_messages)
self.ui.comboBoxFuzzingLabel.addItems([l.name for l in self.message.message_type])
self.ui.comboBoxFuzzingLabel.setCurrentIndex(label_index)
self.proto_view = proto_view
self.fuzz_table_model = FuzzingTableModel(self.current_label, proto_view)
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.ui.tblFuzzingValues.setModel(self.fuzz_table_model)
self.fuzz_table_model.update()
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingStart.setMaximum(len(self.message_data))
self.ui.spinBoxFuzzingEnd.setMaximum(len(self.message_data))
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.create_connects()
self.restoreGeometry(settings.read("{}/geometry".format(self.__class__.__name__), type=bytes))
@property
def message(self):
return self.protocol.messages[int(self.ui.spinBoxFuzzMessage.value() - 1)]
@property
def current_label_index(self):
return self.ui.comboBoxFuzzingLabel.currentIndex()
@property
def current_label(self) -> ProtocolLabel:
if len(self.message.message_type) == 0:
return None
cur_label = self.message.message_type[self.current_label_index].get_copy()
self.message.message_type[self.current_label_index] = cur_label
cur_label.fuzz_values = [fv for fv in cur_label.fuzz_values if fv] # Remove empty strings
if len(cur_label.fuzz_values) == 0:
cur_label.fuzz_values.append(self.message.plain_bits_str[cur_label.start:cur_label.end])
return cur_label
@property
def current_label_start(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[0]
else:
return -1
@property
def current_label_end(self):
if self.current_label and self.message:
return self.message.get_label_range(self.current_label, self.proto_view, False)[1]
else:
return -1
@property
def message_data(self):
if self.proto_view == 0:
return self.message.plain_bits_str
elif self.proto_view == 1:
return self.message.plain_hex_str
elif self.proto_view == 2:
return self.message.plain_ascii_str
else:
return None
def create_connects(self):
self.ui.spinBoxFuzzingStart.valueChanged.connect(self.on_fuzzing_start_changed)
self.ui.spinBoxFuzzingEnd.valueChanged.connect(self.on_fuzzing_end_changed)
self.ui.comboBoxFuzzingLabel.currentIndexChanged.connect(self.on_combo_box_fuzzing_label_current_index_changed)
self.ui.btnRepeatValues.clicked.connect(self.on_btn_repeat_values_clicked)
self.ui.btnAddRow.clicked.connect(self.on_btn_add_row_clicked)
self.ui.btnDelRow.clicked.connect(self.on_btn_del_row_clicked)
self.ui.tblFuzzingValues.deletion_wanted.connect(self.delete_lines)
self.ui.chkBRemoveDuplicates.stateChanged.connect(self.on_remove_duplicates_state_changed)
self.ui.sBAddRangeStart.valueChanged.connect(self.on_fuzzing_range_start_changed)
self.ui.sBAddRangeEnd.valueChanged.connect(self.on_fuzzing_range_end_changed)
self.ui.checkBoxLowerBound.stateChanged.connect(self.on_lower_bound_checked_changed)
self.ui.checkBoxUpperBound.stateChanged.connect(self.on_upper_bound_checked_changed)
self.ui.spinBoxLowerBound.valueChanged.connect(self.on_lower_bound_changed)
self.ui.spinBoxUpperBound.valueChanged.connect(self.on_upper_bound_changed)
self.ui.spinBoxRandomMinimum.valueChanged.connect(self.on_random_range_min_changed)
self.ui.spinBoxRandomMaximum.valueChanged.connect(self.on_random_range_max_changed)
self.ui.spinBoxFuzzMessage.valueChanged.connect(self.on_fuzz_msg_changed)
self.ui.btnAddFuzzingValues.clicked.connect(self.on_btn_add_fuzzing_values_clicked)
self.ui.comboBoxFuzzingLabel.editTextChanged.connect(self.set_current_label_name)
def update_message_data_string(self):
fuz_start = self.current_label_start
fuz_end = self.current_label_end
num_proto_bits = 10
num_fuz_bits = 16
proto_start = fuz_start - num_proto_bits
preambel = "... "
if proto_start <= 0:
proto_start = 0
preambel = ""
proto_end = fuz_end + num_proto_bits
postambel = " ..."
if proto_end >= len(self.message_data) - 1:
proto_end = len(self.message_data) - 1
postambel = ""
fuzamble = ""
if fuz_end - fuz_start > num_fuz_bits:
fuz_end = fuz_start + num_fuz_bits
fuzamble = "..."
self.ui.lPreBits.setText(preambel + self.message_data[proto_start:self.current_label_start])
self.ui.lFuzzedBits.setText(self.message_data[fuz_start:fuz_end] + fuzamble)
self.ui.lPostBits.setText(self.message_data[self.current_label_end:proto_end] + postambel)
self.set_add_spinboxes_maximum_on_label_change()
def closeEvent(self, event: QCloseEvent):
settings.write("{}/geometry".format(self.__class__.__name__), self.saveGeometry())
super().closeEvent(event)
@pyqtSlot(int)
def on_fuzzing_start_changed(self, value: int):
self.ui.spinBoxFuzzingEnd.setMinimum(self.ui.spinBoxFuzzingStart.value())
new_start = self.message.convert_index(value - 1, self.proto_view, 0, False)[0]
self.current_label.start = new_start
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me()
@pyqtSlot(int)
def on_fuzzing_end_changed(self, value: int):
self.ui.spinBoxFuzzingStart.setMaximum(self.ui.spinBoxFuzzingEnd.value())
new_end = self.message.convert_index(value - 1, self.proto_view, 0, False)[1] + 1
self.current_label.end = new_end
self.current_label.fuzz_values[:] = []
self.update_message_data_string()
self.fuzz_table_model.update()
self.ui.tblFuzzingValues.resize_me()
@pyqtSlot(int)
def on_combo_box_fuzzing_label_current_index_changed(self, index: int):
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
self.ui.tblFuzzingValues.resize_me()
self.ui.spinBoxFuzzingStart.blockSignals(True)
self.ui.spinBoxFuzzingStart.setValue(self.current_label_start + 1)
self.ui.spinBoxFuzzingStart.blockSignals(False)
self.ui.spinBoxFuzzingEnd.blockSignals(True)
self.ui.spinBoxFuzzingEnd.setValue(self.current_label_end)
self.ui.spinBoxFuzzingEnd.blockSignals(False)
@pyqtSlot()
def on_btn_add_row_clicked(self):
self.current_label.add_fuzz_value()
self.fuzz_table_model.update()
@pyqtSlot()
def on_btn_del_row_clicked(self):
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
self.delete_lines(min_row, max_row)
@pyqtSlot(int, int)
def delete_lines(self, min_row, max_row):
if min_row == -1:
self.current_label.fuzz_values = self.current_label.fuzz_values[:-1]
else:
self.current_label.fuzz_values = self.current_label.fuzz_values[:min_row] + self.current_label.fuzz_values[
max_row + 1:]
_ = self.current_label # if user deleted all, this will restore a fuzz value
self.fuzz_table_model.update()
@pyqtSlot()
def on_remove_duplicates_state_changed(self):
self.fuzz_table_model.remove_duplicates = self.ui.chkBRemoveDuplicates.isChecked()
self.fuzz_table_model.update()
self.remove_duplicates()
@pyqtSlot()
def set_add_spinboxes_maximum_on_label_change(self):
nbits = self.current_label.end - self.current_label.start # Use Bit Start/End for maximum calc.
if nbits >= 32:
nbits = 31
max_val = 2 ** nbits - 1
self.ui.sBAddRangeStart.setMaximum(max_val - 1)
self.ui.sBAddRangeEnd.setMaximum(max_val)
self.ui.sBAddRangeEnd.setValue(max_val)
self.ui.sBAddRangeStep.setMaximum(max_val)
self.ui.spinBoxLowerBound.setMaximum(max_val - 1)
self.ui.spinBoxUpperBound.setMaximum(max_val)
self.ui.spinBoxUpperBound.setValue(max_val)
self.ui.spinBoxBoundaryNumber.setMaximum(int(max_val / 2) + 1)
self.ui.spinBoxRandomMinimum.setMaximum(max_val - 1)
self.ui.spinBoxRandomMaximum.setMaximum(max_val)
self.ui.spinBoxRandomMaximum.setValue(max_val)
@pyqtSlot(int)
def on_fuzzing_range_start_changed(self, value: int):
self.ui.sBAddRangeEnd.setMinimum(value)
self.ui.sBAddRangeStep.setMaximum(self.ui.sBAddRangeEnd.value() - value)
@pyqtSlot(int)
def on_fuzzing_range_end_changed(self, value: int):
self.ui.sBAddRangeStart.setMaximum(value - 1)
self.ui.sBAddRangeStep.setMaximum(value - self.ui.sBAddRangeStart.value())
@pyqtSlot()
def on_lower_bound_checked_changed(self):
if self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxLowerBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxLowerBound.setEnabled(False)
@pyqtSlot()
def on_upper_bound_checked_changed(self):
if self.ui.checkBoxUpperBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(True)
self.ui.spinBoxBoundaryNumber.setEnabled(True)
elif not self.ui.checkBoxLowerBound.isChecked():
self.ui.spinBoxUpperBound.setEnabled(False)
self.ui.spinBoxBoundaryNumber.setEnabled(False)
else:
self.ui.spinBoxUpperBound.setEnabled(False)
@pyqtSlot()
def on_lower_bound_changed(self):
self.ui.spinBoxUpperBound.setMinimum(self.ui.spinBoxLowerBound.value())
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2))
@pyqtSlot()
def on_upper_bound_changed(self):
self.ui.spinBoxLowerBound.setMaximum(self.ui.spinBoxUpperBound.value() - 1)
self.ui.spinBoxBoundaryNumber.setMaximum(math.ceil((self.ui.spinBoxUpperBound.value()
- self.ui.spinBoxLowerBound.value()) / 2))
@pyqtSlot()
def on_random_range_min_changed(self):
self.ui.spinBoxRandomMaximum.setMinimum(self.ui.spinBoxRandomMinimum.value())
@pyqtSlot()
def on_random_range_max_changed(self):
self.ui.spinBoxRandomMinimum.setMaximum(self.ui.spinBoxRandomMaximum.value() - 1)
@pyqtSlot()
def on_btn_add_fuzzing_values_clicked(self):
if self.ui.comboBoxStrategy.currentIndex() == 0:
self.__add_fuzzing_range()
elif self.ui.comboBoxStrategy.currentIndex() == 1:
self.__add_fuzzing_boundaries()
elif self.ui.comboBoxStrategy.currentIndex() == 2:
self.__add_random_fuzzing_values()
def __add_fuzzing_range(self):
start = self.ui.sBAddRangeStart.value()
end = self.ui.sBAddRangeEnd.value()
step = self.ui.sBAddRangeStep.value()
self.fuzz_table_model.add_range(start, end + 1, step)
def __add_fuzzing_boundaries(self):
lower_bound = -1
if self.ui.spinBoxLowerBound.isEnabled():
lower_bound = self.ui.spinBoxLowerBound.value()
upper_bound = -1
if self.ui.spinBoxUpperBound.isEnabled():
upper_bound = self.ui.spinBoxUpperBound.value()
num_vals = self.ui.spinBoxBoundaryNumber.value()
self.fuzz_table_model.add_boundaries(lower_bound, upper_bound, num_vals)
def __add_random_fuzzing_values(self):
n = self.ui.spinBoxNumberRandom.value()
minimum = self.ui.spinBoxRandomMinimum.value()
maximum = self.ui.spinBoxRandomMaximum.value()
self.fuzz_table_model.add_random(n, minimum, maximum)
def remove_duplicates(self):
if self.ui.chkBRemoveDuplicates.isChecked():
for lbl in self.message.message_type:
seq = lbl.fuzz_values[:]
seen = set()
add_seen = seen.add
lbl.fuzz_values = [l for l in seq if not (l in seen or add_seen(l))]
@pyqtSlot()
def set_current_label_name(self):
self.current_label.name = self.ui.comboBoxFuzzingLabel.currentText()
self.ui.comboBoxFuzzingLabel.setItemText(self.ui.comboBoxFuzzingLabel.currentIndex(), self.current_label.name)
@pyqtSlot(int)
def on_fuzz_msg_changed(self, index: int):
self.ui.comboBoxFuzzingLabel.setDisabled(False)
sel_label_ind = self.ui.comboBoxFuzzingLabel.currentIndex()
self.ui.comboBoxFuzzingLabel.blockSignals(True)
self.ui.comboBoxFuzzingLabel.clear()
if len(self.message.message_type) == 0:
self.ui.comboBoxFuzzingLabel.setDisabled(True)
return
self.ui.comboBoxFuzzingLabel.addItems([lbl.name for lbl in self.message.message_type])
self.ui.comboBoxFuzzingLabel.blockSignals(False)
if sel_label_ind < self.ui.comboBoxFuzzingLabel.count():
self.ui.comboBoxFuzzingLabel.setCurrentIndex(sel_label_ind)
else:
self.ui.comboBoxFuzzingLabel.setCurrentIndex(0)
self.fuzz_table_model.fuzzing_label = self.current_label
self.fuzz_table_model.update()
self.update_message_data_string()
@pyqtSlot()
def on_btn_repeat_values_clicked(self):
num_repeats, ok = QInputDialog.getInt(self, self.tr("How many times shall values be repeated?"),
self.tr("Number of repeats:"), 1, 1)
if ok:
self.ui.chkBRemoveDuplicates.setChecked(False)
min_row, max_row, _, _ = self.ui.tblFuzzingValues.selection_range()
if min_row == -1:
start, end = 0, len(self.current_label.fuzz_values)
else:
start, end = min_row, max_row + 1
self.fuzz_table_model.repeat_fuzzing_values(start, end, num_repeats)
| jopohl/urh | src/urh/controller/dialogs/FuzzingDialog.py | Python | gpl-3.0 | 15,833 |
import os
import unittest
from vsg.rules import iteration_scheme
from vsg import vhdlFile
from vsg.tests import utils
sTestDir = os.path.dirname(__file__)
lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd'))
dIndentMap = utils.read_indent_file()
lExpected = []
lExpected.append('')
utils.read_file(os.path.join(sTestDir, 'rule_300_test_input.fixed.vhd'), lExpected)
class test_iteration_scheme_rule(unittest.TestCase):
def setUp(self):
self.oFile = vhdlFile.vhdlFile(lFile)
self.assertIsNone(eError)
self.oFile.set_indent_map(dIndentMap)
def test_rule_300(self):
oRule = iteration_scheme.rule_300()
self.assertTrue(oRule)
self.assertEqual(oRule.name, 'iteration_scheme')
self.assertEqual(oRule.identifier, '300')
lExpected = [13, 17]
oRule.analyze(self.oFile)
self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations))
def test_fix_rule_300(self):
oRule = iteration_scheme.rule_300()
oRule.fix(self.oFile)
lActual = self.oFile.get_lines()
self.assertEqual(lExpected, lActual)
oRule.analyze(self.oFile)
self.assertEqual(oRule.violations, [])
| jeremiah-c-leary/vhdl-style-guide | vsg/tests/iteration_scheme/test_rule_300.py | Python | gpl-3.0 | 1,279 |
<?php
class ControllerCheckoutRegister extends Controller {
public function index() {
$this->language->load('checkout/checkout');
$this->data['text_checkout_payment_address'] = __('text_checkout_payment_address');
$this->data['text_your_details'] = __('text_your_details');
$this->data['text_your_address'] = __('text_your_address');
$this->data['text_your_password'] = __('text_your_password');
$this->data['text_select'] = __('text_select');
$this->data['text_none'] = __('text_none');
$this->data['text_modify'] = __('text_modify');
$this->data['entry_firstname'] = __('entry_firstname');
$this->data['entry_lastname'] = __('entry_lastname');
$this->data['entry_email'] = __('entry_email');
$this->data['entry_telephone'] = __('entry_telephone');
$this->data['entry_fax'] = __('entry_fax');
$this->data['entry_company'] = __('entry_company');
$this->data['entry_customer_group'] = __('entry_customer_group');
$this->data['entry_address_1'] = __('entry_address_1');
$this->data['entry_address_2'] = __('entry_address_2');
$this->data['entry_postcode'] = __('entry_postcode');
$this->data['entry_city'] = __('entry_city');
$this->data['entry_country'] = __('entry_country');
$this->data['entry_zone'] = __('entry_zone');
$this->data['entry_newsletter'] = sprintf(__('entry_newsletter'), $this->config->get('config_name'));
$this->data['entry_password'] = __('entry_password');
$this->data['entry_confirm'] = __('entry_confirm');
$this->data['entry_shipping'] = __('entry_shipping');
$this->data['button_continue'] = __('button_continue');
$this->data['customer_groups'] = array();
if (is_array($this->config->get('config_customer_group_display'))) {
$this->load->model('account/customer_group');
$customer_groups = $this->model_account_customer_group->getCustomerGroups();
foreach ($customer_groups as $customer_group) {
if (in_array($customer_group['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$this->data['customer_groups'][] = $customer_group;
}
}
}
$this->data['customer_group_id'] = $this->config->get('config_customer_group_id');
if (isset($this->session->data['shipping_addess']['postcode'])) {
$this->data['postcode'] = $this->session->data['shipping_addess']['postcode'];
} else {
$this->data['postcode'] = '';
}
if (isset($this->session->data['shipping_addess']['country_id'])) {
$this->data['country_id'] = $this->session->data['shipping_addess']['country_id'];
} else {
$this->data['country_id'] = $this->config->get('config_country_id');
}
if (isset($this->session->data['shipping_addess']['zone_id'])) {
$this->data['zone_id'] = $this->session->data['shipping_addess']['zone_id'];
} else {
$this->data['zone_id'] = '';
}
$this->load->model('localisation/country');
$this->data['countries'] = $this->model_localisation_country->getCountries();
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info) {
$this->data['text_agree'] = sprintf(__('text_agree'), $this->url->link('information/information/info', 'information_id=' . $this->config->get('config_account_id'), 'SSL'), $information_info['title'], $information_info['title']);
} else {
$this->data['text_agree'] = '';
}
} else {
$this->data['text_agree'] = '';
}
$this->data['shipping_required'] = $this->cart->hasShipping();
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/register.tpl')) {
$this->template = $this->config->get('config_template') . '/template/checkout/register.tpl';
} else {
$this->template = 'default/template/checkout/register.tpl';
}
$this->response->setOutput($this->render());
}
public function save() {
$this->language->load('checkout/checkout');
$json = array();
// Validate if customer is already logged out.
if ($this->customer->isLogged()) {
$json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
}
// Validate cart has products and has stock.
if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
$json['redirect'] = $this->url->link('checkout/cart');
}
// Validate minimum quantity requirments.
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$json['redirect'] = $this->url->link('checkout/cart');
break;
}
}
if (!$json) {
$this->load->model('account/customer');
if ((utf8_strlen($this->request->post['firstname']) < 1) || (utf8_strlen($this->request->post['firstname']) > 32)) {
$json['error']['firstname'] = __('error_firstname');
}
if ((utf8_strlen($this->request->post['lastname']) < 1) || (utf8_strlen($this->request->post['lastname']) > 32)) {
$json['error']['lastname'] = __('error_lastname');
}
if ((utf8_strlen($this->request->post['email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
$json['error']['email'] = __('error_email');
}
if ($this->model_account_customer->getTotalCustomersByEmail($this->request->post['email'])) {
$json['error']['warning'] = __('error_exists');
}
if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
$json['error']['telephone'] = __('error_telephone');
}
// Customer Group
$this->load->model('account/customer_group');
if (isset($this->request->post['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($this->request->post['customer_group_id'], $this->config->get('config_customer_group_display'))) {
$customer_group_id = $this->request->post['customer_group_id'];
} else {
$customer_group_id = $this->config->get('config_customer_group_id');
}
$customer_group = $this->model_account_customer_group->getCustomerGroup($customer_group_id);
if ($customer_group) {
}
if ((utf8_strlen($this->request->post['address_1']) < 3) || (utf8_strlen($this->request->post['address_1']) > 128)) {
$json['error']['address_1'] = __('error_address_1');
}
if ((utf8_strlen($this->request->post['city']) < 2) || (utf8_strlen($this->request->post['city']) > 128)) {
$json['error']['city'] = __('error_city');
}
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->request->post['country_id']);
if ($country_info && $country_info['postcode_required'] && (utf8_strlen($this->request->post['postcode']) < 2) || (utf8_strlen($this->request->post['postcode']) > 10)) {
$json['error']['postcode'] = __('error_postcode');
}
if ($this->request->post['country_id'] == '') {
$json['error']['country'] = __('error_country');
}
if (!isset($this->request->post['zone_id']) || $this->request->post['zone_id'] == '') {
$json['error']['zone'] = __('error_zone');
}
if ((utf8_strlen($this->request->post['password']) < 4) || (utf8_strlen($this->request->post['password']) > 20)) {
$json['error']['password'] = __('error_password');
}
if ($this->request->post['confirm'] != $this->request->post['password']) {
$json['error']['confirm'] = __('error_confirm');
}
if ($this->config->get('config_account_id')) {
$this->load->model('catalog/information');
$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));
if ($information_info && !isset($this->request->post['agree'])) {
$json['error']['warning'] = sprintf(__('error_agree'), $information_info['title']);
}
}
}
if (!$json) {
$this->model_account_customer->addCustomer($this->request->post);
$this->session->data['account'] = 'register';
if ($customer_group && !$customer_group['approval']) {
$this->customer->login($this->request->post['email'], $this->request->post['password']);
// Default Payment Address
$this->load->model('account/address');
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
if (!empty($this->request->post['shipping_address'])) {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
} else {
$json['redirect'] = $this->url->link('account/success');
}
unset($this->session->data['guest']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
}
$this->response->setOutput(json_encode($json));
}
}
?> | maddes/madcart | catalog/controller/checkout/register.php | PHP | gpl-3.0 | 9,487 |
/*
* Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
* Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#include "claws-features.h"
#endif
#include <glib.h>
#include <glib/gi18n.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#ifdef G_OS_WIN32
# include <w32lib.h>
#endif
#include "procheader.h"
#include "procmsg.h"
#include "codeconv.h"
#include "prefs_common.h"
#include "hooks.h"
#include "utils.h"
#include "defs.h"
#define BUFFSIZE 8192
static gchar monthstr[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
typedef char *(*getlinefunc) (char *, size_t, void *);
typedef int (*peekcharfunc) (void *);
typedef int (*getcharfunc) (void *);
typedef gint (*get_one_field_func) (gchar *, size_t, void *, HeaderEntry[]);
static gint string_get_one_field(gchar *buf, size_t len, char **str,
HeaderEntry hentry[]);
static char *string_getline(char *buf, size_t len, char **str);
static int string_peekchar(char **str);
static int file_peekchar(FILE *fp);
static gint generic_get_one_field(gchar *buf, size_t len, void *data,
HeaderEntry hentry[],
getlinefunc getline,
peekcharfunc peekchar,
gboolean unfold);
static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
gboolean full, gboolean decrypted);
gint procheader_get_one_field(gchar *buf, size_t len, FILE *fp,
HeaderEntry hentry[])
{
return generic_get_one_field(buf, len, fp, hentry,
(getlinefunc)fgets_crlf, (peekcharfunc)file_peekchar,
TRUE);
}
static gint string_get_one_field(gchar *buf, size_t len, char **str,
HeaderEntry hentry[])
{
return generic_get_one_field(buf, len, str, hentry,
(getlinefunc)string_getline,
(peekcharfunc)string_peekchar,
TRUE);
}
static char *string_getline(char *buf, size_t len, char **str)
{
gboolean is_cr = FALSE;
gboolean last_was_cr = FALSE;
if (!*str || !**str)
return NULL;
for (; **str && len > 1; --len) {
is_cr = (**str == '\r');
if ((*buf++ = *(*str)++) == '\n') {
break;
}
if (last_was_cr) {
*(--buf) = '\n';
buf++;
break;
}
last_was_cr = is_cr;
}
*buf = '\0';
return buf;
}
static int string_peekchar(char **str)
{
return **str;
}
static int file_peekchar(FILE *fp)
{
return ungetc(getc(fp), fp);
}
static gint generic_get_one_field(gchar *buf, size_t len, void *data,
HeaderEntry *hentry,
getlinefunc getline, peekcharfunc peekchar,
gboolean unfold)
{
gint nexthead;
gint hnum = 0;
HeaderEntry *hp = NULL;
if (hentry != NULL) {
/* skip non-required headers */
do {
do {
if (getline(buf, len, data) == NULL)
return -1;
if (buf[0] == '\r' || buf[0] == '\n')
return -1;
} while (buf[0] == ' ' || buf[0] == '\t');
for (hp = hentry, hnum = 0; hp->name != NULL;
hp++, hnum++) {
if (!g_ascii_strncasecmp(hp->name, buf,
strlen(hp->name)))
break;
}
} while (hp->name == NULL);
} else {
if (getline(buf, len, data) == NULL) return -1;
if (buf[0] == '\r' || buf[0] == '\n') return -1;
}
/* unfold line */
while (1) {
nexthead = peekchar(data);
/* ([*WSP CRLF] 1*WSP) */
if (nexthead == ' ' || nexthead == '\t') {
size_t buflen;
gboolean skiptab = (nexthead == '\t');
/* trim previous trailing \n if requesting one header or
* unfolding was requested */
if ((!hentry && unfold) || (hp && hp->unfold))
strretchomp(buf);
buflen = strlen(buf);
/* concatenate next line */
if ((len - buflen) > 2) {
if (getline(buf + buflen, len - buflen, data) == NULL)
break;
if (skiptab) { /* replace tab with space */
*(buf + buflen) = ' ';
}
} else
break;
} else {
/* remove trailing new line */
strretchomp(buf);
break;
}
}
return hnum;
}
gint procheader_get_one_field_asis(gchar *buf, size_t len, FILE *fp)
{
return generic_get_one_field(buf, len, fp, NULL,
(getlinefunc)fgets_crlf,
(peekcharfunc)file_peekchar,
FALSE);
}
GPtrArray *procheader_get_header_array_asis(FILE *fp)
{
gchar buf[BUFFSIZE];
GPtrArray *headers;
Header *header;
cm_return_val_if_fail(fp != NULL, NULL);
headers = g_ptr_array_new();
while (procheader_get_one_field_asis(buf, sizeof(buf), fp) != -1) {
if ((header = procheader_parse_header(buf)) != NULL)
g_ptr_array_add(headers, header);
}
return headers;
}
void procheader_header_array_destroy(GPtrArray *harray)
{
gint i;
Header *header;
for (i = 0; i < harray->len; i++) {
header = g_ptr_array_index(harray, i);
procheader_header_free(header);
}
g_ptr_array_free(harray, TRUE);
}
void procheader_header_free(Header *header)
{
if (!header) return;
g_free(header->name);
g_free(header->body);
g_free(header);
}
/*
tests whether two headers' names are equal
remove the trailing ':' or ' ' before comparing
*/
gboolean procheader_headername_equal(char * hdr1, char * hdr2)
{
int len1;
int len2;
len1 = strlen(hdr1);
len2 = strlen(hdr2);
if (hdr1[len1 - 1] == ':')
len1--;
if (hdr2[len2 - 1] == ':')
len2--;
if (len1 != len2)
return 0;
return (g_ascii_strncasecmp(hdr1, hdr2, len1) == 0);
}
/*
parse headers, for example :
From: [email protected] becomes :
header->name = "From:"
header->body = "[email protected]"
*/
static gboolean header_is_addr_field(const gchar *hdr)
{
static char *addr_headers[] = {
"To:",
"Cc:",
"Bcc:",
"From:",
"Reply-To:",
"Followup-To:",
"Followup-and-Reply-To:",
"Disposition-Notification-To:",
"Return-Receipt-To:",
NULL};
int i;
if (!hdr)
return FALSE;
for (i = 0; addr_headers[i] != NULL; i++)
if (!strcasecmp(hdr, addr_headers[i]))
return FALSE;
return FALSE;
}
Header * procheader_parse_header(gchar * buf)
{
gchar *p;
Header * header;
gboolean addr_field = FALSE;
if ((*buf == ':') || (*buf == ' '))
return NULL;
for (p = buf; *p ; p++) {
if ((*p == ':') || (*p == ' ')) {
header = g_new(Header, 1);
header->name = g_strndup(buf, p - buf + 1);
addr_field = header_is_addr_field(header->name);
p++;
while (*p == ' ' || *p == '\t') p++;
header->body = conv_unmime_header(p, NULL, addr_field);
return header;
}
}
return NULL;
}
void procheader_get_header_fields(FILE *fp, HeaderEntry hentry[])
{
gchar buf[BUFFSIZE];
HeaderEntry *hp;
gint hnum;
gchar *p;
if (hentry == NULL) return;
while ((hnum = procheader_get_one_field(buf, sizeof(buf), fp, hentry))
!= -1) {
hp = hentry + hnum;
p = buf + strlen(hp->name);
while (*p == ' ' || *p == '\t') p++;
if (hp->body == NULL)
hp->body = g_strdup(p);
else if (procheader_headername_equal(hp->name, "To") ||
procheader_headername_equal(hp->name, "Cc")) {
gchar *tp = hp->body;
hp->body = g_strconcat(tp, ", ", p, NULL);
g_free(tp);
}
}
}
MsgInfo *procheader_parse_file(const gchar *file, MsgFlags flags,
gboolean full, gboolean decrypted)
{
GStatBuf s;
FILE *fp;
MsgInfo *msginfo;
if (g_stat(file, &s) < 0) {
FILE_OP_ERROR(file, "stat");
return NULL;
}
if (!S_ISREG(s.st_mode))
return NULL;
if ((fp = g_fopen(file, "rb")) == NULL) {
FILE_OP_ERROR(file, "fopen");
return NULL;
}
msginfo = procheader_parse_stream(fp, flags, full, decrypted);
fclose(fp);
if (msginfo) {
msginfo->size = s.st_size;
msginfo->mtime = s.st_mtime;
}
return msginfo;
}
MsgInfo *procheader_parse_str(const gchar *str, MsgFlags flags, gboolean full,
gboolean decrypted)
{
return parse_stream(&str, TRUE, flags, full, decrypted);
}
enum
{
H_DATE = 0,
H_FROM,
H_TO,
H_CC,
H_NEWSGROUPS,
H_SUBJECT,
H_MSG_ID,
H_REFERENCES,
H_IN_REPLY_TO,
H_CONTENT_TYPE,
H_SEEN,
H_STATUS,
H_FROM_SPACE,
H_SC_PLANNED_DOWNLOAD,
H_SC_MESSAGE_SIZE,
H_FACE,
H_X_FACE,
H_DISPOSITION_NOTIFICATION_TO,
H_RETURN_RECEIPT_TO,
H_SC_PARTIALLY_RETRIEVED,
H_SC_ACCOUNT_SERVER,
H_SC_ACCOUNT_LOGIN,
H_LIST_POST,
H_LIST_SUBSCRIBE,
H_LIST_UNSUBSCRIBE,
H_LIST_HELP,
H_LIST_ARCHIVE,
H_LIST_OWNER,
H_RESENT_FROM,
};
static HeaderEntry hentry_full[] = {
{"Date:", NULL, FALSE},
{"From:", NULL, TRUE},
{"To:", NULL, TRUE},
{"Cc:", NULL, TRUE},
{"Newsgroups:", NULL, TRUE},
{"Subject:", NULL, TRUE},
{"Message-ID:", NULL, FALSE},
{"References:", NULL, FALSE},
{"In-Reply-To:", NULL, FALSE},
{"Content-Type:", NULL, FALSE},
{"Seen:", NULL, FALSE},
{"Status:", NULL, FALSE},
{"From ", NULL, FALSE},
{"SC-Marked-For-Download:", NULL, FALSE},
{"SC-Message-Size:", NULL, FALSE},
{"Face:", NULL, FALSE},
{"X-Face:", NULL, FALSE},
{"Disposition-Notification-To:", NULL, FALSE},
{"Return-Receipt-To:", NULL, FALSE},
{"SC-Partially-Retrieved:", NULL, FALSE},
{"SC-Account-Server:", NULL, FALSE},
{"SC-Account-Login:",NULL, FALSE},
{"List-Post:", NULL, TRUE},
{"List-Subscribe:", NULL, TRUE},
{"List-Unsubscribe:",NULL, TRUE},
{"List-Help:", NULL, TRUE},
{"List-Archive:", NULL, TRUE},
{"List-Owner:", NULL, TRUE},
{"Resent-From:", NULL, TRUE},
{NULL, NULL, FALSE}};
static HeaderEntry hentry_short[] = {
{"Date:", NULL, FALSE},
{"From:", NULL, TRUE},
{"To:", NULL, TRUE},
{"Cc:", NULL, TRUE},
{"Newsgroups:", NULL, TRUE},
{"Subject:", NULL, TRUE},
{"Message-ID:", NULL, FALSE},
{"References:", NULL, FALSE},
{"In-Reply-To:", NULL, FALSE},
{"Content-Type:", NULL, FALSE},
{"Seen:", NULL, FALSE},
{"Status:", NULL, FALSE},
{"From ", NULL, FALSE},
{"SC-Marked-For-Download:", NULL, FALSE},
{"SC-Message-Size:",NULL, FALSE},
{NULL, NULL, FALSE}};
static HeaderEntry* procheader_get_headernames(gboolean full)
{
return full ? hentry_full : hentry_short;
}
MsgInfo *procheader_parse_stream(FILE *fp, MsgFlags flags, gboolean full,
gboolean decrypted)
{
return parse_stream(fp, FALSE, flags, full, decrypted);
}
static gboolean avatar_from_some_face(gpointer source, gpointer userdata)
{
AvatarCaptureData *acd = (AvatarCaptureData *)source;
if (*(acd->content) == '\0') /* won't be null, but may be empty */
return FALSE;
if (!strcmp(acd->header, hentry_full[H_FACE].name)) {
debug_print("avatar_from_some_face: found 'Face' header\n");
procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_FACE, acd->content);
}
#if HAVE_LIBCOMPFACE
else if (!strcmp(acd->header, hentry_full[H_X_FACE].name)) {
debug_print("avatar_from_some_face: found 'X-Face' header\n");
procmsg_msginfo_add_avatar(acd->msginfo, AVATAR_XFACE, acd->content);
}
#endif
return FALSE;
}
static guint avatar_hook_id = 0;
static MsgInfo *parse_stream(void *data, gboolean isstring, MsgFlags flags,
gboolean full, gboolean decrypted)
{
MsgInfo *msginfo;
gchar buf[BUFFSIZE];
gchar *p, *tmp;
gchar *hp;
HeaderEntry *hentry;
gint hnum;
void *orig_data = data;
get_one_field_func get_one_field =
isstring ? (get_one_field_func)string_get_one_field
: (get_one_field_func)procheader_get_one_field;
hentry = procheader_get_headernames(full);
if (MSG_IS_QUEUED(flags) || MSG_IS_DRAFT(flags)) {
while (get_one_field(buf, sizeof(buf), data, NULL) != -1) {
if ((!strncmp(buf, "X-Claws-End-Special-Headers: 1",
strlen("X-Claws-End-Special-Headers:"))) ||
(!strncmp(buf, "X-Sylpheed-End-Special-Headers: 1",
strlen("X-Sylpheed-End-Special-Headers:"))))
break;
/* from other mailers */
if (!strncmp(buf, "Date: ", 6)
|| !strncmp(buf, "To: ", 4)
|| !strncmp(buf, "From: ", 6)
|| !strncmp(buf, "Subject: ", 9)) {
if (isstring)
data = orig_data;
else
rewind((FILE *)data);
break;
}
}
}
msginfo = procmsg_msginfo_new();
if (flags.tmp_flags || flags.perm_flags)
msginfo->flags = flags;
else
MSG_SET_PERM_FLAGS(msginfo->flags, MSG_NEW | MSG_UNREAD);
msginfo->inreplyto = NULL;
if (avatar_hook_id == 0 && (prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
avatar_hook_id = hooks_register_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_from_some_face, NULL);
} else if (avatar_hook_id != 0 && !(prefs_common.enable_avatars & AVATARS_ENABLE_CAPTURE)) {
hooks_unregister_hook(AVATAR_HEADER_UPDATE_HOOKLIST, avatar_hook_id);
avatar_hook_id = 0;
}
while ((hnum = get_one_field(buf, sizeof(buf), data, hentry))
!= -1) {
hp = buf + strlen(hentry[hnum].name);
while (*hp == ' ' || *hp == '\t') hp++;
switch (hnum) {
case H_DATE:
if (msginfo->date) break;
msginfo->date_t =
procheader_date_parse(NULL, hp, 0);
if (g_utf8_validate(hp, -1, NULL)) {
msginfo->date = g_strdup(hp);
} else {
gchar *utf = conv_codeset_strdup(
hp,
conv_get_locale_charset_str_no_utf8(),
CS_INTERNAL);
if (utf == NULL ||
!g_utf8_validate(utf, -1, NULL)) {
g_free(utf);
utf = g_malloc(strlen(buf)*2+1);
conv_localetodisp(utf,
strlen(hp)*2+1, hp);
}
msginfo->date = utf;
}
break;
case H_FROM:
if (msginfo->from) break;
msginfo->from = conv_unmime_header(hp, NULL, TRUE);
msginfo->fromname = procheader_get_fromname(msginfo->from);
remove_return(msginfo->from);
remove_return(msginfo->fromname);
break;
case H_TO:
tmp = conv_unmime_header(hp, NULL, TRUE);
remove_return(tmp);
if (msginfo->to) {
p = msginfo->to;
msginfo->to =
g_strconcat(p, ", ", tmp, NULL);
g_free(p);
} else
msginfo->to = g_strdup(tmp);
g_free(tmp);
break;
case H_CC:
tmp = conv_unmime_header(hp, NULL, TRUE);
remove_return(tmp);
if (msginfo->cc) {
p = msginfo->cc;
msginfo->cc =
g_strconcat(p, ", ", tmp, NULL);
g_free(p);
} else
msginfo->cc = g_strdup(tmp);
g_free(tmp);
break;
case H_NEWSGROUPS:
if (msginfo->newsgroups) {
p = msginfo->newsgroups;
msginfo->newsgroups =
g_strconcat(p, ",", hp, NULL);
g_free(p);
} else
msginfo->newsgroups = g_strdup(hp);
break;
case H_SUBJECT:
if (msginfo->subject) break;
msginfo->subject = conv_unmime_header(hp, NULL, FALSE);
unfold_line(msginfo->subject);
break;
case H_MSG_ID:
if (msginfo->msgid) break;
extract_parenthesis(hp, '<', '>');
remove_space(hp);
msginfo->msgid = g_strdup(hp);
break;
case H_REFERENCES:
msginfo->references =
references_list_prepend(msginfo->references,
hp);
break;
case H_IN_REPLY_TO:
if (msginfo->inreplyto) break;
eliminate_parenthesis(hp, '(', ')');
if ((p = strrchr(hp, '<')) != NULL &&
strchr(p + 1, '>') != NULL) {
extract_parenthesis(p, '<', '>');
remove_space(p);
if (*p != '\0')
msginfo->inreplyto = g_strdup(p);
}
break;
case H_CONTENT_TYPE:
if (!g_ascii_strncasecmp(hp, "multipart/", 10))
MSG_SET_TMP_FLAGS(msginfo->flags, MSG_MULTIPART);
break;
case H_DISPOSITION_NOTIFICATION_TO:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->dispositionnotificationto) break;
msginfo->extradata->dispositionnotificationto = g_strdup(hp);
break;
case H_RETURN_RECEIPT_TO:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->returnreceiptto) break;
msginfo->extradata->returnreceiptto = g_strdup(hp);
break;
/* partial download infos */
case H_SC_PARTIALLY_RETRIEVED:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->partial_recv) break;
msginfo->extradata->partial_recv = g_strdup(hp);
break;
case H_SC_ACCOUNT_SERVER:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->account_server) break;
msginfo->extradata->account_server = g_strdup(hp);
break;
case H_SC_ACCOUNT_LOGIN:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->account_login) break;
msginfo->extradata->account_login = g_strdup(hp);
break;
case H_SC_MESSAGE_SIZE:
if (msginfo->total_size) break;
msginfo->total_size = atoi(hp);
break;
case H_SC_PLANNED_DOWNLOAD:
msginfo->planned_download = atoi(hp);
break;
/* end partial download infos */
case H_FROM_SPACE:
if (msginfo->fromspace) break;
msginfo->fromspace = g_strdup(hp);
remove_return(msginfo->fromspace);
break;
/* list infos */
case H_LIST_POST:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_post) break;
msginfo->extradata->list_post = g_strdup(hp);
break;
case H_LIST_SUBSCRIBE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_subscribe) break;
msginfo->extradata->list_subscribe = g_strdup(hp);
break;
case H_LIST_UNSUBSCRIBE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_unsubscribe) break;
msginfo->extradata->list_unsubscribe = g_strdup(hp);
break;
case H_LIST_HELP:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_help) break;
msginfo->extradata->list_help = g_strdup(hp);
break;
case H_LIST_ARCHIVE:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_archive) break;
msginfo->extradata->list_archive = g_strdup(hp);
break;
case H_LIST_OWNER:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->list_owner) break;
msginfo->extradata->list_owner = g_strdup(hp);
break;
case H_RESENT_FROM:
if (!msginfo->extradata)
msginfo->extradata = g_new0(MsgInfoExtraData, 1);
if (msginfo->extradata->resent_from) break;
msginfo->extradata->resent_from = g_strdup(hp);
break;
/* end list infos */
default:
break;
}
/* to avoid performance penalty hooklist is invoked only for
headers known to be able to generate avatars */
if (hnum == H_FROM || hnum == H_X_FACE || hnum == H_FACE) {
AvatarCaptureData *acd = g_new0(AvatarCaptureData, 1);
/* no extra memory is wasted, hooks are expected to
take care of copying members when needed */
acd->msginfo = msginfo;
acd->header = hentry_full[hnum].name;
acd->content = hp;
hooks_invoke(AVATAR_HEADER_UPDATE_HOOKLIST, (gpointer)acd);
g_free(acd);
}
}
if (!msginfo->inreplyto && msginfo->references)
msginfo->inreplyto =
g_strdup((gchar *)msginfo->references->data);
return msginfo;
}
gchar *procheader_get_fromname(const gchar *str)
{
gchar *tmp, *name;
Xstrdup_a(tmp, str, return NULL);
if (*tmp == '\"') {
extract_quote(tmp, '\"');
g_strstrip(tmp);
} else if (strchr(tmp, '<')) {
eliminate_parenthesis(tmp, '<', '>');
g_strstrip(tmp);
if (*tmp == '\0') {
strcpy(tmp, str);
extract_parenthesis(tmp, '<', '>');
g_strstrip(tmp);
}
} else if (strchr(tmp, '(')) {
extract_parenthesis(tmp, '(', ')');
g_strstrip(tmp);
}
if (*tmp == '\0')
name = g_strdup(str);
else
name = g_strdup(tmp);
return name;
}
static gint procheader_scan_date_string(const gchar *str,
gchar *weekday, gint *day,
gchar *month, gint *year,
gint *hh, gint *mm, gint *ss,
gchar *zone)
{
gint result;
gint month_n;
gint secfract;
gint zone1 = 0, zone2 = 0;
gchar offset_sign, zonestr[7];
gchar sep1;
if (str == NULL)
return -1;
result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d %6s",
weekday, day, month, year, hh, mm, ss, zone);
if (result == 8) return 0;
/* RFC2822 */
result = sscanf(str, "%3s,%d %9s %d %2d:%2d:%2d %6s",
weekday, day, month, year, hh, mm, ss, zone);
if (result == 8) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d:%2d %6s",
day, month, year, hh, mm, ss, zone);
if (result == 7) return 0;
*zone = '\0';
result = sscanf(str, "%10s %d %9s %d %2d:%2d:%2d",
weekday, day, month, year, hh, mm, ss);
if (result == 7) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d:%2d",
day, month, year, hh, mm, ss);
if (result == 6) return 0;
*ss = 0;
result = sscanf(str, "%10s %d %9s %d %2d:%2d %6s",
weekday, day, month, year, hh, mm, zone);
if (result == 7) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d %5s",
day, month, year, hh, mm, zone);
if (result == 6) return 0;
*zone = '\0';
result = sscanf(str, "%10s %d %9s %d %2d:%2d",
weekday, day, month, year, hh, mm);
if (result == 6) return 0;
result = sscanf(str, "%d %9s %d %2d:%2d",
day, month, year, hh, mm);
if (result == 5) return 0;
*weekday = '\0';
/* RFC3339 subset, with fraction of second */
result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d.%d%6s",
year, &month_n, day, &sep1, hh, mm, ss, &secfract, zonestr);
if (result == 9
&& (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
if (month_n >= 1 && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
strcat(zone, "+00:00");
} else if (sscanf(zonestr, "%c%2d:%2d",
&offset_sign, &zone1, &zone2) == 3) {
strcat(zone, zonestr);
}
return 0;
}
}
/* RFC3339 subset, no fraction of second */
result = sscanf(str, "%4d-%2d-%2d%c%2d:%2d:%2d%6s",
year, &month_n, day, &sep1, hh, mm, ss, zonestr);
if (result == 8
&& (sep1 == 'T' || sep1 == 't' || sep1 == ' ')) {
if (month_n >= 1 && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
if (zonestr[0] == 'z' || zonestr[0] == 'Z') {
strcat(zone, "+00:00");
} else if (sscanf(zonestr, "%c%2d:%2d",
&offset_sign, &zone1, &zone2) == 3) {
strcat(zone, zonestr);
}
return 0;
}
}
*zone = '\0';
/* RFC3339 subset */
/* This particular "subset" is invalid, RFC requires the time offset */
result = sscanf(str, "%4d-%2d-%2d %2d:%2d:%2d",
year, &month_n, day, hh, mm, ss);
if (result == 6) {
if (1 <= month_n && month_n <= 12) {
strncpy2(month, monthstr+((month_n-1)*3), 4);
return 0;
}
}
return -1;
}
/*
* Hiro, most UNIXen support this function:
* http://www.mcsr.olemiss.edu/cgi-bin/man-cgi?getdate
*/
gboolean procheader_date_parse_to_tm(const gchar *src, struct tm *t, char *zone)
{
gchar weekday[11];
gint day;
gchar month[10];
gint year;
gint hh, mm, ss;
GDateMonth dmonth;
gchar *p;
if (!t)
return FALSE;
memset(t, 0, sizeof *t);
if (procheader_scan_date_string(src, weekday, &day, month, &year,
&hh, &mm, &ss, zone) < 0) {
g_warning("Invalid date: %s", src);
return FALSE;
}
/* Y2K compliant :) */
if (year < 100) {
if (year < 70)
year += 2000;
else
year += 1900;
}
month[3] = '\0';
if ((p = strstr(monthstr, month)) != NULL)
dmonth = (gint)(p - monthstr) / 3 + 1;
else {
g_warning("Invalid month: %s", month);
dmonth = G_DATE_BAD_MONTH;
}
t->tm_sec = ss;
t->tm_min = mm;
t->tm_hour = hh;
t->tm_mday = day;
t->tm_mon = dmonth - 1;
t->tm_year = year - 1900;
t->tm_wday = 0;
t->tm_yday = 0;
t->tm_isdst = -1;
mktime(t);
return TRUE;
}
time_t procheader_date_parse(gchar *dest, const gchar *src, gint len)
{
gchar weekday[11];
gint day;
gchar month[10];
gint year;
gint hh, mm, ss;
gchar zone[7];
GDateMonth dmonth = G_DATE_BAD_MONTH;
struct tm t;
gchar *p;
time_t timer;
time_t tz_offset;
if (procheader_scan_date_string(src, weekday, &day, month, &year,
&hh, &mm, &ss, zone) < 0) {
if (dest && len > 0)
strncpy2(dest, src, len);
return 0;
}
/* Y2K compliant :) */
if (year < 1000) {
if (year < 50)
year += 2000;
else
year += 1900;
}
month[3] = '\0';
for (p = monthstr; *p != '\0'; p += 3) {
if (!g_ascii_strncasecmp(p, month, 3)) {
dmonth = (gint)(p - monthstr) / 3 + 1;
break;
}
}
t.tm_sec = ss;
t.tm_min = mm;
t.tm_hour = hh;
t.tm_mday = day;
t.tm_mon = dmonth - 1;
t.tm_year = year - 1900;
t.tm_wday = 0;
t.tm_yday = 0;
t.tm_isdst = -1;
timer = mktime(&t);
tz_offset = remote_tzoffset_sec(zone);
if (tz_offset != -1)
timer += tzoffset_sec(&timer) - tz_offset;
if (dest)
procheader_date_get_localtime(dest, len, timer);
return timer;
}
void procheader_date_get_localtime(gchar *dest, gint len, const time_t timer)
{
struct tm *lt;
gchar *default_format = "%y/%m/%d(%a) %H:%M";
gchar *str;
const gchar *src_codeset, *dest_codeset;
struct tm buf;
if (timer > 0)
lt = localtime_r(&timer, &buf);
else {
time_t dummy = 1;
lt = localtime_r(&dummy, &buf);
}
if (prefs_common.date_format)
fast_strftime(dest, len, prefs_common.date_format, lt);
else
fast_strftime(dest, len, default_format, lt);
if (!g_utf8_validate(dest, -1, NULL)) {
src_codeset = conv_get_locale_charset_str_no_utf8();
dest_codeset = CS_UTF_8;
str = conv_codeset_strdup(dest, src_codeset, dest_codeset);
if (str) {
strncpy2(dest, str, len);
g_free(str);
}
}
}
/* Added by Mel Hadasht on 27 Aug 2001 */
/* Get a header from msginfo */
gint procheader_get_header_from_msginfo(MsgInfo *msginfo, gchar *buf, gint len, gchar *header)
{
gchar *file;
FILE *fp;
HeaderEntry hentry[]={ { NULL, NULL, TRUE },
{ NULL, NULL, FALSE } };
gint val;
hentry[0].name = header;
cm_return_val_if_fail(msginfo != NULL, -1);
file = procmsg_get_message_file_path(msginfo);
if ((fp = g_fopen(file, "rb")) == NULL) {
FILE_OP_ERROR(file, "fopen");
g_free(file);
return -1;
}
val = procheader_get_one_field(buf,len, fp, hentry);
if (fclose(fp) == EOF) {
FILE_OP_ERROR(file, "fclose");
claws_unlink(file);
g_free(file);
return -1;
}
g_free(file);
if (val == -1)
return -1;
return 0;
}
HeaderEntry *procheader_entries_from_str(const gchar *str)
{
HeaderEntry *entries = NULL, *he;
int numh = 0, i = 0;
gchar **names = NULL;
const gchar *s = str;
if (s == NULL) {
return NULL;
}
while (*s != '\0') {
if (*s == ' ') ++numh;
++s;
}
if (numh == 0) {
return NULL;
}
entries = g_new0(HeaderEntry, numh + 1); /* room for last NULL */
s = str;
++s; /* skip first space */
names = g_strsplit(s, " ", numh);
he = entries;
while (names[i]) {
he->name = g_strdup_printf("%s:", names[i]);
he->body = NULL;
he->unfold = FALSE;
++i, ++he;
}
he->name = NULL;
g_strfreev(names);
return entries;
}
void procheader_entries_free (HeaderEntry *entries)
{
if (entries != NULL) {
HeaderEntry *he = entries;
while (he->name != NULL) {
g_free(he->name);
if (he->body != NULL)
g_free(he->body);
++he;
}
g_free(entries);
}
}
gboolean procheader_header_is_internal(const gchar *hdr_name)
{
const gchar *internal_hdrs[] = {
"AF:", "NF:", "PS:", "SRH:", "SFN:", "DSR:", "MID:", "CFG:",
"PT:", "S:", "RQ:", "SSV:", "NSV:", "SSH:", "R:", "MAID:",
"SCF:", "RMID:", "FMID:", "NAID:",
"X-Claws-Account-Id:",
"X-Claws-Sign:",
"X-Claws-Encrypt:",
"X-Claws-Privacy-System:",
"X-Claws-Auto-Wrapping:",
"X-Claws-Auto-Indent:",
"X-Claws-End-Special-Headers:",
"X-Sylpheed-Account-Id:",
"X-Sylpheed-Sign:",
"X-Sylpheed-Encrypt:",
"X-Sylpheed-Privacy-System:",
"X-Sylpheed-End-Special-Headers:",
NULL
};
int i;
for (i = 0; internal_hdrs[i]; i++) {
if (!strcmp(hdr_name, internal_hdrs[i]))
return TRUE;
}
return FALSE;
}
| ferdv/claws | src/procheader.c | C | gpl-3.0 | 28,320 |
../../../linux-headers-3.0.0-12/include/linux/ide.h | Alberto-Beralix/Beralix | i386-squashfs-root/usr/src/linux-headers-3.0.0-12-generic/include/linux/ide.h | C | gpl-3.0 | 51 |
package telinc.telicraft.util;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.ChatMessageComponent;
import net.minecraft.util.StatCollector;
public class PetrifyDamageSource extends TelicraftDamageSource {
protected EntityLivingBase entity;
protected PetrifyDamageSource(EntityLivingBase par1EntityLivingBase) {
super("petrify");
this.setDamageAllowedInCreativeMode();
this.setDamageBypassesArmor();
this.entity = par1EntityLivingBase;
}
@Override
public Entity getEntity() {
return this.entity;
}
@Override
public ChatMessageComponent getDeathMessage(EntityLivingBase par1EntityLivingBase) {
EntityLivingBase attacker = par1EntityLivingBase.func_94060_bK();
String deathSelf = this.getRawDeathMessage();
String deathPlayer = deathSelf + ".player";
return attacker != null && StatCollector.func_94522_b(deathPlayer) ? ChatMessageComponent.func_111082_b(deathPlayer, new Object[]{par1EntityLivingBase.getTranslatedEntityName(), attacker.getTranslatedEntityName()}) : ChatMessageComponent.func_111082_b(deathSelf, new Object[]{par1EntityLivingBase.getTranslatedEntityName()});
}
}
| telinc1/Telicraft | telicraft_common/telinc/telicraft/util/PetrifyDamageSource.java | Java | gpl-3.0 | 1,253 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Fri Dec 04 23:17:14 GMT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 5.4.0 API)</title>
<meta name="date" content="2015-12-04">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory (Solr 5.4.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/update/processor/class-use/ParseBooleanFieldUpdateProcessorFactory.html" target="_top">Frames</a></li>
<li><a href="ParseBooleanFieldUpdateProcessorFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory" class="title">Uses of Class<br>org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.update.processor.ParseBooleanFieldUpdateProcessorFactory</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/update/processor/class-use/ParseBooleanFieldUpdateProcessorFactory.html" target="_top">Frames</a></li>
<li><a href="ParseBooleanFieldUpdateProcessorFactory.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| jmmnn/linksSDGs | solr-5.4.0/docs/solr-core/org/apache/solr/update/processor/class-use/ParseBooleanFieldUpdateProcessorFactory.html | HTML | gpl-3.0 | 5,185 |
$Name = 'VyOS'
$SwitchName = 'Internal'
$HardDiskSize = 2GB
$HDPath = 'E:\Hyper-V\Virtual Hard Disks'+'\'+$Name+'.vhdx'
$Generation = '1'
$ISO_Path = 'D:\ISOs\vyos-1.1.6-amd64.iso'
New-VM -Name $Name -SwitchName $SwitchName `
-NewVHDSizeBytes $HardDiskSize `
-NewVHDPath $HDPath -Generation $Generation -MemoryStartupBytes 512MB
Add-VMDvdDrive -VMName $Name -Path $ISO_Path
Add-VMNetworkAdapter -VMName $Name -SwitchName External | Duffney/IAC-DSC | Hyper-V/Provision-VirtualRouter.ps1 | PowerShell | gpl-3.0 | 435 |
<?php namespace Darryldecode\Cart;
/**
* Created by PhpStorm.
* User: darryl
* Date: 1/15/2015
* Time: 9:46 PM
*/
use Illuminate\Support\Collection;
class CartConditionCollection extends Collection {
} | vijaysebastian/bill | vendor/darryldecode/cart/src/Darryldecode/Cart/CartConditionCollection.php | PHP | gpl-3.0 | 210 |
<!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">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>GNU Radio 7f75d35b C++ API: volk_32fc_x2_square_dist_32f_a.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">GNU Radio 7f75d35b C++ API
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('volk__32fc__x2__square__dist__32f__a_8h.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">volk_32fc_x2_square_dist_32f_a.h</div> </div>
</div><!--header-->
<div class="contents">
<a href="volk__32fc__x2__square__dist__32f__a_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="preprocessor">#ifndef INCLUDED_volk_32fc_x2_square_dist_32f_a_H</span>
<a name="l00002"></a>00002 <span class="preprocessor"></span><span class="preprocessor">#define INCLUDED_volk_32fc_x2_square_dist_32f_a_H</span>
<a name="l00003"></a>00003 <span class="preprocessor"></span>
<a name="l00004"></a>00004 <span class="preprocessor">#include<<a class="code" href="inttypes_8h.html">inttypes.h</a>></span>
<a name="l00005"></a>00005 <span class="preprocessor">#include<stdio.h></span>
<a name="l00006"></a>00006 <span class="preprocessor">#include<<a class="code" href="volk__complex_8h.html">volk/volk_complex.h</a>></span>
<a name="l00007"></a>00007
<a name="l00008"></a>00008 <span class="preprocessor">#ifdef LV_HAVE_SSE3</span>
<a name="l00009"></a>00009 <span class="preprocessor"></span><span class="preprocessor">#include<xmmintrin.h></span>
<a name="l00010"></a>00010 <span class="preprocessor">#include<pmmintrin.h></span>
<a name="l00011"></a>00011
<a name="l00012"></a>00012 <span class="keyword">static</span> <span class="keyword">inline</span> <span class="keywordtype">void</span> volk_32fc_x2_square_dist_32f_a_sse3(<span class="keywordtype">float</span>* target, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* src0, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* points, <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> num_bytes) {
<a name="l00013"></a>00013
<a name="l00014"></a>00014
<a name="l00015"></a>00015 __m128 xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7;
<a name="l00016"></a>00016
<a name="l00017"></a>00017 <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a> diff;
<a name="l00018"></a>00018 <span class="keywordtype">float</span> sq_dist;
<a name="l00019"></a>00019 <span class="keywordtype">int</span> bound = num_bytes >> 5;
<a name="l00020"></a>00020 <span class="keywordtype">int</span> leftovers0 = (num_bytes >> 4) & 1;
<a name="l00021"></a>00021 <span class="keywordtype">int</span> leftovers1 = (num_bytes >> 3) & 1;
<a name="l00022"></a>00022 <span class="keywordtype">int</span> i = 0;
<a name="l00023"></a>00023
<a name="l00024"></a>00024 xmm1 = _mm_setzero_ps();
<a name="l00025"></a>00025 xmm1 = _mm_loadl_pi(xmm1, (__m64*)src0);
<a name="l00026"></a>00026 xmm2 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[0]);
<a name="l00027"></a>00027 xmm1 = _mm_movelh_ps(xmm1, xmm1);
<a name="l00028"></a>00028 xmm3 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[2]);
<a name="l00029"></a>00029
<a name="l00030"></a>00030
<a name="l00031"></a>00031 <span class="keywordflow">for</span>(; i < bound - 1; ++i) {
<a name="l00032"></a>00032 xmm4 = _mm_sub_ps(xmm1, xmm2);
<a name="l00033"></a>00033 xmm5 = _mm_sub_ps(xmm1, xmm3);
<a name="l00034"></a>00034 points += 4;
<a name="l00035"></a>00035 xmm6 = _mm_mul_ps(xmm4, xmm4);
<a name="l00036"></a>00036 xmm7 = _mm_mul_ps(xmm5, xmm5);
<a name="l00037"></a>00037
<a name="l00038"></a>00038 xmm2 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[0]);
<a name="l00039"></a>00039
<a name="l00040"></a>00040 xmm4 = _mm_hadd_ps(xmm6, xmm7);
<a name="l00041"></a>00041
<a name="l00042"></a>00042 xmm3 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[2]);
<a name="l00043"></a>00043
<a name="l00044"></a>00044 _mm_store_ps(target, xmm4);
<a name="l00045"></a>00045
<a name="l00046"></a>00046 target += 4;
<a name="l00047"></a>00047
<a name="l00048"></a>00048 }
<a name="l00049"></a>00049
<a name="l00050"></a>00050 xmm4 = _mm_sub_ps(xmm1, xmm2);
<a name="l00051"></a>00051 xmm5 = _mm_sub_ps(xmm1, xmm3);
<a name="l00052"></a>00052
<a name="l00053"></a>00053
<a name="l00054"></a>00054
<a name="l00055"></a>00055 points += 4;
<a name="l00056"></a>00056 xmm6 = _mm_mul_ps(xmm4, xmm4);
<a name="l00057"></a>00057 xmm7 = _mm_mul_ps(xmm5, xmm5);
<a name="l00058"></a>00058
<a name="l00059"></a>00059 xmm4 = _mm_hadd_ps(xmm6, xmm7);
<a name="l00060"></a>00060
<a name="l00061"></a>00061 _mm_store_ps(target, xmm4);
<a name="l00062"></a>00062
<a name="l00063"></a>00063 target += 4;
<a name="l00064"></a>00064
<a name="l00065"></a>00065 <span class="keywordflow">for</span>(i = 0; i < leftovers0; ++i) {
<a name="l00066"></a>00066
<a name="l00067"></a>00067 xmm2 = _mm_load_ps((<span class="keywordtype">float</span>*)&points[0]);
<a name="l00068"></a>00068
<a name="l00069"></a>00069 xmm4 = _mm_sub_ps(xmm1, xmm2);
<a name="l00070"></a>00070
<a name="l00071"></a>00071 points += 2;
<a name="l00072"></a>00072
<a name="l00073"></a>00073 xmm6 = _mm_mul_ps(xmm4, xmm4);
<a name="l00074"></a>00074
<a name="l00075"></a>00075 xmm4 = _mm_hadd_ps(xmm6, xmm6);
<a name="l00076"></a>00076
<a name="l00077"></a>00077 _mm_storeh_pi((__m64*)target, xmm4);
<a name="l00078"></a>00078
<a name="l00079"></a>00079 target += 2;
<a name="l00080"></a>00080 }
<a name="l00081"></a>00081
<a name="l00082"></a>00082 <span class="keywordflow">for</span>(i = 0; i < leftovers1; ++i) {
<a name="l00083"></a>00083
<a name="l00084"></a>00084 diff = src0[0] - points[0];
<a name="l00085"></a>00085
<a name="l00086"></a>00086 sq_dist = <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) * <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) + <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff) * <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff);
<a name="l00087"></a>00087
<a name="l00088"></a>00088 target[0] = sq_dist;
<a name="l00089"></a>00089 }
<a name="l00090"></a>00090 }
<a name="l00091"></a>00091
<a name="l00092"></a>00092 <span class="preprocessor">#endif </span><span class="comment">/*LV_HAVE_SSE3*/</span>
<a name="l00093"></a>00093
<a name="l00094"></a>00094 <span class="preprocessor">#ifdef LV_HAVE_GENERIC</span>
<a name="l00095"></a>00095 <span class="preprocessor"></span><span class="keyword">static</span> <span class="keyword">inline</span> <span class="keywordtype">void</span> volk_32fc_x2_square_dist_32f_a_generic(<span class="keywordtype">float</span>* target, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* src0, <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a>* points, <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> num_bytes) {
<a name="l00096"></a>00096 <a class="code" href="volk__complex_8h.html#ace50e1c8ef539cdeee04bc86f0e99169">lv_32fc_t</a> diff;
<a name="l00097"></a>00097 <span class="keywordtype">float</span> sq_dist;
<a name="l00098"></a>00098 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> i = 0;
<a name="l00099"></a>00099
<a name="l00100"></a>00100 <span class="keywordflow">for</span>(; i < num_bytes >> 3; ++i) {
<a name="l00101"></a>00101 diff = src0[0] - points[i];
<a name="l00102"></a>00102
<a name="l00103"></a>00103 sq_dist = <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) * <a class="code" href="volk__complex_8h.html#a9e9cedc79eafa6db42f03878b5a5ba47">lv_creal</a>(diff) + <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff) * <a class="code" href="volk__complex_8h.html#a1f58129a88c382411b2e8997c8dd89e4">lv_cimag</a>(diff);
<a name="l00104"></a>00104
<a name="l00105"></a>00105 target[i] = sq_dist;
<a name="l00106"></a>00106 }
<a name="l00107"></a>00107 }
<a name="l00108"></a>00108
<a name="l00109"></a>00109 <span class="preprocessor">#endif </span><span class="comment">/*LV_HAVE_GENERIC*/</span>
<a name="l00110"></a>00110
<a name="l00111"></a>00111
<a name="l00112"></a>00112 <span class="preprocessor">#endif </span><span class="comment">/*INCLUDED_volk_32fc_x2_square_dist_32f_a_H*/</span>
</pre></div></div><!-- contents -->
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="volk__32fc__x2__square__dist__32f__a_8h.html">volk_32fc_x2_square_dist_32f_a.h</a> </li>
<li class="footer">Generated on Thu Sep 27 2012 10:49:26 for GNU Radio 7f75d35b C++ API by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.6.1 </li>
</ul>
</div>
</body>
</html>
| katsikas/gnuradio | build/docs/doxygen/html/volk__32fc__x2__square__dist__32f__a_8h_source.html | HTML | gpl-3.0 | 10,631 |
package com.github.dozzatq.phoenix.advertising;
/**
* Created by Rodion Bartoshik on 04.07.2017.
*/
interface Reflector {
FactoryAd reflection();
int state();
}
| dozzatq/Phoenix | mylibrary/src/main/java/com/github/dozzatq/phoenix/advertising/Reflector.java | Java | gpl-3.0 | 173 |
/*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JasperReports is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.web.commands;
import net.sf.jasperreports.engine.JRConstants;
import net.sf.jasperreports.web.JRInteractiveException;
/**
* @author Narcis Marcu ([email protected])
*/
public class CommandException extends JRInteractiveException
{
private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID;
public CommandException(String message) {
super(message);
}
public CommandException(Throwable t) {
super(t);
}
public CommandException(String message, Throwable t) {
super(message, t);
}
public CommandException(String messageKey, Object[] args, Throwable t)
{
super(messageKey, args, t);
}
public CommandException(String messageKey, Object[] args)
{
super(messageKey, args);
}
}
| aleatorio12/ProVentasConnector | jasperreports-6.2.1-project/jasperreports-6.2.1/src/net/sf/jasperreports/web/commands/CommandException.java | Java | gpl-3.0 | 1,750 |
#
# LMirror is Copyright (C) 2010 Robert Collins <[email protected]>
#
# LMirror is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
#
# In the LMirror source tree the file COPYING.txt contains the GNU General Public
# License version 3.
#
"""Tests for logging support code."""
from StringIO import StringIO
import logging
import os.path
import time
from l_mirror import logging_support
from l_mirror.tests import ResourcedTestCase
from l_mirror.tests.logging_resource import LoggingResourceManager
from l_mirror.tests.stubpackage import TempDirResource
class TestLoggingSetup(ResourcedTestCase):
resources = [('logging', LoggingResourceManager())]
def test_configure_logging_sets_converter(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out)
self.assertEqual(c_log, logging.root.handlers[0])
self.assertEqual(f_log, logging.root.handlers[1])
self.assertEqual(None, c_log.formatter)
self.assertEqual(formatter, f_log.formatter)
self.assertEqual(time.gmtime, formatter.converter)
self.assertEqual("%Y-%m-%d %H:%M:%SZ", formatter.datefmt)
self.assertEqual(logging.StreamHandler, c_log.__class__)
self.assertEqual(out, c_log.stream)
self.assertEqual(logging.FileHandler, f_log.__class__)
self.assertEqual(os.path.expanduser("~/.cache/lmirror/log"), f_log.baseFilename)
def test_can_supply_filename_None(self):
out = StringIO()
c_log, f_log, formatter = logging_support.configure_logging(out, None)
self.assertEqual(None, f_log)
| rbtcollins/lmirror | l_mirror/tests/test_logging_support.py | Python | gpl-3.0 | 2,180 |
namespace _03BarracksWars.Contracts
{
public interface IRunnable
{
void Run();
}
}
| PlamenHP/Softuni | OOP Advanced/Reflection - Exercise/BarracksWars/Contracts/IRunnable.cs | C# | gpl-3.0 | 106 |
using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using System;
using System.Web.Http;
using TodoList.Api.Infrastructure.Authentication;
[assembly: OwinStartup(typeof(TodoList.Api.Startup))]
namespace TodoList.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
//SwaggerConfig.Register();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
//Rest of code is here;
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
} | jsolarz/angular-base | TodoListApi/Startup.cs | C# | gpl-3.0 | 1,323 |
\alpha
\beta
\gamma
\delta
\epsilon
\zeta
\eta
\theta
\iota
\kappa
\lambda
\mu
\nu
\xi
\omicron
\pi
\rho
\sigma
\tau
\upsilon
\phi
\chi
\psi
\omega
| mhameed/LaTeXLex | utf8Test/replacement-test.tex | TeX | gpl-3.0 | 148 |
/*
* Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
* Copyright (C) 1999-2015 Hiroyuki Yamamoto and the Claws Mail team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* alfons - all folder item specific settings should migrate into
* folderlist.xml!!! the old folderitemrc file will only serve for a few
* versions (for compatibility) */
#ifdef HAVE_CONFIG_H
# include "config.h"
#include "claws-features.h"
#endif
#include "defs.h"
#include <glib.h>
#include <glib/gi18n.h>
#include "folder.h"
#include "alertpanel.h"
#include "prefs_folder_item.h"
#include "folderview.h"
#include "folder.h"
#include "summaryview.h"
#include "menu.h"
#include "account.h"
#include "prefs_gtk.h"
#include "manage_window.h"
#include "utils.h"
#include "addr_compl.h"
#include "prefs_common.h"
#include "gtkutils.h"
#include "filtering.h"
#include "folder_item_prefs.h"
#include "gtk/colorsel.h"
#include "string_match.h"
#include "quote_fmt.h"
#include "combobox.h"
#if USE_ENCHANT
#include "gtkaspell.h"
#endif
#define ASSIGN_STRING(string, value) \
{ \
g_free(string); \
string = (value); \
}
typedef struct _FolderItemGeneralPage FolderItemGeneralPage;
typedef struct _FolderItemComposePage FolderItemComposePage;
typedef struct _FolderItemTemplatesPage FolderItemTemplatesPage;
static gboolean can_save = TRUE;
struct _FolderItemGeneralPage
{
PrefsPage page;
FolderItem *item;
GtkWidget *table;
GtkWidget *no_save_warning;
GtkWidget *folder_type;
#ifndef G_OS_WIN32
GtkWidget *checkbtn_simplify_subject;
GtkWidget *entry_simplify_subject;
GtkWidget *entry_regexp_test_string;
GtkWidget *entry_regexp_test_result;
#endif
GtkWidget *checkbtn_folder_chmod;
GtkWidget *entry_folder_chmod;
GtkWidget *folder_color_btn;
GtkWidget *checkbtn_enable_processing;
GtkWidget *checkbtn_enable_processing_when_opening;
GtkWidget *checkbtn_newmailcheck;
GtkWidget *checkbtn_offlinesync;
GtkWidget *label_offlinesync;
GtkWidget *entry_offlinesync;
GtkWidget *label_end_offlinesync;
GtkWidget *checkbtn_remove_old_offlinesync;
GtkWidget *promote_html_part;
/* apply to sub folders */
#ifndef G_OS_WIN32
GtkWidget *simplify_subject_rec_checkbtn;
#endif
GtkWidget *folder_chmod_rec_checkbtn;
GtkWidget *folder_color_rec_checkbtn;
GtkWidget *enable_processing_rec_checkbtn;
GtkWidget *enable_processing_when_opening_rec_checkbtn;
GtkWidget *newmailcheck_rec_checkbtn;
GtkWidget *offlinesync_rec_checkbtn;
GtkWidget *promote_html_part_rec_checkbtn;
gint folder_color;
};
struct _FolderItemComposePage
{
PrefsPage page;
FolderItem *item;
GtkWidget *window;
GtkWidget *table;
GtkWidget *no_save_warning;
GtkWidget *checkbtn_request_return_receipt;
GtkWidget *checkbtn_save_copy_to_folder;
GtkWidget *checkbtn_default_to;
GtkWidget *entry_default_to;
GtkWidget *checkbtn_default_reply_to;
GtkWidget *entry_default_reply_to;
GtkWidget *checkbtn_default_cc;
GtkWidget *entry_default_cc;
GtkWidget *checkbtn_default_bcc;
GtkWidget *entry_default_bcc;
GtkWidget *checkbtn_default_replyto;
GtkWidget *entry_default_replyto;
GtkWidget *checkbtn_enable_default_account;
GtkWidget *optmenu_default_account;
#if USE_ENCHANT
GtkWidget *checkbtn_enable_default_dictionary;
GtkWidget *checkbtn_enable_default_alt_dictionary;
GtkWidget *combo_default_dictionary;
GtkWidget *combo_default_alt_dictionary;
#endif
/* apply to sub folders */
GtkWidget *request_return_receipt_rec_checkbtn;
GtkWidget *save_copy_to_folder_rec_checkbtn;
GtkWidget *default_to_rec_checkbtn;
GtkWidget *default_reply_to_rec_checkbtn;
GtkWidget *default_cc_rec_checkbtn;
GtkWidget *default_bcc_rec_checkbtn;
GtkWidget *default_replyto_rec_checkbtn;
GtkWidget *default_account_rec_checkbtn;
#if USE_ENCHANT
GtkWidget *default_dictionary_rec_checkbtn;
GtkWidget *default_alt_dictionary_rec_checkbtn;
#endif
};
struct _FolderItemTemplatesPage
{
PrefsPage page;
FolderItem *item;
GtkWidget *window;
GtkWidget *table;
GtkWidget *checkbtn_compose_with_format;
GtkWidget *compose_override_from_format;
GtkWidget *compose_subject_format;
GtkWidget *compose_body_format;
GtkWidget *checkbtn_reply_with_format;
GtkWidget *reply_quotemark;
GtkWidget *reply_override_from_format;
GtkWidget *reply_body_format;
GtkWidget *checkbtn_forward_with_format;
GtkWidget *forward_quotemark;
GtkWidget *forward_override_from_format;
GtkWidget *forward_body_format;
/* apply to sub folders */
GtkWidget *new_msg_format_rec_checkbtn;
GtkWidget *reply_format_rec_checkbtn;
GtkWidget *forward_format_rec_checkbtn;
};
static void general_save_folder_prefs(FolderItem *folder, FolderItemGeneralPage *page);
static void compose_save_folder_prefs(FolderItem *folder, FolderItemComposePage *page);
static void templates_save_folder_prefs(FolderItem *folder, FolderItemTemplatesPage *page);
static gboolean general_save_recurse_func(GNode *node, gpointer data);
static gboolean compose_save_recurse_func(GNode *node, gpointer data);
static gboolean templates_save_recurse_func(GNode *node, gpointer data);
static gint prefs_folder_item_chmod_mode (gchar *folder_chmod);
static void folder_color_set_dialog(GtkWidget *widget, gpointer data);
static void clean_cache_cb(GtkWidget *widget, gpointer data);
#ifndef G_OS_WIN32
static void folder_regexp_test_cb(GtkWidget *widget, gpointer data);
static void folder_regexp_set_subject_example_cb(GtkWidget *widget, gpointer data);
#endif
#define SAFE_STRING(str) \
(str) ? (str) : ""
static void prefs_folder_item_general_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_;
FolderItem *item = (FolderItem *) data;
guint rowcount;
GtkWidget *table;
GtkWidget *hbox, *hbox2, *hbox_spc;
GtkWidget *label;
GtkListStore *folder_type_menu;
GtkWidget *folder_type;
GtkTreeIter iter;
GtkWidget *dummy_checkbtn, *clean_cache_btn;
SpecialFolderItemType type;
GtkWidget *no_save_warning = NULL;
#ifndef G_OS_WIN32
GtkWidget *checkbtn_simplify_subject;
GtkWidget *entry_simplify_subject;
GtkWidget *label_regexp_test;
GtkWidget *entry_regexp_test_string;
GtkWidget *label_regexp_result;
GtkWidget *entry_regexp_test_result;
#endif
GtkWidget *checkbtn_folder_chmod;
GtkWidget *entry_folder_chmod;
GtkWidget *folder_color;
GtkWidget *folder_color_btn;
GtkWidget *checkbtn_enable_processing;
GtkWidget *checkbtn_enable_processing_when_opening;
GtkWidget *checkbtn_newmailcheck;
GtkWidget *checkbtn_offlinesync;
GtkWidget *label_offlinesync;
GtkWidget *entry_offlinesync;
GtkWidget *label_end_offlinesync;
GtkWidget *checkbtn_remove_old_offlinesync;
GtkWidget *promote_html_part;
GtkListStore *promote_html_part_menu;
#ifndef G_OS_WIN32
GtkWidget *simplify_subject_rec_checkbtn;
#endif
GtkWidget *folder_chmod_rec_checkbtn;
GtkWidget *folder_color_rec_checkbtn;
GtkWidget *enable_processing_rec_checkbtn;
GtkWidget *enable_processing_when_opening_rec_checkbtn;
GtkWidget *newmailcheck_rec_checkbtn;
GtkWidget *offlinesync_rec_checkbtn;
GtkWidget *promote_html_part_rec_checkbtn;
page->item = item;
/* Table */
table = gtk_table_new(12, 3, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), VBOX_BORDER);
gtk_table_set_row_spacings(GTK_TABLE(table), 4);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
rowcount = 0;
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_table_attach(GTK_TABLE(table), no_save_warning, 0, 3,
rowcount, rowcount + 1, GTK_FILL, 0, 0, 0);
rowcount++;
}
/* Apply to subfolders */
label = gtk_label_new(_("Apply to\nsubfolders"));
gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* folder_type */
folder_type = gtkut_sc_combobox_create(NULL, FALSE);
gtk_widget_show (folder_type);
type = F_NORMAL;
if (item->stype == F_INBOX)
type = F_INBOX;
else if (folder_has_parent_of_type(item, F_OUTBOX))
type = F_OUTBOX;
else if (folder_has_parent_of_type(item, F_DRAFT))
type = F_DRAFT;
else if (folder_has_parent_of_type(item, F_QUEUE))
type = F_QUEUE;
else if (folder_has_parent_of_type(item, F_TRASH))
type = F_TRASH;
folder_type_menu = GTK_LIST_STORE(gtk_combo_box_get_model(
GTK_COMBO_BOX(folder_type)));
COMBOBOX_ADD (folder_type_menu, _("Normal"), F_NORMAL);
COMBOBOX_ADD (folder_type_menu, _("Inbox"), F_INBOX);
COMBOBOX_ADD (folder_type_menu, _("Outbox"), F_OUTBOX);
COMBOBOX_ADD (folder_type_menu, _("Drafts"), F_DRAFT);
COMBOBOX_ADD (folder_type_menu, _("Queue"), F_QUEUE);
COMBOBOX_ADD (folder_type_menu, _("Trash"), F_TRASH);
combobox_select_by_data(GTK_COMBO_BOX(folder_type), type);
dummy_checkbtn = gtk_check_button_new();
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(dummy_checkbtn), type != F_INBOX);
gtk_widget_set_sensitive(dummy_checkbtn, FALSE);
if (type == item->stype && type == F_NORMAL)
gtk_widget_set_sensitive(folder_type, TRUE);
else
gtk_widget_set_sensitive(folder_type, FALSE);
label = gtk_label_new(_("Folder type"));
gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_table_attach(GTK_TABLE(table), folder_type, 1, 2,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_table_attach(GTK_TABLE(table), dummy_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#ifndef G_OS_WIN32
/* Simplify Subject */
checkbtn_simplify_subject = gtk_check_button_new_with_label(_("Simplify Subject RegExp"));
gtk_table_attach(GTK_TABLE(table), checkbtn_simplify_subject, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_simplify_subject),
item->prefs->enable_simplify_subject);
g_signal_connect(G_OBJECT(checkbtn_simplify_subject), "toggled",
G_CALLBACK(folder_regexp_set_subject_example_cb), page);
entry_simplify_subject = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_simplify_subject, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_simplify_subject);
gtk_entry_set_text(GTK_ENTRY(entry_simplify_subject),
SAFE_STRING(item->prefs->simplify_subject_regexp));
g_signal_connect(G_OBJECT(entry_simplify_subject), "changed",
G_CALLBACK(folder_regexp_test_cb), page);
simplify_subject_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), simplify_subject_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Test string */
label_regexp_test = gtk_label_new(_("Test string:"));
gtk_misc_set_alignment(GTK_MISC(label_regexp_test), 1, 0.5);
gtk_table_attach(GTK_TABLE(table), label_regexp_test, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, label_regexp_test);
entry_regexp_test_string = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_regexp_test_string, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_regexp_test_string);
g_signal_connect(G_OBJECT(entry_regexp_test_string), "changed",
G_CALLBACK(folder_regexp_test_cb), page);
rowcount++;
/* Test result */
label_regexp_result = gtk_label_new(_("Result:"));
gtk_misc_set_alignment(GTK_MISC(label_regexp_result), 1, 0.5);
gtk_table_attach(GTK_TABLE(table), label_regexp_result, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, label_regexp_result);
entry_regexp_test_result = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_regexp_test_result, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_simplify_subject, entry_regexp_test_result);
gtk_editable_set_editable(GTK_EDITABLE(entry_regexp_test_result), FALSE);
rowcount++;
#endif
/* Folder chmod */
checkbtn_folder_chmod = gtk_check_button_new_with_label(_("Folder chmod"));
gtk_table_attach(GTK_TABLE(table), checkbtn_folder_chmod, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_folder_chmod),
item->prefs->enable_folder_chmod);
entry_folder_chmod = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_folder_chmod, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_folder_chmod, entry_folder_chmod);
if (item->prefs->folder_chmod) {
gchar *buf;
buf = g_strdup_printf("%o", item->prefs->folder_chmod);
gtk_entry_set_text(GTK_ENTRY(entry_folder_chmod), buf);
g_free(buf);
}
folder_chmod_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), folder_chmod_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Folder color */
folder_color = gtk_label_new(_("Folder color"));
gtk_misc_set_alignment(GTK_MISC(folder_color), 0, 0.5);
gtk_table_attach(GTK_TABLE(table), folder_color, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
hbox = gtk_hbox_new(FALSE, 0);
gtk_table_attach(GTK_TABLE(table), hbox, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
folder_color_btn = gtk_button_new_with_label("");
gtk_widget_set_size_request(folder_color_btn, 36, 26);
gtk_box_pack_start (GTK_BOX(hbox), folder_color_btn, FALSE, FALSE, 0);
CLAWS_SET_TIP(folder_color_btn,
_("Pick color for folder"));
page->folder_color = item->prefs->color;
g_signal_connect(G_OBJECT(folder_color_btn), "clicked",
G_CALLBACK(folder_color_set_dialog),
page);
gtkut_set_widget_bgcolor_rgb(folder_color_btn, item->prefs->color);
folder_color_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), folder_color_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Enable processing at startup */
checkbtn_enable_processing =
gtk_check_button_new_with_label(_("Run Processing rules at start-up"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_processing, 0, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_processing),
item->prefs->enable_processing);
enable_processing_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), enable_processing_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Enable processing rules when opening folder */
checkbtn_enable_processing_when_opening =
gtk_check_button_new_with_label(_("Run Processing rules when opening"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_processing_when_opening, 0, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_processing_when_opening),
item->prefs->enable_processing_when_opening);
enable_processing_when_opening_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), enable_processing_when_opening_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Check folder for new mail */
checkbtn_newmailcheck = gtk_check_button_new_with_label(_("Scan for new mail"));
CLAWS_SET_TIP(checkbtn_newmailcheck,
_("Turn this option on if mail is delivered directly "
"to this folder by server side filtering on IMAP or "
"by an external application"));
gtk_table_attach(GTK_TABLE(table), checkbtn_newmailcheck, 0, 2,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_newmailcheck),
item->prefs->newmailcheck);
newmailcheck_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), newmailcheck_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Select HTML part by default? */
hbox = gtk_hbox_new (FALSE, 2);
gtk_widget_show (hbox);
gtk_table_attach (GTK_TABLE(table), hbox, 0, 2,
rowcount, rowcount+1, GTK_FILL, GTK_FILL, 0, 0);
label = gtk_label_new(_("Select the HTML part of multipart messages"));
gtk_widget_show (label);
gtk_box_pack_start (GTK_BOX(hbox), label, FALSE, FALSE, 0);
promote_html_part = gtkut_sc_combobox_create (NULL, FALSE);
gtk_widget_show (promote_html_part);
gtk_box_pack_start (GTK_BOX(hbox), promote_html_part, FALSE, FALSE, 0);
promote_html_part_menu = GTK_LIST_STORE(gtk_combo_box_get_model(
GTK_COMBO_BOX(promote_html_part)));
COMBOBOX_ADD (promote_html_part_menu, _("Default"), HTML_PROMOTE_DEFAULT);
COMBOBOX_ADD (promote_html_part_menu, _("No"), HTML_PROMOTE_NEVER);
COMBOBOX_ADD (promote_html_part_menu, _("Yes"), HTML_PROMOTE_ALWAYS);
combobox_select_by_data(GTK_COMBO_BOX(promote_html_part),
item->prefs->promote_html_part);
CLAWS_SET_TIP(hbox, _("\"Default\" will follow global preference (found in /Preferences/"
"Message View/Text Options)"));
promote_html_part_rec_checkbtn = gtk_check_button_new();
gtk_widget_show (promote_html_part_rec_checkbtn);
gtk_table_attach(GTK_TABLE(table), promote_html_part_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Synchronise folder for offline use */
checkbtn_offlinesync = gtk_check_button_new_with_label(_("Synchronise for offline use"));
gtk_table_attach(GTK_TABLE(table), checkbtn_offlinesync, 0, 2,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
offlinesync_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), offlinesync_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
hbox = gtk_hbox_new (FALSE, 8);
gtk_widget_show (hbox);
gtk_table_attach(GTK_TABLE(table), hbox, 0, 3,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
rowcount++;
hbox_spc = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox_spc);
gtk_box_pack_start (GTK_BOX (hbox), hbox_spc, FALSE, FALSE, 0);
gtk_widget_set_size_request (hbox_spc, 12, -1);
label_offlinesync = gtk_label_new(_("Fetch message bodies from the last"));
gtk_widget_show (label_offlinesync);
gtk_box_pack_start (GTK_BOX (hbox), label_offlinesync, FALSE, FALSE, 0);
entry_offlinesync = gtk_entry_new();
gtk_widget_set_size_request (entry_offlinesync, 64, -1);
gtk_widget_show (entry_offlinesync);
CLAWS_SET_TIP(entry_offlinesync, _("0: all bodies"));
gtk_box_pack_start (GTK_BOX (hbox), entry_offlinesync, FALSE, FALSE, 0);
label_end_offlinesync = gtk_label_new(_("days"));
gtk_widget_show (label_end_offlinesync);
gtk_box_pack_start (GTK_BOX (hbox), label_end_offlinesync, FALSE, FALSE, 0);
checkbtn_remove_old_offlinesync = gtk_check_button_new_with_label(
_("Remove older messages bodies"));
hbox2 = gtk_hbox_new (FALSE, 8);
gtk_widget_show (hbox2);
gtk_table_attach(GTK_TABLE(table), hbox2, 0, 3,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
rowcount++;
hbox_spc = gtk_hbox_new (FALSE, 0);
gtk_widget_show (hbox_spc);
gtk_box_pack_start (GTK_BOX (hbox2), hbox_spc, FALSE, FALSE, 0);
gtk_widget_set_size_request (hbox_spc, 12, -1);
gtk_box_pack_start (GTK_BOX (hbox2), checkbtn_remove_old_offlinesync, FALSE, FALSE, 0);
SET_TOGGLE_SENSITIVITY (checkbtn_offlinesync, hbox);
SET_TOGGLE_SENSITIVITY (checkbtn_offlinesync, hbox2);
clean_cache_btn = gtk_button_new_with_label(_("Discard folder cache"));
gtk_widget_show (clean_cache_btn);
gtk_table_attach(GTK_TABLE(table), clean_cache_btn, 0, 1,
rowcount, rowcount+1, GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
g_signal_connect(G_OBJECT(clean_cache_btn), "clicked",
G_CALLBACK(clean_cache_cb),
page);
gtk_widget_show_all(table);
if (item->folder && (item->folder->klass->type != F_IMAP &&
item->folder->klass->type != F_NEWS)) {
item->prefs->offlinesync = TRUE;
item->prefs->offlinesync_days = 0;
item->prefs->remove_old_bodies = FALSE;
gtk_widget_set_sensitive(GTK_WIDGET(checkbtn_offlinesync),
FALSE);
gtk_widget_set_sensitive(GTK_WIDGET(offlinesync_rec_checkbtn),
FALSE);
gtk_widget_hide(GTK_WIDGET(checkbtn_offlinesync));
gtk_widget_hide(GTK_WIDGET(hbox));
gtk_widget_hide(GTK_WIDGET(hbox2));
gtk_widget_hide(GTK_WIDGET(offlinesync_rec_checkbtn));
gtk_widget_hide(GTK_WIDGET(clean_cache_btn));
}
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_offlinesync),
item->prefs->offlinesync);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_remove_old_offlinesync),
item->prefs->remove_old_bodies);
gtk_entry_set_text(GTK_ENTRY(entry_offlinesync), itos(item->prefs->offlinesync_days));
page->table = table;
page->folder_type = folder_type;
page->no_save_warning = no_save_warning;
#ifndef G_OS_WIN32
page->checkbtn_simplify_subject = checkbtn_simplify_subject;
page->entry_simplify_subject = entry_simplify_subject;
page->entry_regexp_test_string = entry_regexp_test_string;
page->entry_regexp_test_result = entry_regexp_test_result;
#endif
page->checkbtn_folder_chmod = checkbtn_folder_chmod;
page->entry_folder_chmod = entry_folder_chmod;
page->folder_color_btn = folder_color_btn;
page->checkbtn_enable_processing = checkbtn_enable_processing;
page->checkbtn_enable_processing_when_opening = checkbtn_enable_processing_when_opening;
page->checkbtn_newmailcheck = checkbtn_newmailcheck;
page->checkbtn_offlinesync = checkbtn_offlinesync;
page->label_offlinesync = label_offlinesync;
page->entry_offlinesync = entry_offlinesync;
page->label_end_offlinesync = label_end_offlinesync;
page->checkbtn_remove_old_offlinesync = checkbtn_remove_old_offlinesync;
page->promote_html_part = promote_html_part;
#ifndef G_OS_WIN32
page->simplify_subject_rec_checkbtn = simplify_subject_rec_checkbtn;
#endif
page->folder_chmod_rec_checkbtn = folder_chmod_rec_checkbtn;
page->folder_color_rec_checkbtn = folder_color_rec_checkbtn;
page->enable_processing_rec_checkbtn = enable_processing_rec_checkbtn;
page->enable_processing_when_opening_rec_checkbtn = enable_processing_when_opening_rec_checkbtn;
page->newmailcheck_rec_checkbtn = newmailcheck_rec_checkbtn;
page->offlinesync_rec_checkbtn = offlinesync_rec_checkbtn;
page->promote_html_part_rec_checkbtn = promote_html_part_rec_checkbtn;
page->page.widget = table;
#ifndef G_OS_WIN32
folder_regexp_set_subject_example_cb(NULL, page);
#endif
}
static void prefs_folder_item_general_destroy_widget_func(PrefsPage *page_)
{
/* FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_; */
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void general_save_folder_prefs(FolderItem *folder, FolderItemGeneralPage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gchar *buf;
gboolean all = FALSE, summary_update_needed = FALSE;
SpecialFolderItemType type = F_NORMAL;
FolderView *folderview = mainwindow_get_mainwindow()->folderview;
HTMLPromoteType promote_html_part = HTML_PROMOTE_DEFAULT;
if (folder->path == NULL)
return;
cm_return_if_fail(prefs != NULL);
if (page->item == folder)
all = TRUE;
type = combobox_get_active_data(GTK_COMBO_BOX(page->folder_type));
if (all && folder->stype != type && page->item->parent_stype == F_NORMAL) {
folder_item_change_type(folder, type);
summary_update_needed = TRUE;
}
promote_html_part =
combobox_get_active_data(GTK_COMBO_BOX(page->promote_html_part));
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->promote_html_part_rec_checkbtn)))
prefs->promote_html_part = promote_html_part;
#ifndef G_OS_WIN32
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->simplify_subject_rec_checkbtn))) {
gboolean old_simplify_subject = prefs->enable_simplify_subject;
int regexp_diffs = strcmp2(prefs->simplify_subject_regexp, gtk_editable_get_chars(
GTK_EDITABLE(page->entry_simplify_subject), 0, -1));
prefs->enable_simplify_subject =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_simplify_subject));
ASSIGN_STRING(prefs->simplify_subject_regexp,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_simplify_subject), 0, -1));
if (old_simplify_subject != prefs->enable_simplify_subject || regexp_diffs != 0)
summary_update_needed = TRUE;
}
#endif
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_chmod_rec_checkbtn))) {
prefs->enable_folder_chmod =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_folder_chmod));
buf = gtk_editable_get_chars(GTK_EDITABLE(page->entry_folder_chmod), 0, -1);
prefs->folder_chmod = prefs_folder_item_chmod_mode(buf);
g_free(buf);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_color_rec_checkbtn))) {
int old_color = prefs->color;
prefs->color = page->folder_color;
/* update folder view */
if (prefs->color != old_color)
folder_item_update(folder, F_ITEM_UPDATE_MSGCNT);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_rec_checkbtn))) {
prefs->enable_processing =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_processing));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_when_opening_rec_checkbtn))) {
prefs->enable_processing_when_opening =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_processing_when_opening));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->newmailcheck_rec_checkbtn))) {
prefs->newmailcheck =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_newmailcheck));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->offlinesync_rec_checkbtn))) {
prefs->offlinesync =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_offlinesync));
prefs->offlinesync_days =
atoi(gtk_entry_get_text(GTK_ENTRY(page->entry_offlinesync)));
prefs->remove_old_bodies =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_remove_old_offlinesync));
}
folder_item_prefs_save_config(folder);
if (folder->opened && summary_update_needed) {
summary_set_prefs_from_folderitem(folderview->summaryview, folder);
summary_show(folderview->summaryview, folder);
}
}
static gboolean general_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
general_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) &&
!(
#ifndef G_OS_WIN32
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->simplify_subject_rec_checkbtn)) ||
#endif
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_chmod_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->folder_color_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->enable_processing_when_opening_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->newmailcheck_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->offlinesync_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->promote_html_part_rec_checkbtn))
))
return TRUE;
else
return FALSE;
}
static void prefs_folder_item_general_save_func(PrefsPage *page_)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, general_save_recurse_func, page);
main_window_set_menu_sensitive(mainwindow_get_mainwindow());
}
static RecvProtocol item_protocol(FolderItem *item)
{
if (!item)
return A_NONE;
if (!item->folder)
return A_NONE;
if (!item->folder->account)
return A_NONE;
return item->folder->account->protocol;
}
static void prefs_folder_item_compose_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
FolderItem *item = (FolderItem *) data;
guint rowcount;
gchar *text = NULL;
GtkWidget *table;
GtkWidget *label;
GtkWidget *no_save_warning = NULL;
GtkWidget *checkbtn_request_return_receipt = NULL;
GtkWidget *checkbtn_save_copy_to_folder = NULL;
GtkWidget *checkbtn_default_to = NULL;
GtkWidget *entry_default_to = NULL;
GtkWidget *checkbtn_default_reply_to = NULL;
GtkWidget *entry_default_reply_to = NULL;
GtkWidget *checkbtn_default_cc = NULL;
GtkWidget *entry_default_cc = NULL;
GtkWidget *checkbtn_default_bcc = NULL;
GtkWidget *entry_default_bcc = NULL;
GtkWidget *checkbtn_default_replyto = NULL;
GtkWidget *entry_default_replyto = NULL;
GtkWidget *checkbtn_enable_default_account = NULL;
GtkWidget *optmenu_default_account = NULL;
GtkListStore *optmenu_default_account_menu = NULL;
GtkTreeIter iter;
#if USE_ENCHANT
GtkWidget *checkbtn_enable_default_dictionary = NULL;
GtkWidget *combo_default_dictionary = NULL;
GtkWidget *checkbtn_enable_default_alt_dictionary = NULL;
GtkWidget *combo_default_alt_dictionary = NULL;
GtkWidget *default_dictionary_rec_checkbtn = NULL;
GtkWidget *default_alt_dictionary_rec_checkbtn = NULL;
gchar *dictionary;
#endif
GtkWidget *request_return_receipt_rec_checkbtn = NULL;
GtkWidget *save_copy_to_folder_rec_checkbtn = NULL;
GtkWidget *default_to_rec_checkbtn = NULL;
GtkWidget *default_reply_to_rec_checkbtn = NULL;
GtkWidget *default_cc_rec_checkbtn = NULL;
GtkWidget *default_bcc_rec_checkbtn = NULL;
GtkWidget *default_replyto_rec_checkbtn = NULL;
GtkWidget *default_account_rec_checkbtn = NULL;
GList *cur_ac;
GList *account_list;
PrefsAccount *ac_prefs;
gboolean default_account_set = FALSE;
page->item = item;
/* Table */
#if USE_ENCHANT
# define TABLEHEIGHT 7
#else
# define TABLEHEIGHT 6
#endif
table = gtk_table_new(TABLEHEIGHT, 3, FALSE);
gtk_container_set_border_width (GTK_CONTAINER (table), VBOX_BORDER);
gtk_table_set_row_spacings(GTK_TABLE(table), 4);
gtk_table_set_col_spacings(GTK_TABLE(table), 4);
rowcount = 0;
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_table_attach(GTK_TABLE(table), no_save_warning, 0, 3,
rowcount, rowcount + 1, GTK_FILL, 0, 0, 0);
rowcount++;
}
/* Apply to subfolders */
label = gtk_label_new(_("Apply to\nsubfolders"));
gtk_misc_set_alignment(GTK_MISC(label), 0.5, 0.5);
gtk_table_attach(GTK_TABLE(table), label, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
if (item_protocol(item) != A_NNTP) {
/* Request Return Receipt */
checkbtn_request_return_receipt = gtk_check_button_new_with_label
(_("Request Return Receipt"));
gtk_table_attach(GTK_TABLE(table), checkbtn_request_return_receipt,
0, 2, rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL,
GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_request_return_receipt),
item->ret_rcpt ? TRUE : FALSE);
request_return_receipt_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), request_return_receipt_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Save Copy to Folder */
checkbtn_save_copy_to_folder = gtk_check_button_new_with_label
(_("Save copy of outgoing messages to this folder instead of Sent"));
gtk_table_attach(GTK_TABLE(table), checkbtn_save_copy_to_folder, 0, 2,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_FILL, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_save_copy_to_folder),
item->prefs->save_copy_to_folder ? TRUE : FALSE);
save_copy_to_folder_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), save_copy_to_folder_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default To */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("To:"), NULL);
checkbtn_default_to = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_to, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_to),
item->prefs->enable_default_to);
g_free(text);
entry_default_to = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_to, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_to, entry_default_to);
gtk_entry_set_text(GTK_ENTRY(entry_default_to), SAFE_STRING(item->prefs->default_to));
address_completion_register_entry(GTK_ENTRY(entry_default_to),
TRUE);
default_to_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_to_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default address to reply to */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("To:"),
_(" for replies"), NULL);
checkbtn_default_reply_to = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_reply_to, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_reply_to),
item->prefs->enable_default_reply_to);
g_free(text);
entry_default_reply_to = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_reply_to, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_reply_to, entry_default_reply_to);
gtk_entry_set_text(GTK_ENTRY(entry_default_reply_to), SAFE_STRING(item->prefs->default_reply_to));
address_completion_register_entry(
GTK_ENTRY(entry_default_reply_to), TRUE);
default_reply_to_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_reply_to_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Cc */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Cc:"), NULL);
checkbtn_default_cc = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_cc, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_cc),
item->prefs->enable_default_cc);
g_free(text);
entry_default_cc = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_cc, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_cc, entry_default_cc);
gtk_entry_set_text(GTK_ENTRY(entry_default_cc), SAFE_STRING(item->prefs->default_cc));
address_completion_register_entry(GTK_ENTRY(entry_default_cc),
TRUE);
default_cc_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_cc_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Bcc */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Bcc:"), NULL);
checkbtn_default_bcc = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_bcc, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_bcc),
item->prefs->enable_default_bcc);
g_free(text);
entry_default_bcc = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_bcc, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_bcc, entry_default_bcc);
gtk_entry_set_text(GTK_ENTRY(entry_default_bcc), SAFE_STRING(item->prefs->default_bcc));
address_completion_register_entry(GTK_ENTRY(entry_default_bcc),
TRUE);
default_bcc_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_bcc_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default Reply-to */
text = g_strconcat(_("Default "), prefs_common_translated_header_name("Reply-To:"), NULL);
checkbtn_default_replyto = gtk_check_button_new_with_label(text);
gtk_table_attach(GTK_TABLE(table), checkbtn_default_replyto, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_default_replyto),
item->prefs->enable_default_replyto);
g_free(text);
entry_default_replyto = gtk_entry_new();
gtk_table_attach(GTK_TABLE(table), entry_default_replyto, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
SET_TOGGLE_SENSITIVITY(checkbtn_default_replyto, entry_default_replyto);
gtk_entry_set_text(GTK_ENTRY(entry_default_replyto), SAFE_STRING(item->prefs->default_replyto));
address_completion_register_entry(GTK_ENTRY(entry_default_replyto),
TRUE);
default_replyto_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_replyto_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
}
/* Default account */
checkbtn_enable_default_account = gtk_check_button_new_with_label(_("Default account"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_account, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_account),
item->prefs->enable_default_account);
optmenu_default_account = gtkut_sc_combobox_create(NULL, FALSE);
gtk_table_attach(GTK_TABLE(table), optmenu_default_account, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
optmenu_default_account_menu = GTK_LIST_STORE(
gtk_combo_box_get_model(GTK_COMBO_BOX(optmenu_default_account)));
account_list = account_get_list();
for (cur_ac = account_list; cur_ac != NULL; cur_ac = cur_ac->next) {
ac_prefs = (PrefsAccount *)cur_ac->data;
if (item->folder->account &&
( (item_protocol(item) == A_NNTP && ac_prefs->protocol != A_NNTP)
||(item_protocol(item) != A_NNTP && ac_prefs->protocol == A_NNTP)))
continue;
if (item->folder->klass->type != F_NEWS && ac_prefs->protocol == A_NNTP)
continue;
COMBOBOX_ADD_ESCAPED (optmenu_default_account_menu,
ac_prefs->account_name?ac_prefs->account_name : _("Untitled"),
ac_prefs->account_id);
/* Set combobox to current default account id */
if (ac_prefs->account_id == item->prefs->default_account) {
combobox_select_by_data(GTK_COMBO_BOX(optmenu_default_account),
ac_prefs->account_id);
default_account_set = TRUE;
}
}
/* If nothing has been set (folder doesn't have a default account set),
* pre-select global default account, since that's what actually used
* anyway. We don't want nothing selected in combobox. */
if( !default_account_set )
combobox_select_by_data(GTK_COMBO_BOX(optmenu_default_account),
account_get_default()->account_id);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_account, optmenu_default_account);
default_account_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_account_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#if USE_ENCHANT
/* Default dictionary */
checkbtn_enable_default_dictionary = gtk_check_button_new_with_label(_("Default dictionary"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_dictionary, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_dictionary),
item->prefs->enable_default_dictionary);
combo_default_dictionary = gtkaspell_dictionary_combo_new(TRUE);
gtk_table_attach(GTK_TABLE(table), combo_default_dictionary, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
dictionary = item->prefs->default_dictionary;
if (dictionary && strrchr(dictionary, '/')) {
gchar *tmp = g_strdup(strrchr(dictionary, '/')+1);
g_free(item->prefs->default_dictionary);
item->prefs->default_dictionary = tmp;
dictionary = item->prefs->default_dictionary;
}
if (item->prefs->default_dictionary &&
strchr(item->prefs->default_dictionary, '-')) {
*(strchr(item->prefs->default_dictionary, '-')) = '\0';
}
if (dictionary)
gtkaspell_set_dictionary_menu_active_item(
GTK_COMBO_BOX(combo_default_dictionary), dictionary);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_dictionary, combo_default_dictionary);
default_dictionary_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_dictionary_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
/* Default dictionary */
checkbtn_enable_default_alt_dictionary = gtk_check_button_new_with_label(_("Default alternate dictionary"));
gtk_table_attach(GTK_TABLE(table), checkbtn_enable_default_alt_dictionary, 0, 1,
rowcount, rowcount + 1, GTK_SHRINK | GTK_FILL, GTK_SHRINK, 0, 0);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(checkbtn_enable_default_alt_dictionary),
item->prefs->enable_default_alt_dictionary);
combo_default_alt_dictionary = gtkaspell_dictionary_combo_new(FALSE);
gtk_table_attach(GTK_TABLE(table), combo_default_alt_dictionary, 1, 2,
rowcount, rowcount + 1, GTK_EXPAND | GTK_FILL, GTK_SHRINK, 0, 0);
dictionary = item->prefs->default_alt_dictionary;
if (dictionary && strrchr(dictionary, '/')) {
gchar *tmp = g_strdup(strrchr(dictionary, '/')+1);
g_free(item->prefs->default_alt_dictionary);
item->prefs->default_alt_dictionary = tmp;
dictionary = item->prefs->default_alt_dictionary;
}
if (item->prefs->default_alt_dictionary &&
strchr(item->prefs->default_alt_dictionary, '-')) {
*(strchr(item->prefs->default_alt_dictionary, '-')) = '\0';
}
if (dictionary)
gtkaspell_set_dictionary_menu_active_item(
GTK_COMBO_BOX(combo_default_alt_dictionary), dictionary);
SET_TOGGLE_SENSITIVITY(checkbtn_enable_default_alt_dictionary, combo_default_alt_dictionary);
default_alt_dictionary_rec_checkbtn = gtk_check_button_new();
gtk_table_attach(GTK_TABLE(table), default_alt_dictionary_rec_checkbtn, 2, 3,
rowcount, rowcount + 1, GTK_SHRINK, GTK_SHRINK, 0, 0);
rowcount++;
#endif
gtk_widget_show_all(table);
page->window = GTK_WIDGET(window);
page->table = table;
page->no_save_warning = no_save_warning;
page->checkbtn_request_return_receipt = checkbtn_request_return_receipt;
page->checkbtn_save_copy_to_folder = checkbtn_save_copy_to_folder;
page->checkbtn_default_to = checkbtn_default_to;
page->entry_default_to = entry_default_to;
page->checkbtn_default_reply_to = checkbtn_default_reply_to;
page->entry_default_reply_to = entry_default_reply_to;
page->checkbtn_default_cc = checkbtn_default_cc;
page->entry_default_cc = entry_default_cc;
page->checkbtn_default_bcc = checkbtn_default_bcc;
page->entry_default_bcc = entry_default_bcc;
page->checkbtn_default_replyto = checkbtn_default_replyto;
page->entry_default_replyto = entry_default_replyto;
page->checkbtn_enable_default_account = checkbtn_enable_default_account;
page->optmenu_default_account = optmenu_default_account;
#ifdef USE_ENCHANT
page->checkbtn_enable_default_dictionary = checkbtn_enable_default_dictionary;
page->combo_default_dictionary = combo_default_dictionary;
page->checkbtn_enable_default_alt_dictionary = checkbtn_enable_default_alt_dictionary;
page->combo_default_alt_dictionary = combo_default_alt_dictionary;
#endif
page->request_return_receipt_rec_checkbtn = request_return_receipt_rec_checkbtn;
page->save_copy_to_folder_rec_checkbtn = save_copy_to_folder_rec_checkbtn;
page->default_to_rec_checkbtn = default_to_rec_checkbtn;
page->default_reply_to_rec_checkbtn = default_reply_to_rec_checkbtn;
page->default_cc_rec_checkbtn = default_cc_rec_checkbtn;
page->default_bcc_rec_checkbtn = default_bcc_rec_checkbtn;
page->default_replyto_rec_checkbtn = default_replyto_rec_checkbtn;
page->default_account_rec_checkbtn = default_account_rec_checkbtn;
#if USE_ENCHANT
page->default_dictionary_rec_checkbtn = default_dictionary_rec_checkbtn;
page->default_alt_dictionary_rec_checkbtn = default_alt_dictionary_rec_checkbtn;
#endif
page->page.widget = table;
}
static void prefs_folder_item_compose_destroy_widget_func(PrefsPage *page_)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
if (page->entry_default_to)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_to));
if (page->entry_default_reply_to)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_reply_to));
if (page->entry_default_cc)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_cc));
if (page->entry_default_bcc)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_bcc));
if (page->entry_default_replyto)
address_completion_unregister_entry(GTK_ENTRY(page->entry_default_replyto));
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void compose_save_folder_prefs(FolderItem *folder, FolderItemComposePage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gboolean all = FALSE;
if (folder->path == NULL)
return;
if (page->item == folder)
all = TRUE;
cm_return_if_fail(prefs != NULL);
if (item_protocol(folder) != A_NNTP) {
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->request_return_receipt_rec_checkbtn))) {
prefs->request_return_receipt =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_request_return_receipt));
/* MIGRATION */
folder->ret_rcpt = prefs->request_return_receipt;
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->save_copy_to_folder_rec_checkbtn))) {
prefs->save_copy_to_folder =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_save_copy_to_folder));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_to_rec_checkbtn))) {
prefs->enable_default_to =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_to));
ASSIGN_STRING(prefs->default_to,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_to), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_reply_to_rec_checkbtn))) {
prefs->enable_default_reply_to =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_reply_to));
ASSIGN_STRING(prefs->default_reply_to,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_reply_to), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_cc_rec_checkbtn))) {
prefs->enable_default_cc =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_cc));
ASSIGN_STRING(prefs->default_cc,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_cc), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_bcc_rec_checkbtn))) {
prefs->enable_default_bcc =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_bcc));
ASSIGN_STRING(prefs->default_bcc,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_bcc), 0, -1));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_replyto_rec_checkbtn))) {
prefs->enable_default_replyto =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_default_replyto));
ASSIGN_STRING(prefs->default_replyto,
gtk_editable_get_chars(GTK_EDITABLE(page->entry_default_replyto), 0, -1));
}
} else {
prefs->request_return_receipt = FALSE;
prefs->save_copy_to_folder = FALSE;
prefs->enable_default_to = FALSE;
prefs->enable_default_reply_to = FALSE;
prefs->enable_default_cc = FALSE;
prefs->enable_default_bcc = FALSE;
prefs->enable_default_replyto = FALSE;
}
if (all || gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn))) {
prefs->enable_default_account =
gtk_toggle_button_get_active(
GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_account));
prefs->default_account = combobox_get_active_data(
GTK_COMBO_BOX(page->optmenu_default_account));
}
#if USE_ENCHANT
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn))) {
prefs->enable_default_dictionary =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_dictionary));
ASSIGN_STRING(prefs->default_dictionary,
gtkaspell_get_dictionary_menu_active_item(
GTK_COMBO_BOX(page->combo_default_dictionary)));
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn))) {
prefs->enable_default_alt_dictionary =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_enable_default_alt_dictionary));
ASSIGN_STRING(prefs->default_alt_dictionary,
gtkaspell_get_dictionary_menu_active_item(
GTK_COMBO_BOX(page->combo_default_alt_dictionary)));
}
#endif
folder_item_prefs_save_config(folder);
}
static gboolean compose_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemComposePage *page = (FolderItemComposePage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
compose_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) && item_protocol(item) != A_NNTP &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->request_return_receipt_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->save_copy_to_folder_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_to_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_cc_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_bcc_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_replyto_rec_checkbtn)) ||
#if USE_ENCHANT
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn)) ||
#endif
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_reply_to_rec_checkbtn))
))
return TRUE;
else if ((node == page->item->node) && item_protocol(item) == A_NNTP &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_account_rec_checkbtn))
#if USE_ENCHANT
|| gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_dictionary_rec_checkbtn))
|| gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->default_alt_dictionary_rec_checkbtn))
#endif
))
return TRUE;
else
return FALSE;
}
static void prefs_folder_item_compose_save_func(PrefsPage *page_)
{
FolderItemComposePage *page = (FolderItemComposePage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, compose_save_recurse_func, page);
}
static void prefs_folder_item_templates_create_widget_func(PrefsPage * page_,
GtkWindow * window,
gpointer data)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
FolderItem *item = (FolderItem *) data;
GtkWidget *notebook;
GtkWidget *vbox;
GtkWidget *page_vbox;
GtkWidget *no_save_warning;
GtkWidget *new_msg_format_rec_checkbtn;
GtkWidget *reply_format_rec_checkbtn;
GtkWidget *forward_format_rec_checkbtn;
GtkWidget *hbox;
GtkWidget *vbox_format;
page->item = item;
page_vbox = gtk_vbox_new (FALSE, 0);
gtk_container_set_border_width (GTK_CONTAINER (page_vbox), VBOX_BORDER);
gtk_widget_show (page_vbox);
if (!can_save) {
no_save_warning = gtk_label_new(
_("<i>These preferences will not be saved as this folder "
"is a top-level folder. However, you can set them for the "
"whole mailbox tree by using \"Apply to subfolders\".</i>"));
gtk_label_set_use_markup(GTK_LABEL(no_save_warning), TRUE);
gtk_label_set_line_wrap(GTK_LABEL(no_save_warning), TRUE);
gtk_misc_set_alignment(GTK_MISC(no_save_warning), 0.0, 0.5);
gtk_box_pack_start(GTK_BOX(page_vbox), no_save_warning, FALSE, FALSE, 0);
}
/* Notebook */
notebook = gtk_notebook_new();
gtk_widget_show(notebook);
gtk_box_pack_start(GTK_BOX(page_vbox), notebook, TRUE, TRUE, 4);
/* compose format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_new_msg_fmt_widgets(
window,
vbox,
&page->checkbtn_compose_with_format,
&page->compose_override_from_format,
&page->compose_subject_format,
&page->compose_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->compose_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->compose_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
new_msg_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), new_msg_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Compose")));
/* reply format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_reply_fmt_widgets(
window,
vbox,
&page->checkbtn_reply_with_format,
&page->reply_override_from_format,
&page->reply_quotemark,
&page->reply_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->reply_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->reply_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
reply_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), reply_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Reply")));
/* forward format */
vbox = gtk_vbox_new (FALSE, VSPACING);
gtk_widget_show (vbox);
gtk_container_set_border_width (GTK_CONTAINER (vbox), VBOX_BORDER);
quotefmt_create_forward_fmt_widgets(
window,
vbox,
&page->checkbtn_forward_with_format,
&page->forward_override_from_format,
&page->forward_quotemark,
&page->forward_body_format,
FALSE, FALSE);
address_completion_register_entry(GTK_ENTRY(page->forward_override_from_format),
TRUE);
vbox_format = gtk_widget_get_parent(
gtk_widget_get_parent(page->forward_body_format));
hbox = gtk_hbox_new (FALSE, 0);
gtk_box_pack_end (GTK_BOX(vbox_format), hbox, FALSE, FALSE, 0);
quotefmt_add_info_button(window, hbox);
forward_format_rec_checkbtn = gtk_check_button_new_with_label(
_("Apply to subfolders"));
gtk_box_pack_end (GTK_BOX(hbox), forward_format_rec_checkbtn, FALSE, FALSE, 0);
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), vbox, gtk_label_new(_("Forward")));
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_compose_with_format),
item->prefs->compose_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->compose_override_from_format),
item->prefs->compose_override_from_format);
pref_set_entry_from_pref(GTK_ENTRY(page->compose_subject_format),
item->prefs->compose_subject_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->compose_body_format),
item->prefs->compose_body_format);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_reply_with_format),
item->prefs->reply_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->reply_quotemark),
item->prefs->reply_quotemark);
pref_set_entry_from_pref(GTK_ENTRY(page->reply_override_from_format),
item->prefs->reply_override_from_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->reply_body_format),
item->prefs->reply_body_format);
gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(page->checkbtn_forward_with_format),
item->prefs->forward_with_format);
pref_set_entry_from_pref(GTK_ENTRY(page->forward_quotemark),
item->prefs->forward_quotemark);
pref_set_entry_from_pref(GTK_ENTRY(page->forward_override_from_format),
item->prefs->forward_override_from_format);
pref_set_textview_from_pref(GTK_TEXT_VIEW(page->forward_body_format),
item->prefs->forward_body_format);
gtk_widget_show_all(page_vbox);
page->window = GTK_WIDGET(window);
page->new_msg_format_rec_checkbtn = new_msg_format_rec_checkbtn;
page->reply_format_rec_checkbtn = reply_format_rec_checkbtn;
page->forward_format_rec_checkbtn = forward_format_rec_checkbtn;
page->page.widget = page_vbox;
}
static void prefs_folder_item_templates_destroy_widget_func(PrefsPage *page_)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
if (page->compose_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->compose_override_from_format));
if (page->reply_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->reply_override_from_format));
if (page->forward_override_from_format)
address_completion_unregister_entry(GTK_ENTRY(page->forward_override_from_format));
}
/** \brief Save the prefs in page to folder.
*
* If the folder is not the one specified in page->item, then only those properties
* that have the relevant 'apply to sub folders' button checked are saved
*/
static void templates_save_folder_prefs(FolderItem *folder, FolderItemTemplatesPage *page)
{
FolderItemPrefs *prefs = folder->prefs;
gboolean all = FALSE;
if (folder->path == NULL)
return;
if (page->item == folder)
all = TRUE;
cm_return_if_fail(prefs != NULL);
/* save and check formats */
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->new_msg_format_rec_checkbtn))) {
prefs->compose_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_compose_with_format));
prefs->compose_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->compose_override_from_format));
prefs->compose_subject_format = pref_get_pref_from_entry(
GTK_ENTRY(page->compose_subject_format));
prefs->compose_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->compose_body_format));
quotefmt_check_new_msg_formats(prefs->compose_with_format,
prefs->compose_override_from_format,
prefs->compose_subject_format,
prefs->compose_body_format);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->reply_format_rec_checkbtn))) {
prefs->reply_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_reply_with_format));
prefs->reply_quotemark = gtk_editable_get_chars(
GTK_EDITABLE(page->reply_quotemark), 0, -1);
prefs->reply_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->reply_override_from_format));
prefs->reply_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->reply_body_format));
quotefmt_check_reply_formats(prefs->reply_with_format,
prefs->reply_override_from_format,
prefs->reply_quotemark,
prefs->reply_body_format);
}
if (all || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->forward_format_rec_checkbtn))) {
prefs->forward_with_format =
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_forward_with_format));
prefs->forward_quotemark = gtk_editable_get_chars(
GTK_EDITABLE(page->forward_quotemark), 0, -1);
prefs->forward_override_from_format = pref_get_pref_from_entry(
GTK_ENTRY(page->forward_override_from_format));
prefs->forward_body_format = pref_get_pref_from_textview(
GTK_TEXT_VIEW(page->forward_body_format));
quotefmt_check_forward_formats(prefs->forward_with_format,
prefs->forward_override_from_format,
prefs->forward_quotemark,
prefs->forward_body_format);
}
folder_item_prefs_save_config(folder);
}
static gboolean templates_save_recurse_func(GNode *node, gpointer data)
{
FolderItem *item = (FolderItem *) node->data;
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) data;
cm_return_val_if_fail(item != NULL, TRUE);
cm_return_val_if_fail(page != NULL, TRUE);
templates_save_folder_prefs(item, page);
/* optimise by not continuing if none of the 'apply to sub folders'
check boxes are selected - and optimise the checking by only doing
it once */
if ((node == page->item->node) &&
!(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->new_msg_format_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->reply_format_rec_checkbtn)) ||
gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->forward_format_rec_checkbtn))))
return TRUE;
else
return FALSE;
return FALSE;
}
static void prefs_folder_item_templates_save_func(PrefsPage *page_)
{
FolderItemTemplatesPage *page = (FolderItemTemplatesPage *) page_;
g_node_traverse(page->item->node, G_PRE_ORDER, G_TRAVERSE_ALL,
-1, templates_save_recurse_func, page);
}
static gint prefs_folder_item_chmod_mode(gchar *folder_chmod)
{
gint newmode = 0;
gchar *tmp;
if (folder_chmod) {
newmode = strtol(folder_chmod, &tmp, 8);
if (!(*(folder_chmod) && !(*tmp)))
newmode = 0;
}
return newmode;
}
static void folder_color_set_dialog(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
gint rgbcolor;
rgbcolor = colorsel_select_color_rgb(_("Pick color for folder"),
page->folder_color);
gtkut_set_widget_bgcolor_rgb(page->folder_color_btn, rgbcolor);
page->folder_color = rgbcolor;
}
static void clean_cache_cb(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *) data;
FolderItem *item = page->item;
gboolean was_open = FALSE;
FolderView *folderview = NULL;
if (alertpanel_full(_("Discard cache"),
_("Do you really want to discard the local cached "
"data for this folder?"),
GTK_STOCK_CANCEL, _("+Discard"), NULL, FALSE,
NULL, ALERT_WARNING, G_ALERTDEFAULT)
!= G_ALERTALTERNATE)
return;
if (mainwindow_get_mainwindow())
folderview = mainwindow_get_mainwindow()->folderview;
if (folderview && item->opened) {
folderview_close_opened(folderview);
was_open = TRUE;
}
folder_item_discard_cache(item);
if (was_open)
folderview_select(folderview,item);
}
#ifndef G_OS_WIN32
static regex_t *summary_compile_simplify_regexp(gchar *simplify_subject_regexp)
{
int err;
gchar buf[BUFFSIZE];
regex_t *preg = NULL;
preg = g_new0(regex_t, 1);
err = string_match_precompile(simplify_subject_regexp,
preg, REG_EXTENDED);
if (err) {
regerror(err, preg, buf, BUFFSIZE);
g_free(preg);
preg = NULL;
}
return preg;
}
static void folder_regexp_test_cb(GtkWidget *widget, gpointer data)
{
#if !GTK_CHECK_VERSION(3, 0, 0)
static GdkColor red;
static gboolean colors_initialised = FALSE;
#else
static GdkColor red = { (guint32)0, (guint16)0xff, (guint16)0x70, (guint16)0x70 };
#endif
static gchar buf[BUFFSIZE];
FolderItemGeneralPage *page = (FolderItemGeneralPage *)data;
gchar *test_string, *regexp;
regex_t *preg;
regexp = g_strdup(gtk_entry_get_text(GTK_ENTRY(page->entry_simplify_subject)));
test_string = g_strdup(gtk_entry_get_text(GTK_ENTRY(page->entry_regexp_test_string)));
if (!regexp || !regexp[0]) {
gtk_widget_modify_base(page->entry_simplify_subject,
GTK_STATE_NORMAL, NULL);
if (test_string)
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_result), test_string);
g_free(test_string);
g_free(regexp);
return;
}
if (!test_string || !test_string[0]) {
g_free(test_string);
g_free(regexp);
return;
}
#if !GTK_CHECK_VERSION(3, 0, 0)
if (!colors_initialised) {
gdk_color_parse("#ff7070", &red);
colors_initialised = gdk_colormap_alloc_color(
gdk_colormap_get_system(), &red, FALSE, TRUE);
}
#endif
preg = summary_compile_simplify_regexp(regexp);
#if !GTK_CHECK_VERSION(3, 0, 0)
if (colors_initialised)
gtk_widget_modify_base(page->entry_simplify_subject,
GTK_STATE_NORMAL, preg ? NULL : &red);
#endif
if (preg != NULL) {
string_remove_match(buf, BUFFSIZE, test_string, preg);
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_result), buf);
regfree(preg);
g_free(preg);
}
g_free(test_string);
g_free(regexp);
}
static gchar *folder_regexp_get_subject_example(void)
{
MsgInfo *msginfo_selected;
SummaryView *summaryview = NULL;
if (!mainwindow_get_mainwindow())
return NULL;
summaryview = mainwindow_get_mainwindow()->summaryview;
msginfo_selected = summary_get_selected_msg(summaryview);
return msginfo_selected ? g_strdup(msginfo_selected->subject) : NULL;
}
static void folder_regexp_set_subject_example_cb(GtkWidget *widget, gpointer data)
{
FolderItemGeneralPage *page = (FolderItemGeneralPage *)data;
if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(page->checkbtn_simplify_subject))) {
gchar *subject = folder_regexp_get_subject_example();
if (subject) {
gtk_entry_set_text(GTK_ENTRY(page->entry_regexp_test_string), subject);
g_free(subject);
}
}
}
#endif
static void register_general_page()
{
static gchar *pfi_general_path[2];
static FolderItemGeneralPage folder_item_general_page;
pfi_general_path[0] = _("General");
pfi_general_path[1] = NULL;
folder_item_general_page.page.path = pfi_general_path;
folder_item_general_page.page.create_widget = prefs_folder_item_general_create_widget_func;
folder_item_general_page.page.destroy_widget = prefs_folder_item_general_destroy_widget_func;
folder_item_general_page.page.save_page = prefs_folder_item_general_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_general_page, NULL);
}
static void register_compose_page(void)
{
static gchar *pfi_compose_path[2];
static FolderItemComposePage folder_item_compose_page;
pfi_compose_path[0] = _("Compose");
pfi_compose_path[1] = NULL;
folder_item_compose_page.page.path = pfi_compose_path;
folder_item_compose_page.page.create_widget = prefs_folder_item_compose_create_widget_func;
folder_item_compose_page.page.destroy_widget = prefs_folder_item_compose_destroy_widget_func;
folder_item_compose_page.page.save_page = prefs_folder_item_compose_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_compose_page, NULL);
}
static void register_templates_page(void)
{
static gchar *pfi_templates_path[2];
static FolderItemTemplatesPage folder_item_templates_page;
pfi_templates_path[0] = _("Templates");
pfi_templates_path[1] = NULL;
folder_item_templates_page.page.path = pfi_templates_path;
folder_item_templates_page.page.create_widget = prefs_folder_item_templates_create_widget_func;
folder_item_templates_page.page.destroy_widget = prefs_folder_item_templates_destroy_widget_func;
folder_item_templates_page.page.save_page = prefs_folder_item_templates_save_func;
prefs_folder_item_register_page((PrefsPage *) &folder_item_templates_page, NULL);
}
static GSList *prefs_pages = NULL;
static void prefs_folder_item_address_completion_start(PrefsWindow *window)
{
address_completion_start(window->window);
}
static void prefs_folder_item_address_completion_end(PrefsWindow *window)
{
address_completion_end(window->window);
}
void prefs_folder_item_open(FolderItem *item)
{
gchar *id, *title;
GSList *pages;
if (prefs_pages == NULL) {
register_general_page();
register_compose_page();
register_templates_page();
}
if (item->path) {
id = folder_item_get_identifier (item);
can_save = TRUE;
} else {
id = g_strdup(item->name);
can_save = FALSE;
}
pages = g_slist_concat(
g_slist_copy(prefs_pages),
g_slist_copy(item->folder->klass->prefs_pages));
title = g_strdup_printf (_("Properties for folder %s"), id);
g_free (id);
prefswindow_open(title, pages, item,
&prefs_common.folderitemwin_width, &prefs_common.folderitemwin_height,
prefs_folder_item_address_completion_start,
NULL,
prefs_folder_item_address_completion_end);
g_slist_free(pages);
g_free (title);
}
void prefs_folder_item_register_page(PrefsPage *page, FolderClass *klass)
{
if (klass != NULL)
klass->prefs_pages = g_slist_append(klass->prefs_pages, page);
else
prefs_pages = g_slist_append(prefs_pages, page);
}
void prefs_folder_item_unregister_page(PrefsPage *page, FolderClass *klass)
{
if (klass != NULL)
klass->prefs_pages = g_slist_remove(klass->prefs_pages, page);
else
prefs_pages = g_slist_remove(prefs_pages, page);
}
| buzz/claws | src/prefs_folder_item.c | C | gpl-3.0 | 71,677 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>FcAtomicCreate</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REL="HOME"
HREF="index.html"><LINK
REL="UP"
TITLE="FcAtomic"
HREF="x102.html#AEN3766"><LINK
REL="PREVIOUS"
TITLE="FUNCTIONS"
HREF="x102.html"><LINK
REL="NEXT"
TITLE="FcAtomicLock"
HREF="fcatomiclock.html"></HEAD
><BODY
CLASS="REFENTRY"
BGCOLOR="#FFFFFF"
TEXT="#000000"
LINK="#0000FF"
VLINK="#840084"
ALINK="#0000FF"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="3"
ALIGN="center"
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="bottom"
><A
HREF="x102.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="80%"
ALIGN="center"
VALIGN="bottom"
></TD
><TD
WIDTH="10%"
ALIGN="right"
VALIGN="bottom"
><A
HREF="fcatomiclock.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><H1
><A
NAME="FCATOMICCREATE"
></A
>FcAtomicCreate</H1
><DIV
CLASS="REFNAMEDIV"
><A
NAME="AEN3774"
></A
><H2
>Name</H2
>FcAtomicCreate -- create an FcAtomic object</DIV
><DIV
CLASS="REFSYNOPSISDIV"
><A
NAME="AEN3777"
></A
><H2
>Synopsis</H2
><DIV
CLASS="FUNCSYNOPSIS"
><P
></P
><A
NAME="AEN3778"
></A
><PRE
CLASS="FUNCSYNOPSISINFO"
>#include <fontconfig/fontconfig.h>
</PRE
><P
><CODE
><CODE
CLASS="FUNCDEF"
>FcAtomic * FcAtomicCreate</CODE
>(const FcChar8 *file);</CODE
></P
><P
></P
></DIV
></DIV
><DIV
CLASS="REFSECT1"
><A
NAME="AEN3785"
></A
><H2
>Description</H2
><P
>Creates a data structure containing data needed to control access to <CODE
CLASS="PARAMETER"
>file</CODE
>.
Writing is done to a separate file. Once that file is complete, the original
configuration file is atomically replaced so that reading process always see
a consistent and complete file without the need to lock for reading.
</P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="x102.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="fcatomiclock.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>FUNCTIONS</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="x102.html#AEN3766"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>FcAtomicLock</TD
></TR
></TABLE
></DIV
></BODY
></HTML
> | mgood7123/UPM | Tests/PACKAGES/hexchat-2.12.4-6-x86_64/usr/share/doc/fontconfig/fontconfig-devel/fcatomiccreate.html | HTML | gpl-3.0 | 2,691 |
# -*- coding: utf8 -*-
###########################################################################
# This is the package latexparser
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
###########################################################################
# copyright (c) Laurent Claessens, 2010,2012-2016
# email: [email protected]
import codecs
from latexparser.InputPaths import InputPaths
class Occurrence(object):
"""
self.as_written : the code as it appears in the file, including \MyMacro, including the backslash.
self.position : the position at which this occurrence appears.
Example, if we look at the LatexCode
Hello word, \MyMacro{first}
and then \MyMacro{second}
the first occurrence of \MyMacro has position=12
"""
def __init__(self,name,arguments,as_written="",position=0):
self.arguments = arguments
self.number_of_arguments = len(arguments)
self.name = name
self.as_written = as_written
self.arguments_list = arguments
self.position = position
def configuration(self):
r"""
Return the way the arguments are separated in as_written.
Example, if we have
\MyMacro<space>{A}<tab>{B}
{C},
we return the list
["<space>","tab","\n"]
The following has to be true:
self.as_written == self.name+self.configuration()[0]+self.arguments_list[0]+etc.
"""
l=[]
a = self.as_written.split(self.name)[1]
for arg in self.arguments_list:
split = a.split("{"+arg+"}")
separator=split[0]
try:
a=split[1]
except IndexError:
print(self.as_written)
raise
l.append(separator)
return l
def change_argument(self,num,func):
r"""
Apply the function <func> to the <n>th argument of self. Then return a new object.
"""
n=num-1 # Internally, the arguments are numbered from 0.
arguments=self.arguments_list
configuration=self.configuration()
arguments[n]=func(arguments[n])
new_text=self.name
if len(arguments) != len(configuration):
print("Error : length of the configuration list has to be the same as the number of arguments")
raise ValueError
for i in range(len(arguments)):
new_text=new_text+configuration[i]+"{"+arguments[i]+"}"
return Occurrence(self.name,arguments,new_text,self.position)
def analyse(self):
return globals()["Occurrence_"+self.name[1:]](self) # We have to remove the initial "\" in the name of the macro.
def __getitem__(self,a):
return self.arguments[a]
def __str__(self):
return self.as_written
class Occurrence_newlabel(object):
r"""
takes an occurrence of \newlabel and creates an object which contains the information.
In the self.section_name we remove "\relax" from the string.
"""
def __init__(self,occurrence):
self.occurrence = occurrence
self.arguments = self.occurrence.arguments
if len(self.arguments) == 0 :
self.name = "Non interesting; probably the definition"
self.listoche = [None,None,None,None,None]
self.value,self.page,self.section_name,self.fourth,self.fifth=(None,None,None,None,None)
else :
self.name = self.arguments[0][0]
self.listoche = [a[0] for a in SearchArguments(self.arguments[1][0],5)[0]]
self.value = self.listoche[0]
self.page = self.listoche[1]
self.section_name = self.listoche[2].replace(r"\relax","")
self.fourth = self.listoche[3] # I don't know the role of the fourth argument of \newlabel
self.fifth = self.listoche[4] # I don't know the role of the fifth argument of \newlabel
class Occurrence_addInputPath(object):
def __init__(self,Occurrence):
self.directory=Occurrence[0]
class Occurrence_cite(object):
def __init__(self,occurrence):
self.label = occurrence[0]
def entry(self,codeBibtex):
return codeBibtex[self.label]
class Occurrence_newcommand(object):
def __init__(self,occurrence):
self.occurrence = occurrence
self.number_of_arguments = 0
if self.occurrence[1][1] == "[]":
self.number_of_arguments = self.occurrence[1][0]
self.name = self.occurrence[0][0]#[0]
self.definition = self.occurrence[-1][0]
class Occurrence_label(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_ref(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_eqref(object):
def __init__(self,occurrence):
self.occurrence=occurrence
self.label=self.occurrence.arguments[0]
class Occurrence_input(Occurrence):
def __init__(self,occurrence):
Occurrence.__init__(self,occurrence.name,occurrence.arguments,as_written=occurrence.as_written,position=occurrence.position)
self.occurrence = occurrence
self.filename = self.occurrence[0]
self.input_paths=InputPaths()
self._file_content=None # Make file_content "lazy"
def file_content(self,input_paths=None):
r"""
return the content of the file corresponding to this occurrence of
\input.
This is not recursive.
- 'input_path' is the list of paths in which we can search for files.
See the macro `\addInputPath` in the file
https://github.com/LaurentClaessens/mazhe/blob/master/configuration.tex
"""
import os.path
# Memoize
if self._file_content is not None :
return self._file_content
# At least, we are searching in the current directory :
if input_paths is None :
raise # Just to know who should do something like that
# Creating the filename
filename=self.filename
strict_filename = filename
if "." not in filename:
strict_filename=filename+".tex"
# Searching for the correct file in the subdirectories
fn=input_paths.get_file(strict_filename)
try:
# Without [:-1] I got an artificial empty line at the end.
text = "".join( codecs.open(fn,"r",encoding="utf8") )[:-1]
except IOError :
print("Warning : file %s not found."%strict_filename)
raise
self._file_content=text
return self._file_content
| LaurentClaessens/LaTeXparser | Occurrence.py | Python | gpl-3.0 | 7,331 |
<div>
<nav>
<ul id="menu">
{% for m in menu %}
<li>
{% if m.subsistemas %}
{{ m.nombreDireccion }}
<ul>
{% for submenu in m.subsistemas %}
<li>
<a href="{{submenu.target}}">{{ submenu.nombreSistema }}</a>
</li>
{% endfor %}
</ul>
{% else %}
<a href="{{m.target}}"> {{ m.nombreDireccion }}</a>
{% endif%}
</li>
{% endfor %}
<li>
{% firstof user.get_short_name user.get_username %}
<a href="{% url 'logout_view' %}" id="logout">Cerrar sesion</a>
</li>
</ul>
</nav>
</br> </br> </br>
</div>
| mmanto/sstuv | secur/templates/menu.html | HTML | gpl-3.0 | 669 |
% acronyms for text or math mode
\newcommand {\ccast} {\mbox{\small CCAST}}
\newcommand {\cris} {\mbox{\small CrIS}}
\newcommand {\airs} {\mbox{\small AIRS}}
\newcommand {\iasi} {\mbox{\small IASI}}
\newcommand {\idps} {\mbox{\small IDPS}}
\newcommand {\nasa} {\mbox{\small NASA}}
\newcommand {\noaa} {\mbox{\small NOAA}}
\newcommand {\umbc} {\mbox{\small UMBC}}
\newcommand {\uw} {\mbox{\small UW}}
\newcommand {\fft} {\mbox{\small FFT}}
\newcommand {\ifft} {\mbox{\small IFFT}}
\newcommand {\fir} {\mbox{\small FIR}}
\newcommand {\fov} {\mbox{\small FOV}}
\newcommand {\for} {\mbox{\small FOR}}
\newcommand {\ict} {\mbox{\small ICT}}
\newcommand {\ils} {\mbox{\small ILS}}
\newcommand {\igm} {\mbox{\small IGM}}
\newcommand {\opd} {\mbox{\small OPD}}
\newcommand {\rms} {\mbox{\small RMS}}
\newcommand {\zpd} {\mbox{\small ZPD}}
\newcommand {\ppm} {\mbox{\small PPM}}
\newcommand {\srf} {\mbox{\small SRF}}
\newcommand {\ES} {\mbox{\small ES}}
\newcommand {\SP} {\mbox{\small SP}}
\newcommand {\IT} {\mbox{\small IT}}
\newcommand {\SA} {\mbox{\small SA}}
\newcommand {\ET} {\mbox{\small ET}}
\newcommand {\FT} {\mbox{\small FT}}
% abbreviations, mainly for math mode
\newcommand {\real} {\mbox{real}}
\newcommand {\imag} {\mbox{imag}}
\newcommand {\atan} {\mbox{atan}}
\newcommand {\obs} {\mbox{obs}}
\newcommand {\calc} {\mbox{calc}}
\newcommand {\sinc} {\mbox{sinc}}
\newcommand {\psinc} {\mbox{psinc}}
% symbols, for math mode only
\newcommand {\wnum} {\mbox{cm$^{-1}$}}
\newcommand {\lmax} {L_{\mbox{\tiny max}}}
\newcommand {\vmax} {V_{\mbox{\tiny max}}}
\newcommand {\rIT} {R_{\mbox{\tiny IT}}}
\newcommand {\tauobs} {\tau_{\mbox{\tiny obs}}}
\newcommand {\taucal} {\tau_{\mbox{\tiny calc}}}
\newcommand {\Vdc} {V_{\mbox{\tiny DC}}}
| motteler/cris_telecon | ccast_noaa1/crisdefs.tex | TeX | gpl-3.0 | 1,764 |
#!/bin/bash
APP_DIR=`pwd`/books/
LOCALE_DIR=$APP_DIR/locale/
echo $APP_DIR
pushd $APP_DIR
echo `pwd`
for lang in `ls $LOCALE_DIR`; do
echo "Setting up locale for $lang"
django-admin.py makemessages -l $lang
done
echo "*************************"
django-admin.py compilemessages
popd
| datakid/dj-library | locale.sh | Shell | gpl-3.0 | 294 |
/********************************************************************************
Copyright (C) Binod Nepal, Mix Open Foundation (http://mixof.org).
This file is part of MixERP.
MixERP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MixERP 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 MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using MixERP.Net.Common.Helpers;
using MixERP.Net.Common.Models.Core;
using MixERP.Net.Common.Models.Transactions;
using System;
using System.Collections.ObjectModel;
namespace MixERP.Net.Core.Modules.Sales.Data.Transactions
{
public static class Delivery
{
public static long Add(DateTime valueDate, int storeId, string partyCode, int priceTypeId, int paymentTermId, Collection<StockMasterDetailModel> details, int shipperId, string shippingAddressCode, decimal shippingCharge, int costCenterId, string referenceNumber, int agentId, string statementReference, Collection<int> transactionIdCollection, Collection<AttachmentModel> attachments, bool nonTaxable)
{
StockMasterModel stockMaster = new StockMasterModel();
stockMaster.PartyCode = partyCode;
stockMaster.IsCredit = true;//Credit
stockMaster.PaymentTermId = paymentTermId;
stockMaster.PriceTypeId = priceTypeId;
stockMaster.ShipperId = shipperId;
stockMaster.ShippingAddressCode = shippingAddressCode;
stockMaster.ShippingCharge = shippingCharge;
stockMaster.SalespersonId = agentId;
stockMaster.CashRepositoryId = 0;//Credit
stockMaster.StoreId = storeId;
long transactionMasterId = GlTransaction.Add("Sales.Delivery", valueDate, SessionHelper.GetOfficeId(), SessionHelper.GetUserId(), SessionHelper.GetLogOnId(), costCenterId, referenceNumber, statementReference, stockMaster, details, attachments, nonTaxable);
TransactionGovernor.Autoverification.Autoverify.PassTransactionMasterId(transactionMasterId);
return transactionMasterId;
}
}
} | jacquet33/miERP | FrontEnd/MixERP.Net.FrontEnd/Modules/Sales.Data/Transactions/Delivery.cs | C# | gpl-3.0 | 2,573 |
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_FM_session' | kunagpal/recommend-fm | config/initializers/session_store.rb | Ruby | gpl-3.0 | 133 |
import java.util.*;
public class Pali {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str=sc.next();
StringBuffer buff=new StringBuffer(str).reverse();
String str1=buff.toString();
if(str.isequals(str1))
{
System.out.println("Palindrome");
}
else
{
System.out.println("Not a Palindrome");
}
}
| RaviVengatesh/Guvi_codes | Pali.java | Java | gpl-3.0 | 449 |
/******************************************************************************
* NTRU Cryptography Reference Source Code
* Copyright (c) 2009-2013, by Security Innovation, Inc. All rights reserved.
*
* ntru_crypto_hash.c is a component of ntru-crypto.
*
* Copyright (C) 2009-2013 Security Innovation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*****************************************************************************/
/******************************************************************************
*
* File: ntru_crypto_hash.c
*
* Contents: Routines implementing the hash object abstraction.
*
*****************************************************************************/
#include "ntru_crypto.h"
#include "ntru_crypto_hash.h"
typedef uint32_t (*NTRU_CRYPTO_HASH_INIT_FN)(
void *c);
typedef uint32_t (*NTRU_CRYPTO_HASH_UPDATE_FN)(
void *c,
void const *data,
uint32_t len);
typedef uint32_t (*NTRU_CRYPTO_HASH_FINAL_FN)(
void *c,
void *md);
typedef uint32_t (*NTRU_CRYPTO_HASH_DIGEST_FN)(
void const *data,
uint32_t len,
void *md);
typedef struct _NTRU_CRYPTO_HASH_ALG_PARAMS {
uint8_t algid;
uint16_t block_length;
uint16_t digest_length;
NTRU_CRYPTO_HASH_INIT_FN init;
NTRU_CRYPTO_HASH_UPDATE_FN update;
NTRU_CRYPTO_HASH_FINAL_FN final;
NTRU_CRYPTO_HASH_DIGEST_FN digest;
} NTRU_CRYPTO_HASH_ALG_PARAMS;
static NTRU_CRYPTO_HASH_ALG_PARAMS const algs_params[] = {
{
NTRU_CRYPTO_HASH_ALGID_SHA1,
SHA_1_BLK_LEN,
SHA_1_MD_LEN,
(NTRU_CRYPTO_HASH_INIT_FN) SHA_1_INIT_FN,
(NTRU_CRYPTO_HASH_UPDATE_FN) SHA_1_UPDATE_FN,
(NTRU_CRYPTO_HASH_FINAL_FN) SHA_1_FINAL_FN,
(NTRU_CRYPTO_HASH_DIGEST_FN) SHA_1_DIGEST_FN,
},
{
NTRU_CRYPTO_HASH_ALGID_SHA256,
SHA_256_BLK_LEN,
SHA_256_MD_LEN,
(NTRU_CRYPTO_HASH_INIT_FN) SHA_256_INIT_FN,
(NTRU_CRYPTO_HASH_UPDATE_FN) SHA_256_UPDATE_FN,
(NTRU_CRYPTO_HASH_FINAL_FN) SHA_256_FINAL_FN,
(NTRU_CRYPTO_HASH_DIGEST_FN) SHA_256_DIGEST_FN,
},
};
static int const numalgs = (sizeof(algs_params)/sizeof(algs_params[0]));
/* get_alg_params
*
* Return a pointer to the hash algorithm parameters for the hash algorithm
* specified, by looking for algid in the global algs_params table.
* If not found, return NULL.
*/
static NTRU_CRYPTO_HASH_ALG_PARAMS const *
get_alg_params(
NTRU_CRYPTO_HASH_ALGID algid) /* in - the hash algorithm to find */
{
int i;
for (i = 0; i < numalgs; i++)
{
if (algs_params[i].algid == algid)
{
return &algs_params[i];
}
}
return NULL;
}
/* ntru_crypto_hash_set_alg
*
* Sets the hash algorithm for the hash context. This must be called before
* any calls to ntru_crypto_hash_block_length(),
* ntru_crypto_hash_digest_length(), or ntru_crypto_hash_init() are made.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the specified algorithm is not supported.
*/
uint32_t
ntru_crypto_hash_set_alg(
NTRU_CRYPTO_HASH_ALGID algid, /* in - hash algorithm to be used */
NTRU_CRYPTO_HASH_CTX *c) /* in/out - pointer to the hash context */
{
if (!c)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
c->alg_params = get_alg_params(algid);
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_block_length
*
* Gets the number of bytes in an input block for the hash algorithm
* specified in the hash context. The hash algorithm must have been set
* in the hash context with a call to ntru_crypto_hash_set_alg() prior to
* calling this function.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_block_length(
NTRU_CRYPTO_HASH_CTX *c, /* in - pointer to the hash context */
uint16_t *blk_len) /* out - address for block length in bytes */
{
if (!c || !blk_len)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
*blk_len = c->alg_params->block_length;
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_digest_length
*
* Gets the number of bytes needed to hold the message digest for the
* hash algorithm specified in the hash context. The algorithm must have
* been set in the hash context with a call to ntru_crypto_hash_set_alg() prior
* to calling this function.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_digest_length(
NTRU_CRYPTO_HASH_CTX const *c, /* in - pointer to the hash context */
uint16_t *md_len) /* out - addr for digest length in bytes */
{
if (!c || !md_len)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
*md_len = c->alg_params->digest_length;
HASH_RET(NTRU_CRYPTO_HASH_OK);
}
/* ntru_crypto_hash_init
*
* This routine performs standard initialization of the hash state.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_init(
NTRU_CRYPTO_HASH_CTX *c) /* in/out - pointer to hash context */
{
if (!c)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->init(&c->alg_ctx);
}
/* ntru_crypto_hash_update
*
* This routine processes input data and updates the hash calculation.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_OVERFLOW if too much text has been fed to the
* hash algorithm. The size limit is dependent on the hash algorithm,
* and not all algorithms have this limit.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_update(
NTRU_CRYPTO_HASH_CTX *c, /* in/out - pointer to hash context */
uint8_t const *data, /* in - pointer to input data */
uint32_t data_len) /* in - number of bytes of input data */
{
if (!c || (data_len && !data))
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->update(&c->alg_ctx, data, data_len);
}
/* ntru_crypto_hash_final
*
* This routine completes the hash calculation and returns the message digest.
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the algorithm has not been set.
*/
uint32_t
ntru_crypto_hash_final(
NTRU_CRYPTO_HASH_CTX *c, /* in/out - pointer to hash context */
uint8_t *md) /* out - address for message digest */
{
if (!c || !md)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
if (!c->alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
return c->alg_params->final(&c->alg_ctx, md);
}
/* ntru_crypto_hash_digest
*
* This routine computes a message digest. It is assumed that the
* output buffer md is large enough to hold the output (see
* ntru_crypto_hash_digest_length)
*
* Returns NTRU_CRYPTO_HASH_OK on success.
* Returns NTRU_CRYPTO_HASH_FAIL with corrupted context.
* Returns NTRU_CRYPTO_HASH_BAD_PARAMETER if inappropriate NULL pointers are
* passed.
* Returns NTRU_CRYPTO_HASH_OVERFLOW if too much text has been fed to the
* hash algorithm. The size limit is dependent on the hash algorithm,
* and not all algorithms have this limit.
* Returns NTRU_CRYPTO_HASH_BAD_ALG if the specified algorithm is not supported.
*/
uint32_t
ntru_crypto_hash_digest(
NTRU_CRYPTO_HASH_ALGID algid, /* in - the hash algorithm to use */
uint8_t const *data, /* in - pointer to input data */
uint32_t data_len, /* in - number of bytes of input data */
uint8_t *md) /* out - address for message digest */
{
NTRU_CRYPTO_HASH_ALG_PARAMS const *alg_params = get_alg_params(algid);
if (!alg_params)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_ALG);
}
if ((data_len && !data) || !md)
{
HASH_RET(NTRU_CRYPTO_HASH_BAD_PARAMETER);
}
return alg_params->digest(data, data_len, md);
}
| jschanck-si/NTRUEncrypt | src/ntru_crypto_hash.c | C | gpl-3.0 | 10,074 |
#!/usr/bin/env python
#
# MCP320x
#
# Author: Maurik Holtrop
#
# This module interfaces with the MCP300x or MCP320x family of chips. These
# are 10-bit and 12-bit ADCs respectively. The x number indicates the number
# of multiplexed analog inputs: 2 (MCP3202), 4 (MCP3204) or 8 (MCP3208)
# Communications with this chip are over the SPI protocol.
# See: https://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
#
# The version of the code has two SPI interfaces: the builtin hardware
# SPI interface on the RPI, or a "bit-banged" GPIO version.
#
# Bit-Bang GPIO:
# We emulate a SPI port in software using the GPIO lines.
# This is a bit slower than the hardware interface, but it is far more
# clear what is going on, plus the RPi has only one SPI device.
# Connections: RPi GPIO to MCP320x
# CS_bar_pin = CS/SHDN
# CLK_pin = CLK
# MOSI_pin = D_in
# MISO_pin = D_out
#
# Hardware SPI:
# This uses the builtin hardware on the RPi. You need to enable this with the
# raspi-config program first. The data rate can be up to 1MHz.
# Connections: RPi pins to MCP320x
# CE0 or CE1 = CS/SHDN (chip select) set CS_bar = 0 or 1
# SCK = CLK set CLK_pin = 1000000 (transfer speed)
# MOSI = D_in set MOSI_pin = 0
# MISO = D_out set MISO_pin = 0
# The SPI protocol simulated here is MODE=0, CPHA=0, which has a positive polarity clock,
# (the clock is 0 at rest, active at 1) and a positive phase (0 to 1 transition) for reading
# or writing the data. Thus corresponds to the specifications of the MCP320x chips.
#
# From MCP3208 datasheet:
# Outging data : MCU latches data to A/D converter on rising edges of SCLK
# Incoming data: Data is clocked out of A/D converter on falling edges, so should be read on rising edge.
try:
import RPi.GPIO as GPIO
except ImportError as error:
pass
try:
import Adafruit_BBIO as GPIO
except ImportError as error:
pass
try:
import spidev
except ImportError as error:
pass
from DevLib.MyValues import MyValues
class MCP320x:
"""This is an class that implements an interface to the MCP320x ADC chips.
Standard is the MCP3208, but is will also work wiht the MCP3202, MCP3204, MCP3002, MCP3004 and MCP3008."""
def __init__(self, cs_bar_pin, clk_pin=1000000, mosi_pin=0, miso_pin=0, chip='MCP3208',
channel_max=None, bit_length=None, single_ended=True):
"""Initialize the code and set the GPIO pins.
The last argument, ch_max, is 2 for the MCP3202, 4 for the
MCP3204 or 8 for the MCS3208."""
self._CLK = clk_pin
self._MOSI = mosi_pin
self._MISO = miso_pin
self._CS_bar = cs_bar_pin
chip_dictionary = {
"MCP3202": (2, 12),
"MCP3204": (4, 12),
"MCP3208": (8, 12),
"MCP3002": (2, 10),
"MCP3004": (4, 10),
"MCP3008": (8, 10)
}
if chip in chip_dictionary:
self._ChannelMax = chip_dictionary[chip][0]
self._BitLength = chip_dictionary[chip][1]
elif chip is None and (channel_max is not None) and (bit_length is not None):
self._ChannelMax = channel_max
self._BitLength = bit_length
else:
print("Unknown chip: {} - Please re-initialize.")
self._ChannelMax = 0
self._BitLength = 0
return
self._SingleEnded = single_ended
self._Vref = 3.3
self._values = MyValues(self.read_adc, self._ChannelMax)
self._volts = MyValues(self.read_volts, self._ChannelMax)
# This is used to speed up the SPIDEV communication. Send out MSB first.
# control[0] - bit7-3: upper 5 bits 0, because we can only send 8 bit sequences.
# - bit2 : Start bit - starts conversion in ADCs
# - bit1 : Select single_ended=1 or differential=0
# - bit0 : D2 high bit of channel select.
# control[1] - bit7 : D1 middle bit of channel select.
# - bit6 : D0 low bit of channel select.
# - bit5-0 : Don't care.
if self._SingleEnded:
self._control0 = [0b00000110, 0b00100000, 0] # Pre-compute part of the control word.
else:
self._control0 = [0b00000100, 0b00100000, 0] # Pre-compute part of the control word.
if self._MOSI > 0: # Bing Bang mode
assert self._MISO != 0 and self._CLK < 32
if GPIO.getmode() != 11:
GPIO.setmode(GPIO.BCM) # Use the BCM numbering scheme
GPIO.setup(self._CLK, GPIO.OUT) # Setup the ports for in and output
GPIO.setup(self._MOSI, GPIO.OUT)
GPIO.setup(self._MISO, GPIO.IN)
GPIO.setup(self._CS_bar, GPIO.OUT)
GPIO.output(self._CLK, 0) # Set the clock low.
GPIO.output(self._MOSI, 0) # Set the Master Out low
GPIO.output(self._CS_bar, 1) # Set the CS_bar high
else:
self._dev = spidev.SpiDev(0, self._CS_bar) # Start a SpiDev device
self._dev.mode = 0 # Set SPI mode (phase)
self._dev.max_speed_hz = self._CLK # Set the data rate
self._dev.bits_per_word = 8 # Number of bit per word. ALWAYS 8
def __del__(self):
""" Cleanup the GPIO before being destroyed """
if self._MOSI > 0:
GPIO.cleanup(self._CS_bar)
GPIO.cleanup(self._CLK)
GPIO.cleanup(self._MOSI)
GPIO.cleanup(self._MISO)
def get_channel_max(self):
"""Return the maximum number of channels"""
return self._ChannelMax
def get_bit_length(self):
"""Return the number of bits that will be read"""
return self._BitLength
def get_value_max(self):
"""Return the maximum value possible for an ADC read"""
return 2 ** self._BitLength - 1
def send_bit(self, bit):
""" Send out a single bit, and pulse clock."""
if self._MOSI == 0:
return
#
# The input is read on the rising edge of the clock.
#
GPIO.output(self._MOSI, bit) # Set the bit.
GPIO.output(self._CLK, 1) # Rising edge sends data
GPIO.output(self._CLK, 0) # Return clock to zero.
def read_bit(self):
""" Read a single bit from the ADC and pulse clock."""
if self._MOSI == 0:
return 0
#
# The output is going out on the falling edge of the clock,
# and is to be read on the rising edge of the clock.
# Clock should be already low, and data should already be set.
GPIO.output(self._CLK, 1) # Set the clock high. Ready to read.
bit = GPIO.input(self._MISO) # Read the bit.
GPIO.output(self._CLK, 0) # Return clock low, next bit will be set.
return bit
def read_adc(self, channel):
"""This reads the actual ADC value, after connecting the analog multiplexer to
the desired channel.
ADC value is returned at a n-bit integer value, with n=10 or 12 depending on the chip.
The value can be converted to a voltage with:
volts = data*Vref/(2**n-1)"""
if channel < 0 or channel >= self._ChannelMax:
print("Error - chip does not have channel = {}".format(channel))
if self._MOSI == 0:
# SPIdev Code
# This builds up the control word, which selects the channel
# and sets single/differential more.
control = [self._control0[0] + ((channel & 0b100) >> 2), self._control0[1]+((channel & 0b011) << 6), 0]
dat = self._dev.xfer(control)
value = (dat[1] << 8)+dat[2] # Unpack the two 8-bit words to a single integer.
return value
else:
# Bit Bang code.
# To read out this chip you need to send:
# 1 - start bit
# 2 - Single ended (1) or differential (0) mode
# 3 - Channel select: 1 bit for x=2 or 3 bits for x=4,8
# 4 - MSB first (1) or LSB first (0)
#
# Start of sequence sets CS_bar low, and sends sequence
#
GPIO.output(self._CLK, 0) # Make sure clock starts low.
GPIO.output(self._MOSI, 0)
GPIO.output(self._CS_bar, 0) # Select the chip.
self.send_bit(1) # Start bit = 1
self.send_bit(self._SingleEnded) # Select single or differential
if self._ChannelMax > 2:
self.send_bit(int((channel & 0b100) > 0)) # Send high bit of channel = DS2
self.send_bit(int((channel & 0b010) > 0)) # Send mid bit of channel = DS1
self.send_bit(int((channel & 0b001) > 0)) # Send low bit of channel = DS0
else:
self.send_bit(channel)
self.send_bit(0) # MSB First (for MCP3x02) or don't care.
# The clock is currently low, and the dummy bit = 0 is on the output of the ADC
#
self.read_bit() # Read the bit.
data = 0
for i in range(self._BitLength):
# Note you need to shift left first, or else you shift the last bit (bit 0)
# to the 1 position.
data <<= 1
bit = self.read_bit()
data += bit
GPIO.output(self._CS_bar, 1) # Unselect the chip.
return data
def read_volts(self, channel):
"""Read the ADC value from channel and convert to volts, assuming that Vref is set correctly. """
return self._Vref * self.read_adc(channel) / self.get_value_max()
def fast_read_adc0(self):
"""This reads the actual ADC value of channel 0, with as little overhead as possible.
Use with SPIDEV ONLY!!!!
returns: The ADC value as an n-bit integer value, with n=10 or 12 depending on the chip."""
dat = self._dev.xfer(self._control0)
value = (dat[1] << 8) + dat[2]
return value
@property
def values(self):
"""ADC values presented as a list."""
return self._values
@property
def volts(self):
"""ADC voltages presented as a list"""
return self._volts
@property
def accuracy(self):
"""The fractional voltage of the least significant bit. """
return self._Vref / float(self.get_value_max())
@property
def vref(self):
"""Reference voltage used by the chip. You need to set this. It defaults to 3.3V"""
return self._Vref
@vref.setter
def vref(self, vr):
self._Vref = vr
def main(argv):
"""Test code for the MCP320x driver. This assumes you are using a MCP3208
If no arguments are supplied, then use SPIdev for CE0 and read channel 0"""
if len(argv) < 3:
print("Args : ", argv)
cs_bar = 0
clk_pin = 1000000
mosi_pin = 0
miso_pin = 0
if len(argv) < 2:
channel = 0
else:
channel = int(argv[1])
elif len(argv) < 6:
print("Please supply: cs_bar_pin clk_pin mosi_pin miso_pin channel")
sys.exit(1)
else:
cs_bar = int(argv[1])
clk_pin = int(argv[2])
mosi_pin = int(argv[3])
miso_pin = int(argv[4])
channel = int(argv[5])
adc_chip = MCP320x(cs_bar, clk_pin, mosi_pin, miso_pin)
try:
while True:
value = adc_chip.read_adc(channel)
print("{:4d}".format(value))
time.sleep(0.1)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
import sys
import time
main(sys.argv)
| mholtrop/Phys605 | Python/DevLib/MCP320x.py | Python | gpl-3.0 | 11,971 |
/*
No-Babylon a job search engine with filtering ability
Copyright (C) 2012-2014 [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.laatusys.nobabylon.support;
import java.util.regex.Pattern;
public class ExcludeRegexpFilter implements Filter {
private final Pattern pattern;
public ExcludeRegexpFilter(String regexp, boolean caseSensitive) {
pattern = caseSensitive ? Pattern.compile(regexp) : Pattern.compile(regexp, Pattern.CASE_INSENSITIVE);
}
public ExcludeRegexpFilter(String regexp) {
this(regexp, false);
}
@Override
public boolean accept(String description) {
return !pattern.matcher(description).find();
}
}
| ferenc-jdev/no-babylon | src/main/java/org/laatusys/nobabylon/support/ExcludeRegexpFilter.java | Java | gpl-3.0 | 1,328 |
# __init__.py
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Michael Bayer [email protected]
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
__version__ = '0.3.4'
| codendev/rapidwsgi | src/mako/__init__.py | Python | gpl-3.0 | 256 |
#!/usr/bin/python
import sys
print "divsum_analysis.py DivsumFile NumberOfNucleotides"
try:
file = sys.argv[1]
except:
file = raw_input("Introduce RepeatMasker's Divsum file: ")
try:
nucs = sys.argv[2]
except:
nucs = raw_input("Introduce number of analysed nucleotides: ")
nucs = int(nucs)
data = open(file).readlines()
s_matrix = data.index("Coverage for each repeat class and divergence (Kimura)\n")
matrix = []
elements = data[s_matrix+1]
elements = elements.split()
for element in elements[1:]:
matrix.append([element,[]])
n_el = len(matrix)
for line in data[s_matrix+2:]:
# print line
info = line.split()
info = info[1:]
for n in range(0,n_el):
matrix[n][1].append(int(info[n]))
abs = open(file+".abs", "w")
rel = open(file+".rel", "w")
for n in range(0,n_el):
abs.write("%s\t%s\n" % (matrix[n][0], sum(matrix[n][1])))
rel.write("%s\t%s\n" % (matrix[n][0], round(1.0*sum(matrix[n][1])/nucs,100)))
| fjruizruano/ngs-protocols | divsum_analysis.py | Python | gpl-3.0 | 974 |
/*
TShock, a server mod for Terraria
Copyright (C) 2011-2018 Pryaxis & TShock Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Terraria;
using Terraria.ID;
using Terraria.Localization;
using TShockAPI.DB;
using TerrariaApi.Server;
using TShockAPI.Hooks;
using Terraria.GameContent.Events;
using Microsoft.Xna.Framework;
using OTAPI.Tile;
using TShockAPI.Localization;
using System.Text.RegularExpressions;
namespace TShockAPI
{
public delegate void CommandDelegate(CommandArgs args);
public class CommandArgs : EventArgs
{
public string Message { get; private set; }
public TSPlayer Player { get; private set; }
public bool Silent { get; private set; }
/// <summary>
/// Parameters passed to the arguement. Does not include the command name.
/// IE '/kick "jerk face"' will only have 1 argument
/// </summary>
public List<string> Parameters { get; private set; }
public Player TPlayer
{
get { return Player.TPlayer; }
}
public CommandArgs(string message, TSPlayer ply, List<string> args)
{
Message = message;
Player = ply;
Parameters = args;
Silent = false;
}
public CommandArgs(string message, bool silent, TSPlayer ply, List<string> args)
{
Message = message;
Player = ply;
Parameters = args;
Silent = silent;
}
}
public class Command
{
/// <summary>
/// Gets or sets whether to allow non-players to use this command.
/// </summary>
public bool AllowServer { get; set; }
/// <summary>
/// Gets or sets whether to do logging of this command.
/// </summary>
public bool DoLog { get; set; }
/// <summary>
/// Gets or sets the help text of this command.
/// </summary>
public string HelpText { get; set; }
/// <summary>
/// Gets or sets an extended description of this command.
/// </summary>
public string[] HelpDesc { get; set; }
/// <summary>
/// Gets the name of the command.
/// </summary>
public string Name { get { return Names[0]; } }
/// <summary>
/// Gets the names of the command.
/// </summary>
public List<string> Names { get; protected set; }
/// <summary>
/// Gets the permissions of the command.
/// </summary>
public List<string> Permissions { get; protected set; }
private CommandDelegate commandDelegate;
public CommandDelegate CommandDelegate
{
get { return commandDelegate; }
set
{
if (value == null)
throw new ArgumentNullException();
commandDelegate = value;
}
}
public Command(List<string> permissions, CommandDelegate cmd, params string[] names)
: this(cmd, names)
{
Permissions = permissions;
}
public Command(string permissions, CommandDelegate cmd, params string[] names)
: this(cmd, names)
{
Permissions = new List<string> { permissions };
}
public Command(CommandDelegate cmd, params string[] names)
{
if (cmd == null)
throw new ArgumentNullException("cmd");
if (names == null || names.Length < 1)
throw new ArgumentException("names");
AllowServer = true;
CommandDelegate = cmd;
DoLog = true;
HelpText = "No help available.";
HelpDesc = null;
Names = new List<string>(names);
Permissions = new List<string>();
}
public bool Run(string msg, bool silent, TSPlayer ply, List<string> parms)
{
if (!CanRun(ply))
return false;
try
{
CommandDelegate(new CommandArgs(msg, silent, ply, parms));
}
catch (Exception e)
{
ply.SendErrorMessage("Command failed, check logs for more details.");
TShock.Log.Error(e.ToString());
}
return true;
}
public bool Run(string msg, TSPlayer ply, List<string> parms)
{
return Run(msg, false, ply, parms);
}
public bool HasAlias(string name)
{
return Names.Contains(name);
}
public bool CanRun(TSPlayer ply)
{
if (Permissions == null || Permissions.Count < 1)
return true;
foreach (var Permission in Permissions)
{
if (ply.HasPermission(Permission))
return true;
}
return false;
}
}
public static class Commands
{
public static List<Command> ChatCommands = new List<Command>();
public static ReadOnlyCollection<Command> TShockCommands = new ReadOnlyCollection<Command>(new List<Command>());
/// <summary>
/// The command specifier, defaults to "/"
/// </summary>
public static string Specifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSpecifier) ? "/" : TShock.Config.CommandSpecifier; }
}
/// <summary>
/// The silent command specifier, defaults to "."
/// </summary>
public static string SilentSpecifier
{
get { return string.IsNullOrWhiteSpace(TShock.Config.CommandSilentSpecifier) ? "." : TShock.Config.CommandSilentSpecifier; }
}
private delegate void AddChatCommand(string permission, CommandDelegate command, params string[] names);
public static void InitCommands()
{
List<Command> tshockCommands = new List<Command>(100);
Action<Command> add = (cmd) =>
{
tshockCommands.Add(cmd);
ChatCommands.Add(cmd);
};
add(new Command(SetupToken, "setup")
{
AllowServer = false,
HelpText = "Used to authenticate as superadmin when first setting up TShock."
});
add(new Command(Permissions.user, ManageUsers, "user")
{
DoLog = false,
HelpText = "Manages user accounts."
});
#region Account Commands
add(new Command(Permissions.canlogin, AttemptLogin, "login")
{
AllowServer = false,
DoLog = false,
HelpText = "Logs you into an account."
});
add(new Command(Permissions.canlogout, Logout, "logout")
{
AllowServer = false,
DoLog = false,
HelpText = "Logs you out of your current account."
});
add(new Command(Permissions.canchangepassword, PasswordUser, "password")
{
AllowServer = false,
DoLog = false,
HelpText = "Changes your account's password."
});
add(new Command(Permissions.canregister, RegisterUser, "register")
{
AllowServer = false,
DoLog = false,
HelpText = "Registers you an account."
});
add(new Command(Permissions.checkaccountinfo, ViewAccountInfo, "accountinfo", "ai")
{
HelpText = "Shows information about a user."
});
#endregion
#region Admin Commands
add(new Command(Permissions.ban, Ban, "ban")
{
HelpText = "Manages player bans."
});
add(new Command(Permissions.broadcast, Broadcast, "broadcast", "bc", "say")
{
HelpText = "Broadcasts a message to everyone on the server."
});
add(new Command(Permissions.logs, DisplayLogs, "displaylogs")
{
HelpText = "Toggles whether you receive server logs."
});
add(new Command(Permissions.managegroup, Group, "group")
{
HelpText = "Manages groups."
});
add(new Command(Permissions.manageitem, ItemBan, "itemban")
{
HelpText = "Manages item bans."
});
add(new Command(Permissions.manageprojectile, ProjectileBan, "projban")
{
HelpText = "Manages projectile bans."
});
add(new Command(Permissions.managetile, TileBan, "tileban")
{
HelpText = "Manages tile bans."
});
add(new Command(Permissions.manageregion, Region, "region")
{
HelpText = "Manages regions."
});
add(new Command(Permissions.kick, Kick, "kick")
{
HelpText = "Removes a player from the server."
});
add(new Command(Permissions.mute, Mute, "mute", "unmute")
{
HelpText = "Prevents a player from talking."
});
add(new Command(Permissions.savessc, OverrideSSC, "overridessc", "ossc")
{
HelpText = "Overrides serverside characters for a player, temporarily."
});
add(new Command(Permissions.savessc, SaveSSC, "savessc")
{
HelpText = "Saves all serverside characters."
});
add(new Command(Permissions.uploaddata, UploadJoinData, "uploadssc")
{
HelpText = "Upload the account information when you joined the server as your Server Side Character data."
});
add(new Command(Permissions.settempgroup, TempGroup, "tempgroup")
{
HelpText = "Temporarily sets another player's group."
});
add(new Command(Permissions.su, SubstituteUser, "su")
{
HelpText = "Temporarily elevates you to Super Admin."
});
add(new Command(Permissions.su, SubstituteUserDo, "sudo")
{
HelpText = "Executes a command as the super admin."
});
add(new Command(Permissions.userinfo, GrabUserUserInfo, "userinfo", "ui")
{
HelpText = "Shows information about a player."
});
#endregion
#region Annoy Commands
add(new Command(Permissions.annoy, Annoy, "annoy")
{
HelpText = "Annoys a player for an amount of time."
});
add(new Command(Permissions.annoy, Confuse, "confuse")
{
HelpText = "Confuses a player for an amount of time."
});
add(new Command(Permissions.annoy, Rocket, "rocket")
{
HelpText = "Rockets a player upwards. Requires SSC."
});
add(new Command(Permissions.annoy, FireWork, "firework")
{
HelpText = "Spawns fireworks at a player."
});
#endregion
#region Configuration Commands
add(new Command(Permissions.maintenance, CheckUpdates, "checkupdates")
{
HelpText = "Checks for TShock updates."
});
add(new Command(Permissions.maintenance, Off, "off", "exit", "stop")
{
HelpText = "Shuts down the server while saving."
});
add(new Command(Permissions.maintenance, OffNoSave, "off-nosave", "exit-nosave", "stop-nosave")
{
HelpText = "Shuts down the server without saving."
});
add(new Command(Permissions.cfgreload, Reload, "reload")
{
HelpText = "Reloads the server configuration file."
});
add(new Command(Permissions.cfgpassword, ServerPassword, "serverpassword")
{
HelpText = "Changes the server password."
});
add(new Command(Permissions.maintenance, GetVersion, "version")
{
HelpText = "Shows the TShock version."
});
add(new Command(Permissions.whitelist, Whitelist, "whitelist")
{
HelpText = "Manages the server whitelist."
});
#endregion
#region Item Commands
add(new Command(Permissions.give, Give, "give", "g")
{
HelpText = "Gives another player an item."
});
add(new Command(Permissions.item, Item, "item", "i")
{
AllowServer = false,
HelpText = "Gives yourself an item."
});
#endregion
#region NPC Commands
add(new Command(Permissions.butcher, Butcher, "butcher")
{
HelpText = "Kills hostile NPCs or NPCs of a certain type."
});
add(new Command(Permissions.renamenpc, RenameNPC, "renamenpc")
{
HelpText = "Renames an NPC."
});
add(new Command(Permissions.invade, Invade, "invade")
{
HelpText = "Starts an NPC invasion."
});
add(new Command(Permissions.maxspawns, MaxSpawns, "maxspawns")
{
HelpText = "Sets the maximum number of NPCs."
});
add(new Command(Permissions.spawnboss, SpawnBoss, "spawnboss", "sb")
{
AllowServer = false,
HelpText = "Spawns a number of bosses around you."
});
add(new Command(Permissions.spawnmob, SpawnMob, "spawnmob", "sm")
{
AllowServer = false,
HelpText = "Spawns a number of mobs around you."
});
add(new Command(Permissions.spawnrate, SpawnRate, "spawnrate")
{
HelpText = "Sets the spawn rate of NPCs."
});
add(new Command(Permissions.clearangler, ClearAnglerQuests, "clearangler")
{
HelpText = "Resets the list of users who have completed an angler quest that day."
});
#endregion
#region TP Commands
add(new Command(Permissions.home, Home, "home")
{
AllowServer = false,
HelpText = "Sends you to your spawn point."
});
add(new Command(Permissions.spawn, Spawn, "spawn")
{
AllowServer = false,
HelpText = "Sends you to the world's spawn point."
});
add(new Command(Permissions.tp, TP, "tp")
{
AllowServer = false,
HelpText = "Teleports a player to another player."
});
add(new Command(Permissions.tpothers, TPHere, "tphere")
{
AllowServer = false,
HelpText = "Teleports a player to yourself."
});
add(new Command(Permissions.tpnpc, TPNpc, "tpnpc")
{
AllowServer = false,
HelpText = "Teleports you to an npc."
});
add(new Command(Permissions.tppos, TPPos, "tppos")
{
AllowServer = false,
HelpText = "Teleports you to tile coordinates."
});
add(new Command(Permissions.getpos, GetPos, "pos")
{
AllowServer = false,
HelpText = "Returns the user's or specified user's current position."
});
add(new Command(Permissions.tpallow, TPAllow, "tpallow")
{
AllowServer = false,
HelpText = "Toggles whether other people can teleport you."
});
#endregion
#region World Commands
add(new Command(Permissions.toggleexpert, ToggleExpert, "expert", "expertmode")
{
HelpText = "Toggles expert mode."
});
add(new Command(Permissions.antibuild, ToggleAntiBuild, "antibuild")
{
HelpText = "Toggles build protection."
});
add(new Command(Permissions.bloodmoon, Bloodmoon, "bloodmoon")
{
HelpText = "Sets a blood moon."
});
add(new Command(Permissions.grow, Grow, "grow")
{
AllowServer = false,
HelpText = "Grows plants at your location."
});
add(new Command(Permissions.dropmeteor, DropMeteor, "dropmeteor")
{
HelpText = "Drops a meteor somewhere in the world."
});
add(new Command(Permissions.eclipse, Eclipse, "eclipse")
{
HelpText = "Sets an eclipse."
});
add(new Command(Permissions.halloween, ForceHalloween, "forcehalloween")
{
HelpText = "Toggles halloween mode (goodie bags, pumpkins, etc)."
});
add(new Command(Permissions.xmas, ForceXmas, "forcexmas")
{
HelpText = "Toggles christmas mode (present spawning, santa, etc)."
});
add(new Command(Permissions.fullmoon, Fullmoon, "fullmoon")
{
HelpText = "Sets a full moon."
});
add(new Command(Permissions.hardmode, Hardmode, "hardmode")
{
HelpText = "Toggles the world's hardmode status."
});
add(new Command(Permissions.editspawn, ProtectSpawn, "protectspawn")
{
HelpText = "Toggles spawn protection."
});
add(new Command(Permissions.sandstorm, Sandstorm, "sandstorm")
{
HelpText = "Toggles sandstorms."
});
add(new Command(Permissions.rain, Rain, "rain")
{
HelpText = "Toggles the rain."
});
add(new Command(Permissions.worldsave, Save, "save")
{
HelpText = "Saves the world file."
});
add(new Command(Permissions.worldspawn, SetSpawn, "setspawn")
{
AllowServer = false,
HelpText = "Sets the world's spawn point to your location."
});
add(new Command(Permissions.dungeonposition, SetDungeon, "setdungeon")
{
AllowServer = false,
HelpText = "Sets the dungeon's position to your location."
});
add(new Command(Permissions.worldsettle, Settle, "settle")
{
HelpText = "Forces all liquids to update immediately."
});
add(new Command(Permissions.time, Time, "time")
{
HelpText = "Sets the world time."
});
add(new Command(Permissions.wind, Wind, "wind")
{
HelpText = "Changes the wind speed."
});
add(new Command(Permissions.worldinfo, WorldInfo, "world")
{
HelpText = "Shows information about the current world."
});
#endregion
#region Other Commands
add(new Command(Permissions.buff, Buff, "buff")
{
AllowServer = false,
HelpText = "Gives yourself a buff for an amount of time."
});
add(new Command(Permissions.clear, Clear, "clear")
{
HelpText = "Clears item drops or projectiles."
});
add(new Command(Permissions.buffplayer, GBuff, "gbuff", "buffplayer")
{
HelpText = "Gives another player a buff for an amount of time."
});
add(new Command(Permissions.godmode, ToggleGodMode, "godmode")
{
HelpText = "Toggles godmode on a player."
});
add(new Command(Permissions.heal, Heal, "heal")
{
HelpText = "Heals a player in HP and MP."
});
add(new Command(Permissions.kill, Kill, "kill")
{
HelpText = "Kills another player."
});
add(new Command(Permissions.cantalkinthird, ThirdPerson, "me")
{
HelpText = "Sends an action message to everyone."
});
add(new Command(Permissions.canpartychat, PartyChat, "party", "p")
{
AllowServer = false,
HelpText = "Sends a message to everyone on your team."
});
add(new Command(Permissions.whisper, Reply, "reply", "r")
{
HelpText = "Replies to a PM sent to you."
});
add(new Command(Rests.RestPermissions.restmanage, ManageRest, "rest")
{
HelpText = "Manages the REST API."
});
add(new Command(Permissions.slap, Slap, "slap")
{
HelpText = "Slaps a player, dealing damage."
});
add(new Command(Permissions.serverinfo, ServerInfo, "serverinfo")
{
HelpText = "Shows the server information."
});
add(new Command(Permissions.warp, Warp, "warp")
{
HelpText = "Teleports you to a warp point or manages warps."
});
add(new Command(Permissions.whisper, Whisper, "whisper", "w", "tell")
{
HelpText = "Sends a PM to a player."
});
add(new Command(Permissions.createdumps, CreateDumps, "dump-reference-data")
{
HelpText = "Creates a reference tables for Terraria data types and the TShock permission system in the server folder."
});
#endregion
add(new Command(Aliases, "aliases")
{
HelpText = "Shows a command's aliases."
});
add(new Command(Help, "help")
{
HelpText = "Lists commands or gives help on them."
});
add(new Command(Motd, "motd")
{
HelpText = "Shows the message of the day."
});
add(new Command(ListConnectedPlayers, "playing", "online", "who")
{
HelpText = "Shows the currently connected players."
});
add(new Command(Rules, "rules")
{
HelpText = "Shows the server's rules."
});
TShockCommands = new ReadOnlyCollection<Command>(tshockCommands);
}
public static bool HandleCommand(TSPlayer player, string text)
{
string cmdText = text.Remove(0, 1);
string cmdPrefix = text[0].ToString();
bool silent = false;
if (cmdPrefix == SilentSpecifier)
silent = true;
int index = -1;
for (int i = 0; i < cmdText.Length; i++)
{
if (IsWhiteSpace(cmdText[i]))
{
index = i;
break;
}
}
string cmdName;
if (index == 0) // Space after the command specifier should not be supported
{
player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
return true;
}
else if (index < 0)
cmdName = cmdText.ToLower();
else
cmdName = cmdText.Substring(0, index).ToLower();
List<string> args;
if (index < 0)
args = new List<string>();
else
args = ParseParameters(cmdText.Substring(index));
IEnumerable<Command> cmds = ChatCommands.FindAll(c => c.HasAlias(cmdName));
if (Hooks.PlayerHooks.OnPlayerCommand(player, cmdName, cmdText, args, ref cmds, cmdPrefix))
return true;
if (cmds.Count() == 0)
{
if (player.AwaitingResponse.ContainsKey(cmdName))
{
Action<CommandArgs> call = player.AwaitingResponse[cmdName];
player.AwaitingResponse.Remove(cmdName);
call(new CommandArgs(cmdText, player, args));
return true;
}
player.SendErrorMessage("Invalid command entered. Type {0}help for a list of valid commands.", Specifier);
return true;
}
foreach (Command cmd in cmds)
{
if (!cmd.CanRun(player))
{
TShock.Utils.SendLogs(string.Format("{0} tried to execute {1}{2}.", player.Name, Specifier, cmdText), Color.PaleVioletRed, player);
player.SendErrorMessage("You do not have access to this command.");
if (player.HasPermission(Permissions.su))
{
player.SendInfoMessage("You can use '{0}sudo {0}{1}' to override this check.", Specifier, cmdText);
}
}
else if (!cmd.AllowServer && !player.RealPlayer)
{
player.SendErrorMessage("You must use this command in-game.");
}
else
{
if (cmd.DoLog)
TShock.Utils.SendLogs(string.Format("{0} executed: {1}{2}.", player.Name, silent ? SilentSpecifier : Specifier, cmdText), Color.PaleVioletRed, player);
cmd.Run(cmdText, silent, player, args);
}
}
return true;
}
/// <summary>
/// Parses a string of parameters into a list. Handles quotes.
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static List<String> ParseParameters(string str)
{
var ret = new List<string>();
var sb = new StringBuilder();
bool instr = false;
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (c == '\\' && ++i < str.Length)
{
if (str[i] != '"' && str[i] != ' ' && str[i] != '\\')
sb.Append('\\');
sb.Append(str[i]);
}
else if (c == '"')
{
instr = !instr;
if (!instr)
{
ret.Add(sb.ToString());
sb.Clear();
}
else if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else if (IsWhiteSpace(c) && !instr)
{
if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else
sb.Append(c);
}
if (sb.Length > 0)
ret.Add(sb.ToString());
return ret;
}
private static bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t' || c == '\n';
}
#region Account commands
private static void AttemptLogin(CommandArgs args)
{
if (args.Player.LoginAttempts > TShock.Config.MaximumLoginAttempts && (TShock.Config.MaximumLoginAttempts != -1))
{
TShock.Log.Warn(String.Format("{0} ({1}) had {2} or more invalid login attempts and was kicked automatically.",
args.Player.IP, args.Player.Name, TShock.Config.MaximumLoginAttempts));
args.Player.Kick("Too many invalid login attempts.");
return;
}
if (args.Player.IsLoggedIn)
{
args.Player.SendErrorMessage("You are already logged in, and cannot login again.");
return;
}
UserAccount account = TShock.UserAccounts.GetUserAccountByName(args.Player.Name);
string password = "";
bool usingUUID = false;
if (args.Parameters.Count == 0 && !TShock.Config.DisableUUIDLogin)
{
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, ""))
return;
usingUUID = true;
}
else if (args.Parameters.Count == 1)
{
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Player.Name, args.Parameters[0]))
return;
password = args.Parameters[0];
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowLoginAnyUsername)
{
if (String.IsNullOrEmpty(args.Parameters[0]))
{
args.Player.SendErrorMessage("Bad login attempt.");
return;
}
if (PlayerHooks.OnPlayerPreLogin(args.Player, args.Parameters[0], args.Parameters[1]))
return;
account = TShock.UserAccounts.GetUserAccountByName(args.Parameters[0]);
password = args.Parameters[1];
}
else
{
args.Player.SendErrorMessage("Syntax: {0}login - Logs in using your UUID and character name", Specifier);
args.Player.SendErrorMessage(" {0}login <password> - Logs in using your password and character name", Specifier);
args.Player.SendErrorMessage(" {0}login <username> <password> - Logs in using your username and password", Specifier);
args.Player.SendErrorMessage("If you forgot your password, there is no way to recover it.");
return;
}
try
{
if (account == null)
{
args.Player.SendErrorMessage("A user account by that name does not exist.");
}
else if (account.VerifyPassword(password) ||
(usingUUID && account.UUID == args.Player.UUID && !TShock.Config.DisableUUIDLogin &&
!String.IsNullOrWhiteSpace(args.Player.UUID)))
{
args.Player.PlayerData = TShock.CharacterDB.GetPlayerData(args.Player, account.ID);
var group = TShock.Groups.GetGroupByName(account.Group);
args.Player.Group = group;
args.Player.tempGroup = null;
args.Player.Account = account;
args.Player.IsLoggedIn = true;
args.Player.IsDisabledForSSC = false;
if (Main.ServerSideCharacter)
{
if (args.Player.HasPermission(Permissions.bypassssc))
{
args.Player.PlayerData.CopyCharacter(args.Player);
TShock.CharacterDB.InsertPlayerData(args.Player);
}
args.Player.PlayerData.RestoreCharacter(args.Player);
}
args.Player.LoginFailsBySsi = false;
if (args.Player.HasPermission(Permissions.ignorestackhackdetection))
args.Player.IsDisabledForStackDetection = false;
if (args.Player.HasPermission(Permissions.usebanneditem))
args.Player.IsDisabledForBannedWearable = false;
args.Player.SendSuccessMessage("Authenticated as " + account.Name + " successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " authenticated successfully as user: " + account.Name + ".");
if ((args.Player.LoginHarassed) && (TShock.Config.RememberLeavePos))
{
if (TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP) != Vector2.Zero)
{
Vector2 pos = TShock.RememberedPos.GetLeavePos(args.Player.Name, args.Player.IP);
args.Player.Teleport((int)pos.X * 16, (int)pos.Y * 16);
}
args.Player.LoginHarassed = false;
}
TShock.UserAccounts.SetUserAccountUUID(account, args.Player.UUID);
Hooks.PlayerHooks.OnPlayerPostLogin(args.Player);
}
else
{
if (usingUUID && !TShock.Config.DisableUUIDLogin)
{
args.Player.SendErrorMessage("UUID does not match this character!");
}
else
{
args.Player.SendErrorMessage("Invalid password!");
}
TShock.Log.Warn(args.Player.IP + " failed to authenticate as user: " + account.Name + ".");
args.Player.LoginAttempts++;
}
}
catch (Exception ex)
{
args.Player.SendErrorMessage("There was an error processing your request.");
TShock.Log.Error(ex.ToString());
}
}
private static void Logout(CommandArgs args)
{
if (!args.Player.IsLoggedIn)
{
args.Player.SendErrorMessage("You are not logged in.");
return;
}
args.Player.Logout();
args.Player.SendSuccessMessage("You have been successfully logged out of your account.");
if (Main.ServerSideCharacter)
{
args.Player.SendWarningMessage("Server side characters are enabled. You need to be logged in to play.");
}
}
private static void PasswordUser(CommandArgs args)
{
try
{
if (args.Player.IsLoggedIn && args.Parameters.Count == 2)
{
string password = args.Parameters[0];
if (args.Player.Account.VerifyPassword(password))
{
try
{
args.Player.SendSuccessMessage("You changed your password!");
TShock.UserAccounts.SetUserAccountPassword(args.Player.Account, args.Parameters[1]); // SetUserPassword will hash it for you.
TShock.Log.ConsoleInfo(args.Player.IP + " named " + args.Player.Name + " changed the password of account " +
args.Player.Account.Name + ".");
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
}
}
else
{
args.Player.SendErrorMessage("You failed to change your password!");
TShock.Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for account: " +
args.Player.Account.Name + ".");
}
}
else
{
args.Player.SendErrorMessage("Not logged in or invalid syntax! Proper syntax: {0}password <oldpassword> <newpassword>", Specifier);
}
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("PasswordUser returned an error: " + ex);
}
}
private static void RegisterUser(CommandArgs args)
{
try
{
var account = new UserAccount();
string echoPassword = "";
if (args.Parameters.Count == 1)
{
account.Name = args.Player.Name;
echoPassword = args.Parameters[0];
try
{
account.CreateBCryptHash(args.Parameters[0]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
}
else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
{
account.Name = args.Parameters[0];
echoPassword = args.Parameters[1];
try
{
account.CreateBCryptHash(args.Parameters[1]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}register <password>", Specifier);
return;
}
account.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
account.UUID = args.Player.UUID;
if (TShock.UserAccounts.GetUserAccountByName(account.Name) == null && account.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user
{
args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", account.Name);
args.Player.SendSuccessMessage("Your password is {0}.", echoPassword);
TShock.UserAccounts.AddUserAccount(account);
TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, account.Name);
}
else
{
args.Player.SendErrorMessage("Sorry, " + account.Name + " was already taken by another person.");
args.Player.SendErrorMessage("Please try a different username.");
TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + account.Name);
}
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
TShock.Log.ConsoleError("RegisterUser returned an error: " + ex);
}
}
private static void ManageUsers(CommandArgs args)
{
// This guy needs to be here so that people don't get exceptions when they type /user
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
return;
}
string subcmd = args.Parameters[0];
// Add requires a username, password, and a group specified.
if (subcmd == "add" && args.Parameters.Count == 4)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
account.CreateBCryptHash(args.Parameters[2]);
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
return;
}
account.Group = args.Parameters[3];
try
{
TShock.UserAccounts.AddUserAccount(account);
args.Player.SendSuccessMessage("Account " + account.Name + " has been added to group " + account.Group + "!");
TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + account.Name + " to group " + account.Group);
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("Group " + account.Group + " does not exist!");
}
catch (UserAccountExistsException)
{
args.Player.SendErrorMessage("User " + account.Name + " already exists!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("User " + account.Name + " could not be added, check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
// User deletion requires a username
else if (subcmd == "del" && args.Parameters.Count == 2)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.RemoveUserAccount(account);
args.Player.SendSuccessMessage("Account removed successfully.");
TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + ".");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("The user " + account.Name + " does not exist! Deleted nobody!");
}
catch (UserAccountManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
TShock.Log.ConsoleError(ex.ToString());
}
}
// Password changing requires a username, and a new password to set
else if (subcmd == "password" && args.Parameters.Count == 3)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.SetUserAccountPassword(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + account.Name);
args.Player.SendSuccessMessage("Password change succeeded for " + account.Name + ".");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("Password change for " + account.Name + " failed! Check console!");
TShock.Log.ConsoleError(e.ToString());
}
catch (ArgumentOutOfRangeException)
{
args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
}
}
// Group changing requires a username or IP address, and a new group to set
else if (subcmd == "group" && args.Parameters.Count == 3)
{
var account = new UserAccount();
account.Name = args.Parameters[1];
try
{
TShock.UserAccounts.SetUserGroup(account, args.Parameters[2]);
TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + account.Name + " to group " + args.Parameters[2] + ".");
args.Player.SendSuccessMessage("Account " + account.Name + " has been changed to group " + args.Parameters[2] + "!");
}
catch (GroupNotExistsException)
{
args.Player.SendErrorMessage("That group does not exist!");
}
catch (UserAccountNotExistException)
{
args.Player.SendErrorMessage("User " + account.Name + " does not exist!");
}
catch (UserAccountManagerException e)
{
args.Player.SendErrorMessage("User " + account.Name + " could not be added. Check console for details.");
TShock.Log.ConsoleError(e.ToString());
}
}
else if (subcmd == "help")
{
args.Player.SendInfoMessage("Use command help:");
args.Player.SendInfoMessage("{0}user add username password group -- Adds a specified user", Specifier);
args.Player.SendInfoMessage("{0}user del username -- Removes a specified user", Specifier);
args.Player.SendInfoMessage("{0}user password username newpassword -- Changes a user's password", Specifier);
args.Player.SendInfoMessage("{0}user group username newgroup -- Changes a user's group", Specifier);
}
else
{
args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
}
}
#endregion
#region Stupid commands
private static void ServerInfo(CommandArgs args)
{
args.Player.SendInfoMessage("Memory usage: " + Process.GetCurrentProcess().WorkingSet64);
args.Player.SendInfoMessage("Allocated memory: " + Process.GetCurrentProcess().VirtualMemorySize64);
args.Player.SendInfoMessage("Total processor time: " + Process.GetCurrentProcess().TotalProcessorTime);
args.Player.SendInfoMessage("WinVer: " + Environment.OSVersion);
args.Player.SendInfoMessage("Proc count: " + Environment.ProcessorCount);
args.Player.SendInfoMessage("Machine name: " + Environment.MachineName);
}
private static void WorldInfo(CommandArgs args)
{
args.Player.SendInfoMessage("World name: " + (TShock.Config.UseServerName ? TShock.Config.ServerName : Main.worldName));
args.Player.SendInfoMessage("World size: {0}x{1}", Main.maxTilesX, Main.maxTilesY);
args.Player.SendInfoMessage("World ID: " + Main.worldID);
}
#endregion
#region Player Management Commands
private static void GrabUserUserInfo(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}userinfo <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count < 1)
args.Player.SendErrorMessage("Invalid player.");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var message = new StringBuilder();
message.Append("IP Address: ").Append(players[0].IP);
if (players[0].Account != null && players[0].IsLoggedIn)
message.Append(" | Logged in as: ").Append(players[0].Account.Name).Append(" | Group: ").Append(players[0].Group.Name);
args.Player.SendSuccessMessage(message.ToString());
}
}
private static void ViewAccountInfo(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}accountinfo <username>", Specifier);
return;
}
string username = String.Join(" ", args.Parameters);
if (!string.IsNullOrWhiteSpace(username))
{
var account = TShock.UserAccounts.GetUserAccountByName(username);
if (account != null)
{
DateTime LastSeen;
string Timezone = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).Hours.ToString("+#;-#");
if (DateTime.TryParse(account.LastAccessed, out LastSeen))
{
LastSeen = DateTime.Parse(account.LastAccessed).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s last login occured {1} {2} UTC{3}.", account.Name, LastSeen.ToShortDateString(),
LastSeen.ToShortTimeString(), Timezone);
}
if (args.Player.Group.HasPermission(Permissions.advaccountinfo))
{
List<string> KnownIps = JsonConvert.DeserializeObject<List<string>>(account.KnownIps?.ToString() ?? string.Empty);
string ip = KnownIps?[KnownIps.Count - 1] ?? "N/A";
DateTime Registered = DateTime.Parse(account.Registered).ToLocalTime();
args.Player.SendSuccessMessage("{0}'s group is {1}.", account.Name, account.Group);
args.Player.SendSuccessMessage("{0}'s last known IP is {1}.", account.Name, ip);
args.Player.SendSuccessMessage("{0}'s register date is {1} {2} UTC{3}.", account.Name, Registered.ToShortDateString(), Registered.ToShortTimeString(), Timezone);
}
}
else
args.Player.SendErrorMessage("User {0} does not exist.", username);
}
else args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}accountinfo <username>", Specifier);
}
private static void Kick(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}kick <player> [reason]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Missing player name.");
return;
}
string plStr = args.Parameters[0];
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
string reason = args.Parameters.Count > 1
? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1))
: "Misbehaviour.";
if (!players[0].Kick(reason, !args.Player.RealPlayer, false, args.Player.Name))
{
args.Player.SendErrorMessage("You can't kick another admin!");
}
}
}
private static void Ban(CommandArgs args)
{
string subcmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subcmd)
{
case "add":
#region Add Ban
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid command. Format: {0}ban add <player> [time] [reason]", Specifier);
args.Player.SendErrorMessage("Example: {0}ban add Shank 10d Hacking and cheating", Specifier);
args.Player.SendErrorMessage("Example: {0}ban add Ash", Specifier);
args.Player.SendErrorMessage("Use the time 0 (zero) for a permanent ban.");
return;
}
// Used only to notify if a ban was successful and who the ban was about
bool success = false;
string targetGeneralizedName = "";
// Effective ban target assignment
List<TSPlayer> players = TSPlayer.FindByNameOrID(args.Parameters[1]);
// Bad case: Players contains more than 1 person so we can't ban them
if (players.Count > 1)
{
//Fail fast
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
UserAccount offlineUserAccount = TShock.UserAccounts.GetUserAccountByName(args.Parameters[1]);
// Storage variable to determine if the command executor is the server console
// If it is, we assume they have full control and let them override permission checks
bool callerIsServerConsole = args.Player is TSServerPlayer;
// The ban reason the ban is going to have
string banReason = "Unknown.";
// The default ban length
// 0 is permanent ban, otherwise temp ban
int banLengthInSeconds = 0;
// Figure out if param 2 is a time or 0 or garbage
if (args.Parameters.Count >= 3)
{
bool parsedOkay = false;
if (args.Parameters[2] != "0")
{
parsedOkay = TShock.Utils.TryParseTime(args.Parameters[2], out banLengthInSeconds);
}
else
{
parsedOkay = true;
}
if (!parsedOkay)
{
args.Player.SendErrorMessage("Invalid time format. Example: 10d 5h 3m 2s.");
args.Player.SendErrorMessage("Use 0 (zero) for a permanent ban.");
return;
}
}
// If a reason exists, use the given reason.
if (args.Parameters.Count > 3)
{
banReason = String.Join(" ", args.Parameters.Skip(3));
}
// Good case: Online ban for matching character.
if (players.Count == 1)
{
TSPlayer target = players[0];
if (target.HasPermission(Permissions.immunetoban) && !callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", target.Name);
return;
}
targetGeneralizedName = target.Name;
success = TShock.Bans.AddBan(target.IP, target.Name, target.UUID, target.Account?.Name ?? "", banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
// Since this is an online ban, we need to dc the player and tell them now.
if (success)
{
if (banLengthInSeconds == 0)
{
target.Disconnect(String.Format("Permanently banned for {0}", banReason));
}
else
{
target.Disconnect(String.Format("Banned for {0} seconds for {1}", banLengthInSeconds, banReason));
}
}
}
// Case: Players & user are invalid, could be IP?
// Note: Order matters. If this method is above the online player check,
// This enables you to ban an IP even if the player exists in the database as a player.
// You'll get two bans for the price of one, in theory, because both IP and user named IP will be banned.
// ??? edge cases are weird, but this is going to happen
// The only way around this is to either segregate off the IP code or do something else.
if (players.Count == 0)
{
// If the target is a valid IP...
string pattern = @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
if (r.IsMatch(args.Parameters[1]))
{
targetGeneralizedName = "IP: " + args.Parameters[1];
success = TShock.Bans.AddBan(args.Parameters[1], "", "", "", banReason,
false, args.Player.Account.Name, banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
if (success && offlineUserAccount != null)
{
args.Player.SendSuccessMessage("Target IP {0} was banned successfully.", targetGeneralizedName);
args.Player.SendErrorMessage("Note: An account named with this IP address also exists.");
args.Player.SendErrorMessage("Note: It will also be banned.");
}
}
else
{
// Apparently there is no way to not IP ban someone
// This means that where we would normally just ban a "character name" here
// We can't because it requires some IP as a primary key.
if (offlineUserAccount == null)
{
args.Player.SendErrorMessage("Unable to ban target {0}.", args.Parameters[1]);
args.Player.SendErrorMessage("Target is not a valid IP address, a valid online player, or a known offline user.");
return;
}
}
}
// Case: Offline ban
if (players.Count == 0 && offlineUserAccount != null)
{
// Catch: we don't know an offline player's last login character name
// This means that we're banning their *user name* on the assumption that
// user name == character name
// (which may not be true)
// This needs to be fixed in a future implementation.
targetGeneralizedName = offlineUserAccount.Name;
if (TShock.Groups.GetGroupByName(offlineUserAccount.Group).HasPermission(Permissions.immunetoban) &&
!callerIsServerConsole)
{
args.Player.SendErrorMessage("Permission denied. Target {0} is immune to ban.", targetGeneralizedName);
return;
}
if (offlineUserAccount.KnownIps == null)
{
args.Player.SendErrorMessage("Unable to ban target {0} because they have no valid IP to ban.", targetGeneralizedName);
return;
}
string lastIP = JsonConvert.DeserializeObject<List<string>>(offlineUserAccount.KnownIps).Last();
success =
TShock.Bans.AddBan(lastIP,
"", offlineUserAccount.UUID, offlineUserAccount.Name, banReason, false, args.Player.Account.Name,
banLengthInSeconds == 0 ? "" : DateTime.UtcNow.AddSeconds(banLengthInSeconds).ToString("s"));
}
if (success)
{
args.Player.SendSuccessMessage("{0} was successfully banned.", targetGeneralizedName);
args.Player.SendInfoMessage("Length: {0}", banLengthInSeconds == 0 ? "Permanent." : banLengthInSeconds + " seconds.");
args.Player.SendInfoMessage("Reason: {0}", banReason);
if (!args.Silent)
{
if (banLengthInSeconds == 0)
{
TSPlayer.All.SendErrorMessage("{0} was permanently banned by {1} for: {2}",
targetGeneralizedName, args.Player.Account.Name, banReason);
}
else
{
TSPlayer.All.SendErrorMessage("{0} was temp banned for {1} seconds by {2} for: {3}",
targetGeneralizedName, banLengthInSeconds, args.Player.Account.Name, banReason);
}
}
}
else
{
args.Player.SendErrorMessage("{0} was NOT banned due to a database error or other system problem.", targetGeneralizedName);
args.Player.SendErrorMessage("If this player is online, they have NOT been kicked.");
args.Player.SendErrorMessage("Check the system logs for details.");
}
return;
}
#endregion
case "del":
#region Delete ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban del <player>", Specifier);
return;
}
string plStr = args.Parameters[1];
Ban ban = TShock.Bans.GetBanByName(plStr, false);
if (ban != null)
{
if (TShock.Bans.RemoveBan(ban.Name, true))
args.Player.SendSuccessMessage("Unbanned {0} ({1}).", ban.Name, ban.IP);
else
args.Player.SendErrorMessage("Failed to unban {0} ({1}), check logs.", ban.Name, ban.IP);
}
else
args.Player.SendErrorMessage("No bans for {0} exist.", plStr);
}
#endregion
return;
case "delip":
#region Delete IP ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}ban delip <ip>", Specifier);
return;
}
string ip = args.Parameters[1];
Ban ban = TShock.Bans.GetBanByIp(ip);
if (ban != null)
{
if (TShock.Bans.RemoveBan(ban.IP, false))
args.Player.SendSuccessMessage("Unbanned IP {0} ({1}).", ban.IP, ban.Name);
else
args.Player.SendErrorMessage("Failed to unban IP {0} ({1}), check logs.", ban.IP, ban.Name);
}
else
args.Player.SendErrorMessage("IP {0} is not banned.", ip);
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <target> <time> [reason] - Bans a player or user account if the player is not online.",
"del <player> - Unbans a player.",
"delip <ip> - Unbans an IP.",
"list [page] - Lists all player bans.",
"listip [page] - Lists all IP bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}ban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
{
return;
}
List<Ban> bans = TShock.Bans.GetBans();
var nameBans = from ban in bans
where !String.IsNullOrEmpty(ban.Name)
select ban.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(nameBans),
new PaginationTools.Settings
{
HeaderFormat = "Bans ({0}/{1}):",
FooterFormat = "Type {0}ban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no bans."
});
}
#endregion
return;
case "listip":
#region List IP bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
{
return;
}
List<Ban> bans = TShock.Bans.GetBans();
var ipBans = from ban in bans
where String.IsNullOrEmpty(ban.Name)
select ban.IP;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(ipBans),
new PaginationTools.Settings
{
HeaderFormat = "IP Bans ({0}/{1}):",
FooterFormat = "Type {0}ban listip {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no IP bans."
});
}
#endregion
return;
default:
args.Player.SendErrorMessage("Invalid subcommand! Type {0}ban help for more information.", Specifier);
return;
}
}
private static void Whitelist(CommandArgs args)
{
if (args.Parameters.Count == 1)
{
using (var tw = new StreamWriter(FileTools.WhitelistPath, true))
{
tw.WriteLine(args.Parameters[0]);
}
args.Player.SendSuccessMessage("Added " + args.Parameters[0] + " to the whitelist.");
}
}
private static void DisplayLogs(CommandArgs args)
{
args.Player.DisplayLogs = (!args.Player.DisplayLogs);
args.Player.SendSuccessMessage("You will " + (args.Player.DisplayLogs ? "now" : "no longer") + " receive logs.");
}
private static void SaveSSC(CommandArgs args)
{
if (Main.ServerSideCharacter)
{
args.Player.SendSuccessMessage("SSC has been saved.");
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.IsLoggedIn && !player.IsDisabledPendingTrashRemoval)
{
TShock.CharacterDB.InsertPlayerData(player, true);
}
}
}
}
private static void OverrideSSC(CommandArgs args)
{
if (!Main.ServerSideCharacter)
{
args.Player.SendErrorMessage("Server Side Characters is disabled.");
return;
}
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Correct usage: {0}overridessc|{0}ossc <player name>", Specifier);
return;
}
string playerNameToMatch = string.Join(" ", args.Parameters);
var matchedPlayers = TSPlayer.FindByNameOrID(playerNameToMatch);
if (matchedPlayers.Count < 1)
{
args.Player.SendErrorMessage("No players matched \"{0}\".", playerNameToMatch);
return;
}
else if (matchedPlayers.Count > 1)
{
args.Player.SendMultipleMatchError(matchedPlayers.Select(p => p.Name));
return;
}
TSPlayer matchedPlayer = matchedPlayers[0];
if (matchedPlayer.IsLoggedIn)
{
args.Player.SendErrorMessage("Player \"{0}\" is already logged in.", matchedPlayer.Name);
return;
}
if (!matchedPlayer.LoginFailsBySsi)
{
args.Player.SendErrorMessage("Player \"{0}\" has to perform a /login attempt first.", matchedPlayer.Name);
return;
}
if (matchedPlayer.IsDisabledPendingTrashRemoval)
{
args.Player.SendErrorMessage("Player \"{0}\" has to reconnect first.", matchedPlayer.Name);
return;
}
TShock.CharacterDB.InsertPlayerData(matchedPlayer);
args.Player.SendSuccessMessage("SSC of player \"{0}\" has been overriden.", matchedPlayer.Name);
}
private static void UploadJoinData(CommandArgs args)
{
TSPlayer targetPlayer = args.Player;
if (args.Parameters.Count == 1 && args.Player.HasPermission(Permissions.uploadothersdata))
{
List<TSPlayer> players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else if (players.Count == 0)
{
args.Player.SendErrorMessage("No player was found matching'{0}'", args.Parameters[0]);
return;
}
else
{
targetPlayer = players[0];
}
}
else if (args.Parameters.Count == 1)
{
args.Player.SendErrorMessage("You do not have permission to upload another player's character data.");
return;
}
else if (args.Parameters.Count > 0)
{
args.Player.SendErrorMessage("Usage: /uploadssc [playername]");
return;
}
else if (args.Parameters.Count == 0 && args.Player is TSServerPlayer)
{
args.Player.SendErrorMessage("A console can not upload their player data.");
args.Player.SendErrorMessage("Usage: /uploadssc [playername]");
return;
}
if (targetPlayer.IsLoggedIn)
{
if (TShock.CharacterDB.InsertSpecificPlayerData(targetPlayer, targetPlayer.DataWhenJoined))
{
targetPlayer.DataWhenJoined.RestoreCharacter(targetPlayer);
targetPlayer.SendSuccessMessage("Your local character data has been uploaded to the server.");
args.Player.SendSuccessMessage("The player's character data was successfully uploaded.");
}
else
{
args.Player.SendErrorMessage("Failed to upload your character data, are you logged in to an account?");
}
}
else
{
args.Player.SendErrorMessage("The target player has not logged in yet.");
}
}
private static void ForceHalloween(CommandArgs args)
{
TShock.Config.ForceHalloween = !TShock.Config.ForceHalloween;
Main.checkHalloween();
if (args.Silent)
args.Player.SendInfoMessage("{0}abled halloween mode!", (TShock.Config.ForceHalloween ? "en" : "dis"));
else
TSPlayer.All.SendInfoMessage("{0} {1}abled halloween mode!", args.Player.Name, (TShock.Config.ForceHalloween ? "en" : "dis"));
}
private static void ForceXmas(CommandArgs args)
{
TShock.Config.ForceXmas = !TShock.Config.ForceXmas;
Main.checkXMas();
if (args.Silent)
args.Player.SendInfoMessage("{0}abled Christmas mode!", (TShock.Config.ForceXmas ? "en" : "dis"));
else
TSPlayer.All.SendInfoMessage("{0} {1}abled Christmas mode!", args.Player.Name, (TShock.Config.ForceXmas ? "en" : "dis"));
}
private static void TempGroup(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendInfoMessage("Invalid usage");
args.Player.SendInfoMessage("Usage: {0}tempgroup <username> <new group> [time]", Specifier);
return;
}
List<TSPlayer> ply = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (ply.Count < 1)
{
args.Player.SendErrorMessage("Could not find player {0}.", args.Parameters[0]);
return;
}
if (ply.Count > 1)
{
args.Player.SendMultipleMatchError(ply.Select(p => p.Account.Name));
}
if (!TShock.Groups.GroupExists(args.Parameters[1]))
{
args.Player.SendErrorMessage("Could not find group {0}", args.Parameters[1]);
return;
}
if (args.Parameters.Count > 2)
{
int time;
if (!TShock.Utils.TryParseTime(args.Parameters[2], out time))
{
args.Player.SendErrorMessage("Invalid time string! Proper format: _d_h_m_s, with at least one time specifier.");
args.Player.SendErrorMessage("For example, 1d and 10h-30m+2m are both valid time strings, but 2 is not.");
return;
}
ply[0].tempGroupTimer = new System.Timers.Timer(time * 1000);
ply[0].tempGroupTimer.Elapsed += ply[0].TempGroupTimerElapsed;
ply[0].tempGroupTimer.Start();
}
Group g = TShock.Groups.GetGroupByName(args.Parameters[1]);
ply[0].tempGroup = g;
if (args.Parameters.Count < 3)
{
args.Player.SendSuccessMessage(String.Format("You have changed {0}'s group to {1}", ply[0].Name, g.Name));
ply[0].SendSuccessMessage(String.Format("Your group has temporarily been changed to {0}", g.Name));
}
else
{
args.Player.SendSuccessMessage(String.Format("You have changed {0}'s group to {1} for {2}",
ply[0].Name, g.Name, args.Parameters[2]));
ply[0].SendSuccessMessage(String.Format("Your group has been changed to {0} for {1}",
g.Name, args.Parameters[2]));
}
}
private static void SubstituteUser(CommandArgs args)
{
if (args.Player.tempGroup != null)
{
args.Player.tempGroup = null;
args.Player.tempGroupTimer.Stop();
args.Player.SendSuccessMessage("Your previous permission set has been restored.");
return;
}
else
{
args.Player.tempGroup = new SuperAdminGroup();
args.Player.tempGroupTimer = new System.Timers.Timer(600 * 1000);
args.Player.tempGroupTimer.Elapsed += args.Player.TempGroupTimerElapsed;
args.Player.tempGroupTimer.Start();
args.Player.SendSuccessMessage("Your account has been elevated to Super Admin for 10 minutes.");
return;
}
}
#endregion Player Management Commands
#region Server Maintenence Commands
// Executes a command as a superuser if you have sudo rights.
private static void SubstituteUserDo(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Usage: /sudo [command].");
args.Player.SendErrorMessage("Example: /sudo /ban add Shank 2d Hacking.");
return;
}
string replacementCommand = String.Join(" ", args.Parameters);
args.Player.tempGroup = new SuperAdminGroup();
HandleCommand(args.Player, replacementCommand);
args.Player.tempGroup = null;
return;
}
private static void Broadcast(CommandArgs args)
{
string message = string.Join(" ", args.Parameters);
TShock.Utils.Broadcast(
"(Server Broadcast) " + message,
Convert.ToByte(TShock.Config.BroadcastRGB[0]), Convert.ToByte(TShock.Config.BroadcastRGB[1]),
Convert.ToByte(TShock.Config.BroadcastRGB[2]));
}
private static void Off(CommandArgs args)
{
if (Main.ServerSideCharacter)
{
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.IsLoggedIn && !player.IsDisabledPendingTrashRemoval)
{
player.SaveServerCharacter();
}
}
}
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
TShock.Utils.StopServer(true, reason);
}
private static void OffNoSave(CommandArgs args)
{
string reason = ((args.Parameters.Count > 0) ? "Server shutting down: " + String.Join(" ", args.Parameters) : "Server shutting down!");
TShock.Utils.StopServer(false, reason);
}
private static void CheckUpdates(CommandArgs args)
{
args.Player.SendInfoMessage("An update check has been queued.");
try
{
TShock.UpdateManager.UpdateCheckAsync(null);
}
catch (Exception)
{
//swallow the exception
return;
}
}
private static void ManageRest(CommandArgs args)
{
string subCommand = "help";
if (args.Parameters.Count > 0)
subCommand = args.Parameters[0];
switch (subCommand.ToLower())
{
case "listusers":
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
Dictionary<string, int> restUsersTokens = new Dictionary<string, int>();
foreach (Rests.SecureRest.TokenData tokenData in TShock.RestApi.Tokens.Values)
{
if (restUsersTokens.ContainsKey(tokenData.Username))
restUsersTokens[tokenData.Username]++;
else
restUsersTokens.Add(tokenData.Username, 1);
}
List<string> restUsers = new List<string>(
restUsersTokens.Select(ut => string.Format("{0} ({1} tokens)", ut.Key, ut.Value)));
PaginationTools.SendPage(
args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(restUsers), new PaginationTools.Settings
{
NothingToDisplayString = "There are currently no active REST users.",
HeaderFormat = "Active REST Users ({0}/{1}):",
FooterFormat = "Type {0}rest listusers {{0}} for more.".SFormat(Specifier)
}
);
break;
}
case "destroytokens":
{
TShock.RestApi.Tokens.Clear();
args.Player.SendSuccessMessage("All REST tokens have been destroyed.");
break;
}
default:
{
args.Player.SendInfoMessage("Available REST Sub-Commands:");
args.Player.SendMessage("listusers - Lists all REST users and their current active tokens.", Color.White);
args.Player.SendMessage("destroytokens - Destroys all current REST tokens.", Color.White);
break;
}
}
}
#endregion Server Maintenence Commands
#region Cause Events and Spawn Monsters Commands
private static void DropMeteor(CommandArgs args)
{
WorldGen.spawnMeteor = false;
WorldGen.dropMeteor();
if (args.Silent)
{
args.Player.SendInfoMessage("A meteor has been triggered.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} triggered a meteor.", args.Player.Name);
}
}
private static void Fullmoon(CommandArgs args)
{
TSPlayer.Server.SetFullMoon();
if (args.Silent)
{
args.Player.SendInfoMessage("Started a full moon.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} started a full moon.", args.Player.Name);
}
}
private static void Bloodmoon(CommandArgs args)
{
TSPlayer.Server.SetBloodMoon(!Main.bloodMoon);
if (args.Silent)
{
args.Player.SendInfoMessage("{0}ed a blood moon.", Main.bloodMoon ? "start" : "stopp");
}
else
{
TSPlayer.All.SendInfoMessage("{0} {1}ed a blood moon.", args.Player.Name, Main.bloodMoon ? "start" : "stopp");
}
}
private static void Eclipse(CommandArgs args)
{
TSPlayer.Server.SetEclipse(!Main.eclipse);
if (args.Silent)
{
args.Player.SendInfoMessage("{0}ed an eclipse.", Main.eclipse ? "start" : "stopp");
}
else
{
TSPlayer.All.SendInfoMessage("{0} {1}ed an eclipse.", args.Player.Name, Main.eclipse ? "start" : "stopp");
}
}
private static void Invade(CommandArgs args)
{
if (Main.invasionSize <= 0)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}invade <invasion type> [wave]", Specifier);
return;
}
int wave = 1;
switch (args.Parameters[0].ToLower())
{
case "goblin":
case "goblins":
TSPlayer.All.SendInfoMessage("{0} has started a goblin army invasion.", args.Player.Name);
TShock.Utils.StartInvasion(1);
break;
case "snowman":
case "snowmen":
TSPlayer.All.SendInfoMessage("{0} has started a snow legion invasion.", args.Player.Name);
TShock.Utils.StartInvasion(2);
break;
case "pirate":
case "pirates":
TSPlayer.All.SendInfoMessage("{0} has started a pirate invasion.", args.Player.Name);
TShock.Utils.StartInvasion(3);
break;
case "pumpkin":
case "pumpkinmoon":
if (args.Parameters.Count > 1)
{
if (!int.TryParse(args.Parameters[1], out wave) || wave <= 0)
{
args.Player.SendErrorMessage("Invalid wave!");
break;
}
}
TSPlayer.Server.SetPumpkinMoon(true);
Main.bloodMoon = false;
NPC.waveKills = 0f;
NPC.waveNumber = wave;
TSPlayer.All.SendInfoMessage("{0} started the pumpkin moon at wave {1}!", args.Player.Name, wave);
break;
case "frost":
case "frostmoon":
if (args.Parameters.Count > 1)
{
if (!int.TryParse(args.Parameters[1], out wave) || wave <= 0)
{
args.Player.SendErrorMessage("Invalid wave!");
return;
}
}
TSPlayer.Server.SetFrostMoon(true);
Main.bloodMoon = false;
NPC.waveKills = 0f;
NPC.waveNumber = wave;
TSPlayer.All.SendInfoMessage("{0} started the frost moon at wave {1}!", args.Player.Name, wave);
break;
case "martian":
case "martians":
TSPlayer.All.SendInfoMessage("{0} has started a martian invasion.", args.Player.Name);
TShock.Utils.StartInvasion(4);
break;
}
}
else if (DD2Event.Ongoing)
{
DD2Event.StopInvasion();
TSPlayer.All.SendInfoMessage("{0} has ended the Old One's Army event.", args.Player.Name);
}
else
{
TSPlayer.All.SendInfoMessage("{0} has ended the invasion.", args.Player.Name);
Main.invasionSize = 0;
}
}
private static void ClearAnglerQuests(CommandArgs args)
{
if (args.Parameters.Count > 0)
{
var result = Main.anglerWhoFinishedToday.RemoveAll(s => s.ToLower().Equals(args.Parameters[0].ToLower()));
if (result > 0)
{
args.Player.SendSuccessMessage("Removed {0} players from the angler quest completion list for today.", result);
foreach (TSPlayer ply in TShock.Players.Where(p => p != null && p.Active && p.TPlayer.name.ToLower().Equals(args.Parameters[0].ToLower())))
{
//this will always tell the client that they have not done the quest today.
ply.SendData((PacketTypes)74, "");
}
}
else
args.Player.SendErrorMessage("Failed to find any users by that name on the list.");
}
else
{
Main.anglerWhoFinishedToday.Clear();
NetMessage.SendAnglerQuest(-1);
args.Player.SendSuccessMessage("Cleared all users from the angler quest completion list for today.");
}
}
private static void ToggleExpert(CommandArgs args)
{
Main.expertMode = !Main.expertMode;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
args.Player.SendSuccessMessage("Expert mode is now {0}.", Main.expertMode ? "on" : "off");
}
private static void Hardmode(CommandArgs args)
{
if (Main.hardMode)
{
Main.hardMode = false;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
args.Player.SendSuccessMessage("Hardmode is now off.");
}
else if (!TShock.Config.DisableHardmode)
{
WorldGen.StartHardmode();
args.Player.SendSuccessMessage("Hardmode is now on.");
}
else
{
args.Player.SendErrorMessage("Hardmode is disabled via config.");
}
}
private static void SpawnBoss(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnboss <boss type> [amount]", Specifier);
return;
}
int amount = 1;
if (args.Parameters.Count == 2 && (!int.TryParse(args.Parameters[1], out amount) || amount <= 0))
{
args.Player.SendErrorMessage("Invalid boss amount!");
return;
}
NPC npc = new NPC();
switch (args.Parameters[0].ToLower())
{
case "*":
case "all":
int[] npcIds = { 4, 13, 35, 50, 125, 126, 127, 134, 222, 245, 262, 266, 370, 398 };
TSPlayer.Server.SetTime(false, 0.0);
foreach (int i in npcIds)
{
npc.SetDefaults(i);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
}
TSPlayer.All.SendSuccessMessage("{0} has spawned all bosses {1} time(s).", args.Player.Name, amount);
return;
case "brain":
case "brain of cthulhu":
npc.SetDefaults(266);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Brain of Cthulhu {1} time(s).", args.Player.Name, amount);
return;
case "destroyer":
npc.SetDefaults(134);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Destroyer {1} time(s).", args.Player.Name, amount);
return;
case "duke":
case "duke fishron":
case "fishron":
npc.SetDefaults(370);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Duke Fishron {1} time(s).", args.Player.Name, amount);
return;
case "eater":
case "eater of worlds":
npc.SetDefaults(13);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Eater of Worlds {1} time(s).", args.Player.Name, amount);
return;
case "eye":
case "eye of cthulhu":
npc.SetDefaults(4);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Eye of Cthulhu {1} time(s).", args.Player.Name, amount);
return;
case "golem":
npc.SetDefaults(245);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Golem {1} time(s).", args.Player.Name, amount);
return;
case "king":
case "king slime":
npc.SetDefaults(50);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned King Slime {1} time(s).", args.Player.Name, amount);
return;
case "plantera":
npc.SetDefaults(262);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Plantera {1} time(s).", args.Player.Name, amount);
return;
case "prime":
case "skeletron prime":
npc.SetDefaults(127);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron Prime {1} time(s).", args.Player.Name, amount);
return;
case "queen":
case "queen bee":
npc.SetDefaults(222);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Queen Bee {1} time(s).", args.Player.Name, amount);
return;
case "skeletron":
npc.SetDefaults(35);
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned Skeletron {1} time(s).", args.Player.Name, amount);
return;
case "twins":
TSPlayer.Server.SetTime(false, 0.0);
npc.SetDefaults(125);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
npc.SetDefaults(126);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Twins {1} time(s).", args.Player.Name, amount);
return;
case "wof":
case "wall of flesh":
if (Main.wof >= 0)
{
args.Player.SendErrorMessage("There is already a Wall of Flesh!");
return;
}
if (args.Player.Y / 16f < Main.maxTilesY - 205)
{
args.Player.SendErrorMessage("You must spawn the Wall of Flesh in hell!");
return;
}
NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
TSPlayer.All.SendSuccessMessage("{0} has spawned the Wall of Flesh.", args.Player.Name);
return;
case "moon":
case "moon lord":
npc.SetDefaults(398);
TSPlayer.Server.SpawnNPC(npc.type, npc.FullName, amount, args.Player.TileX, args.Player.TileY);
TSPlayer.All.SendSuccessMessage("{0} has spawned the Moon Lord {1} time(s).", args.Player.Name, amount);
return;
default:
args.Player.SendErrorMessage("Invalid boss type!");
return;
}
}
private static void SpawnMob(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnmob <mob type> [amount]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
int amount = 1;
if (args.Parameters.Count == 2 && !int.TryParse(args.Parameters[1], out amount))
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}spawnmob <mob type> [amount]", Specifier);
return;
}
amount = Math.Min(amount, Main.maxNPCs);
var npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
}
else
{
var npc = npcs[0];
if (npc.type >= 1 && npc.type < Main.maxNPCTypes && npc.type != 113)
{
TSPlayer.Server.SpawnNPC(npc.netID, npc.FullName, amount, args.Player.TileX, args.Player.TileY, 50, 20);
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned {0} {1} time(s).", npc.FullName, amount);
}
else
{
TSPlayer.All.SendSuccessMessage("{0} has spawned {1} {2} time(s).", args.Player.Name, npc.FullName, amount);
}
}
else if (npc.type == 113)
{
if (Main.wof >= 0 || (args.Player.Y / 16f < (Main.maxTilesY - 205)))
{
args.Player.SendErrorMessage("Can't spawn Wall of Flesh!");
return;
}
NPC.SpawnWOF(new Vector2(args.Player.X, args.Player.Y));
if (args.Silent)
{
args.Player.SendSuccessMessage("Spawned Wall of Flesh!");
}
else
{
TSPlayer.All.SendSuccessMessage("{0} has spawned a Wall of Flesh!", args.Player.Name);
}
}
else
{
args.Player.SendErrorMessage("Invalid mob type!");
}
}
}
#endregion Cause Events and Spawn Monsters Commands
#region Teleport Commands
private static void Home(CommandArgs args)
{
args.Player.Spawn();
args.Player.SendSuccessMessage("Teleported to your spawnpoint.");
}
private static void Spawn(CommandArgs args)
{
if (args.Player.Teleport(Main.spawnTileX * 16, (Main.spawnTileY * 16) - 48))
args.Player.SendSuccessMessage("Teleported to the map's spawnpoint.");
}
private static void TP(CommandArgs args)
{
if (args.Parameters.Count != 1 && args.Parameters.Count != 2)
{
if (args.Player.HasPermission(Permissions.tpothers))
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tp <player> [player 2]", Specifier);
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tp <player>", Specifier);
return;
}
if (args.Parameters.Count == 1)
{
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var target = players[0];
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", target.Name);
return;
}
if (args.Player.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
args.Player.SendSuccessMessage("Teleported to {0}.", target.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported to you.", args.Player.Name);
}
}
}
else
{
if (!args.Player.HasPermission(Permissions.tpothers))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
var players1 = TSPlayer.FindByNameOrID(args.Parameters[0]);
var players2 = TSPlayer.FindByNameOrID(args.Parameters[1]);
if (players2.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players2.Count > 1)
args.Player.SendMultipleMatchError(players2.Select(p => p.Name));
else if (players1.Count == 0)
{
if (args.Parameters[0] == "*")
{
if (!args.Player.HasPermission(Permissions.tpallothers))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
var target = players2[0];
foreach (var source in TShock.Players.Where(p => p != null && p != args.Player))
{
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
continue;
if (source.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
if (args.Player != source)
{
if (args.Player.HasPermission(Permissions.tpsilent))
source.SendSuccessMessage("You were teleported to {0}.", target.Name);
else
source.SendSuccessMessage("{0} teleported you to {1}.", args.Player.Name, target.Name);
}
if (args.Player != target)
{
if (args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} was teleported to you.", source.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported {1} to you.", args.Player.Name, source.Name);
}
}
}
args.Player.SendSuccessMessage("Teleported everyone to {0}.", target.Name);
}
else
args.Player.SendErrorMessage("Invalid player!");
}
else if (players1.Count > 1)
args.Player.SendMultipleMatchError(players1.Select(p => p.Name));
else
{
var source = players1[0];
if (!source.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", source.Name);
return;
}
var target = players2[0];
if (!target.TPAllow && !args.Player.HasPermission(Permissions.tpoverride))
{
args.Player.SendErrorMessage("{0} has disabled players from teleporting.", target.Name);
return;
}
args.Player.SendSuccessMessage("Teleported {0} to {1}.", source.Name, target.Name);
if (source.Teleport(target.TPlayer.position.X, target.TPlayer.position.Y))
{
if (args.Player != source)
{
if (args.Player.HasPermission(Permissions.tpsilent))
source.SendSuccessMessage("You were teleported to {0}.", target.Name);
else
source.SendSuccessMessage("{0} teleported you to {1}.", args.Player.Name, target.Name);
}
if (args.Player != target)
{
if (args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} was teleported to you.", source.Name);
if (!args.Player.HasPermission(Permissions.tpsilent))
target.SendInfoMessage("{0} teleported {1} to you.", args.Player.Name, source.Name);
}
}
}
}
}
private static void TPHere(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
if (args.Player.HasPermission(Permissions.tpallothers))
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tphere <player|*>", Specifier);
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tphere <player>", Specifier);
return;
}
string playerName = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(playerName);
if (players.Count == 0)
{
if (playerName == "*")
{
if (!args.Player.HasPermission(Permissions.tpallothers))
{
args.Player.SendErrorMessage("You do not have permission to use this command.");
return;
}
for (int i = 0; i < Main.maxPlayers; i++)
{
if (Main.player[i].active && (Main.player[i] != args.TPlayer))
{
if (TShock.Players[i].Teleport(args.TPlayer.position.X, args.TPlayer.position.Y))
TShock.Players[i].SendSuccessMessage(String.Format("You were teleported to {0}.", args.Player.Name));
}
}
args.Player.SendSuccessMessage("Teleported everyone to yourself.");
}
else
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var plr = players[0];
if (plr.Teleport(args.TPlayer.position.X, args.TPlayer.position.Y))
{
plr.SendInfoMessage("You were teleported to {0}.", args.Player.Name);
args.Player.SendSuccessMessage("Teleported {0} to yourself.", plr.Name);
}
}
}
private static void TPNpc(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tpnpc <NPC>", Specifier);
return;
}
var npcStr = string.Join(" ", args.Parameters);
var matches = new List<NPC>();
foreach (var npc in Main.npc.Where(npc => npc.active))
{
var englishName = EnglishLanguage.GetNpcNameById(npc.netID);
if (string.Equals(npc.FullName, npcStr, StringComparison.InvariantCultureIgnoreCase) ||
string.Equals(englishName, npcStr, StringComparison.InvariantCultureIgnoreCase))
{
matches = new List<NPC> { npc };
break;
}
if (npc.FullName.ToLowerInvariant().StartsWith(npcStr.ToLowerInvariant()) ||
englishName?.StartsWith(npcStr, StringComparison.InvariantCultureIgnoreCase) == true)
matches.Add(npc);
}
if (matches.Count > 1)
{
args.Player.SendMultipleMatchError(matches.Select(n => $"{n.FullName}({n.whoAmI})"));
return;
}
if (matches.Count == 0)
{
args.Player.SendErrorMessage("Invalid NPC!");
return;
}
var target = matches[0];
args.Player.Teleport(target.position.X, target.position.Y);
args.Player.SendSuccessMessage("Teleported to the '{0}'.", target.FullName);
}
private static void GetPos(CommandArgs args)
{
var player = args.Player.Name;
if (args.Parameters.Count > 0)
{
player = String.Join(" ", args.Parameters);
}
var players = TSPlayer.FindByNameOrID(player);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
args.Player.SendSuccessMessage("Location of {0} is ({1}, {2}).", players[0].Name, players[0].TileX, players[0].TileY);
}
}
private static void TPPos(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tppos <tile x> <tile y>", Specifier);
return;
}
int x, y;
if (!int.TryParse(args.Parameters[0], out x) || !int.TryParse(args.Parameters[1], out y))
{
args.Player.SendErrorMessage("Invalid tile positions!");
return;
}
x = Math.Max(0, x);
y = Math.Max(0, y);
x = Math.Min(x, Main.maxTilesX - 1);
y = Math.Min(y, Main.maxTilesY - 1);
args.Player.Teleport(16 * x, 16 * y);
args.Player.SendSuccessMessage("Teleported to {0}, {1}!", x, y);
}
private static void TPAllow(CommandArgs args)
{
if (!args.Player.TPAllow)
args.Player.SendSuccessMessage("You have removed your teleportation protection.");
if (args.Player.TPAllow)
args.Player.SendSuccessMessage("You have enabled teleportation protection.");
args.Player.TPAllow = !args.Player.TPAllow;
}
private static void Warp(CommandArgs args)
{
bool hasManageWarpPermission = args.Player.HasPermission(Permissions.managewarp);
if (args.Parameters.Count < 1)
{
if (hasManageWarpPermission)
{
args.Player.SendInfoMessage("Invalid syntax! Proper syntax: {0}warp [command] [arguments]", Specifier);
args.Player.SendInfoMessage("Commands: add, del, hide, list, send, [warpname]");
args.Player.SendInfoMessage("Arguments: add [warp name], del [warp name], list [page]");
args.Player.SendInfoMessage("Arguments: send [player] [warp name], hide [warp name] [Enable(true/false)]");
args.Player.SendInfoMessage("Examples: {0}warp add foobar, {0}warp hide foobar true, {0}warp foobar", Specifier);
return;
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp [name] or {0}warp list <page>", Specifier);
return;
}
}
if (args.Parameters[0].Equals("list"))
{
#region List warps
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> warpNames = from warp in TShock.Warps.Warps
where !warp.IsPrivate
select warp.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(warpNames),
new PaginationTools.Settings
{
HeaderFormat = "Warps ({0}/{1}):",
FooterFormat = "Type {0}warp list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no warps defined."
});
#endregion
}
else if (args.Parameters[0].ToLower() == "add" && hasManageWarpPermission)
{
#region Add warp
if (args.Parameters.Count == 2)
{
string warpName = args.Parameters[1];
if (warpName == "list" || warpName == "hide" || warpName == "del" || warpName == "add")
{
args.Player.SendErrorMessage("Name reserved, use a different name.");
}
else if (TShock.Warps.Add(args.Player.TileX, args.Player.TileY, warpName))
{
args.Player.SendSuccessMessage("Warp added: " + warpName);
}
else
{
args.Player.SendErrorMessage("Warp " + warpName + " already exists.");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp add [name]", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "del" && hasManageWarpPermission)
{
#region Del warp
if (args.Parameters.Count == 2)
{
string warpName = args.Parameters[1];
if (TShock.Warps.Remove(warpName))
{
args.Player.SendSuccessMessage("Warp deleted: " + warpName);
}
else
args.Player.SendErrorMessage("Could not find the specified warp.");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp del [name]", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "hide" && hasManageWarpPermission)
{
#region Hide warp
if (args.Parameters.Count == 3)
{
string warpName = args.Parameters[1];
bool state = false;
if (Boolean.TryParse(args.Parameters[2], out state))
{
if (TShock.Warps.Hide(args.Parameters[1], state))
{
if (state)
args.Player.SendSuccessMessage("Warp " + warpName + " is now private.");
else
args.Player.SendSuccessMessage("Warp " + warpName + " is now public.");
}
else
args.Player.SendErrorMessage("Could not find specified warp.");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp hide [name] <true/false>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp hide [name] <true/false>", Specifier);
#endregion
}
else if (args.Parameters[0].ToLower() == "send" && args.Player.HasPermission(Permissions.tpothers))
{
#region Warp send
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}warp send [player] [warpname]", Specifier);
return;
}
var foundplr = TSPlayer.FindByNameOrID(args.Parameters[1]);
if (foundplr.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (foundplr.Count > 1)
{
args.Player.SendMultipleMatchError(foundplr.Select(p => p.Name));
return;
}
string warpName = args.Parameters[2];
var warp = TShock.Warps.Find(warpName);
var plr = foundplr[0];
if (warp.Position != Point.Zero)
{
if (plr.Teleport(warp.Position.X * 16, warp.Position.Y * 16))
{
plr.SendSuccessMessage(String.Format("{0} warped you to {1}.", args.Player.Name, warpName));
args.Player.SendSuccessMessage(String.Format("You warped {0} to {1}.", plr.Name, warpName));
}
}
else
{
args.Player.SendErrorMessage("Specified warp not found.");
}
#endregion
}
else
{
string warpName = String.Join(" ", args.Parameters);
var warp = TShock.Warps.Find(warpName);
if (warp != null)
{
if (args.Player.Teleport(warp.Position.X * 16, warp.Position.Y * 16))
args.Player.SendSuccessMessage("Warped to " + warpName + ".");
}
else
{
args.Player.SendErrorMessage("The specified warp was not found.");
}
}
}
#endregion Teleport Commands
#region Group Management
private static void Group(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add group
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group add <group name> [permissions]", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
string permissions = String.Join(",", args.Parameters);
try
{
TShock.Groups.AddGroup(groupName, null, permissions, TShockAPI.Group.defaultChatColor);
args.Player.SendSuccessMessage("The group was added successfully!");
}
catch (GroupExistsException)
{
args.Player.SendErrorMessage("That group already exists!");
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "addperm":
#region Add permissions
{
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group addperm <group name> <permissions...>", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
if (groupName == "*")
{
foreach (Group g in TShock.Groups)
{
TShock.Groups.AddPermissions(g.Name, args.Parameters);
}
args.Player.SendSuccessMessage("Modified all groups.");
return;
}
try
{
string response = TShock.Groups.AddPermissions(groupName, args.Parameters);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
return;
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <name> <permissions...> - Adds a new group.",
"addperm <group> <permissions...> - Adds permissions to a group.",
"color <group> <rrr,ggg,bbb> - Changes a group's chat color.",
"rename <group> <new name> - Changes a group's name.",
"del <group> - Deletes a group.",
"delperm <group> <permissions...> - Removes permissions from a group.",
"list [page] - Lists groups.",
"listperm <group> [page] - Lists a group's permissions.",
"parent <group> <parent group> - Changes a group's parent group.",
"prefix <group> <prefix> - Changes a group's prefix.",
"suffix <group> <suffix> - Changes a group's suffix."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Group Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}group help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "parent":
#region Parent
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group parent <group name> [new parent group name]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newParentGroupName = string.Join(" ", args.Parameters.Skip(2));
if (!string.IsNullOrWhiteSpace(newParentGroupName) && !TShock.Groups.GroupExists(newParentGroupName))
{
args.Player.SendErrorMessage("No such group \"{0}\".", newParentGroupName);
return;
}
try
{
TShock.Groups.UpdateGroup(groupName, newParentGroupName, group.Permissions, group.ChatColor, group.Suffix, group.Prefix);
if (!string.IsNullOrWhiteSpace(newParentGroupName))
args.Player.SendSuccessMessage("Parent of group \"{0}\" set to \"{1}\".", groupName, newParentGroupName);
else
args.Player.SendSuccessMessage("Removed parent of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (group.Parent != null)
args.Player.SendSuccessMessage("Parent of \"{0}\" is \"{1}\".", group.Name, group.Parent.Name);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no parent.", group.Name);
}
}
#endregion
return;
case "suffix":
#region Suffix
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group suffix <group name> [new suffix]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newSuffix = string.Join(" ", args.Parameters.Skip(2));
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, group.ChatColor, newSuffix, group.Prefix);
if (!string.IsNullOrWhiteSpace(newSuffix))
args.Player.SendSuccessMessage("Suffix of group \"{0}\" set to \"{1}\".", groupName, newSuffix);
else
args.Player.SendSuccessMessage("Removed suffix of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (!string.IsNullOrWhiteSpace(group.Suffix))
args.Player.SendSuccessMessage("Suffix of \"{0}\" is \"{1}\".", group.Name, group.Suffix);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no suffix.", group.Name);
}
}
#endregion
return;
case "prefix":
#region Prefix
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group prefix <group name> [new prefix]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count > 2)
{
string newPrefix = string.Join(" ", args.Parameters.Skip(2));
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, group.ChatColor, group.Suffix, newPrefix);
if (!string.IsNullOrWhiteSpace(newPrefix))
args.Player.SendSuccessMessage("Prefix of group \"{0}\" set to \"{1}\".", groupName, newPrefix);
else
args.Player.SendSuccessMessage("Removed prefix of group \"{0}\".", groupName);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
if (!string.IsNullOrWhiteSpace(group.Prefix))
args.Player.SendSuccessMessage("Prefix of \"{0}\" is \"{1}\".", group.Name, group.Prefix);
else
args.Player.SendSuccessMessage("Group \"{0}\" has no prefix.", group.Name);
}
}
#endregion
return;
case "color":
#region Color
{
if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group color <group name> [new color(000,000,000)]", Specifier);
return;
}
string groupName = args.Parameters[1];
Group group = TShock.Groups.GetGroupByName(groupName);
if (group == null)
{
args.Player.SendErrorMessage("No such group \"{0}\".", groupName);
return;
}
if (args.Parameters.Count == 3)
{
string newColor = args.Parameters[2];
String[] parts = newColor.Split(',');
byte r;
byte g;
byte b;
if (parts.Length == 3 && byte.TryParse(parts[0], out r) && byte.TryParse(parts[1], out g) && byte.TryParse(parts[2], out b))
{
try
{
TShock.Groups.UpdateGroup(groupName, group.ParentName, group.Permissions, newColor, group.Suffix, group.Prefix);
args.Player.SendSuccessMessage("Color of group \"{0}\" set to \"{1}\".", groupName, newColor);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
else
{
args.Player.SendErrorMessage("Invalid syntax for color, expected \"rrr,ggg,bbb\"");
}
}
else
{
args.Player.SendSuccessMessage("Color of \"{0}\" is \"{1}\".", group.Name, group.ChatColor);
}
}
#endregion
return;
case "rename":
#region Rename group
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group rename <group> <new name>", Specifier);
return;
}
string group = args.Parameters[1];
string newName = args.Parameters[2];
try
{
string response = TShock.Groups.RenameGroup(group, newName);
args.Player.SendSuccessMessage(response);
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.Message);
}
}
#endregion
return;
case "del":
#region Delete group
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group del <group name>", Specifier);
return;
}
try
{
string response = TShock.Groups.DeleteGroup(args.Parameters[1]);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "delperm":
#region Delete permissions
{
if (args.Parameters.Count < 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group delperm <group name> <permissions...>", Specifier);
return;
}
string groupName = args.Parameters[1];
args.Parameters.RemoveRange(0, 2);
if (groupName == "*")
{
foreach (Group g in TShock.Groups)
{
TShock.Groups.DeletePermissions(g.Name, args.Parameters);
}
args.Player.SendSuccessMessage("Modified all groups.");
return;
}
try
{
string response = TShock.Groups.DeletePermissions(groupName, args.Parameters);
if (response.Length > 0)
{
args.Player.SendSuccessMessage(response);
}
return;
}
catch (GroupManagerException ex)
{
args.Player.SendErrorMessage(ex.ToString());
}
}
#endregion
return;
case "list":
#region List groups
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var groupNames = from grp in TShock.Groups.groups
select grp.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(groupNames),
new PaginationTools.Settings
{
HeaderFormat = "Groups ({0}/{1}):",
FooterFormat = "Type {0}group list {{0}} for more.".SFormat(Specifier)
});
}
#endregion
return;
case "listperm":
#region List permissions
{
if (args.Parameters.Count == 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}group listperm <group name> [page]", Specifier);
return;
}
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 2, args.Player, out pageNumber))
return;
if (!TShock.Groups.GroupExists(args.Parameters[1]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
Group grp = TShock.Groups.GetGroupByName(args.Parameters[1]);
List<string> permissions = grp.TotalPermissions;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(permissions),
new PaginationTools.Settings
{
HeaderFormat = "Permissions for " + grp.Name + " ({0}/{1}):",
FooterFormat = "Type {0}group listperm {1} {{0}} for more.".SFormat(Specifier, grp.Name),
NothingToDisplayString = "There are currently no permissions for " + grp.Name + "."
});
}
#endregion
return;
}
}
#endregion Group Management
#region Item Management
private static void ItemBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add item
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban add <item name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
TShock.Itembans.AddNewBan(EnglishLanguage.GetItemNameById(items[0].type));
args.Player.SendSuccessMessage("Banned " + items[0].Name + ".");
}
}
#endregion
return;
case "allow":
#region Allow group to item
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban allow <item name> <group name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ItemBan ban = TShock.Itembans.GetItemBanByName(EnglishLanguage.GetItemNameById(items[0].type));
if (ban == null)
{
args.Player.SendErrorMessage("{0} is not banned.", items[0].Name);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.Itembans.AllowGroup(EnglishLanguage.GetItemNameById(items[0].type), args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to use {1}.", args.Parameters[2], items[0].Name);
}
else
{
args.Player.SendWarningMessage("{0} is already allowed to use {1}.", args.Parameters[2], items[0].Name);
}
}
}
#endregion
return;
case "del":
#region Delete item
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban del <item name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
TShock.Itembans.RemoveBan(EnglishLanguage.GetItemNameById(items[0].type));
args.Player.SendSuccessMessage("Unbanned " + items[0].Name + ".");
}
}
#endregion
return;
case "disallow":
#region Disllow group from item
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}itemban disallow <item name> <group name>", Specifier);
return;
}
List<Item> items = TShock.Utils.GetItemByIdOrName(args.Parameters[1]);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item.");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ItemBan ban = TShock.Itembans.GetItemBanByName(EnglishLanguage.GetItemNameById(items[0].type));
if (ban == null)
{
args.Player.SendErrorMessage("{0} is not banned.", items[0].Name);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.Itembans.RemoveGroup(EnglishLanguage.GetItemNameById(items[0].type), args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed to use {1}.", args.Parameters[2], items[0].Name);
}
else
{
args.Player.SendWarningMessage("{0} is already disallowed to use {1}.", args.Parameters[2], items[0].Name);
}
}
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <item> - Adds an item ban.",
"allow <item> <group> - Allows a group to use an item.",
"del <item> - Deletes an item ban.",
"disallow <item> <group> - Disallows a group from using an item.",
"list [page] - Lists all item bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Item Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}itemban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List items
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> itemNames = from itemBan in TShock.Itembans.ItemBans
select itemBan.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(itemNames),
new PaginationTools.Settings
{
HeaderFormat = "Item bans ({0}/{1}):",
FooterFormat = "Type {0}itemban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned items."
});
}
#endregion
return;
}
}
#endregion Item Management
#region Projectile Management
private static void ProjectileBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add projectile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban add <proj id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
TShock.ProjectileBans.AddNewBan(id);
args.Player.SendSuccessMessage("Banned projectile {0}.", id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "allow":
#region Allow group to projectile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban allow <id> <group>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ProjectileBan ban = TShock.ProjectileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Projectile {0} is not banned.", id);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.ProjectileBans.AllowGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to use projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendWarningMessage("{0} is already allowed to use projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "del":
#region Delete projectile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban del <id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
TShock.ProjectileBans.RemoveBan(id);
args.Player.SendSuccessMessage("Unbanned projectile {0}.", id);
return;
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "disallow":
#region Disallow group from projectile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}projban disallow <id> <group name>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id > 0 && id < Main.maxProjectileTypes)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
ProjectileBan ban = TShock.ProjectileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Projectile {0} is not banned.", id);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.ProjectileBans.RemoveGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed from using projectile {1}.", args.Parameters[2], id);
return;
}
else
args.Player.SendWarningMessage("{0} is already prevented from using projectile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid projectile ID!");
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <projectile ID> - Adds a projectile ban.",
"allow <projectile ID> <group> - Allows a group to use a projectile.",
"del <projectile ID> - Deletes an projectile ban.",
"disallow <projectile ID> <group> - Disallows a group from using a projectile.",
"list [page] - Lists all projectile bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Projectile Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}projban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List projectiles
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<Int16> projectileIds = from projectileBan in TShock.ProjectileBans.ProjectileBans
select projectileBan.ID;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(projectileIds),
new PaginationTools.Settings
{
HeaderFormat = "Projectile bans ({0}/{1}):",
FooterFormat = "Type {0}projban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned projectiles."
});
}
#endregion
return;
}
}
#endregion Projectile Management
#region Tile Management
private static void TileBan(CommandArgs args)
{
string subCmd = args.Parameters.Count == 0 ? "help" : args.Parameters[0].ToLower();
switch (subCmd)
{
case "add":
#region Add tile
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban add <tile id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
TShock.TileBans.AddNewBan(id);
args.Player.SendSuccessMessage("Banned tile {0}.", id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "allow":
#region Allow group to place tile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban allow <id> <group>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
TileBan ban = TShock.TileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Tile {0} is not banned.", id);
return;
}
if (!ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.TileBans.AllowGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been allowed to place tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendWarningMessage("{0} is already allowed to place tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "del":
#region Delete tile ban
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban del <id>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
TShock.TileBans.RemoveBan(id);
args.Player.SendSuccessMessage("Unbanned tile {0}.", id);
return;
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "disallow":
#region Disallow group from placing tile
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}tileban disallow <id> <group name>", Specifier);
return;
}
short id;
if (Int16.TryParse(args.Parameters[1], out id) && id >= 0 && id < Main.maxTileSets)
{
if (!TShock.Groups.GroupExists(args.Parameters[2]))
{
args.Player.SendErrorMessage("Invalid group.");
return;
}
TileBan ban = TShock.TileBans.GetBanById(id);
if (ban == null)
{
args.Player.SendErrorMessage("Tile {0} is not banned.", id);
return;
}
if (ban.AllowedGroups.Contains(args.Parameters[2]))
{
TShock.TileBans.RemoveGroup(id, args.Parameters[2]);
args.Player.SendSuccessMessage("{0} has been disallowed from placing tile {1}.", args.Parameters[2], id);
return;
}
else
args.Player.SendWarningMessage("{0} is already prevented from placing tile {1}.", args.Parameters[2], id);
}
else
args.Player.SendErrorMessage("Invalid tile ID!");
}
#endregion
return;
case "help":
#region Help
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
var lines = new List<string>
{
"add <tile ID> - Adds a tile ban.",
"allow <tile ID> <group> - Allows a group to place a tile.",
"del <tile ID> - Deletes a tile ban.",
"disallow <tile ID> <group> - Disallows a group from place a tile.",
"list [page] - Lists all tile bans."
};
PaginationTools.SendPage(args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Tile Ban Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}tileban help {{0}} for more sub-commands.".SFormat(Specifier)
}
);
}
#endregion
return;
case "list":
#region List tile bans
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<Int16> tileIds = from tileBan in TShock.TileBans.TileBans
select tileBan.ID;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(tileIds),
new PaginationTools.Settings
{
HeaderFormat = "Tile bans ({0}/{1}):",
FooterFormat = "Type {0}tileban list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no banned tiles."
});
}
#endregion
return;
}
}
#endregion Tile Management
#region Server Config Commands
private static void SetSpawn(CommandArgs args)
{
Main.spawnTileX = args.Player.TileX + 1;
Main.spawnTileY = args.Player.TileY + 3;
SaveManager.Instance.SaveWorld(false);
args.Player.SendSuccessMessage("Spawn has now been set at your location.");
}
private static void SetDungeon(CommandArgs args)
{
Main.dungeonX = args.Player.TileX + 1;
Main.dungeonY = args.Player.TileY + 3;
SaveManager.Instance.SaveWorld(false);
args.Player.SendSuccessMessage("The dungeon's position has now been set at your location.");
}
private static void Reload(CommandArgs args)
{
TShock.Utils.Reload();
Hooks.GeneralHooks.OnReloadEvent(args.Player);
args.Player.SendSuccessMessage(
"Configuration, permissions, and regions reload complete. Some changes may require a server restart.");
}
private static void ServerPassword(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}serverpassword \"<new password>\"", Specifier);
return;
}
string passwd = args.Parameters[0];
TShock.Config.ServerPassword = passwd;
args.Player.SendSuccessMessage(string.Format("Server password has been changed to: {0}.", passwd));
}
private static void Save(CommandArgs args)
{
SaveManager.Instance.SaveWorld(false);
foreach (TSPlayer tsply in TShock.Players.Where(tsply => tsply != null))
{
tsply.SaveServerCharacter();
}
args.Player.SendSuccessMessage("Save succeeded.");
}
private static void Settle(CommandArgs args)
{
if (Liquid.panicMode)
{
args.Player.SendWarningMessage("Liquids are already settling!");
return;
}
Liquid.StartPanic();
args.Player.SendInfoMessage("Settling liquids.");
}
private static void MaxSpawns(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendInfoMessage("Current maximum spawns: {0}", TShock.Config.DefaultMaximumSpawns);
return;
}
if (String.Equals(args.Parameters[0], "default", StringComparison.CurrentCultureIgnoreCase))
{
TShock.Config.DefaultMaximumSpawns = NPC.defaultMaxSpawns = 5;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the maximum spawns to 5.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the maximum spawns to 5.", args.Player.Name);
}
return;
}
int maxSpawns = -1;
if (!int.TryParse(args.Parameters[0], out maxSpawns) || maxSpawns < 0 || maxSpawns > Main.maxNPCs)
{
args.Player.SendWarningMessage("Invalid maximum spawns! Acceptable range is {0} to {1}", 0, Main.maxNPCs);
return;
}
TShock.Config.DefaultMaximumSpawns = NPC.defaultMaxSpawns = maxSpawns;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the maximum spawns to {0}.", maxSpawns);
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the maximum spawns to {1}.", args.Player.Name, maxSpawns);
}
}
private static void SpawnRate(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendInfoMessage("Current spawn rate: {0}", TShock.Config.DefaultSpawnRate);
return;
}
if (String.Equals(args.Parameters[0], "default", StringComparison.CurrentCultureIgnoreCase))
{
TShock.Config.DefaultSpawnRate = NPC.defaultSpawnRate = 600;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the spawn rate to 600.");
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the spawn rate to 600.", args.Player.Name);
}
return;
}
int spawnRate = -1;
if (!int.TryParse(args.Parameters[0], out spawnRate) || spawnRate < 0)
{
args.Player.SendWarningMessage("Invalid spawn rate!");
return;
}
TShock.Config.DefaultSpawnRate = NPC.defaultSpawnRate = spawnRate;
if (args.Silent)
{
args.Player.SendInfoMessage("Changed the spawn rate to {0}.", spawnRate);
}
else
{
TSPlayer.All.SendInfoMessage("{0} changed the spawn rate to {1}.", args.Player.Name, spawnRate);
}
}
#endregion Server Config Commands
#region Time/PvpFun Commands
private static void Time(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
double time = Main.time / 3600.0;
time += 4.5;
if (!Main.dayTime)
time += 15.0;
time = time % 24.0;
args.Player.SendInfoMessage("The current time is {0}:{1:D2}.", (int)Math.Floor(time), (int)Math.Floor((time % 1.0) * 60.0));
return;
}
switch (args.Parameters[0].ToLower())
{
case "day":
TSPlayer.Server.SetTime(true, 0.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 4:30.", args.Player.Name);
break;
case "night":
TSPlayer.Server.SetTime(false, 0.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 19:30.", args.Player.Name);
break;
case "noon":
TSPlayer.Server.SetTime(true, 27000.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 12:00.", args.Player.Name);
break;
case "midnight":
TSPlayer.Server.SetTime(false, 16200.0);
TSPlayer.All.SendInfoMessage("{0} set the time to 0:00.", args.Player.Name);
break;
default:
string[] array = args.Parameters[0].Split(':');
if (array.Length != 2)
{
args.Player.SendErrorMessage("Invalid time string! Proper format: hh:mm, in 24-hour time.");
return;
}
int hours;
int minutes;
if (!int.TryParse(array[0], out hours) || hours < 0 || hours > 23
|| !int.TryParse(array[1], out minutes) || minutes < 0 || minutes > 59)
{
args.Player.SendErrorMessage("Invalid time string! Proper format: hh:mm, in 24-hour time.");
return;
}
decimal time = hours + (minutes / 60.0m);
time -= 4.50m;
if (time < 0.00m)
time += 24.00m;
if (time >= 15.00m)
{
TSPlayer.Server.SetTime(false, (double)((time - 15.00m) * 3600.0m));
}
else
{
TSPlayer.Server.SetTime(true, (double)(time * 3600.0m));
}
TSPlayer.All.SendInfoMessage("{0} set the time to {1}:{2:D2}.", args.Player.Name, hours, minutes);
break;
}
}
private static void Sandstorm(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}sandstorm <stop/start>", Specifier);
return;
}
switch (args.Parameters[0].ToLowerInvariant())
{
case "start":
Terraria.GameContent.Events.Sandstorm.StartSandstorm();
TSPlayer.All.SendInfoMessage("{0} started a sandstorm.", args.Player.Name);
break;
case "stop":
Terraria.GameContent.Events.Sandstorm.StopSandstorm();
TSPlayer.All.SendInfoMessage("{0} stopped the sandstorm.", args.Player.Name);
break;
default:
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}sandstorm <stop/start>", Specifier);
break;
}
}
private static void Rain(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rain [slime] <stop/start>", Specifier);
return;
}
int switchIndex = 0;
if (args.Parameters.Count == 2 && args.Parameters[0].ToLowerInvariant() == "slime")
{
switchIndex = 1;
}
switch (args.Parameters[switchIndex].ToLower())
{
case "start":
if (switchIndex == 1)
{
Main.StartSlimeRain(false);
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} caused it to rain slime.", args.Player.Name);
}
else
{
Main.StartRain();
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} caused it to rain.", args.Player.Name);
}
break;
case "stop":
if (switchIndex == 1)
{
Main.StopSlimeRain(false);
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} ended the slimey downpour.", args.Player.Name);
}
else
{
Main.StopRain();
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} ended the downpour.", args.Player.Name);
}
break;
default:
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rain [slime] <stop/start>", Specifier);
break;
}
}
private static void Slap(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}slap <player> [damage]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
string plStr = args.Parameters[0];
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
int damage = 5;
if (args.Parameters.Count == 2)
{
int.TryParse(args.Parameters[1], out damage);
}
if (!args.Player.HasPermission(Permissions.kill))
{
damage = TShock.Utils.Clamp(damage, 15, 0);
}
plr.DamagePlayer(damage);
TSPlayer.All.SendInfoMessage("{0} slapped {1} for {2} damage.", args.Player.Name, plr.Name, damage);
TShock.Log.Info("{0} slapped {1} for {2} damage.", args.Player.Name, plr.Name, damage);
}
}
private static void Wind(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}wind <speed>", Specifier);
return;
}
int speed;
if (!int.TryParse(args.Parameters[0], out speed) || speed * 100 < 0)
{
args.Player.SendErrorMessage("Invalid wind speed!");
return;
}
Main.windSpeed = speed;
Main.windSpeedSet = speed;
Main.windSpeedSpeed = 0f;
TSPlayer.All.SendData(PacketTypes.WorldInfo);
TSPlayer.All.SendInfoMessage("{0} changed the wind speed to {1}.", args.Player.Name, speed);
}
#endregion Time/PvpFun Commands
#region Region Commands
private static void Region(CommandArgs args)
{
string cmd = "help";
if (args.Parameters.Count > 0)
{
cmd = args.Parameters[0].ToLower();
}
switch (cmd)
{
case "name":
{
{
args.Player.SendInfoMessage("Hit a block to get the name of the region");
args.Player.AwaitingName = true;
args.Player.AwaitingNameParameters = args.Parameters.Skip(1).ToArray();
}
break;
}
case "set":
{
int choice = 0;
if (args.Parameters.Count == 2 &&
int.TryParse(args.Parameters[1], out choice) &&
choice >= 1 && choice <= 2)
{
args.Player.SendInfoMessage("Hit a block to Set Point " + choice);
args.Player.AwaitingTempPoint = choice;
}
else
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /region set <1/2>");
}
break;
}
case "define":
{
if (args.Parameters.Count > 1)
{
if (!args.Player.TempPoints.Any(p => p == Point.Zero))
{
string regionName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
var x = Math.Min(args.Player.TempPoints[0].X, args.Player.TempPoints[1].X);
var y = Math.Min(args.Player.TempPoints[0].Y, args.Player.TempPoints[1].Y);
var width = Math.Abs(args.Player.TempPoints[0].X - args.Player.TempPoints[1].X);
var height = Math.Abs(args.Player.TempPoints[0].Y - args.Player.TempPoints[1].Y);
if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.Account.Name,
Main.worldID.ToString()))
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
args.Player.SendInfoMessage("Set region " + regionName);
}
else
{
args.Player.SendErrorMessage("Region " + regionName + " already exists");
}
}
else
{
args.Player.SendErrorMessage("Points not set up yet");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region define <name>", Specifier);
break;
}
case "protect":
{
if (args.Parameters.Count == 3)
{
string regionName = args.Parameters[1];
if (args.Parameters[2].ToLower() == "true")
{
if (TShock.Regions.SetRegionState(regionName, true))
args.Player.SendInfoMessage("Protected region " + regionName);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else if (args.Parameters[2].ToLower() == "false")
{
if (TShock.Regions.SetRegionState(regionName, false))
args.Player.SendInfoMessage("Unprotected region " + regionName);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region protect <name> <true/false>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /region protect <name> <true/false>", Specifier);
break;
}
case "delete":
{
if (args.Parameters.Count > 1)
{
string regionName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1));
if (TShock.Regions.DeleteRegion(regionName))
{
args.Player.SendInfoMessage("Deleted region \"{0}\".", regionName);
}
else
args.Player.SendErrorMessage("Could not find the specified region!");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region delete <name>", Specifier);
break;
}
case "clear":
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
args.Player.SendInfoMessage("Cleared temporary points.");
args.Player.AwaitingTempPoint = 0;
break;
}
case "allow":
{
if (args.Parameters.Count > 2)
{
string playerName = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.AddNewUser(regionName, playerName))
{
args.Player.SendInfoMessage("Added user " + playerName + " to " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Player " + playerName + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region allow <name> <region>", Specifier);
break;
}
case "remove":
if (args.Parameters.Count > 2)
{
string playerName = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.UserAccounts.GetUserAccountByName(playerName) != null)
{
if (TShock.Regions.RemoveUser(regionName, playerName))
{
args.Player.SendInfoMessage("Removed user " + playerName + " from " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Player " + playerName + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region remove <name> <region>", Specifier);
break;
case "allowg":
{
if (args.Parameters.Count > 2)
{
string group = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.Groups.GroupExists(group))
{
if (TShock.Regions.AllowGroup(regionName, group))
{
args.Player.SendInfoMessage("Added group " + group + " to " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Group " + group + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region allowg <group> <region>", Specifier);
break;
}
case "removeg":
if (args.Parameters.Count > 2)
{
string group = args.Parameters[1];
string regionName = "";
for (int i = 2; i < args.Parameters.Count; i++)
{
if (regionName == "")
{
regionName = args.Parameters[2];
}
else
{
regionName = regionName + " " + args.Parameters[i];
}
}
if (TShock.Groups.GroupExists(group))
{
if (TShock.Regions.RemoveGroup(regionName, group))
{
args.Player.SendInfoMessage("Removed group " + group + " from " + regionName);
}
else
args.Player.SendErrorMessage("Region " + regionName + " not found");
}
else
{
args.Player.SendErrorMessage("Group " + group + " not found");
}
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region removeg <group> <region>", Specifier);
break;
case "list":
{
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, 1, args.Player, out pageNumber))
return;
IEnumerable<string> regionNames = from region in TShock.Regions.Regions
where region.WorldID == Main.worldID.ToString()
select region.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(regionNames),
new PaginationTools.Settings
{
HeaderFormat = "Regions ({0}/{1}):",
FooterFormat = "Type {0}region list {{0}} for more.".SFormat(Specifier),
NothingToDisplayString = "There are currently no regions defined."
});
break;
}
case "info":
{
if (args.Parameters.Count == 1 || args.Parameters.Count > 4)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region info <region> [-d] [page]", Specifier);
break;
}
string regionName = args.Parameters[1];
bool displayBoundaries = args.Parameters.Skip(2).Any(
p => p.Equals("-d", StringComparison.InvariantCultureIgnoreCase)
);
Region region = TShock.Regions.GetRegionByName(regionName);
if (region == null)
{
args.Player.SendErrorMessage("Region \"{0}\" does not exist.", regionName);
break;
}
int pageNumberIndex = displayBoundaries ? 3 : 2;
int pageNumber;
if (!PaginationTools.TryParsePageNumber(args.Parameters, pageNumberIndex, args.Player, out pageNumber))
break;
List<string> lines = new List<string>
{
string.Format("X: {0}; Y: {1}; W: {2}; H: {3}, Z: {4}", region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Z),
string.Concat("Owner: ", region.Owner),
string.Concat("Protected: ", region.DisableBuild.ToString()),
};
if (region.AllowedIDs.Count > 0)
{
IEnumerable<string> sharedUsersSelector = region.AllowedIDs.Select(userId =>
{
UserAccount account = TShock.UserAccounts.GetUserAccountByID(userId);
if (account != null)
return account.Name;
return string.Concat("{ID: ", userId, "}");
});
List<string> extraLines = PaginationTools.BuildLinesFromTerms(sharedUsersSelector.Distinct());
extraLines[0] = "Shared with: " + extraLines[0];
lines.AddRange(extraLines);
}
else
{
lines.Add("Region is not shared with any users.");
}
if (region.AllowedGroups.Count > 0)
{
List<string> extraLines = PaginationTools.BuildLinesFromTerms(region.AllowedGroups.Distinct());
extraLines[0] = "Shared with groups: " + extraLines[0];
lines.AddRange(extraLines);
}
else
{
lines.Add("Region is not shared with any groups.");
}
PaginationTools.SendPage(
args.Player, pageNumber, lines, new PaginationTools.Settings
{
HeaderFormat = string.Format("Information About Region \"{0}\" ({{0}}/{{1}}):", region.Name),
FooterFormat = string.Format("Type {0}region info {1} {{0}} for more information.", Specifier, regionName)
}
);
if (displayBoundaries)
{
Rectangle regionArea = region.Area;
foreach (Point boundaryPoint in Utils.Instance.EnumerateRegionBoundaries(regionArea))
{
// Preferring dotted lines as those should easily be distinguishable from actual wires.
if ((boundaryPoint.X + boundaryPoint.Y & 1) == 0)
{
// Could be improved by sending raw tile data to the client instead but not really
// worth the effort as chances are very low that overwriting the wire for a few
// nanoseconds will cause much trouble.
ITile tile = Main.tile[boundaryPoint.X, boundaryPoint.Y];
bool oldWireState = tile.wire();
tile.wire(true);
try
{
args.Player.SendTileSquare(boundaryPoint.X, boundaryPoint.Y, 1);
}
finally
{
tile.wire(oldWireState);
}
}
}
Timer boundaryHideTimer = null;
boundaryHideTimer = new Timer((state) =>
{
foreach (Point boundaryPoint in Utils.Instance.EnumerateRegionBoundaries(regionArea))
if ((boundaryPoint.X + boundaryPoint.Y & 1) == 0)
args.Player.SendTileSquare(boundaryPoint.X, boundaryPoint.Y, 1);
Debug.Assert(boundaryHideTimer != null);
boundaryHideTimer.Dispose();
},
null, 5000, Timeout.Infinite
);
}
break;
}
case "z":
{
if (args.Parameters.Count == 3)
{
string regionName = args.Parameters[1];
int z = 0;
if (int.TryParse(args.Parameters[2], out z))
{
if (TShock.Regions.SetZ(regionName, z))
args.Player.SendInfoMessage("Region's z is now " + z);
else
args.Player.SendErrorMessage("Could not find specified region");
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region z <name> <#>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region z <name> <#>", Specifier);
break;
}
case "resize":
case "expand":
{
if (args.Parameters.Count == 4)
{
int direction;
switch (args.Parameters[2])
{
case "u":
case "up":
{
direction = 0;
break;
}
case "r":
case "right":
{
direction = 1;
break;
}
case "d":
case "down":
{
direction = 2;
break;
}
case "l":
case "left":
{
direction = 3;
break;
}
default:
{
direction = -1;
break;
}
}
int addAmount;
int.TryParse(args.Parameters[3], out addAmount);
if (TShock.Regions.ResizeRegion(args.Parameters[1], addAmount, direction))
{
args.Player.SendInfoMessage("Region Resized Successfully!");
TShock.Regions.Reload();
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize <region> <u/d/l/r> <amount>", Specifier);
}
else
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region resize <region> <u/d/l/r> <amount>", Specifier);
break;
}
case "rename":
{
if (args.Parameters.Count != 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region rename <region> <new name>", Specifier);
break;
}
else
{
string oldName = args.Parameters[1];
string newName = args.Parameters[2];
if (oldName == newName)
{
args.Player.SendErrorMessage("Error: both names are the same.");
break;
}
Region oldRegion = TShock.Regions.GetRegionByName(oldName);
if (oldRegion == null)
{
args.Player.SendErrorMessage("Invalid region \"{0}\".", oldName);
break;
}
Region newRegion = TShock.Regions.GetRegionByName(newName);
if (newRegion != null)
{
args.Player.SendErrorMessage("Region \"{0}\" already exists.", newName);
break;
}
if(TShock.Regions.RenameRegion(oldName, newName))
{
args.Player.SendInfoMessage("Region renamed successfully!");
}
else
{
args.Player.SendErrorMessage("Failed to rename the region.");
}
}
break;
}
case "tp":
{
if (!args.Player.HasPermission(Permissions.tp))
{
args.Player.SendErrorMessage("You don't have the necessary permission to do that.");
break;
}
if (args.Parameters.Count <= 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}region tp <region>.", Specifier);
break;
}
string regionName = string.Join(" ", args.Parameters.Skip(1));
Region region = TShock.Regions.GetRegionByName(regionName);
if (region == null)
{
args.Player.SendErrorMessage("Region \"{0}\" does not exist.", regionName);
break;
}
args.Player.Teleport(region.Area.Center.X * 16, region.Area.Center.Y * 16);
break;
}
case "help":
default:
{
int pageNumber;
int pageParamIndex = 0;
if (args.Parameters.Count > 1)
pageParamIndex = 1;
if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber))
return;
List<string> lines = new List<string> {
"set <1/2> - Sets the temporary region points.",
"clear - Clears the temporary region points.",
"define <name> - Defines the region with the given name.",
"delete <name> - Deletes the given region.",
"name [-u][-z][-p] - Shows the name of the region at the given point.",
"rename <region> <new name> - Renames the given region.",
"list - Lists all regions.",
"resize <region> <u/d/l/r> <amount> - Resizes a region.",
"allow <user> <region> - Allows a user to a region.",
"remove <user> <region> - Removes a user from a region.",
"allowg <group> <region> - Allows a user group to a region.",
"removeg <group> <region> - Removes a user group from a region.",
"info <region> [-d] - Displays several information about the given region.",
"protect <name> <true/false> - Sets whether the tiles inside the region are protected or not.",
"z <name> <#> - Sets the z-order of the region.",
};
if (args.Player.HasPermission(Permissions.tp))
lines.Add("tp <region> - Teleports you to the given region's center.");
PaginationTools.SendPage(
args.Player, pageNumber, lines,
new PaginationTools.Settings
{
HeaderFormat = "Available Region Sub-Commands ({0}/{1}):",
FooterFormat = "Type {0}region {{0}} for more sub-commands.".SFormat(Specifier)
}
);
break;
}
}
}
#endregion Region Commands
#region World Protection Commands
private static void ToggleAntiBuild(CommandArgs args)
{
TShock.Config.DisableBuild = !TShock.Config.DisableBuild;
TSPlayer.All.SendSuccessMessage(string.Format("Anti-build is now {0}.", (TShock.Config.DisableBuild ? "on" : "off")));
}
private static void ProtectSpawn(CommandArgs args)
{
TShock.Config.SpawnProtection = !TShock.Config.SpawnProtection;
TSPlayer.All.SendSuccessMessage(string.Format("Spawn is now {0}.", (TShock.Config.SpawnProtection ? "protected" : "open")));
}
#endregion World Protection Commands
#region General Commands
private static void Help(CommandArgs args)
{
if (args.Parameters.Count > 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}help <command/page>", Specifier);
return;
}
int pageNumber;
if (args.Parameters.Count == 0 || int.TryParse(args.Parameters[0], out pageNumber))
{
if (!PaginationTools.TryParsePageNumber(args.Parameters, 0, args.Player, out pageNumber))
{
return;
}
IEnumerable<string> cmdNames = from cmd in ChatCommands
where cmd.CanRun(args.Player) && (cmd.Name != "auth" || TShock.SetupToken != 0)
select Specifier + cmd.Name;
PaginationTools.SendPage(args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(cmdNames),
new PaginationTools.Settings
{
HeaderFormat = "Commands ({0}/{1}):",
FooterFormat = "Type {0}help {{0}} for more.".SFormat(Specifier)
});
}
else
{
string commandName = args.Parameters[0].ToLower();
if (commandName.StartsWith(Specifier))
{
commandName = commandName.Substring(1);
}
Command command = ChatCommands.Find(c => c.Names.Contains(commandName));
if (command == null)
{
args.Player.SendErrorMessage("Invalid command.");
return;
}
if (!command.CanRun(args.Player))
{
args.Player.SendErrorMessage("You do not have access to this command.");
return;
}
args.Player.SendSuccessMessage("{0}{1} help: ", Specifier, command.Name);
if (command.HelpDesc == null)
{
args.Player.SendInfoMessage(command.HelpText);
return;
}
foreach (string line in command.HelpDesc)
{
args.Player.SendInfoMessage(line);
}
}
}
private static void GetVersion(CommandArgs args)
{
args.Player.SendInfoMessage("TShock: {0} ({1}).", TShock.VersionNum, TShock.VersionCodename);
}
private static void ListConnectedPlayers(CommandArgs args)
{
bool invalidUsage = (args.Parameters.Count > 2);
bool displayIdsRequested = false;
int pageNumber = 1;
if (!invalidUsage)
{
foreach (string parameter in args.Parameters)
{
if (parameter.Equals("-i", StringComparison.InvariantCultureIgnoreCase))
{
displayIdsRequested = true;
continue;
}
if (!int.TryParse(parameter, out pageNumber))
{
invalidUsage = true;
break;
}
}
}
if (invalidUsage)
{
args.Player.SendErrorMessage("Invalid usage, proper usage: {0}who [-i] [pagenumber]", Specifier);
return;
}
if (displayIdsRequested && !args.Player.HasPermission(Permissions.seeids))
{
args.Player.SendErrorMessage("You don't have the required permission to list player ids.");
return;
}
args.Player.SendSuccessMessage("Online Players ({0}/{1})", TShock.Utils.GetActivePlayerCount(), TShock.Config.MaxSlots);
var players = new List<string>();
foreach (TSPlayer ply in TShock.Players)
{
if (ply != null && ply.Active)
{
if (displayIdsRequested)
{
players.Add(String.Format("{0} (ID: {1}{2})", ply.Name, ply.Index, ply.Account != null ? ", ID: " + ply.Account.ID : ""));
}
else
{
players.Add(ply.Name);
}
}
}
PaginationTools.SendPage(
args.Player, pageNumber, PaginationTools.BuildLinesFromTerms(players),
new PaginationTools.Settings
{
IncludeHeader = false,
FooterFormat = string.Format("Type {0}who {1}{{0}} for more.", Specifier, displayIdsRequested ? "-i " : string.Empty)
}
);
}
private static void SetupToken(CommandArgs args)
{
if (TShock.SetupToken == 0)
{
if (args.Player.Group.Name == new SuperAdminGroup().Name)
args.Player.SendInfoMessage("The initial setup system is already disabled.");
else
{
args.Player.SendWarningMessage("The initial setup system is disabled. This incident has been logged.");
TShock.Log.Warn("{0} attempted to use the initial setup system even though it's disabled.", args.Player.IP);
return;
}
}
// If the user account is already a superadmin (permanent), disable the system
if (args.Player.IsLoggedIn && args.Player.tempGroup == null)
{
args.Player.SendSuccessMessage("Your new account has been verified, and the {0}setup system has been turned off.", Specifier);
args.Player.SendSuccessMessage("You can always use the {0}user command to manage players.", Specifier);
args.Player.SendSuccessMessage("The setup system will remain disabled as long as a superadmin exists (even if you delete setup.lock).");
args.Player.SendSuccessMessage("Share your server, talk with other admins, and more on our forums -- https://tshock.co/");
args.Player.SendSuccessMessage("Thank you for using TShock for Terraria!");
FileTools.CreateFile(Path.Combine(TShock.SavePath, "setup.lock"));
File.Delete(Path.Combine(TShock.SavePath, "setup-code.txt"));
TShock.SetupToken = 0;
return;
}
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("You must provide a setup code!");
return;
}
int givenCode;
if (!Int32.TryParse(args.Parameters[0], out givenCode) || givenCode != TShock.SetupToken)
{
args.Player.SendErrorMessage("Incorrect setup code. This incident has been logged.");
TShock.Log.Warn(args.Player.IP + " attempted to use an incorrect setup code.");
return;
}
if (args.Player.Group.Name != "superadmin")
args.Player.tempGroup = new SuperAdminGroup();
args.Player.SendInfoMessage("Temporary system access has been given to you, so you can run one command.");
args.Player.SendInfoMessage("Please use the following to create a permanent account for you.");
args.Player.SendInfoMessage("{0}user add <username> <password> owner", Specifier);
args.Player.SendInfoMessage("Creates: <username> with the password <password> as part of the owner group.");
args.Player.SendInfoMessage("Please use {0}login <username> <password> after this process.", Specifier);
args.Player.SendInfoMessage("If you understand, please {0}login <username> <password> now, and then type {0}setup.", Specifier);
return;
}
private static void ThirdPerson(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}me <text>", Specifier);
return;
}
if (args.Player.mute)
args.Player.SendErrorMessage("You are muted.");
else
TSPlayer.All.SendMessage(string.Format("*{0} {1}", args.Player.Name, String.Join(" ", args.Parameters)), 205, 133, 63);
}
private static void PartyChat(CommandArgs args)
{
if (args.Parameters.Count == 0)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}p <team chat text>", Specifier);
return;
}
int playerTeam = args.Player.Team;
if (args.Player.mute)
args.Player.SendErrorMessage("You are muted.");
else if (playerTeam != 0)
{
string msg = string.Format("<{0}> {1}", args.Player.Name, String.Join(" ", args.Parameters));
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active && player.Team == playerTeam)
player.SendMessage(msg, Main.teamColor[playerTeam].R, Main.teamColor[playerTeam].G, Main.teamColor[playerTeam].B);
}
}
else
args.Player.SendErrorMessage("You are not in a party!");
}
private static void Mute(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}mute <player> [reason]", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else if (players[0].HasPermission(Permissions.mute))
{
args.Player.SendErrorMessage("You cannot mute this player.");
}
else if (players[0].mute)
{
var plr = players[0];
plr.mute = false;
TSPlayer.All.SendInfoMessage("{0} has been unmuted by {1}.", plr.Name, args.Player.Name);
}
else
{
string reason = "No reason specified.";
if (args.Parameters.Count > 1)
reason = String.Join(" ", args.Parameters.ToArray(), 1, args.Parameters.Count - 1);
var plr = players[0];
plr.mute = true;
TSPlayer.All.SendInfoMessage("{0} has been muted by {1} for {2}.", plr.Name, args.Player.Name, reason);
}
}
private static void Motd(CommandArgs args)
{
args.Player.SendFileTextAsMessage(FileTools.MotdPath);
}
private static void Rules(CommandArgs args)
{
args.Player.SendFileTextAsMessage(FileTools.RulesPath);
}
private static void Whisper(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}whisper <player> <text>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else if (args.Player.mute)
{
args.Player.SendErrorMessage("You are muted.");
}
else
{
var plr = players[0];
var msg = string.Join(" ", args.Parameters.ToArray(), 1, args.Parameters.Count - 1);
plr.SendMessage(String.Format("<From {0}> {1}", args.Player.Name, msg), Color.MediumPurple);
args.Player.SendMessage(String.Format("<To {0}> {1}", plr.Name, msg), Color.MediumPurple);
plr.LastWhisper = args.Player;
args.Player.LastWhisper = plr;
}
}
private static void Reply(CommandArgs args)
{
if (args.Player.mute)
{
args.Player.SendErrorMessage("You are muted.");
}
else if (args.Player.LastWhisper != null)
{
var msg = string.Join(" ", args.Parameters);
args.Player.LastWhisper.SendMessage(String.Format("<From {0}> {1}", args.Player.Name, msg), Color.MediumPurple);
args.Player.SendMessage(String.Format("<To {0}> {1}", args.Player.LastWhisper.Name, msg), Color.MediumPurple);
}
else
{
args.Player.SendErrorMessage("You haven't previously received any whispers. Please use {0}whisper to whisper to other people.", Specifier);
}
}
private static void Annoy(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}annoy <player> <seconds to annoy>", Specifier);
return;
}
int annoy = 5;
int.TryParse(args.Parameters[1], out annoy);
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
args.Player.SendSuccessMessage("Annoying " + ply.Name + " for " + annoy + " seconds.");
(new Thread(ply.Whoopie)).Start(annoy);
}
}
private static void Confuse(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}confuse <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
ply.Confused = !ply.Confused;
args.Player.SendSuccessMessage("{0} is {1} confused.", ply.Name, ply.Confused ? "now" : "no longer");
}
}
private static void Rocket(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}rocket <player>", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
var ply = players[0];
if (ply.IsLoggedIn && Main.ServerSideCharacter)
{
ply.TPlayer.velocity.Y = -50;
TSPlayer.All.SendData(PacketTypes.PlayerUpdate, "", ply.Index);
args.Player.SendSuccessMessage("Rocketed {0}.", ply.Name);
}
else
{
args.Player.SendErrorMessage("Failed to rocket player: Not logged in or not SSC mode.");
}
}
}
private static void FireWork(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}firework <player> [red|green|blue|yellow]", Specifier);
return;
}
var players = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (players.Count == 0)
args.Player.SendErrorMessage("Invalid player!");
else if (players.Count > 1)
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
else
{
int type = 167;
if (args.Parameters.Count > 1)
{
if (args.Parameters[1].ToLower() == "green")
type = 168;
else if (args.Parameters[1].ToLower() == "blue")
type = 169;
else if (args.Parameters[1].ToLower() == "yellow")
type = 170;
}
var ply = players[0];
int p = Projectile.NewProjectile(ply.TPlayer.position.X, ply.TPlayer.position.Y - 64f, 0f, -8f, type, 0, (float)0);
Main.projectile[p].Kill();
args.Player.SendSuccessMessage("Launched Firework on {0}.", ply.Name);
}
}
private static void Aliases(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}aliases <command or alias>", Specifier);
return;
}
string givenCommandName = string.Join(" ", args.Parameters);
if (string.IsNullOrWhiteSpace(givenCommandName))
{
args.Player.SendErrorMessage("Please enter a proper command name or alias.");
return;
}
string commandName;
if (givenCommandName[0] == Specifier[0])
commandName = givenCommandName.Substring(1);
else
commandName = givenCommandName;
bool didMatch = false;
foreach (Command matchingCommand in ChatCommands.Where(cmd => cmd.Names.IndexOf(commandName) != -1))
{
if (matchingCommand.Names.Count > 1)
args.Player.SendInfoMessage(
"Aliases of {0}{1}: {0}{2}", Specifier, matchingCommand.Name, string.Join(", {0}".SFormat(Specifier), matchingCommand.Names.Skip(1)));
else
args.Player.SendInfoMessage("{0}{1} defines no aliases.", Specifier, matchingCommand.Name);
didMatch = true;
}
if (!didMatch)
args.Player.SendErrorMessage("No command or command alias matching \"{0}\" found.", givenCommandName);
}
private static void CreateDumps(CommandArgs args)
{
TShock.Utils.DumpPermissionMatrix("PermissionMatrix.txt");
TShock.Utils.Dump(false);
args.Player.SendSuccessMessage("Your reference dumps have been created in the server folder.");
return;
}
#endregion General Commands
#region Cheat Commands
private static void Clear(CommandArgs args)
{
if (args.Parameters.Count != 1 && args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}clear <item/npc/projectile> [radius]", Specifier);
return;
}
int radius = 50;
if (args.Parameters.Count == 2)
{
if (!int.TryParse(args.Parameters[1], out radius) || radius <= 0)
{
args.Player.SendErrorMessage("Invalid radius.");
return;
}
}
switch (args.Parameters[0].ToLower())
{
case "item":
case "items":
{
int cleared = 0;
for (int i = 0; i < Main.maxItems; i++)
{
float dX = Main.item[i].position.X - args.Player.X;
float dY = Main.item[i].position.Y - args.Player.Y;
if (Main.item[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.item[i].active = false;
TSPlayer.All.SendData(PacketTypes.ItemDrop, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} items within a radius of {1}.", cleared, radius);
}
break;
case "npc":
case "npcs":
{
int cleared = 0;
for (int i = 0; i < Main.maxNPCs; i++)
{
float dX = Main.npc[i].position.X - args.Player.X;
float dY = Main.npc[i].position.Y - args.Player.Y;
if (Main.npc[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.npc[i].active = false;
Main.npc[i].type = 0;
TSPlayer.All.SendData(PacketTypes.NpcUpdate, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} NPCs within a radius of {1}.", cleared, radius);
}
break;
case "proj":
case "projectile":
case "projectiles":
{
int cleared = 0;
for (int i = 0; i < Main.maxProjectiles; i++)
{
float dX = Main.projectile[i].position.X - args.Player.X;
float dY = Main.projectile[i].position.Y - args.Player.Y;
if (Main.projectile[i].active && dX * dX + dY * dY <= radius * radius * 256f)
{
Main.projectile[i].active = false;
Main.projectile[i].type = 0;
TSPlayer.All.SendData(PacketTypes.ProjectileNew, "", i);
cleared++;
}
}
args.Player.SendSuccessMessage("Deleted {0} projectiles within a radius of {1}.", cleared, radius);
}
break;
default:
args.Player.SendErrorMessage("Invalid clear option!");
break;
}
}
private static void Kill(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}kill <player>", Specifier);
return;
}
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
plr.KillPlayer();
args.Player.SendSuccessMessage(string.Format("You just killed {0}!", plr.Name));
plr.SendErrorMessage("{0} just killed you!", args.Player.Name);
}
}
private static void Butcher(CommandArgs args)
{
if (args.Parameters.Count > 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}butcher [mob type]", Specifier);
return;
}
int npcId = 0;
if (args.Parameters.Count == 1)
{
var npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
return;
}
else
{
npcId = npcs[0].netID;
}
}
int kills = 0;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && ((npcId == 0 && !Main.npc[i].townNPC && Main.npc[i].netID != NPCID.TargetDummy) || Main.npc[i].netID == npcId))
{
TSPlayer.Server.StrikeNPC(i, (int)(Main.npc[i].life + (Main.npc[i].defense * 0.6)), 0, 0);
kills++;
}
}
TSPlayer.All.SendInfoMessage("{0} butchered {1} NPCs.", args.Player.Name, kills);
}
private static void Item(CommandArgs args)
{
if (args.Parameters.Count < 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}item <item name/id> [item amount] [prefix id/name]", Specifier);
return;
}
int amountParamIndex = -1;
int itemAmount = 0;
for (int i = 1; i < args.Parameters.Count; i++)
{
if (int.TryParse(args.Parameters[i], out itemAmount))
{
amountParamIndex = i;
break;
}
}
string itemNameOrId;
if (amountParamIndex == -1)
itemNameOrId = string.Join(" ", args.Parameters);
else
itemNameOrId = string.Join(" ", args.Parameters.Take(amountParamIndex));
Item item;
List<Item> matchedItems = TShock.Utils.GetItemByIdOrName(itemNameOrId);
if (matchedItems.Count == 0)
{
args.Player.SendErrorMessage("Invalid item type!");
return;
}
else if (matchedItems.Count > 1)
{
args.Player.SendMultipleMatchError(matchedItems.Select(i => $"{i.Name}({i.netID})"));
return;
}
else
{
item = matchedItems[0];
}
if (item.type < 1 && item.type >= Main.maxItemTypes)
{
args.Player.SendErrorMessage("The item type {0} is invalid.", itemNameOrId);
return;
}
int prefixId = 0;
if (amountParamIndex != -1 && args.Parameters.Count > amountParamIndex + 1)
{
string prefixidOrName = args.Parameters[amountParamIndex + 1];
var prefixIds = TShock.Utils.GetPrefixByIdOrName(prefixidOrName);
if (item.accessory && prefixIds.Contains(PrefixID.Quick))
{
prefixIds.Remove(PrefixID.Quick);
prefixIds.Remove(PrefixID.Quick2);
prefixIds.Add(PrefixID.Quick2);
}
else if (!item.accessory && prefixIds.Contains(PrefixID.Quick))
prefixIds.Remove(PrefixID.Quick2);
if (prefixIds.Count > 1)
{
args.Player.SendMultipleMatchError(prefixIds.Select(p => p.ToString()));
return;
}
else if (prefixIds.Count == 0)
{
args.Player.SendErrorMessage("No prefix matched \"{0}\".", prefixidOrName);
return;
}
else
{
prefixId = prefixIds[0];
}
}
if (args.Player.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184)
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
if (args.Player.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefixId))
{
item.prefix = (byte)prefixId;
args.Player.SendSuccessMessage("Gave {0} {1}(s).", itemAmount, item.AffixName());
}
else
{
args.Player.SendErrorMessage("You cannot spawn banned items.");
}
}
else
{
args.Player.SendErrorMessage("Your inventory seems full.");
}
}
private static void RenameNPC(CommandArgs args)
{
if (args.Parameters.Count != 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}renameNPC <guide, nurse, etc.> <newname>", Specifier);
return;
}
int npcId = 0;
if (args.Parameters.Count == 2)
{
List<NPC> npcs = TShock.Utils.GetNPCByIdOrName(args.Parameters[0]);
if (npcs.Count == 0)
{
args.Player.SendErrorMessage("Invalid mob type!");
return;
}
else if (npcs.Count > 1)
{
args.Player.SendMultipleMatchError(npcs.Select(n => $"{n.FullName}({n.type})"));
return;
}
else if (args.Parameters[1].Length > 200)
{
args.Player.SendErrorMessage("New name is too large!");
return;
}
else
{
npcId = npcs[0].netID;
}
}
int done = 0;
for (int i = 0; i < Main.npc.Length; i++)
{
if (Main.npc[i].active && ((npcId == 0 && !Main.npc[i].townNPC) || (Main.npc[i].netID == npcId && Main.npc[i].townNPC)))
{
Main.npc[i].GivenName = args.Parameters[1];
NetMessage.SendData(56, -1, -1, NetworkText.FromLiteral(args.Parameters[1]), i, 0f, 0f, 0f, 0);
done++;
}
}
if (done > 0)
{
TSPlayer.All.SendInfoMessage("{0} renamed the {1}.", args.Player.Name, args.Parameters[0]);
}
else
{
args.Player.SendErrorMessage("Could not rename {0}!", args.Parameters[0]);
}
}
private static void Give(CommandArgs args)
{
if (args.Parameters.Count < 2)
{
args.Player.SendErrorMessage(
"Invalid syntax! Proper syntax: {0}give <item type/id> <player> [item amount] [prefix id/name]", Specifier);
return;
}
if (args.Parameters[0].Length == 0)
{
args.Player.SendErrorMessage("Missing item name/id.");
return;
}
if (args.Parameters[1].Length == 0)
{
args.Player.SendErrorMessage("Missing player name.");
return;
}
int itemAmount = 0;
int prefix = 0;
var items = TShock.Utils.GetItemByIdOrName(args.Parameters[0]);
args.Parameters.RemoveAt(0);
string plStr = args.Parameters[0];
args.Parameters.RemoveAt(0);
if (args.Parameters.Count == 1)
int.TryParse(args.Parameters[0], out itemAmount);
if (items.Count == 0)
{
args.Player.SendErrorMessage("Invalid item type!");
}
else if (items.Count > 1)
{
args.Player.SendMultipleMatchError(items.Select(i => $"{i.Name}({i.netID})"));
}
else
{
var item = items[0];
if (args.Parameters.Count == 2)
{
int.TryParse(args.Parameters[0], out itemAmount);
var prefixIds = TShock.Utils.GetPrefixByIdOrName(args.Parameters[1]);
if (item.accessory && prefixIds.Contains(PrefixID.Quick))
{
prefixIds.Remove(PrefixID.Quick);
prefixIds.Remove(PrefixID.Quick2);
prefixIds.Add(PrefixID.Quick2);
}
else if (!item.accessory && prefixIds.Contains(PrefixID.Quick))
prefixIds.Remove(PrefixID.Quick2);
if (prefixIds.Count == 1)
prefix = prefixIds[0];
}
if (item.type >= 1 && item.type < Main.maxItemTypes)
{
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
}
else
{
var plr = players[0];
if (plr.InventorySlotAvailable || (item.type > 70 && item.type < 75) || item.ammo > 0 || item.type == 58 || item.type == 184)
{
if (itemAmount == 0 || itemAmount > item.maxStack)
itemAmount = item.maxStack;
if (plr.GiveItemCheck(item.type, EnglishLanguage.GetItemNameById(item.type), itemAmount, prefix))
{
args.Player.SendSuccessMessage(string.Format("Gave {0} {1} {2}(s).", plr.Name, itemAmount, item.Name));
plr.SendSuccessMessage(string.Format("{0} gave you {1} {2}(s).", args.Player.Name, itemAmount, item.Name));
}
else
{
args.Player.SendErrorMessage("You cannot spawn banned items.");
}
}
else
{
args.Player.SendErrorMessage("Player does not have free slots!");
}
}
}
else
{
args.Player.SendErrorMessage("Invalid item type!");
}
}
}
private static void Heal(CommandArgs args)
{
TSPlayer playerToHeal;
if (args.Parameters.Count > 0)
{
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else
{
playerToHeal = players[0];
}
}
else if (!args.Player.RealPlayer)
{
args.Player.SendErrorMessage("You can't heal yourself!");
return;
}
else
{
playerToHeal = args.Player;
}
playerToHeal.Heal();
if (playerToHeal == args.Player)
{
args.Player.SendSuccessMessage("You just got healed!");
}
else
{
args.Player.SendSuccessMessage(string.Format("You just healed {0}", playerToHeal.Name));
playerToHeal.SendSuccessMessage(string.Format("{0} just healed you!", args.Player.Name));
}
}
private static void Buff(CommandArgs args)
{
if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}buff <buff id/name> [time(seconds)]", Specifier);
return;
}
int id = 0;
int time = 60;
if (!int.TryParse(args.Parameters[0], out id))
{
var found = TShock.Utils.GetBuffByName(args.Parameters[0]);
if (found.Count == 0)
{
args.Player.SendErrorMessage("Invalid buff name!");
return;
}
else if (found.Count > 1)
{
args.Player.SendMultipleMatchError(found.Select(f => Lang.GetBuffName(f)));
return;
}
id = found[0];
}
if (args.Parameters.Count == 2)
int.TryParse(args.Parameters[1], out time);
if (id > 0 && id < Main.maxBuffTypes)
{
if (time < 0 || time > short.MaxValue)
time = 60;
args.Player.SetBuff(id, time * 60);
args.Player.SendSuccessMessage(string.Format("You have buffed yourself with {0}({1}) for {2} seconds!",
TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)));
}
else
args.Player.SendErrorMessage("Invalid buff ID!");
}
private static void GBuff(CommandArgs args)
{
if (args.Parameters.Count < 2 || args.Parameters.Count > 3)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}gbuff <player> <buff id/name> [time(seconds)]", Specifier);
return;
}
int id = 0;
int time = 60;
var foundplr = TSPlayer.FindByNameOrID(args.Parameters[0]);
if (foundplr.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (foundplr.Count > 1)
{
args.Player.SendMultipleMatchError(foundplr.Select(p => p.Name));
return;
}
else
{
if (!int.TryParse(args.Parameters[1], out id))
{
var found = TShock.Utils.GetBuffByName(args.Parameters[1]);
if (found.Count == 0)
{
args.Player.SendErrorMessage("Invalid buff name!");
return;
}
else if (found.Count > 1)
{
args.Player.SendMultipleMatchError(found.Select(b => Lang.GetBuffName(b)));
return;
}
id = found[0];
}
if (args.Parameters.Count == 3)
int.TryParse(args.Parameters[2], out time);
if (id > 0 && id < Main.maxBuffTypes)
{
if (time < 0 || time > short.MaxValue)
time = 60;
foundplr[0].SetBuff(id, time * 60);
args.Player.SendSuccessMessage(string.Format("You have buffed {0} with {1}({2}) for {3} seconds!",
foundplr[0].Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)));
foundplr[0].SendSuccessMessage(string.Format("{0} has buffed you with {1}({2}) for {3} seconds!",
args.Player.Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)));
}
else
args.Player.SendErrorMessage("Invalid buff ID!");
}
}
private static void Grow(CommandArgs args)
{
if (args.Parameters.Count != 1)
{
args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}grow <tree/epictree/mushroom/cactus/herb>", Specifier);
return;
}
var name = "Fail";
var x = args.Player.TileX;
var y = args.Player.TileY + 3;
if (!TShock.Regions.CanBuild(x, y, args.Player))
{
args.Player.SendErrorMessage("You're not allowed to change tiles here!");
return;
}
switch (args.Parameters[0].ToLower())
{
case "tree":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 2;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
WorldGen.GrowTree(x, y);
name = "Tree";
break;
case "epictree":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 2;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
Main.tile[x, y - 1].liquid = 0;
Main.tile[x, y - 1].active(true);
WorldGen.GrowEpicTree(x, y);
name = "Epic Tree";
break;
case "mushroom":
for (int i = x - 1; i < x + 2; i++)
{
Main.tile[i, y].active(true);
Main.tile[i, y].type = 70;
Main.tile[i, y].wall = 0;
}
Main.tile[x, y - 1].wall = 0;
WorldGen.GrowShroom(x, y);
name = "Mushroom";
break;
case "cactus":
Main.tile[x, y].type = 53;
WorldGen.GrowCactus(x, y);
name = "Cactus";
break;
case "herb":
Main.tile[x, y].active(true);
Main.tile[x, y].frameX = 36;
Main.tile[x, y].type = 83;
WorldGen.GrowAlch(x, y);
name = "Herb";
break;
default:
args.Player.SendErrorMessage("Unknown plant!");
return;
}
args.Player.SendTileSquare(x, y);
args.Player.SendSuccessMessage("Tried to grow a " + name + ".");
}
private static void ToggleGodMode(CommandArgs args)
{
TSPlayer playerToGod;
if (args.Parameters.Count > 0)
{
if (!args.Player.HasPermission(Permissions.godmodeother))
{
args.Player.SendErrorMessage("You do not have permission to god mode another player!");
return;
}
string plStr = String.Join(" ", args.Parameters);
var players = TSPlayer.FindByNameOrID(plStr);
if (players.Count == 0)
{
args.Player.SendErrorMessage("Invalid player!");
return;
}
else if (players.Count > 1)
{
args.Player.SendMultipleMatchError(players.Select(p => p.Name));
return;
}
else
{
playerToGod = players[0];
}
}
else if (!args.Player.RealPlayer)
{
args.Player.SendErrorMessage("You can't god mode a non player!");
return;
}
else
{
playerToGod = args.Player;
}
playerToGod.GodMode = !playerToGod.GodMode;
if (playerToGod == args.Player)
{
args.Player.SendSuccessMessage(string.Format("You are {0} in god mode.", args.Player.GodMode ? "now" : "no longer"));
}
else
{
args.Player.SendSuccessMessage(string.Format("{0} is {1} in god mode.", playerToGod.Name, playerToGod.GodMode ? "now" : "no longer"));
playerToGod.SendSuccessMessage(string.Format("You are {0} in god mode.", playerToGod.GodMode ? "now" : "no longer"));
}
}
#endregion Cheat Comamnds
}
}
| ProfessorXZ/TShock | TShockAPI/Commands.cs | C# | gpl-3.0 | 183,890 |
package com.sk89q.craftbook.cart;
import java.util.ArrayList;
import java.util.Arrays;
import org.bukkit.block.Chest;
import org.bukkit.block.Sign;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.StorageMinecart;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import com.sk89q.craftbook.util.RailUtil;
import com.sk89q.craftbook.util.RedstoneUtil.Power;
import com.sk89q.craftbook.util.RegexUtil;
public class CartDeposit extends CartMechanism {
@Override
public void impact(Minecart cart, CartMechanismBlocks blocks, boolean minor) {
// validate
if (cart == null) return;
// care?
if (minor) return;
if (!(cart instanceof StorageMinecart)) return;
Inventory cartinventory = ((StorageMinecart) cart).getInventory();
// enabled?
if (Power.OFF == isActive(blocks.rail, blocks.base, blocks.sign)) return;
// collect/deposit set?
if (blocks.sign == null) return;
if (!blocks.matches("collect") && !blocks.matches("deposit")) return;
boolean collecting = blocks.matches("collect");
// search for containers
ArrayList<Chest> containers = RailUtil.getNearbyChests(blocks.base);
// are there any containers?
if (containers.isEmpty()) return;
// go
ArrayList<ItemStack> leftovers = new ArrayList<ItemStack>();
int itemID = -1;
byte itemData = -1;
try {
String[] splitLine = RegexUtil.COLON_PATTERN.split(((Sign) blocks.sign.getState()).getLine(2));
itemID = Integer.parseInt(splitLine[0]);
itemData = Byte.parseByte(splitLine[1]);
} catch (Exception ignored) {
}
if (collecting) {
// collecting
ArrayList<ItemStack> transferItems = new ArrayList<ItemStack>();
if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) {
for (ItemStack item : cartinventory.getContents()) {
if (item == null) {
continue;
}
if (itemID < 0 || itemID == item.getTypeId()) {
if (itemData < 0 || itemData == item.getDurability()) {
transferItems.add(new ItemStack(item.getTypeId(), item.getAmount(), item.getDurability()));
cartinventory.remove(item);
}
}
}
} else {
transferItems.addAll(Arrays.asList(cartinventory.getContents()));
cartinventory.clear();
}
while (transferItems.remove(null)) {
}
// is cart non-empty?
if (transferItems.isEmpty()) return;
// System.out.println("collecting " + transferItems.size() + " item stacks");
// for (ItemStack stack: transferItems) System.out.println("collecting " + stack.getAmount() + " items of
// type " + stack.getType().toString());
for (Chest container : containers) {
if (transferItems.isEmpty()) {
break;
}
Inventory containerinventory = container.getInventory();
leftovers.addAll(containerinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()
])).values());
transferItems.clear();
transferItems.addAll(leftovers);
leftovers.clear();
container.update();
}
// System.out.println("collected items. " + transferItems.size() + " stacks left over.");
leftovers.addAll(cartinventory.addItem(transferItems.toArray(new ItemStack[transferItems.size()])).values
());
transferItems.clear();
transferItems.addAll(leftovers);
leftovers.clear();
// System.out.println("collection done. " + transferItems.size() + " stacks wouldn't fit back.");
} else {
// depositing
ArrayList<ItemStack> transferitems = new ArrayList<ItemStack>();
for (Chest container : containers) {
Inventory containerinventory = container.getInventory();
if (!((Sign) blocks.sign.getState()).getLine(2).isEmpty()) {
for (ItemStack item : containerinventory.getContents()) {
if (item == null) {
continue;
}
if (itemID < 0 || itemID == item.getTypeId())
if (itemData < 0 || itemData == item.getDurability()) {
transferitems.add(new ItemStack(item.getTypeId(), item.getAmount(),
item.getDurability()));
containerinventory.remove(item);
}
}
} else {
transferitems.addAll(Arrays.asList(containerinventory.getContents()));
containerinventory.clear();
}
container.update();
}
while (transferitems.remove(null)) {
}
// are chests empty?
if (transferitems.isEmpty()) return;
// System.out.println("depositing " + transferitems.size() + " stacks");
// for (ItemStack stack: transferitems) System.out.println("depositing " + stack.getAmount() + " items of
// type " + stack.getType().toString());
leftovers.addAll(cartinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()])).values
());
transferitems.clear();
transferitems.addAll(leftovers);
leftovers.clear();
// System.out.println("deposited, " + transferitems.size() + " items left over.");
for (Chest container : containers) {
if (transferitems.isEmpty()) {
break;
}
Inventory containerinventory = container.getInventory();
leftovers.addAll(containerinventory.addItem(transferitems.toArray(new ItemStack[transferitems.size()
])).values());
transferitems.clear();
transferitems.addAll(leftovers);
leftovers.clear();
}
// System.out.println("deposit done. " + transferitems.size() + " items wouldn't fit back.");
}
}
@Override
public String getName() {
return "Deposit";
}
@Override
public String[] getApplicableSigns() {
return new String[] {"Collect", "Deposit"};
}
} | wizjany/craftbook | src/main/java/com/sk89q/craftbook/cart/CartDeposit.java | Java | gpl-3.0 | 7,011 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Lang strings for course_overview block
*
* @package block_course_overview
* @copyright 2012 Adam Olley <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
$string['activityoverview'] = 'You have {$a}s that need attention';
$string['alwaysshowall'] = 'Always show all';
$string['collapseall'] = 'Collapse all course lists';
$string['configotherexpanded'] = 'If enabled, other courses will be expanded by default unless overriden by user preferences.';
$string['configpreservestates'] = 'If enabled, the collapsed/expanded states set by the user are stored and used on each load.';
$string['course_overview:addinstance'] = 'Add a new course overview block';
$string['course_overview:myaddinstance'] = 'Add a new course overview block to My home';
$string['defaultmaxcourses'] = 'Default maximum courses';
$string['defaultmaxcoursesdesc'] = 'Maximum courses which should be displayed on course overview block, 0 will show all courses';
$string['expandall'] = 'Expand all course lists';
$string['forcedefaultmaxcourses'] = 'Force maximum courses';
$string['forcedefaultmaxcoursesdesc'] = 'If set then user will not be able to change his/her personal setting';
$string['hiddencoursecount'] = 'You have {$a} hidden course';
$string['hiddencoursecountplural'] = 'You have {$a} hidden courses';
$string['hiddencoursecountwithshowall'] = 'You have {$a->coursecount} hidden course ({$a->showalllink})';
$string['hiddencoursecountwithshowallplural'] = 'You have {$a->coursecount} hidden courses ({$a->showalllink})';
$string['message'] = 'message';
$string['messages'] = 'messages';
$string['movecourse'] = 'Move course: {$a}';
$string['movecoursehere'] = 'Move course here';
$string['movetofirst'] = 'Move {$a} course to top';
$string['moveafterhere'] = 'Move {$a->movingcoursename} course after {$a->currentcoursename}';
$string['movingcourse'] = 'You are moving: {$a->fullname} ({$a->cancellink})';
$string['numtodisplay'] = 'Number of courses to display: ';
$string['otherexpanded'] = 'Other courses expanded';
$string['pluginname'] = 'Assigned Courses';
$string['preservestates'] = 'Preserve expanded states';
$string['shortnameprefix'] = 'Includes {$a}';
$string['shortnamesufixsingular'] = ' (and {$a} other)';
$string['shortnamesufixprural'] = ' (and {$a} others)';
$string['showchildren'] = 'Show children';
$string['showchildrendesc'] = 'Should child courses be listed underneath the main course title?';
$string['showwelcomearea'] = 'Show welcome area';
$string['showwelcomeareadesc'] = 'Show the welcome area above the course list?';
$string['view_edit_profile'] = '(View and edit your profile.)';
$string['welcome'] = 'Welcome {$a}';
$string['youhavemessages'] = 'You have {$a} unread ';
$string['youhavenomessages'] = 'You have no unread ';
| sumitnegi933/GWL_MOODLE | blocks/course_overview/lang/en/block_course_overview.php | PHP | gpl-3.0 | 3,501 |
//
// CHNOrderedCollection.h
//
// Auther:
// ned rihine <[email protected]>
//
// Copyright (c) 2012 rihine All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#ifndef coreHezelnut_classes_CHNOrderedCollection_h
#define coreHezelnut_classes_CHNOrderedCollection_h
#include "coreHezelnut/classes/CHNSequenceableCollection.h"
CHN_EXTERN_C_BEGIN
CHN_EXTERN_C_END
#endif /* coreHezelnut_classes_CHNOrderedCollection_h */
// Local Variables:
// coding: utf-8
// End:
| noqisofon/coreHezelnut | include/coreHezelnut/classes/CHNOrderedCollection.h | C | gpl-3.0 | 1,127 |
<?php
session_start();
include("../connect.php");
include("../function.php");
//session_start();
if($_REQUEST['cat_id'])
{
$data="";
$count=0;
$select_list_data="select * from users_data where int_fid in(".$_REQUEST['cat_id'].") and int_del_status='0'";
$result_list_data=mysql_query($select_list_data) or die(mysql_error());
$data.="<br>";
$data.="<table style='width: 270px;' id='alternatecolor' class='altrowstable1' >";
while($fetch_list_data=mysql_fetch_array($result_list_data))
{ $count++;
$imgsrc="../".$fetch_list_data['txt_real_path'];
$data.="<tr >";
$data.="<td style='padding-left:5px;'>";
$data.="<div style='width:240px;overflow:hidden;'>".$fetch_list_data['txt_file_name']."</div>";
$data.="</td>";
$data.="<td >";
$data.="<img src='images/play-icon.png' style='cursor:pointer;' title='Play Item' onclick='go(\"$imgsrc\");'>";
$data.="</td>";
$data.="</tr>";
//$main_data="<a href='javascript:load_data(\"".$fetch_list_data['txt_file_name']."\");'>".$fetch_list_data['txt_file_name']."</a>";
//$data=$data.$main_data;
//$data.="</br></br>";
}
$data.="</table>";
echo $data;
}
?> | aroramanish63/bulmail_app | Live Backup/databagg 30 jan backup/user/ajax_load_list_11_7.php | PHP | gpl-3.0 | 1,421 |
////////////////////////////////////////////////////////
//
// GEM - Graphics Environment for Multimedia
//
// Implementation file
//
// Copyright (c) 2002-2011 IOhannes m zmölnig. forum::für::umläute. IEM. [email protected]
// [email protected]
// For information on usage and redistribution, and for a DISCLAIMER
// * OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS"
//
// this file has been generated...
////////////////////////////////////////////////////////
#include "GEMglTexCoord3s.h"
CPPEXTERN_NEW_WITH_THREE_ARGS ( GEMglTexCoord3s , t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT, t_floatarg, A_DEFFLOAT);
/////////////////////////////////////////////////////////
//
// GEMglViewport
//
/////////////////////////////////////////////////////////
// Constructor
//
GEMglTexCoord3s :: GEMglTexCoord3s (t_floatarg arg0=0, t_floatarg arg1=0, t_floatarg arg2=0) :
s(static_cast<GLshort>(arg0)),
t(static_cast<GLshort>(arg1)),
r(static_cast<GLshort>(arg2))
{
m_inlet[0] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("s"));
m_inlet[1] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("t"));
m_inlet[2] = inlet_new(this->x_obj, &this->x_obj->ob_pd, &s_float, gensym("r"));
}
/////////////////////////////////////////////////////////
// Destructor
//
GEMglTexCoord3s :: ~GEMglTexCoord3s () {
inlet_free(m_inlet[0]);
inlet_free(m_inlet[1]);
inlet_free(m_inlet[2]);
}
/////////////////////////////////////////////////////////
// Render
//
void GEMglTexCoord3s :: render(GemState *state) {
glTexCoord3s (s, t, r);
}
/////////////////////////////////////////////////////////
// Variables
//
void GEMglTexCoord3s :: sMess (t_float arg1) { // FUN
s = static_cast<GLshort>(arg1);
setModified();
}
void GEMglTexCoord3s :: tMess (t_float arg1) { // FUN
t = static_cast<GLshort>(arg1);
setModified();
}
void GEMglTexCoord3s :: rMess (t_float arg1) { // FUN
r = static_cast<GLshort>(arg1);
setModified();
}
/////////////////////////////////////////////////////////
// static member functions
//
void GEMglTexCoord3s :: obj_setupCallback(t_class *classPtr) {
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::sMessCallback), gensym("s"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::tMessCallback), gensym("t"), A_DEFFLOAT, A_NULL);
class_addmethod(classPtr, reinterpret_cast<t_method>(&GEMglTexCoord3s::rMessCallback), gensym("r"), A_DEFFLOAT, A_NULL);
};
void GEMglTexCoord3s :: sMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->sMess ( static_cast<t_float>(arg0));
}
void GEMglTexCoord3s :: tMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->tMess ( static_cast<t_float>(arg0));
}
void GEMglTexCoord3s :: rMessCallback (void* data, t_floatarg arg0){
GetMyClass(data)->rMess ( static_cast<t_float>(arg0));
}
| rvega/morphasynth | vendors/pd-extended-0.43.4/externals/Gem/src/openGL/GEMglTexCoord3s.cpp | C++ | gpl-3.0 | 2,880 |
/*
* This file is part of CRISIS, an economics simulator.
*
* Copyright (C) 2015 Victor Spirin
*
* CRISIS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CRISIS 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 CRISIS. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.crisis_economics.abm.markets.nonclearing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import eu.crisis_economics.abm.markets.Party;
import eu.crisis_economics.abm.markets.nonclearing.DefaultFilters.Filter;
/**
* Represents relationships between banks in the interbank market
*
* @author Victor Spirin
*/
public class InterbankNetwork {
private final Map<Party, Set<Party>> adj = new HashMap<Party, Set<Party>>();
/**
* Adds a new node to the graph. If the node already exists, this
* function is a no-op.
*
* @param node The node to add.
* @return Whether or not the node was added.
*/
private boolean addNode(Party node) {
/* If the node already exists, don't do anything. */
if (adj.containsKey(node))
return false;
/* Otherwise, add the node with an empty set of outgoing edges. */
adj.put(node, new HashSet<Party>());
return true;
}
// protected
/**
* Generates a filter from the network. This allows the network class to be used
* with a Limit Order Book.
*
* @param a Bank, for which we want to generate a filter
* @return Returns a Limit Order Book filter for the given bank. If the bank is not in the network, returns an empty filter.
*/
protected Filter generateFilter(Party party) {
if (!adj.containsKey(party))
return DefaultFilters.only(party);
return DefaultFilters.only((Party[]) adj.get(party).toArray());
}
// public interface
/**
* Adds a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, also adds them to the network.
*
* @param a Bank a
* @param b Bank b
*/
public void addRelationship(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a))
addNode(a);
if (!adj.containsKey(b))
addNode(b);
/* Add the edge in both directions. */
adj.get(a).add(b);
adj.get(b).add(a);
}
/**
* Removes a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, throws a NoSuchElementException
*
* @param a Bank a
* @param b Bank b
*/
public void removeRelationship(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a) || !adj.containsKey(b))
throw new NoSuchElementException("Both banks must be in the network.");
/* Remove the edges from both adjacency lists. */
adj.get(a).remove(b);
adj.get(b).remove(a);
}
/**
* Returns true if there is a bilateral relationship between banks 'a' and 'b'.
* If the banks are not already in the network, throws a NoSuchElementException
*
* @param a Bank a
* @param b Bank b
* @return Returns true if there is a relationship between banks 'a' and 'b'
*/
public boolean isRelated(Party a, Party b) {
/* Confirm both endpoints exist. */
if (!adj.containsKey(a) || !adj.containsKey(b))
throw new NoSuchElementException("Both banks must be in the network.");
/* Network is symmetric, so we can just check either endpoint. */
return adj.get(a).contains(b);
}
}
| crisis-economics/CRISIS | CRISIS/src/eu/crisis_economics/abm/markets/nonclearing/InterbankNetwork.java | Java | gpl-3.0 | 4,215 |
{-# LANGUAGE OverloadedStrings #-}
module Response.Export
(pdfResponse) where
import Happstack.Server
import qualified Data.ByteString.Lazy as BS
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString.Base64.Lazy as BEnc
import ImageConversion
import TimetableImageCreator (renderTable)
import System.Random
import Latex
-- | Returns a PDF containing the image of the timetable
-- requested by the user.
pdfResponse :: String -> String -> ServerPart Response
pdfResponse courses session =
liftIO $ getPdf courses session
getPdf :: String -> String -> IO Response
getPdf courses session = do
gen <- newStdGen
let (rand, _) = next gen
svgFilename = (show rand ++ ".svg")
imageFilename = (show rand ++ ".png")
texFilename = (show rand ++ ".tex")
pdfFilename = (drop 4 texFilename) ++ ".pdf"
renderTable svgFilename courses session
returnPdfData svgFilename imageFilename pdfFilename texFilename
returnPdfData :: String -> String -> String -> String -> IO Response
returnPdfData svgFilename imageFilename pdfFilename texFilename = do
createImageFile svgFilename imageFilename
compileTex texFilename imageFilename
_ <- compileTexToPdf texFilename
pdfData <- BS.readFile texFilename
_ <- removeImage svgFilename
_ <- removeImage imageFilename
_ <- removeImage pdfFilename
_ <- removeImage texFilename
let encodedData = BEnc.encode pdfData
return $ toResponse encodedData
| pkukulak/courseography | hs/Response/Export.hs | Haskell | gpl-3.0 | 1,487 |
<?php
# server running the wolframe daemon
$WOLFRAME_SERVER = "localhost";
# wolframe daemon port
$WOLFRAME_PORT = 7962;
# for SSL secured communication, a file with combined client certificate
# and client key
$WOLFRAME_COMBINED_CERTS = "certs/combinedcert.pem";
# which user agents should use client XSLT
$BROWSERS_USING_CLIENT_XSLT = array(
# "op12", "ie8", "ie9", "ie10", "moz23", "webkit27", "webkit28", "moz11"
);
| Wolframe/wolfzilla | phpclient/config.php | PHP | gpl-3.0 | 425 |
/**
*
*/
/**
* @author dewan
*
*/
package gradingTools.comp401f16.assignment11.testcases; | pdewan/Comp401LocalChecks | src/gradingTools/comp401f16/assignment11/testcases/package-info.java | Java | gpl-3.0 | 95 |
package main
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println(rand.Int())
fmt.Println(rand.Float64())
}
| alsotoes/MCS_programmingLanguages | go/slides/code/imports.go | GO | gpl-3.0 | 152 |
package mcid.anubisset.letsmodreboot.block;
import mcid.anubisset.letsmodreboot.creativetab.CreativeTabLMRB;
/**
* Created by Luke on 30/08/2014.
*/
public class BlockFlag extends BlockLMRB
{
public BlockFlag()
{
super();
this.setBlockName("flag");
this.setBlockTextureName("flag");
}
}
| AnubisSet/LetsModReboot | src/main/java/mcid/anubisset/letsmodreboot/block/BlockFlag.java | Java | gpl-3.0 | 327 |
require 'package'
class Libxau < Package
description 'xau library for libX11'
homepage 'https://x.org'
version '1.0.8'
source_url 'https://www.x.org/archive/individual/lib/libXau-1.0.8.tar.gz'
source_sha256 'c343b4ef66d66a6b3e0e27aa46b37ad5cab0f11a5c565eafb4a1c7590bc71d7b'
depends_on 'xproto'
def self.build
system "./configure"
system "make"
end
def self.install
system "make", "DESTDIR=#{CREW_DEST_DIR}", "install"
end
end
| richard-fisher/chromebrew | packages/libxau.rb | Ruby | gpl-3.0 | 466 |
#include "config.h"
#include "syshead.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <setjmp.h>
#include <cmocka.h>
#include <assert.h>
#include "argv.h"
#include "buffer.h"
/* Defines for use in the tests and the mock parse_line() */
#define PATH1 "/s p a c e"
#define PATH2 "/foo bar/baz"
#define PARAM1 "param1"
#define PARAM2 "param two"
#define SCRIPT_CMD "\"" PATH1 PATH2 "\"" PARAM1 "\"" PARAM2 "\""
int
__wrap_parse_line(const char *line, char **p, const int n, const char *file,
const int line_num, int msglevel, struct gc_arena *gc)
{
p[0] = PATH1 PATH2;
p[1] = PARAM1;
p[2] = PARAM2;
return 3;
}
static void
argv_printf__multiple_spaces_in_format__parsed_as_one(void **state)
{
struct argv a = argv_new();
argv_printf(&a, " %s %s %d ", PATH1, PATH2, 42);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_printf_cat__multiple_spaces_in_format__parsed_as_one(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s ", PATH1);
argv_printf_cat(&a, " %s %s", PATH2, PARAM1);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_printf__combined_path_with_spaces__argc_correct(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s%sc", PATH1, PATH2);
assert_int_equal(a.argc, 1);
argv_printf(&a, "%s%sc %d", PATH1, PATH2, 42);
assert_int_equal(a.argc, 2);
argv_printf(&a, "foo %s%sc %s x y", PATH2, PATH1, "foo");
assert_int_equal(a.argc, 5);
argv_reset(&a);
}
static void
argv_parse_cmd__command_string__argc_correct(void **state)
{
struct argv a = argv_new();
argv_parse_cmd(&a, SCRIPT_CMD);
assert_int_equal(a.argc, 3);
argv_reset(&a);
}
static void
argv_parse_cmd__command_and_extra_options__argc_correct(void **state)
{
struct argv a = argv_new();
argv_parse_cmd(&a, SCRIPT_CMD);
argv_printf_cat(&a, "bar baz %d %s", 42, PATH1);
assert_int_equal(a.argc, 7);
argv_reset(&a);
}
static void
argv_printf_cat__used_twice__argc_correct(void **state)
{
struct argv a = argv_new();
argv_printf(&a, "%s %s %s", PATH1, PATH2, PARAM1);
argv_printf_cat(&a, "%s", PARAM2);
argv_printf_cat(&a, "foo");
assert_int_equal(a.argc, 5);
argv_reset(&a);
}
static void
argv_str__multiple_argv__correct_output(void **state)
{
struct argv a = argv_new();
struct gc_arena gc = gc_new();
const char *output;
argv_printf(&a, "%s%sc", PATH1, PATH2);
argv_printf_cat(&a, "%s", PARAM1);
argv_printf_cat(&a, "%s", PARAM2);
output = argv_str(&a, &gc, PA_BRACKET);
assert_string_equal(output, "[" PATH1 PATH2 "] [" PARAM1 "] [" PARAM2 "]");
argv_reset(&a);
gc_free(&gc);
}
static void
argv_insert_head__empty_argv__head_only(void **state)
{
struct argv a = argv_new();
struct argv b;
b = argv_insert_head(&a, PATH1);
assert_int_equal(b.argc, 1);
assert_string_equal(b.argv[0], PATH1);
argv_reset(&b);
argv_reset(&a);
}
static void
argv_insert_head__non_empty_argv__head_added(void **state)
{
struct argv a = argv_new();
struct argv b;
int i;
argv_printf(&a, "%s", PATH2);
b = argv_insert_head(&a, PATH1);
assert_int_equal(b.argc, a.argc + 1);
for (i = 0; i < b.argc; i++) {
if (i == 0)
{
assert_string_equal(b.argv[i], PATH1);
}
else
{
assert_string_equal(b.argv[i], a.argv[i - 1]);
}
}
argv_reset(&b);
argv_reset(&a);
}
int
main(void)
{
const struct CMUnitTest tests[] = {
cmocka_unit_test(argv_printf__multiple_spaces_in_format__parsed_as_one),
cmocka_unit_test(argv_printf_cat__multiple_spaces_in_format__parsed_as_one),
cmocka_unit_test(argv_printf__combined_path_with_spaces__argc_correct),
cmocka_unit_test(argv_parse_cmd__command_string__argc_correct),
cmocka_unit_test(argv_parse_cmd__command_and_extra_options__argc_correct),
cmocka_unit_test(argv_printf_cat__used_twice__argc_correct),
cmocka_unit_test(argv_str__multiple_argv__correct_output),
cmocka_unit_test(argv_insert_head__non_empty_argv__head_added),
};
return cmocka_run_group_tests_name("argv", tests, NULL, NULL);
}
| anoidgit/padavan | trunk/user/openvpn/openvpn-2.4.x/tests/unit_tests/openvpn/test_argv.c | C | gpl-3.0 | 4,359 |
#!/bin/sh -xe
if [ "$1" = "ci" ]; then
armloc=$(brew fetch --bottle-tag=arm64_big_sur libomp | grep -i downloaded | grep tar.gz | cut -f2 -d:)
x64loc=$(brew fetch --bottle-tag=big_sur libomp | grep -i downloaded | grep tar.gz | cut -f2 -d:)
cp $armloc /tmp/libomp-arm64.tar.gz
mkdir /tmp/libomp-arm64 || true
tar -xzvf /tmp/libomp-arm64.tar.gz -C /tmp/libomp-arm64
cp $x64loc /tmp/libomp-x86_64.tar.gz
mkdir /tmp/libomp-x86_64 || true
tar -xzvf /tmp/libomp-x86_64.tar.gz -C /tmp/libomp-x86_64
else
brew install libomp
fi
git submodule update --init extlib/cairo extlib/freetype extlib/libdxfrw extlib/libpng extlib/mimalloc extlib/pixman extlib/zlib extlib/eigen
| solvespace/solvespace | .github/scripts/install-macos.sh | Shell | gpl-3.0 | 701 |
/*
* Unix SMB/CIFS implementation.
* NetApi LocalGroup Support
* Copyright (C) Guenther Deschner 2008
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "librpc/gen_ndr/libnetapi.h"
#include "lib/netapi/netapi.h"
#include "lib/netapi/netapi_private.h"
#include "lib/netapi/libnetapi.h"
#include "rpc_client/rpc_client.h"
#include "../librpc/gen_ndr/ndr_samr_c.h"
#include "../librpc/gen_ndr/ndr_lsa_c.h"
#include "rpc_client/cli_lsarpc.h"
#include "rpc_client/init_lsa.h"
#include "../libcli/security/security.h"
static NTSTATUS libnetapi_samr_lookup_and_open_alias(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *domain_handle,
const char *group_name,
uint32_t access_rights,
struct policy_handle *alias_handle)
{
NTSTATUS status, result;
struct lsa_String lsa_account_name;
struct samr_Ids user_rids, name_types;
struct dcerpc_binding_handle *b = pipe_cli->binding_handle;
init_lsa_String(&lsa_account_name, group_name);
status = dcerpc_samr_LookupNames(b, mem_ctx,
domain_handle,
1,
&lsa_account_name,
&user_rids,
&name_types,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
if (!NT_STATUS_IS_OK(result)) {
return result;
}
if (user_rids.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
if (name_types.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
switch (name_types.ids[0]) {
case SID_NAME_ALIAS:
case SID_NAME_WKN_GRP:
break;
default:
return NT_STATUS_INVALID_SID;
}
status = dcerpc_samr_OpenAlias(b, mem_ctx,
domain_handle,
access_rights,
user_rids.ids[0],
alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
return status;
}
return result;
}
/****************************************************************
****************************************************************/
static NTSTATUS libnetapi_samr_open_alias_queryinfo(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *pipe_cli,
struct policy_handle *handle,
uint32_t rid,
uint32_t access_rights,
enum samr_AliasInfoEnum level,
union samr_AliasInfo **alias_info)
{
NTSTATUS status, result;
struct policy_handle alias_handle;
union samr_AliasInfo *_alias_info = NULL;
struct dcerpc_binding_handle *b = pipe_cli->binding_handle;
ZERO_STRUCT(alias_handle);
status = dcerpc_samr_OpenAlias(b, mem_ctx,
handle,
access_rights,
rid,
&alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
status = result;
goto done;
}
status = dcerpc_samr_QueryAliasInfo(b, mem_ctx,
&alias_handle,
level,
&_alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
status = result;
goto done;
}
*alias_info = _alias_info;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, mem_ctx, &alias_handle, &result);
}
return status;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAdd_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t rid;
struct dcerpc_binding_handle *b = NULL;
struct LOCALGROUP_INFO_0 *info0 = NULL;
struct LOCALGROUP_INFO_1 *info1 = NULL;
const char *alias_name = NULL;
if (!r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)r->in.buffer;
alias_name = info0->lgrpi0_name;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)r->in.buffer;
alias_name = info1->lgrpi1_name;
break;
default:
werr = WERR_UNKNOWN_LEVEL;
goto done;
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
alias_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
werr = WERR_ALIAS_EXISTS;
goto done;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, alias_name);
status = dcerpc_samr_CreateDomAlias(b, talloc_tos(),
&domain_handle,
&lsa_account_name,
SEC_STD_DELETE |
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle,
&rid,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->in.level == 1 && info1->lgrpi1_comment) {
union samr_AliasInfo alias_info;
init_lsa_String(&alias_info.description, info1->lgrpi1_comment);
status = dcerpc_samr_SetAliasInfo(b, talloc_tos(),
&alias_handle,
ALIASINFODESCRIPTION,
&alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAdd_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAdd *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupAdd);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDel_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto delete_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SEC_STD_DELETE,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
delete_alias:
status = dcerpc_samr_DeleteDomAlias(b, talloc_tos(),
&alias_handle,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
ZERO_STRUCT(alias_handle);
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDel_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDel *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupDel);
}
/****************************************************************
****************************************************************/
static WERROR map_alias_info_to_buffer(TALLOC_CTX *mem_ctx,
const char *alias_name,
struct samr_AliasInfoAll *info,
uint32_t level,
uint32_t *entries_read,
uint8_t **buffer)
{
struct LOCALGROUP_INFO_0 g0;
struct LOCALGROUP_INFO_1 g1;
struct LOCALGROUP_INFO_1002 g1002;
switch (level) {
case 0:
g0.lgrpi0_name = talloc_strdup(mem_ctx, alias_name);
W_ERROR_HAVE_NO_MEMORY(g0.lgrpi0_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_0, g0,
(struct LOCALGROUP_INFO_0 **)buffer, entries_read);
break;
case 1:
g1.lgrpi1_name = talloc_strdup(mem_ctx, alias_name);
g1.lgrpi1_comment = talloc_strdup(mem_ctx, info->description.string);
W_ERROR_HAVE_NO_MEMORY(g1.lgrpi1_name);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1, g1,
(struct LOCALGROUP_INFO_1 **)buffer, entries_read);
break;
case 1002:
g1002.lgrpi1002_comment = talloc_strdup(mem_ctx, info->description.string);
ADD_TO_ARRAY(mem_ctx, struct LOCALGROUP_INFO_1002, g1002,
(struct LOCALGROUP_INFO_1002 **)buffer, entries_read);
break;
default:
return WERR_UNKNOWN_LEVEL;
}
return WERR_OK;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetInfo_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetInfo *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
union samr_AliasInfo *alias_info = NULL;
uint32_t entries_read = 0;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto query_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_CREATE_ALIAS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
query_alias:
status = dcerpc_samr_QueryAliasInfo(b, talloc_tos(),
&alias_handle,
ALIASINFOALL,
&alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
werr = map_alias_info_to_buffer(ctx,
r->in.group_name,
&alias_info->all,
r->in.level, &entries_read,
r->out.buffer);
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetInfo_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetInfo *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupGetInfo);
}
/****************************************************************
****************************************************************/
static WERROR map_buffer_to_alias_info(TALLOC_CTX *mem_ctx,
uint32_t level,
uint8_t *buffer,
enum samr_AliasInfoEnum *alias_level,
union samr_AliasInfo **alias_info)
{
struct LOCALGROUP_INFO_0 *info0;
struct LOCALGROUP_INFO_1 *info1;
struct LOCALGROUP_INFO_1002 *info1002;
union samr_AliasInfo *info = NULL;
info = talloc_zero(mem_ctx, union samr_AliasInfo);
W_ERROR_HAVE_NO_MEMORY(info);
switch (level) {
case 0:
info0 = (struct LOCALGROUP_INFO_0 *)buffer;
init_lsa_String(&info->name, info0->lgrpi0_name);
*alias_level = ALIASINFONAME;
break;
case 1:
info1 = (struct LOCALGROUP_INFO_1 *)buffer;
/* group name will be ignored */
init_lsa_String(&info->description, info1->lgrpi1_comment);
*alias_level = ALIASINFODESCRIPTION;
break;
case 1002:
info1002 = (struct LOCALGROUP_INFO_1002 *)buffer;
init_lsa_String(&info->description, info1002->lgrpi1002_comment);
*alias_level = ALIASINFODESCRIPTION;
break;
}
*alias_info = info;
return WERR_OK;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetInfo_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetInfo *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
enum samr_AliasInfoEnum alias_level = 0;
union samr_AliasInfo *alias_info = NULL;
struct dcerpc_binding_handle *b = NULL;
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
case 1002:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto set_alias;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_SET_INFO,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
set_alias:
werr = map_buffer_to_alias_info(ctx, r->in.level, r->in.buffer,
&alias_level, &alias_info);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = dcerpc_samr_SetAliasInfo(b, talloc_tos(),
&alias_handle,
alias_level,
alias_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
werr = WERR_OK;
done:
if (is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetInfo_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetInfo *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupSetInfo);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupEnum_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
struct rpc_pipe_client *pipe_cli = NULL;
NTSTATUS status, result;
WERROR werr;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
uint32_t entries_read = 0;
union samr_DomainInfo *domain_info = NULL;
union samr_DomainInfo *builtin_info = NULL;
struct samr_SamArray *domain_sam_array = NULL;
struct samr_SamArray *builtin_sam_array = NULL;
int i;
struct dcerpc_binding_handle *b = NULL;
if (!r->out.buffer) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 1:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->out.total_entries) {
*r->out.total_entries = 0;
}
if (r->out.entries_read) {
*r->out.entries_read = 0;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_LOOKUP_INFO_2 |
SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_LOOKUP_INFO_2 |
SAMR_DOMAIN_ACCESS_ENUM_ACCOUNTS |
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = dcerpc_samr_QueryDomainInfo(b, talloc_tos(),
&builtin_handle,
2,
&builtin_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += builtin_info->general.num_aliases;
}
status = dcerpc_samr_QueryDomainInfo(b, talloc_tos(),
&domain_handle,
2,
&domain_info,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
if (r->out.total_entries) {
*r->out.total_entries += domain_info->general.num_aliases;
}
status = dcerpc_samr_EnumDomainAliases(b, talloc_tos(),
&builtin_handle,
r->in.resume_handle,
&builtin_sam_array,
r->in.prefmaxlen,
&entries_read,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
for (i=0; i<builtin_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = libnetapi_samr_open_alias_queryinfo(ctx, pipe_cli,
&builtin_handle,
builtin_sam_array->entries[i].idx,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = map_alias_info_to_buffer(ctx,
builtin_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
status = dcerpc_samr_EnumDomainAliases(b, talloc_tos(),
&domain_handle,
r->in.resume_handle,
&domain_sam_array,
r->in.prefmaxlen,
&entries_read,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
for (i=0; i<domain_sam_array->count; i++) {
union samr_AliasInfo *alias_info = NULL;
if (r->in.level == 1) {
status = libnetapi_samr_open_alias_queryinfo(ctx, pipe_cli,
&domain_handle,
domain_sam_array->entries[i].idx,
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
ALIASINFOALL,
&alias_info);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
werr = map_alias_info_to_buffer(ctx,
domain_sam_array->entries[i].name.string,
alias_info ? &alias_info->all : NULL,
r->in.level,
r->out.entries_read,
r->out.buffer);
}
done:
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupEnum_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupEnum *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupEnum);
}
/****************************************************************
****************************************************************/
static NTSTATUS libnetapi_lsa_lookup_names3(TALLOC_CTX *mem_ctx,
struct rpc_pipe_client *lsa_pipe,
const char *name,
struct dom_sid *sid)
{
NTSTATUS status, result;
struct policy_handle lsa_handle;
struct dcerpc_binding_handle *b = lsa_pipe->binding_handle;
struct lsa_RefDomainList *domains = NULL;
struct lsa_TransSidArray3 sids;
uint32_t count = 0;
struct lsa_String names;
uint32_t num_names = 1;
if (!sid || !name) {
return NT_STATUS_INVALID_PARAMETER;
}
ZERO_STRUCT(sids);
init_lsa_String(&names, name);
status = rpccli_lsa_open_policy2(lsa_pipe, mem_ctx,
false,
SEC_STD_READ_CONTROL |
LSA_POLICY_VIEW_LOCAL_INFORMATION |
LSA_POLICY_LOOKUP_NAMES,
&lsa_handle);
NT_STATUS_NOT_OK_RETURN(status);
status = dcerpc_lsa_LookupNames3(b, mem_ctx,
&lsa_handle,
num_names,
&names,
&domains,
&sids,
LSA_LOOKUP_NAMES_ALL, /* sure ? */
&count,
0, 0,
&result);
NT_STATUS_NOT_OK_RETURN(status);
NT_STATUS_NOT_OK_RETURN(result);
if (count != 1 || sids.count != 1) {
return NT_STATUS_INVALID_NETWORK_RESPONSE;
}
sid_copy(sid, sids.sids[0].sid);
return NT_STATUS_OK;
}
/****************************************************************
****************************************************************/
static WERROR NetLocalGroupModifyMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *add,
struct NetLocalGroupDelMembers *del,
struct NetLocalGroupSetMembers *set)
{
struct NetLocalGroupAddMembers *r = NULL;
struct rpc_pipe_client *pipe_cli = NULL;
struct rpc_pipe_client *lsa_pipe = NULL;
NTSTATUS status, result;
WERROR werr;
struct lsa_String lsa_account_name;
struct policy_handle connect_handle, domain_handle, builtin_handle, alias_handle;
struct dom_sid2 *domain_sid = NULL;
struct dom_sid *member_sids = NULL;
int i = 0, k = 0;
struct LOCALGROUP_MEMBERS_INFO_0 *info0 = NULL;
struct LOCALGROUP_MEMBERS_INFO_3 *info3 = NULL;
struct dom_sid *add_sids = NULL;
struct dom_sid *del_sids = NULL;
uint32_t num_add_sids = 0;
uint32_t num_del_sids = 0;
struct dcerpc_binding_handle *b = NULL;
if ((!add && !del && !set) || (add && del && set)) {
return WERR_INVALID_PARAM;
}
if (add) {
r = add;
}
if (del) {
r = (struct NetLocalGroupAddMembers *)del;
}
if (set) {
r = (struct NetLocalGroupAddMembers *)set;
}
if (!r->in.group_name) {
return WERR_INVALID_PARAM;
}
switch (r->in.level) {
case 0:
case 3:
break;
default:
return WERR_UNKNOWN_LEVEL;
}
if (r->in.total_entries == 0 || !r->in.buffer) {
return WERR_INVALID_PARAM;
}
ZERO_STRUCT(connect_handle);
ZERO_STRUCT(builtin_handle);
ZERO_STRUCT(domain_handle);
ZERO_STRUCT(alias_handle);
member_sids = talloc_zero_array(ctx, struct dom_sid,
r->in.total_entries);
W_ERROR_HAVE_NO_MEMORY(member_sids);
switch (r->in.level) {
case 0:
info0 = (struct LOCALGROUP_MEMBERS_INFO_0 *)r->in.buffer;
for (i=0; i < r->in.total_entries; i++) {
sid_copy(&member_sids[i], (struct dom_sid *)info0[i].lgrmi0_sid);
}
break;
case 3:
info3 = (struct LOCALGROUP_MEMBERS_INFO_3 *)r->in.buffer;
break;
default:
break;
}
if (r->in.level == 3) {
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_lsarpc.syntax_id,
&lsa_pipe);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
for (i=0; i < r->in.total_entries; i++) {
status = libnetapi_lsa_lookup_names3(ctx, lsa_pipe,
info3[i].lgrmi3_domainandname,
&member_sids[i]);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
TALLOC_FREE(lsa_pipe);
}
werr = libnetapi_open_pipe(ctx, r->in.server_name,
&ndr_table_samr.syntax_id,
&pipe_cli);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
b = pipe_cli->binding_handle;
werr = libnetapi_samr_open_builtin_domain(ctx, pipe_cli,
SAMR_ACCESS_LOOKUP_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&builtin_handle);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
init_lsa_String(&lsa_account_name, r->in.group_name);
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&builtin_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_ADD_MEMBER |
SAMR_ALIAS_ACCESS_REMOVE_MEMBER |
SAMR_ALIAS_ACCESS_GET_MEMBERS |
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
}
if (NT_STATUS_IS_OK(status)) {
goto modify_membership;
}
werr = libnetapi_samr_open_domain(ctx, pipe_cli,
SAMR_ACCESS_ENUM_DOMAINS |
SAMR_ACCESS_LOOKUP_DOMAIN,
SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
&connect_handle,
&domain_handle,
&domain_sid);
if (!W_ERROR_IS_OK(werr)) {
goto done;
}
status = libnetapi_samr_lookup_and_open_alias(ctx, pipe_cli,
&domain_handle,
r->in.group_name,
SAMR_ALIAS_ACCESS_ADD_MEMBER |
SAMR_ALIAS_ACCESS_REMOVE_MEMBER |
SAMR_ALIAS_ACCESS_GET_MEMBERS |
SAMR_ALIAS_ACCESS_LOOKUP_INFO,
&alias_handle);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
}
modify_membership:
if (add) {
for (i=0; i < r->in.total_entries; i++) {
status = add_sid_to_array_unique(ctx, &member_sids[i],
&add_sids,
&num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (del) {
for (i=0; i < r->in.total_entries; i++) {
status = add_sid_to_array_unique(ctx, &member_sids[i],
&del_sids,
&num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
if (set) {
struct lsa_SidArray current_sids;
status = dcerpc_samr_GetMembersInAlias(b, talloc_tos(),
&alias_handle,
¤t_sids,
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
/* add list */
for (i=0; i < r->in.total_entries; i++) {
bool already_member = false;
for (k=0; k < current_sids.num_sids; k++) {
if (dom_sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
already_member = true;
break;
}
}
if (!already_member) {
status = add_sid_to_array_unique(ctx,
&member_sids[i],
&add_sids, &num_add_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
/* del list */
for (k=0; k < current_sids.num_sids; k++) {
bool keep_member = false;
for (i=0; i < r->in.total_entries; i++) {
if (dom_sid_equal(&member_sids[i],
current_sids.sids[k].sid)) {
keep_member = true;
break;
}
}
if (!keep_member) {
status = add_sid_to_array_unique(ctx,
current_sids.sids[k].sid,
&del_sids, &num_del_sids);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
}
}
}
/* add list */
for (i=0; i < num_add_sids; i++) {
status = dcerpc_samr_AddAliasMember(b, talloc_tos(),
&alias_handle,
&add_sids[i],
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
/* del list */
for (i=0; i < num_del_sids; i++) {
status = dcerpc_samr_DeleteAliasMember(b, talloc_tos(),
&alias_handle,
&del_sids[i],
&result);
if (!NT_STATUS_IS_OK(status)) {
werr = ntstatus_to_werror(status);
goto done;
}
if (!NT_STATUS_IS_OK(result)) {
werr = ntstatus_to_werror(result);
goto done;
}
}
werr = WERR_OK;
done:
if (b && is_valid_policy_hnd(&alias_handle)) {
dcerpc_samr_Close(b, talloc_tos(), &alias_handle, &result);
}
if (ctx->disable_policy_handle_cache) {
libnetapi_samr_close_domain_handle(ctx, &domain_handle);
libnetapi_samr_close_builtin_handle(ctx, &builtin_handle);
libnetapi_samr_close_connect_handle(ctx, &connect_handle);
}
return werr;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAddMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, r, NULL, NULL);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupAddMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupAddMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupAddMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDelMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupDelMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, NULL, r, NULL);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupDelMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupDelMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupDelMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetMembers *r)
{
return WERR_NOT_SUPPORTED;
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupGetMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupGetMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupGetMembers);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetMembers_r(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetMembers *r)
{
return NetLocalGroupModifyMembers_r(ctx, NULL, NULL, r);
}
/****************************************************************
****************************************************************/
WERROR NetLocalGroupSetMembers_l(struct libnetapi_ctx *ctx,
struct NetLocalGroupSetMembers *r)
{
LIBNETAPI_REDIRECT_TO_LOCALHOST(ctx, r, NetLocalGroupSetMembers);
}
| rchicoli/samba | source3/lib/netapi/localgroup.c | C | gpl-3.0 | 36,680 |
/*
* Copyright 2011 kubtek <[email protected]>
*
* This file is part of StarDict.
*
* StarDict is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* StarDict 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 StarDict. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "pluginmanagedlg.h"
#include "desktop.h"
#include <glib/gi18n.h>
#include "stardict.h"
PluginManageDlg::PluginManageDlg()
:
window(NULL),
treeview(NULL),
detail_label(NULL),
pref_button(NULL),
plugin_tree_model(NULL),
dict_changed_(false),
order_changed_(false)
{
}
PluginManageDlg::~PluginManageDlg()
{
g_assert(!window);
g_assert(!treeview);
g_assert(!detail_label);
g_assert(!pref_button);
g_assert(!plugin_tree_model);
}
void PluginManageDlg::response_handler (GtkDialog *dialog, gint res_id, PluginManageDlg *oPluginManageDlg)
{
if (res_id == GTK_RESPONSE_HELP) {
show_help("stardict-plugins");
} else if (res_id == STARDICT_RESPONSE_CONFIGURE) {
GtkTreeSelection *selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(oPluginManageDlg->treeview));
GtkTreeModel *model;
GtkTreeIter iter;
if (! gtk_tree_selection_get_selected (selection, &model, &iter))
return;
if (!gtk_tree_model_iter_has_child(model, &iter)) {
gchar *filename;
StarDictPlugInType plugin_type;
gtk_tree_model_get (model, &iter, 4, &filename, 5, &plugin_type, -1);
gpAppFrame->oStarDictPlugins->configure_plugin(filename, plugin_type);
g_free(filename);
}
}
}
static gboolean get_disable_list(GtkTreeModel *model, GtkTreePath *path, GtkTreeIter *iter, gpointer data)
{
if (!gtk_tree_model_iter_has_child(model, iter)) {
gboolean enable;
gtk_tree_model_get (model, iter, 1, &enable, -1);
if (!enable) {
gchar *filename;
gtk_tree_model_get (model, iter, 4, &filename, -1);
std::list<std::string> *disable_list = (std::list<std::string> *)data;
disable_list->push_back(filename);
g_free(filename);
}
}
return FALSE;
}
void PluginManageDlg::on_plugin_enable_toggled (GtkCellRendererToggle *cell, gchar *path_str, PluginManageDlg *oPluginManageDlg)
{
GtkTreeModel *model = GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model);
GtkTreePath *path = gtk_tree_path_new_from_string (path_str);
GtkTreeIter iter;
gtk_tree_model_get_iter (model, &iter, path);
gtk_tree_path_free (path);
gboolean enable;
gchar *filename;
StarDictPlugInType plugin_type;
gboolean can_configure;
gtk_tree_model_get (model, &iter, 1, &enable, 4, &filename, 5, &plugin_type, 6, &can_configure, -1);
enable = !enable;
gtk_tree_store_set (GTK_TREE_STORE (model), &iter, 1, enable, -1);
if (enable) {
gpAppFrame->oStarDictPlugins->load_plugin(filename);
} else {
gpAppFrame->oStarDictPlugins->unload_plugin(filename, plugin_type);
}
g_free(filename);
if (enable)
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, can_configure);
else
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
if (plugin_type == StarDictPlugInType_VIRTUALDICT
|| plugin_type == StarDictPlugInType_NETDICT) {
oPluginManageDlg->dict_changed_ = true;
} else if (plugin_type == StarDictPlugInType_TTS) {
gpAppFrame->oMidWin.oToolWin.UpdatePronounceMenu();
}
std::list<std::string> disable_list;
gtk_tree_model_foreach(model, get_disable_list, &disable_list);
#ifdef _WIN32
{
std::list<std::string> disable_list_rel;
rel_path_to_data_dir(disable_list, disable_list_rel);
std::swap(disable_list, disable_list_rel);
}
#endif
conf->set_strlist("/apps/stardict/manage_plugins/plugin_disable_list", disable_list);
}
struct plugininfo_ParseUserData {
gchar *info_str;
gchar *detail_str;
std::string filename;
std::string name;
std::string version;
std::string short_desc;
std::string long_desc;
std::string author;
std::string website;
};
static void plugininfo_parse_start_element(GMarkupParseContext *context, const gchar *element_name, const gchar **attribute_names, const gchar **attribute_values, gpointer user_data, GError **error)
{
if (strcmp(element_name, "plugin_info")==0) {
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
Data->name.clear();
Data->version.clear();
Data->short_desc.clear();
Data->long_desc.clear();
Data->author.clear();
Data->website.clear();
}
}
static void plugininfo_parse_end_element(GMarkupParseContext *context, const gchar *element_name, gpointer user_data, GError **error)
{
if (strcmp(element_name, "plugin_info")==0) {
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
Data->info_str = g_markup_printf_escaped("<b>%s</b> %s\n%s", Data->name.c_str(), Data->version.c_str(), Data->short_desc.c_str());
Data->detail_str = g_markup_printf_escaped(_("%s\n\n<b>Author:</b>\t%s\n<b>Website:</b>\t%s\n<b>Filename:</b>\t%s"), Data->long_desc.c_str(), Data->author.c_str(), Data->website.c_str(), Data->filename.c_str());
}
}
static void plugininfo_parse_text(GMarkupParseContext *context, const gchar *text, gsize text_len, gpointer user_data, GError **error)
{
const gchar *element = g_markup_parse_context_get_element(context);
if (!element)
return;
plugininfo_ParseUserData *Data = (plugininfo_ParseUserData *)user_data;
if (strcmp(element, "name")==0) {
Data->name.assign(text, text_len);
} else if (strcmp(element, "version")==0) {
Data->version.assign(text, text_len);
} else if (strcmp(element, "short_desc")==0) {
Data->short_desc.assign(text, text_len);
} else if (strcmp(element, "long_desc")==0) {
Data->long_desc.assign(text, text_len);
} else if (strcmp(element, "author")==0) {
Data->author.assign(text, text_len);
} else if (strcmp(element, "website")==0) {
Data->website.assign(text, text_len);
}
}
static void add_tree_model(GtkTreeStore *tree_model, GtkTreeIter*parent, const std::list<StarDictPluginInfo> &infolist)
{
plugininfo_ParseUserData Data;
GMarkupParser parser;
parser.start_element = plugininfo_parse_start_element;
parser.end_element = plugininfo_parse_end_element;
parser.text = plugininfo_parse_text;
parser.passthrough = NULL;
parser.error = NULL;
GtkTreeIter iter;
for (std::list<StarDictPluginInfo>::const_iterator i = infolist.begin(); i != infolist.end(); ++i) {
Data.info_str = NULL;
Data.detail_str = NULL;
Data.filename = i->filename;
GMarkupParseContext* context = g_markup_parse_context_new(&parser, (GMarkupParseFlags)0, &Data, NULL);
g_markup_parse_context_parse(context, i->info_xml.c_str(), -1, NULL);
g_markup_parse_context_end_parse(context, NULL);
g_markup_parse_context_free(context);
gtk_tree_store_append(tree_model, &iter, parent);
bool loaded = gpAppFrame->oStarDictPlugins->get_loaded(i->filename.c_str());
gtk_tree_store_set(tree_model, &iter, 0, true, 1, loaded, 2, Data.info_str, 3, Data.detail_str, 4, i->filename.c_str(), 5, i->plugin_type, 6, i->can_configure, -1);
g_free(Data.info_str);
g_free(Data.detail_str);
}
}
static void init_tree_model(GtkTreeStore *tree_model)
{
std::list<std::pair<StarDictPlugInType, std::list<StarDictPluginInfo> > > plugin_list;
{
#ifdef _WIN32
std::list<std::string> plugin_order_list;
const std::list<std::string>& plugin_order_list_rel
= conf->get_strlist("/apps/stardict/manage_plugins/plugin_order_list");
abs_path_to_data_dir(plugin_order_list_rel, plugin_order_list);
#else
const std::list<std::string>& plugin_order_list
= conf->get_strlist("/apps/stardict/manage_plugins/plugin_order_list");
#endif
gpAppFrame->oStarDictPlugins->get_plugin_list(plugin_order_list, plugin_list);
}
GtkTreeIter iter;
for (std::list<std::pair<StarDictPlugInType, std::list<StarDictPluginInfo> > >::iterator i = plugin_list.begin(); i != plugin_list.end(); ++i) {
switch (i->first) {
case StarDictPlugInType_VIRTUALDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Virtual Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_NETDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Network Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_SPECIALDICT:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Special Dictionary</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_TTS:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>TTS Engine</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_PARSEDATA:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Data Parsing Engine</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
case StarDictPlugInType_MISC:
gtk_tree_store_append(tree_model, &iter, NULL);
gtk_tree_store_set(tree_model, &iter, 0, false, 2, _("<b>Misc</b>"), -1);
add_tree_model(tree_model, &iter, i->second);
break;
default:
break;
}
}
}
void PluginManageDlg::on_plugin_treeview_selection_changed(GtkTreeSelection *selection, PluginManageDlg *oPluginManageDlg)
{
GtkTreeModel *model;
GtkTreeIter iter;
if (! gtk_tree_selection_get_selected (selection, &model, &iter))
return;
if (gtk_tree_model_iter_has_child(model, &iter)) {
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
} else {
gboolean loaded;
gchar *detail;
gboolean can_configure;
gtk_tree_model_get (model, &iter, 1, &loaded, 3, &detail, 6, &can_configure, -1);
gtk_label_set_markup(GTK_LABEL(oPluginManageDlg->detail_label), detail);
g_free(detail);
if (loaded)
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, can_configure);
else
gtk_widget_set_sensitive(oPluginManageDlg->pref_button, FALSE);
}
}
gboolean PluginManageDlg::on_treeview_button_press(GtkWidget * widget, GdkEventButton * event, PluginManageDlg *oPluginManageDlg)
{
if (event->type==GDK_2BUTTON_PRESS) {
if (gtk_widget_get_sensitive(GTK_WIDGET(oPluginManageDlg->pref_button)))
gtk_dialog_response(GTK_DIALOG(oPluginManageDlg->window), STARDICT_RESPONSE_CONFIGURE);
return true;
} else {
return false;
}
}
static void add_order_list(std::list<std::string> &order_list, GtkTreeModel *now_tree_model, GtkTreeIter *parent)
{
gboolean have_iter;
GtkTreeIter iter;
have_iter = gtk_tree_model_iter_children(now_tree_model, &iter, parent);
gchar *filename;
while (have_iter) {
gtk_tree_model_get (now_tree_model, &iter, 4, &filename, -1);
order_list.push_back(filename);
g_free(filename);
have_iter = gtk_tree_model_iter_next(now_tree_model, &iter);
}
}
void PluginManageDlg::write_order_list()
{
std::list<std::string> order_list;
GtkTreeModel *now_tree_model = GTK_TREE_MODEL(plugin_tree_model);
gboolean have_iter;
GtkTreeIter iter;
have_iter = gtk_tree_model_get_iter_first(now_tree_model, &iter);
while (have_iter) {
if (gtk_tree_model_iter_has_child(now_tree_model, &iter)) {
add_order_list(order_list, now_tree_model, &iter);
}
have_iter = gtk_tree_model_iter_next(now_tree_model, &iter);
}
#ifdef _WIN32
{
std::list<std::string> order_list_rel;
rel_path_to_data_dir(order_list, order_list_rel);
std::swap(order_list, order_list_rel);
}
#endif
conf->set_strlist("/apps/stardict/manage_plugins/plugin_order_list", order_list);
}
void PluginManageDlg::drag_data_get_cb(GtkWidget *widget, GdkDragContext *ctx, GtkSelectionData *data, guint info, guint time, PluginManageDlg *oPluginManageDlg)
{
if (gtk_selection_data_get_target(data) == gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE)) {
GtkTreeRowReference *ref;
GtkTreePath *source_row;
ref = (GtkTreeRowReference *)g_object_get_data(G_OBJECT(ctx), "gtk-tree-view-source-row");
source_row = gtk_tree_row_reference_get_path(ref);
if (source_row == NULL)
return;
GtkTreeIter iter;
gtk_tree_model_get_iter(GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model), &iter, source_row);
gtk_selection_data_set(data, gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE), 8, (const guchar *)&iter, sizeof(iter));
gtk_tree_path_free(source_row);
}
}
void PluginManageDlg::drag_data_received_cb(GtkWidget *widget, GdkDragContext *ctx, guint x, guint y, GtkSelectionData *sd, guint info, guint t, PluginManageDlg *oPluginManageDlg)
{
if (gtk_selection_data_get_target(sd) == gdk_atom_intern("STARDICT_PLUGINMANAGE", FALSE) && gtk_selection_data_get_data(sd)) {
GtkTreePath *path = NULL;
GtkTreeViewDropPosition position;
GtkTreeIter drag_iter;
memcpy(&drag_iter, gtk_selection_data_get_data(sd), sizeof(drag_iter));
if (gtk_tree_view_get_dest_row_at_pos(GTK_TREE_VIEW(widget), x, y, &path, &position)) {
GtkTreeIter iter;
GtkTreeModel *model = GTK_TREE_MODEL(oPluginManageDlg->plugin_tree_model);
gtk_tree_model_get_iter(model, &iter, path);
if (gtk_tree_model_iter_has_child(model, &iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
if (gtk_tree_model_iter_has_child(model, &drag_iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
GtkTreeIter parent_iter;
if (!gtk_tree_model_iter_parent(model, &parent_iter, &iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
GtkTreeIter drag_parent_iter;
if (!gtk_tree_model_iter_parent(model, &drag_parent_iter, &drag_iter)) {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
char *iter_str, *drag_iter_str;
iter_str = gtk_tree_model_get_string_from_iter(model, &parent_iter);
drag_iter_str = gtk_tree_model_get_string_from_iter(model, &drag_parent_iter);
if (strcmp(iter_str, drag_iter_str) != 0) {
g_free(iter_str);
g_free(drag_iter_str);
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
g_free(iter_str);
g_free(drag_iter_str);
switch (position) {
case GTK_TREE_VIEW_DROP_AFTER:
case GTK_TREE_VIEW_DROP_INTO_OR_AFTER:
gtk_tree_store_move_after(GTK_TREE_STORE(model), &drag_iter, &iter);
break;
case GTK_TREE_VIEW_DROP_BEFORE:
case GTK_TREE_VIEW_DROP_INTO_OR_BEFORE:
gtk_tree_store_move_before(GTK_TREE_STORE(model), &drag_iter, &iter);
break;
default: {
gtk_drag_finish (ctx, FALSE, FALSE, t);
return;
}
}
oPluginManageDlg->write_order_list();
oPluginManageDlg->order_changed_ = true;
gtk_drag_finish (ctx, TRUE, FALSE, t);
}
}
}
GtkWidget *PluginManageDlg::create_plugin_list()
{
GtkWidget *sw;
sw = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (sw), GTK_SHADOW_IN);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
plugin_tree_model = gtk_tree_store_new(7, G_TYPE_BOOLEAN, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_INT, G_TYPE_BOOLEAN);
init_tree_model(plugin_tree_model);
treeview = gtk_tree_view_new_with_model (GTK_TREE_MODEL(plugin_tree_model));
g_object_unref (G_OBJECT (plugin_tree_model));
#if GTK_MAJOR_VERSION >= 3
#else
gtk_tree_view_set_rules_hint (GTK_TREE_VIEW (treeview), TRUE);
#endif
g_signal_connect (G_OBJECT (treeview), "button_press_event", G_CALLBACK (on_treeview_button_press), this);
GtkTreeSelection *selection;
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (treeview));
gtk_tree_selection_set_mode (selection, GTK_SELECTION_SINGLE);
g_signal_connect (selection, "changed", G_CALLBACK (on_plugin_treeview_selection_changed), this);
GtkCellRenderer *renderer;
GtkTreeViewColumn *column;
renderer = gtk_cell_renderer_toggle_new ();
g_signal_connect (renderer, "toggled", G_CALLBACK (on_plugin_enable_toggled), this);
column = gtk_tree_view_column_new_with_attributes (_("Enable"), renderer, "visible", 0, "active", 1, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN (column), FALSE);
gtk_tree_view_column_set_clickable (GTK_TREE_VIEW_COLUMN (column), FALSE);
renderer = gtk_cell_renderer_text_new ();
g_object_set (G_OBJECT (renderer), "xalign", 0.0, NULL);
column = gtk_tree_view_column_new_with_attributes (_("Plug-in Name"), renderer, "markup", 2, NULL);
gtk_tree_view_append_column (GTK_TREE_VIEW(treeview), column);
gtk_tree_view_column_set_expand(GTK_TREE_VIEW_COLUMN (column), TRUE);
gtk_tree_view_column_set_clickable (GTK_TREE_VIEW_COLUMN (column), FALSE);
GtkTargetEntry gte[] = {{(gchar *)"STARDICT_PLUGINMANAGE", GTK_TARGET_SAME_APP, 0}};
gtk_tree_view_enable_model_drag_source(GTK_TREE_VIEW(treeview), GDK_BUTTON1_MASK, gte, 1, GDK_ACTION_COPY);
gtk_tree_view_enable_model_drag_dest(GTK_TREE_VIEW(treeview), gte, 1, (GdkDragAction)(GDK_ACTION_COPY | GDK_ACTION_MOVE));
g_signal_connect(G_OBJECT(treeview), "drag-data-received", G_CALLBACK(drag_data_received_cb), this);
g_signal_connect(G_OBJECT(treeview), "drag-data-get", G_CALLBACK(drag_data_get_cb), this);
gtk_tree_view_expand_all(GTK_TREE_VIEW (treeview));
gtk_container_add (GTK_CONTAINER (sw), treeview);
return sw;
}
bool PluginManageDlg::ShowModal(GtkWindow *parent_win, bool &dict_changed, bool &order_changed)
{
window = gtk_dialog_new();
oStarDictPluginSystemInfo.pluginwin = window;
gtk_window_set_transient_for(GTK_WINDOW(window), parent_win);
//gtk_dialog_set_has_separator(GTK_DIALOG(window), false);
gtk_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_HELP, GTK_RESPONSE_HELP);
pref_button = gtk_dialog_add_button(GTK_DIALOG(window), _("Configure Pl_ug-in"), STARDICT_RESPONSE_CONFIGURE);
gtk_widget_set_sensitive(pref_button, FALSE);
gtk_dialog_add_button(GTK_DIALOG(window), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE);
gtk_dialog_set_default_response(GTK_DIALOG(window), GTK_RESPONSE_CLOSE);
g_signal_connect(G_OBJECT(window), "response", G_CALLBACK(response_handler), this);
GtkWidget *vbox;
#if GTK_MAJOR_VERSION >= 3
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
#else
vbox = gtk_vbox_new (FALSE, 5);
#endif
gtk_container_set_border_width (GTK_CONTAINER (vbox), 2);
GtkWidget *pluginlist = create_plugin_list();
gtk_box_pack_start (GTK_BOX (vbox), pluginlist, true, true, 0);
GtkWidget *expander = gtk_expander_new (_("<b>Plug-in Details</b>"));
gtk_expander_set_use_markup(GTK_EXPANDER(expander), TRUE);
gtk_box_pack_start (GTK_BOX (vbox), expander, false, false, 0);
detail_label = gtk_label_new (NULL);
gtk_label_set_line_wrap(GTK_LABEL(detail_label), TRUE);
gtk_label_set_selectable(GTK_LABEL (detail_label), TRUE);
gtk_container_add (GTK_CONTAINER (expander), detail_label);
gtk_box_pack_start (GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG (window))), vbox, true, true, 0);
gtk_widget_show_all (gtk_dialog_get_content_area(GTK_DIALOG (window)));
gtk_window_set_title (GTK_WINDOW (window), _("Manage Plugins"));
gtk_window_set_default_size(GTK_WINDOW(window), 250, 350);
dict_changed_ = false;
order_changed_ = false;
gint result;
while (true) {
result = gtk_dialog_run(GTK_DIALOG(window));
if (result ==GTK_RESPONSE_HELP || result == STARDICT_RESPONSE_CONFIGURE) {
} else {
break;
}
}
/* When do we get GTK_RESPONSE_NONE response? Unable to reproduce. */
if (result != GTK_RESPONSE_NONE) {
dict_changed = dict_changed_;
order_changed = order_changed_;
gtk_widget_destroy(GTK_WIDGET(window));
}
window = NULL;
treeview = NULL;
detail_label = NULL;
pref_button = NULL;
plugin_tree_model = NULL;
oStarDictPluginSystemInfo.pluginwin = NULL;
return result == GTK_RESPONSE_NONE;
}
| huzheng001/stardict-3 | dict/src/pluginmanagedlg.cpp | C++ | gpl-3.0 | 20,060 |
# ChangeLog
## Version 5.2.7 (September 12th 2013)
* Add Ukranian translation from @Krezalis
* Support for do_verp
* Fix bug in CRAM-MD5 AUTH
* Propagate Debugoutput option to SMTP class (@Reblutus)
* Determine MIME type of attachments automatically
* Add cross-platform, multibyte-safe pathinfo replacement (with tests) and use it
* Add a new 'html' Debugoutput type
* Clean up SMTP debug output, remove embedded HTML
* Some small changes in header formatting to improve IETF msglint test results
* Update test_script to use some recently changed features, rename to code_generator
* Generated code actually works!
* Update SyntaxHighlighter
* Major overhaul and cleanup of example code
* New PHPMailer graphic
* msgHTML now uses RFC2392-compliant content ids
* Add line break normalization function and use it in msgHTML
* Don't set unnecessary reply-to addresses
* Make fakesendmail.sh a bit cleaner and safer
* Set a content-transfer-encoding on multiparts (fixes msglint error)
* Fix cid generation in msgHTML (Thanks to @digitalthought)
* Fix handling of multiple SMTP servers (Thanks to @NanoCaiordo)
* SMTP->connect() now supports stream context options (Thanks to @stanislavdavid)
* Add support for iCal event alternatives (Thanks to @reblutus)
* Update to Polish language file (Thanks to Krzysztof Kowalewski)
* Update to Norwegian language file (Thanks to @datagutten)
* Update to Hungarian language file (Thanks to @dominicus-75)
* Add Persian/Farsi translation from @jaii
* Make SMTPDebug property type match type in SMTP class
* Add unit tests for DKIM
* Major refactor of SMTP class
* Reformat to PSR-2 coding standard
* Introduce autoloader
* Allow overriding of SMTP class
* Overhaul of PHPDocs
* Fix broken Q-encoding
* Czech language update (Thanks to @nemelu)
* Removal of excess blank lines in messages
* Added fake POP server and unit tests for POP-before-SMTP
## Version 5.2.6 (April 11th 2013)
* Reflect move to PHPMailer GitHub organisation at https://github.com/PHPMailer/PHPMailer
* Fix unbumped version numbers
* Update packagist.org with new location
* Clean up Changelog
## Version 5.2.5 (April 6th 2013)
* First official release after move from Google Code
* Fixes for qmail when sending via mail()
* Merge in changes from Google code 5.2.4 release
* Minor coding standards cleanup in SMTP class
* Improved unit tests, now tests S/MIME signing
* Travis-CI support on GitHub, runs tests with fake SMTP server
## Version 5.2.4 (February 19, 2013)
* Fix tag and version bug.
* un-deprecate isSMTP(), isMail(), IsSendmail() and isQmail().
* Numerous translation updates
## Version 5.2.3 (February 8, 2013)
* Fix issue with older PCREs and ValidateAddress() (Bugz: 124)
* Add CRAM-MD5 authentication, thanks to Elijah madden, https://github.com/okonomiyaki3000
* Replacement of obsolete Quoted-Printable encoder with a much better implementation
* Composer package definition
* New language added: Hebrew
## Version 5.2.2 (December 3, 2012)
* Some fixes and syncs from https://github.com/Synchro/PHPMailer
* Add Slovak translation, thanks to Michal Tinka
## Version 5.2.2-rc2 (November 6, 2012)
* Fix SMTP server rotation (Bugz: 118)
* Allow override of autogen'ed 'Date' header (for Drupal's
og_mailinglist module)
* No whitespace after '-f' option (Bugz: 116)
* Work around potential warning (Bugz: 114)
## Version 5.2.2-rc1 (September 28, 2012)
* Header encoding works with long lines (Bugz: 93)
* Turkish language update (Bugz: 94)
* undefined $pattern in EncodeQ bug squashed (Bugz: 98)
* use of mail() in safe_mode now works (Bugz: 96)
* ValidateAddress() now 'public static' so people can override the
default and use their own validation scheme.
* ValidateAddress() no longer uses broken FILTER_VALIDATE_EMAIL
* Added in AUTH PLAIN SMTP authentication
## Version 5.2.2-beta2 (August 17, 2012)
* Fixed Postfix VERP support (Bugz: 92)
* Allow action_function callbacks to pass/use
the From address (passed as final param)
* Prevent inf look for get_lines() (Bugz: 77)
* New public var ($UseSendmailOptions). Only pass sendmail()
options iff we really are using sendmail or something sendmail
compatible. (Bugz: 75)
* default setting for LE returned to "\n" due to popular demand.
## Version 5.2.2-beta1 (July 13, 2012)
* Expose PreSend() and PostSend() as public methods to allow
for more control if serializing message sending.
* GetSentMIMEMessage() only constructs the message copy when
needed. Save memory.
* Only pass params to mail() if the underlying MTA is
"sendmail" (as defined as "having the string sendmail
in its pathname") [#69]
* Attachments now work with Amazon SES and others [Bugz#70]
* Debug output now sent to stdout (via echo) or error_log [Bugz#5]
* New var: Debugoutput (for above) [Bugz#5]
* SMTP reads now Timeout aware (new var: Timeout=15) [Bugz#71]
* SMTP reads now can have a Timelimit associated with them
(new var: Timelimit=30)[Bugz#71]
* Fix quoting issue associated with charsets
* default setting for LE is now RFC compliant: "\r\n"
* Return-Path can now be user defined (new var: ReturnPath)
(the default is "" which implies no change from previous
behavior, which was to use either From or Sender) [Bugz#46]
* X-Mailer header can now be disabled (by setting to a
whitespace string, eg " ") [Bugz#66]
* Bugz closed: #68, #60, #42, #43, #59, #55, #66, #48, #49,
#52, #31, #41, #5. #70, #69
## Version 5.2.1 (January 16, 2012)
* Closed several bugs#5
* Performance improvements
* MsgHTML() now returns the message as required.
* New method: GetSentMIMEMessage() (returns full copy of sent message)
## Version 5.2 (July 19, 2011)
* protected MIME body and header
* better DKIM DNS Resource Record support
* better aly handling
* htmlfilter class added to extras
* moved to Apache Extras
## Version 5.1 (October 20, 2009)
* fixed filename issue with AddStringAttachment (thanks to Tony)
* fixed "SingleTo" property, now works with Senmail, Qmail, and SMTP in
addition to PHP mail()
* added DKIM digital signing functionality, new properties:
- DKIM_domain (sets the domain name)
- DKIM_private (holds DKIM private key)
- DKIM_passphrase (holds your DKIM passphrase)
- DKIM_selector (holds the DKIM "selector")
- DKIM_identity (holds the identifying email address)
* added callback function support
- callback function parameters include:
result, to, cc, bcc, subject and body
- see the test/test_callback.php file for usage.
* added "auto" identity functionality
- can automatically add:
- Return-path (if Sender not set)
- Reply-To (if ReplyTo not set)
- can be disabled:
- $mail->SetFrom('[email protected]','First Last',false);
- or by adding the $mail->Sender and/or $mail->ReplyTo properties
Note: "auto" identity added to help with emails ending up in spam or junk boxes because of missing headers
## Version 5.0.2 (May 24, 2009)
* Fix for missing attachments when inline graphics are present
* Fix for missing Cc in header when using SMTP (mail was sent,
but not displayed in header -- Cc receiver only saw email To:
line and no Cc line, but did get the email (To receiver
saw same)
## Version 5.0.1 (April 05, 2009)
* Temporary fix for missing attachments
## Version 5.0.0 (April 02, 2009)
With the release of this version, we are initiating a new version numbering
system to differentiate from the PHP4 version of PHPMailer.
Most notable in this release is fully object oriented code.
### class.smtp.php:
* Refactored class.smtp.php to support new exception handling
* code size reduced from 29.2 Kb to 25.6 Kb
* Removed unnecessary functions from class.smtp.php:
- public function Expand($name) {
- public function Help($keyword="") {
- public function Noop() {
- public function Send($from) {
- public function SendOrMail($from) {
- public function Verify($name) {
### class.phpmailer.php:
* Refactored class.phpmailer.php with new exception handling
* Changed processing functionality of Sendmail and Qmail so they cannot be
inadvertently used
* removed getFile() function, just became a simple wrapper for
file_get_contents()
* added check for PHP version (will gracefully exit if not at least PHP 5.0)
* enhanced code to check if an attachment source is the same as an embedded or
inline graphic source to eliminate duplicate attachments
### New /test_script
We have written a test script you can use to test the script as part of your
installation. Once you press submit, the test script will send a multi-mime
email with either the message you type in or an HTML email with an inline
graphic. Two attachments are included in the email (one of the attachments
is also the inline graphic so you can see that only one copy of the graphic
is sent in the email). The test script will also display the functional
script that you can copy/paste to your editor to duplicate the functionality.
### New examples
All new examples in both basic and advanced modes. Advanced examples show
Exception handling.
### PHPDocumentator (phpdocs) documentation for PHPMailer version 5.0.0
All new documentation
## Version 2.3 (November 06, 2008)
* added Arabic language (many thanks to Bahjat Al Mostafa)
* removed English language from language files and made it a default within
class.phpmailer.php - if no language is found, it will default to use
the english language translation
* fixed public/private declarations
* corrected line 1728, $basedir to $directory
* added $sign_cert_file to avoid improper duplicate use of $sign_key_file
* corrected $this->Hello on line 612 to $this->Helo
* changed default of $LE to "\r\n" to comply with RFC 2822. Can be set by the user
if default is not acceptable
* removed trim() from return results in EncodeQP
* /test and three files it contained are removed from version 2.3
* fixed phpunit.php for compliance with PHP5
* changed $this->AltBody = $textMsg; to $this->AltBody = html_entity_decode($textMsg);
* We have removed the /phpdoc from the downloads. All documentation is now on
the http://phpmailer.codeworxtech.com website.
## Version 2.2.1 () July 19 2008
* fixed line 1092 in class.smtp.php (my apologies, error on my part)
## Version 2.2 () July 15 2008
* Fixed redirect issue (display of UTF-8 in thank you redirect)
* fixed error in getResponse function declaration (class.pop3.php)
* PHPMailer now PHP6 compliant
* fixed line 1092 in class.smtp.php (endless loop from missing = sign)
## Version 2.1 (Wed, June 04 2008)
NOTE: WE HAVE A NEW LANGUAGE VARIABLE FOR DIGITALLY SIGNED S/MIME EMAILS. IF YOU CAN HELP WITH LANGUAGES OTHER THAN ENGLISH AND SPANISH, IT WOULD BE APPRECIATED.
* added S/MIME functionality (ability to digitally sign emails)
BIG THANKS TO "sergiocambra" for posting this patch back in November 2007.
The "Signed Emails" functionality adds the Sign method to pass the private key
filename and the password to read it, and then email will be sent with
content-type multipart/signed and with the digital signature attached.
* fully compatible with E_STRICT error level
- Please note:
In about half the test environments this development version was subjected
to, an error was thrown for the date() functions used (line 1565 and 1569).
This is NOT a PHPMailer error, it is the result of an incorrectly configured
PHP5 installation. The fix is to modify your 'php.ini' file and include the
date.timezone = America/New York
directive, to your own server timezone
- If you do get this error, and are unable to access your php.ini file:
In your PHP script, add
`date_default_timezone_set('America/Toronto');`
- do not try to use
`$myVar = date_default_timezone_get();`
as a test, it will throw an error.
* added ability to define path (mainly for embedded images)
function `MsgHTML($message,$basedir='')` ... where:
`$basedir` is the fully qualified path
* fixed `MsgHTML()` function:
- Embedded Images where images are specified by `<protocol>://` will not be altered or embedded
* fixed the return value of SMTP exit code ( pclose )
* addressed issue of multibyte characters in subject line and truncating
* added ability to have user specified Message ID
(default is still that PHPMailer create a unique Message ID)
* corrected unidentified message type to 'application/octet-stream'
* fixed chunk_split() multibyte issue (thanks to Colin Brown, et al).
* added check for added attachments
* enhanced conversion of HTML to text in MsgHTML (thanks to "brunny")
## Version 2.1.0beta2 (Sun, Dec 02 2007)
* implemented updated EncodeQP (thanks to coolbru, aka Marcus Bointon)
* finished all testing, all known bugs corrected, enhancements tested
Note: will NOT work with PHP4.
Please note, this is BETA software **DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS; INTENDED STRICTLY FOR TESTING**
## Version 2.1.0beta1
Please note, this is BETA software
** DO NOT USE THIS IN PRODUCTION OR LIVE PROJECTS
INTENDED STRICTLY FOR TESTING
## Version 2.0.0 rc2 (Fri, Nov 16 2007), interim release
* implements new property to control VERP in class.smtp.php
example (requires instantiating class.smtp.php):
$mail->do_verp = true;
* POP-before-SMTP functionality included, thanks to Richard Davey
(see class.pop3.php & pop3_before_smtp_test.php for examples)
* included example showing how to use PHPMailer with GMAIL
* fixed the missing Cc in SendMail() and Mail()
******************
A note on sending bulk emails:
If the email you are sending is not personalized, consider using the
"undisclosed-recipient:;" strategy. That is, put all of your recipients
in the Bcc field and set the To field to "undisclosed-recipients:;".
It's a lot faster (only one send) and saves quite a bit on resources.
Contrary to some opinions, this will not get you listed in spam engines -
it's a legitimate way for you to send emails.
A partial example for use with PHPMailer:
```
$mail->AddAddress("undisclosed-recipients:;");
$mail->AddBCC("[email protected],[email protected],[email protected]");
```
Many email service providers restrict the number of emails that can be sent
in any given time period. Often that is between 50 - 60 emails maximum
per hour or per send session.
If that's the case, then break up your Bcc lists into chunks that are one
less than your limit, and put a pause in your script.
*******************
## Version 2.0.0 rc1 (Thu, Nov 08 2007), interim release
* dramatically simplified using inline graphics ... it's fully automated and requires no user input
* added automatic document type detection for attachments and pictures
* added MsgHTML() function to replace Body tag for HTML emails
* fixed the SendMail security issues (input validation vulnerability)
* enhanced the AddAddresses functionality so that the "Name" portion is used in the email address
* removed the need to use the AltBody method (set from the HTML, or default text used)
* set the PHP Mail() function as the default (still support SendMail, SMTP Mail)
* removed the need to set the IsHTML property (set automatically)
* added Estonian language file by Indrek Päri
* added header injection patch
* added "set" method to permit users to create their own pseudo-properties like 'X-Headers', etc.
example of use:
```
$mail->set('X-Priority', '3');
$mail->set('X-MSMail-Priority', 'Normal');
```
* fixed warning message in SMTP get_lines method
* added TLS/SSL SMTP support. Example of use:
```
$mail = new PHPMailer();
$mail->Mailer = "smtp";
$mail->Host = "smtp.example.com";
$mail->SMTPSecure = "tls"; // option
//$mail->SMTPSecure = "ssl"; // option
...
$mail->Send();
```
* PHPMailer has been tested with PHP4 (4.4.7) and PHP5 (5.2.7)
* Works with PHP installed as a module or as CGI-PHP
NOTE: will NOT work with PHP5 in E_STRICT error mode
## Version 1.73 (Sun, Jun 10 2005)
* Fixed denial of service bug: http://www.cybsec.com/vuln/PHPMailer-DOS.pdf
* Now has a total of 20 translations
* Fixed alt attachments bug: http://tinyurl.com/98u9k
## Version 1.72 (Wed, May 25 2004)
* Added Dutch, Swedish, Czech, Norwegian, and Turkish translations.
* Received: Removed this method because spam filter programs like
SpamAssassin reject this header.
* Fixed error count bug.
* SetLanguage default is now "language/".
* Fixed magic_quotes_runtime bug.
## Version 1.71 (Tue, Jul 28 2003)
* Made several speed enhancements
* Added German and Italian translation files
* Fixed HELO/AUTH bugs on keep-alive connects
* Now provides an error message if language file does not load
* Fixed attachment EOL bug
* Updated some unclear documentation
* Added additional tests and improved others
## Version 1.70 (Mon, Jun 20 2003)
* Added SMTP keep-alive support
* Added IsError method for error detection
* Added error message translation support (SetLanguage)
* Refactored many methods to increase library performance
* Hello now sends the newer EHLO message before HELO as per RFC 2821
* Removed the boundary class and replaced it with GetBoundary
* Removed queue support methods
* New $Hostname variable
* New Message-ID header
* Received header reformat
* Helo variable default changed to $Hostname
* Removed extra spaces in Content-Type definition (#667182)
* Return-Path should be set to Sender when set
* Adds Q or B encoding to headers when necessary
* quoted-encoding should now encode NULs \000
* Fixed encoding of body/AltBody (#553370)
* Adds "To: undisclosed-recipients:;" when all recipients are hidden (BCC)
* Multiple bug fixes
## Version 1.65 (Fri, Aug 09 2002)
* Fixed non-visible attachment bug (#585097) for Outlook
* SMTP connections are now closed after each transaction
* Fixed SMTP::Expand return value
* Converted SMTP class documentation to phpDocumentor format
## Version 1.62 (Wed, Jun 26 2002)
* Fixed multi-attach bug
* Set proper word wrapping
* Reduced memory use with attachments
* Added more debugging
* Changed documentation to phpDocumentor format
## Version 1.60 (Sat, Mar 30 2002)
* Sendmail pipe and address patch (Christian Holtje)
* Added embedded image and read confirmation support (A. Ognio)
* Added unit tests
* Added SMTP timeout support (*nix only)
* Added possibly temporary PluginDir variable for SMTP class
* Added LE message line ending variable
* Refactored boundary and attachment code
* Eliminated SMTP class warnings
* Added SendToQueue method for future queuing support
## Version 1.54 (Wed, Dec 19 2001)
* Add some queuing support code
* Fixed a pesky multi/alt bug
* Messages are no longer forced to have "To" addresses
## Version 1.50 (Thu, Nov 08 2001)
* Fix extra lines when not using SMTP mailer
* Set WordWrap variable to int with a zero default
## Version 1.47 (Tue, Oct 16 2001)
* Fixed Received header code format
* Fixed AltBody order error
* Fixed alternate port warning
## Version 1.45 (Tue, Sep 25 2001)
* Added enhanced SMTP debug support
* Added support for multiple ports on SMTP
* Added Received header for tracing
* Fixed AddStringAttachment encoding
* Fixed possible header name quote bug
* Fixed wordwrap() trim bug
* Couple other small bug fixes
## Version 1.41 (Wed, Aug 22 2001)
* Fixed AltBody bug w/o attachments
* Fixed rfc_date() for certain mail servers
## Version 1.40 (Sun, Aug 12 2001)
* Added multipart/alternative support (AltBody)
* Documentation update
* Fixed bug in Mercury MTA
## Version 1.29 (Fri, Aug 03 2001)
* Added AddStringAttachment() method
* Added SMTP authentication support
## Version 1.28 (Mon, Jul 30 2001)
* Fixed a typo in SMTP class
* Fixed header issue with Imail (win32) SMTP server
* Made fopen() calls for attachments use "rb" to fix win32 error
## Version 1.25 (Mon, Jul 02 2001)
* Added RFC 822 date fix (Patrice)
* Added improved error handling by adding a $ErrorInfo variable
* Removed MailerDebug variable (obsolete with new error handler)
## Version 1.20 (Mon, Jun 25 2001)
* Added quoted-printable encoding (Patrice)
* Set Version as public and removed PrintVersion()
* Changed phpdoc to only display public variables and methods
## Version 1.19 (Thu, Jun 21 2001)
* Fixed MS Mail header bug
* Added fix for Bcc problem with mail(). *Does not work on Win32*
(See PHP bug report: http://www.php.net/bugs.php?id=11616)
* mail() no longer passes a fifth parameter when not needed
## Version 1.15 (Fri, Jun 15 2001)
Note: these changes contributed by Patrice Fournier
* Changed all remaining \n to \r\n
* Bcc: header no longer writen to message except
when sent directly to sendmail
* Added a small message to non-MIME compliant mail reader
* Added Sender variable to change the Sender email
used in -f for sendmail/mail and in 'MAIL FROM' for smtp mode
* Changed boundary setting to a place it will be set only once
* Removed transfer encoding for whole message when using multipart
* Message body now uses Encoding in multipart messages
* Can set encoding and type to attachments 7bit, 8bit
and binary attachment are sent as is, base64 are encoded
* Can set Encoding to base64 to send 8 bits body
through 7 bits servers
## Version 1.10 (Tue, Jun 12 2001)
* Fixed win32 mail header bug (printed out headers in message body)
## Version 1.09 (Fri, Jun 08 2001)
* Changed date header to work with Netscape mail programs
* Altered phpdoc documentation
## Version 1.08 (Tue, Jun 05 2001)
* Added enhanced error-checking
* Added phpdoc documentation to source
## Version 1.06 (Fri, Jun 01 2001)
* Added optional name for file attachments
## Version 1.05 (Tue, May 29 2001)
* Code cleanup
* Eliminated sendmail header warning message
* Fixed possible SMTP error
## Version 1.03 (Thu, May 24 2001)
* Fixed problem where qmail sends out duplicate messages
## Version 1.02 (Wed, May 23 2001)
* Added multiple recipient and attachment Clear* methods
* Added Sendmail public variable
* Fixed problem with loading SMTP library multiple times
## Version 0.98 (Tue, May 22 2001)
* Fixed problem with redundant mail hosts sending out multiple messages
* Added additional error handler code
* Added AddCustomHeader() function
* Added support for Microsoft mail client headers (affects priority)
* Fixed small bug with Mailer variable
* Added PrintVersion() function
## Version 0.92 (Tue, May 15 2001)
* Changed file names to class.phpmailer.php and class.smtp.php to match
current PHP class trend.
* Fixed problem where body not being printed when a message is attached
* Several small bug fixes
## Version 0.90 (Tue, April 17 2001)
* Initial public release
| ouyangyu/fdmoodle | lib/phpmailer/changelog.md | Markdown | gpl-3.0 | 22,998 |
// Copyright (c) 2016 GeometryFactory Sarl (France)
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0+
//
//
// Author : Andreas Fabri
#ifndef CGAL_LICENSE_CHECK_H
#define CGAL_LICENSE_CHECK_H
//#define CGAL_LICENSE_WARNING 1 // in order to get a warning during compilation
//#define CGAL_LICENSE_ERROR 1 // in order to get an error during compilation
// if no such define exists, the package is used under the GPL or LGPL
// Otherwise the number encodes the date year/month/day
// Any release made b......
// e.g.
//#define CGAL_AABB_TREE_COMMERCIAL_LICENSE 20140101
#endif // CGAL_LICENSE_CHECK_H
| FEniCS/mshr | 3rdparty/CGAL/include/CGAL/license.h | C | gpl-3.0 | 1,205 |
#ifndef FONTDIALOG_H
#define FONTDIALOG_H
#include "DialogBox.h"
class FontSelector;
// Font selection widget
class FXAPI FontSelector : public FXPacker
{
FXDECLARE(FontSelector)
protected:
FXTextField *family;
FXList *familylist;
FXTextField *weight;
FXList *weightlist;
FXTextField *style;
FXList *stylelist;
FXTextField *size;
FXList *sizelist;
FXComboBox *charset;
FXComboBox *setwidth;
FXComboBox *pitch;
FXCheckButton *scalable;
FXCheckButton *allfonts;
FXButton *accept;
FXButton *cancel;
FXLabel *preview;
FXFont *previewfont;
FXFontDesc selected;
protected:
FontSelector()
{}
void listFontFaces();
void listWeights();
void listSlants();
void listFontSizes();
void previewFont();
private:
FontSelector(const FontSelector&);
FontSelector &operator=(const FontSelector&);
public:
long onCmdFamily(FXObject*,FXSelector,void*);
long onCmdWeight(FXObject*,FXSelector,void*);
long onCmdStyle(FXObject*,FXSelector,void*);
long onCmdStyleText(FXObject*,FXSelector,void*);
long onCmdSize(FXObject*,FXSelector,void*);
long onCmdSizeText(FXObject*,FXSelector,void*);
long onCmdCharset(FXObject*,FXSelector,void*);
long onUpdCharset(FXObject*,FXSelector,void*);
long onCmdSetWidth(FXObject*,FXSelector,void*);
long onUpdSetWidth(FXObject*,FXSelector,void*);
long onCmdPitch(FXObject*,FXSelector,void*);
long onUpdPitch(FXObject*,FXSelector,void*);
long onCmdScalable(FXObject*,FXSelector,void*);
long onUpdScalable(FXObject*,FXSelector,void*);
long onCmdAllFonts(FXObject*,FXSelector,void*);
long onUpdAllFonts(FXObject*,FXSelector,void*);
public:
enum{
ID_FAMILY=FXPacker::ID_LAST,
ID_WEIGHT,
ID_STYLE,
ID_STYLE_TEXT,
ID_SIZE,
ID_SIZE_TEXT,
ID_CHARSET,
ID_SETWIDTH,
ID_PITCH,
ID_SCALABLE,
ID_ALLFONTS,
ID_LAST
};
public:
// Constructor
FontSelector(FXComposite *p,FXObject* tgt=NULL,FXSelector sel=0,unsigned int opts=0,int x=0,int y=0,int w=0,int h=0);
// Create server-side resources
virtual void create();
// Return a pointer to the "Accept" button
FXButton *acceptButton() const
{
return accept;
}
// Return a pointer to the "Cancel" button
FXButton *cancelButton() const
{
return cancel;
}
// Set font selection
void setFontSelection(const FXFontDesc& fontdesc);
// Get font selection
void getFontSelection(FXFontDesc& fontdesc) const;
// Save to a stream
virtual void save(FXStream& store) const;
// Load from a stream
virtual void load(FXStream& store);
// Destructor
virtual ~FontSelector();
};
// Font selection dialog
class FXAPI FontDialog : public DialogBox
{
FXDECLARE(FontDialog)
protected:
FontSelector *fontbox;
protected:
FontDialog()
{}
private:
FontDialog(const FontDialog&);
FontDialog &operator=(const FontDialog&);
public:
// Constructor
FontDialog(FXWindow* owner,const FXString& name,unsigned int opts=0,int x=0,int y=0,int w=750,int h=480);
// Save dialog to a stream
virtual void save(FXStream& store) const;
// Load dialog from a stream
virtual void load(FXStream& store);
// Set the current font selection
void setFontSelection(const FXFontDesc& fontdesc);
// Get the current font selection
void getFontSelection(FXFontDesc& fontdesc) const;
// Destructor
virtual ~FontDialog();
};
#endif
| chriskmanx/qmole | QMOLEDEV/xfe-1.34/src/FontDialog.h | C | gpl-3.0 | 3,664 |
---
title: Reporting Bugs & Getting Help
weight: 10
---
BRAT is under constant development and we are eager to resolve all known issues. However, please search [existing posts](https://github.com/Riverscapes/pyBRAT/issues) first and our help pages before [posting an issue](#Posting an Issue).
# Questions or Help
You can explore or search [other user questions here](https://github.com/Riverscapes/pyBRAT/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22help+wanted%22+).
<a class="button" href="https://github.com/Riverscapes/pyBRAT/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22help+wanted%22+"><i class="fa fa-github"/> BRAT Help Wanted</a>
# Bugs
Before logging a suspected bug, please search [known open bugs](https://github.com/Riverscapes/pyBRAT/labels/bug). If you have more information to report about this bug, please post a comment to the appropriate issue. Otherwise, you can post a new bug, using the 'Bug' label.
<a class="button" href="https://github.com/Riverscapes/pyBRAT/labels/bug"><i class="fa fa-github"/> BRAT Bugs</a>
# Posting an Issue
If you find a bug, or simply want to report an issue with the software, please log a GitHub Issue. <a class="button" href="https://github.com/Riverscapes/pyBRAT/issues"><i class="fa fa-github"/> Github Issues</a>
Anyone in the BRAT community and a member of GitHub can respond, and the development team will recieve a notification. Please be patient for a response. We do not have any budget for supporting users, but we do try and respond to issues when we can.
This video shows you how to post an issue (for [GCD](http://gcd.riverscapes.xyz), but process is similar) and some helpful things to include:
<iframe width="560" height="315" src="https://www.youtube.com/embed/EFAQgvZQY0s?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
### Please always include following information:
> ## The Problem
>
> What went wrong?
>
> ## Reproduction steps
>
> 1. I did this
> 2. Then I did that...
> Include screenshots if you have them (you can drag and drop these in)
> ## Error messages (if applicable)
>
> ```text
>
> Paste the exception message you are getting from the app here. It really helps us.
>
> ```
> ## Datasets
>
> You can provide links to datasets.>
> ## BRAT & ARC Version Info
> - Version of BRAT you were using (e.g. `BRAT 3.0.19`)
> - Version of ArcGIS (e.g. `ArcGIS 10.5.1`)
The issue posting in GitHub uses [markdown syntax](https://guides.github.com/features/mastering-markdown/).
### Optional Information:
- If you do not want to provide a link to the complete copy of the BRAT project, just sharing a copy of the `*project.rs.xml` project file and changing the file extension to text and uploading it to your post can help a lot
- Record a video of what is going wrong (we recommend [FastStone Capture](http://etal.joewheaton.org/faststone-capture.html), post it to YouTube or Vimeo, and share the link (DO NOT SEND VIDEOS as attachments! just stream it). Videos can be really helpful for understanding what you are doing and what is going wrong.
------
<div align="center">
<a class="hollow button" href="{{ site.baseurl }}/Documentation"><i class="fa fa-info-circle"></i> Back to Help </a>
<a class="hollow button" href="{{ site.baseurl }}/"><img src="{{ site.baseurl }}/assets/images/favicons/favicon-16x16.png"> Back to BRAT Home </a>
</div>
| Riverscapes/pyBRAT | docs/BRAT Help/known-bugs.md | Markdown | gpl-3.0 | 3,405 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.