code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/**
* \file InsetMathFontOld.cpp
* This file is part of LyX, the document processor.
* Licence details can be found in the file COPYING.
*
* \author André Pönitz
*
* Full author contact details are available in file CREDITS.
*/
#include <config.h>
#include "InsetMathFontOld.h"
#include "MathData.h"
#include "MathParser.h"
#include "MathStream.h"
#include "MathSupport.h"
#include "MetricsInfo.h"
#include "support/gettext.h"
#include "support/lstrings.h"
#include <ostream>
using namespace lyx::support;
namespace lyx {
InsetMathFontOld::InsetMathFontOld(Buffer * buf, latexkeys const * key)
: InsetMathNest(buf, 1), key_(key), current_mode_(TEXT_MODE)
{
//lock(true);
}
Inset * InsetMathFontOld::clone() const
{
return new InsetMathFontOld(*this);
}
void InsetMathFontOld::metrics(MetricsInfo & mi, Dimension & dim) const
{
current_mode_ = isTextFont(from_ascii(mi.base.fontname))
? TEXT_MODE : MATH_MODE;
docstring const font = current_mode_ == MATH_MODE
? "math" + key_->name : "text" + key_->name;
// When \cal is used in text mode, the font is not changed
bool really_change_font = font != "textcal";
FontSetChanger dummy(mi.base, font, really_change_font);
cell(0).metrics(mi, dim);
metricsMarkers(dim);
}
void InsetMathFontOld::draw(PainterInfo & pi, int x, int y) const
{
current_mode_ = isTextFont(from_ascii(pi.base.fontname))
? TEXT_MODE : MATH_MODE;
docstring const font = current_mode_ == MATH_MODE
? "math" + key_->name : "text" + key_->name;
// When \cal is used in text mode, the font is not changed
bool really_change_font = font != "textcal";
FontSetChanger dummy(pi.base, font, really_change_font);
cell(0).draw(pi, x + 1, y);
drawMarkers(pi, x, y);
}
void InsetMathFontOld::metricsT(TextMetricsInfo const & mi, Dimension & dim) const
{
cell(0).metricsT(mi, dim);
}
void InsetMathFontOld::drawT(TextPainter & pain, int x, int y) const
{
cell(0).drawT(pain, x, y);
}
void InsetMathFontOld::write(WriteStream & os) const
{
os << "{\\" << key_->name << ' ' << cell(0) << '}';
}
void InsetMathFontOld::normalize(NormalStream & os) const
{
os << "[font " << key_->name << ' ' << cell(0) << ']';
}
void InsetMathFontOld::infoize(odocstream & os) const
{
os << bformat(_("Font: %1$s"), key_->name);
}
} // namespace lyx
| xavierm02/lyx-mathpartir | src/mathed/InsetMathFontOld.cpp | C++ | gpl-2.0 | 2,314 |
<?php return array('dependencies' => array(), 'version' => 'a8dca9f7d5fd098db5af94613d2a8ec0'); | tstephen/srp-digital | wp-content/plugins/jetpack/_inc/build/shortcodes/js/recipes.min.asset.php | PHP | gpl-2.0 | 95 |
using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using CmsData;
using CmsWeb.Models;
using UtilityExtensions;
using Query = CmsData.Query;
namespace CmsWeb.Areas.Search.Models
{
public class SavedQueryModel : PagedTableModel<Query, SavedQueryInfo>
{
public bool admin { get; set; }
public bool OnlyMine { get; set; }
public bool PublicOnly { get; set; }
public string SearchQuery { get; set; }
public bool ScratchPadsOnly { get; set; }
public bool StatusFlagsOnly { get; set; }
public SavedQueryModel() : base("Last Run", "desc", true)
{
admin = Roles.IsUserInRole("Admin");
}
public override IQueryable<Query> DefineModelList()
{
var q = from c in DbUtil.Db.Queries
where !PublicOnly || c.Ispublic
where c.Name.Contains(SearchQuery) || c.Owner == SearchQuery || !SearchQuery.HasValue()
select c;
if (ScratchPadsOnly)
q = from c in q
where c.Name == Util.ScratchPad2
select c;
else
q = from c in q
where c.Name != Util.ScratchPad2
select c;
if (StatusFlagsOnly)
q = from c in q
where StatusFlagsOnly == false || SqlMethods.Like(c.Name, "F[0-9][0-9]%")
select c;
DbUtil.Db.SetUserPreference("SavedQueryOnlyMine", OnlyMine);
if (OnlyMine)
q = from c in q
where c.Owner == Util.UserName
select c;
else if (!admin)
q = from c in q
where c.Owner == Util.UserName || c.Ispublic
select c;
return q;
}
public override IQueryable<Query> DefineModelSort(IQueryable<Query> q)
{
switch (SortExpression)
{
case "Public":
return from c in q
orderby c.Ispublic, c.Owner, c.Name
select c;
case "Description":
return from c in q
orderby c.Name
select c;
case "Last Run":
return from c in q
orderby c.LastRun ?? c.Created
select c;
case "Owner":
return from c in q
orderby c.Owner, c.Name
select c;
case "Count":
return from c in q
orderby c.RunCount, c.Name
select c;
case "Public desc":
return from c in q
orderby c.Ispublic descending, c.Owner, c.Name
select c;
case "Description desc":
return from c in q
orderby c.Name descending
select c;
case "Last Run desc":
return from c in q
let dt = c.LastRun ?? c.Created
orderby dt descending
select c;
case "Owner desc":
return from c in q
orderby c.Owner descending, c.Name
select c;
case "Count desc":
return from c in q
orderby c.RunCount descending, c.Name
select c;
}
return q;
}
public override IEnumerable<SavedQueryInfo> DefineViewList(IQueryable<Query> q)
{
var user = Util.UserName;
return from c in q
select new SavedQueryInfo
{
QueryId = c.QueryId,
Name = c.Name,
Ispublic = c.Ispublic,
LastRun = c.LastRun ?? c.Created,
Owner = c.Owner,
CanDelete = admin || c.Owner == user,
RunCount = c.RunCount,
};
}
}
} | RGray1959/MyParish | CmsWeb/Areas/Search/Models/SavedQuery/SavedQueryModel.cs | C# | gpl-2.0 | 4,459 |
import sys
if __name__ == "__main__":
if len(sys.argv) < 2:
print "need input file"
sys.exit(1)
fin = open(sys.argv[1], "r")
lines = fin.readlines()
fin.close()
fout = open("bootloader.h", "w")
fout.write("/* File automatically generated by hex2header.py */\n\n")
fout.write("const unsigned int bootloader_data[] = {");
mem = {}
eAddr = 0
addr = 0
for line in lines:
line = line.strip()
if line[0] != ":":
continue
lType = int(line[7:9], 16)
lAddr = int(line[3:7], 16)
dLen = int(line[1:3], 16)
if lType == 2:
eAddr = int(line[9:13], 16) << 8;
continue
if lType == 4:
eAddr = int(line[9:13], 16) << 16;
continue
if lType == 1:
break
if lType == 0:
idx = 0
data = line[9:-2]
dataLen = len(data)
#print "data = ", data
for idx in range(dataLen / 4):
word = int(data[idx*4:(idx*4)+2], 16)
word |= int(data[(idx*4)+2:(idx*4)+4], 16) << 8;
addr = (lAddr + eAddr + idx*2) >> 1
#print hex(addr), "=", hex(word)
mem[addr] = word
output = []
for addr in range(0x800, 0xfff):
if mem.has_key(addr):
output.append(mem[addr])
else:
output.append(0xffff)
output.reverse()
idx = 0
for word in output:
if word != 0xffff:
break
output = output[1:]
output.reverse()
left = len(output) % 8
if left != 0:
output += [0xffff] * (8-left)
while (idx < len(output)):
fout.write("\n ")
for i in range(8):
fout.write("0x%04x, " % output[idx])
idx += 1
fout.write("\n};\n");
fout.close()
| diydrones/alceosd | firmware/bootloader_updater.X/hex2header.py | Python | gpl-2.0 | 1,513 |
/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
****************************************************************************/
#include "qfontengine_p.h"
#include "qtextengine_p.h"
#include <qglobal.h>
#include "qt_windows.h"
#include <private/qapplication_p.h>
#include <qlibrary.h>
#include <qpaintdevice.h>
#include <qpainter.h>
#include <qlibrary.h>
#include <limits.h>
#include <qendian.h>
#include <qmath.h>
#include <qthreadstorage.h>
#include <private/qunicodetables_p.h>
#include <qbitmap.h>
#include <private/qpainter_p.h>
#include <private/qpdf_p.h>
#include "qpaintengine.h"
#include "qvarlengtharray.h"
#include <private/qpaintengine_raster_p.h>
#if defined(Q_OS_WINCE)
#include "qguifunctions_wince.h"
#endif
//### mingw needed define
#ifndef TT_PRIM_CSPLINE
#define TT_PRIM_CSPLINE 3
#endif
#ifdef MAKE_TAG
#undef MAKE_TAG
#endif
// GetFontData expects the tags in little endian ;(
#define MAKE_TAG(ch1, ch2, ch3, ch4) (\
(((quint32)(ch4)) << 24) | \
(((quint32)(ch3)) << 16) | \
(((quint32)(ch2)) << 8) | \
((quint32)(ch1)) \
)
typedef BOOL (WINAPI *PtrGetCharWidthI)(HDC, UINT, UINT, LPWORD, LPINT);
// common DC for all fonts
QT_BEGIN_NAMESPACE
class QtHDC
{
HDC _hdc;
public:
QtHDC()
{
HDC displayDC = GetDC(0);
_hdc = CreateCompatibleDC(displayDC);
ReleaseDC(0, displayDC);
}
~QtHDC()
{
if (_hdc)
DeleteDC(_hdc);
}
HDC hdc() const
{
return _hdc;
}
};
#ifndef QT_NO_THREAD
Q_GLOBAL_STATIC(QThreadStorage<QtHDC *>, local_shared_dc)
HDC shared_dc()
{
QtHDC *&hdc = local_shared_dc()->localData();
if (!hdc)
hdc = new QtHDC;
return hdc->hdc();
}
#else
HDC shared_dc()
{
return 0;
}
#endif
static HFONT stock_sysfont = 0;
static PtrGetCharWidthI ptrGetCharWidthI = 0;
static bool resolvedGetCharWidthI = false;
static void resolveGetCharWidthI()
{
if (resolvedGetCharWidthI)
return;
resolvedGetCharWidthI = true;
ptrGetCharWidthI = (PtrGetCharWidthI)QLibrary::resolve(QLatin1String("gdi32"), "GetCharWidthI");
}
// Copy a LOGFONTW struct into a LOGFONTA by converting the face name to an 8 bit value.
// This is needed when calling CreateFontIndirect on non-unicode windowses.
inline static void wa_copy_logfont(LOGFONTW *lfw, LOGFONTA *lfa)
{
lfa->lfHeight = lfw->lfHeight;
lfa->lfWidth = lfw->lfWidth;
lfa->lfEscapement = lfw->lfEscapement;
lfa->lfOrientation = lfw->lfOrientation;
lfa->lfWeight = lfw->lfWeight;
lfa->lfItalic = lfw->lfItalic;
lfa->lfUnderline = lfw->lfUnderline;
lfa->lfCharSet = lfw->lfCharSet;
lfa->lfOutPrecision = lfw->lfOutPrecision;
lfa->lfClipPrecision = lfw->lfClipPrecision;
lfa->lfQuality = lfw->lfQuality;
lfa->lfPitchAndFamily = lfw->lfPitchAndFamily;
QString fam = QString::fromUtf16((const ushort*)lfw->lfFaceName);
memcpy(lfa->lfFaceName, fam.toLocal8Bit().constData(), fam.length() + 1);
}
// defined in qtextengine_win.cpp
typedef void *SCRIPT_CACHE;
typedef HRESULT (WINAPI *fScriptFreeCache)(SCRIPT_CACHE *);
extern fScriptFreeCache ScriptFreeCache;
static inline quint32 getUInt(unsigned char *p)
{
quint32 val;
val = *p++ << 24;
val |= *p++ << 16;
val |= *p++ << 8;
val |= *p;
return val;
}
static inline quint16 getUShort(unsigned char *p)
{
quint16 val;
val = *p++ << 8;
val |= *p;
return val;
}
static inline HFONT systemFont()
{
if (stock_sysfont == 0)
stock_sysfont = (HFONT)GetStockObject(SYSTEM_FONT);
return stock_sysfont;
}
// general font engine
QFixed QFontEngineWin::lineThickness() const
{
if(lineWidth > 0)
return lineWidth;
return QFontEngine::lineThickness();
}
#if defined(Q_OS_WINCE)
static OUTLINETEXTMETRICW *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsW(hdc, 0, 0);
OUTLINETEXTMETRICW *otm = (OUTLINETEXTMETRICW *)malloc(size);
GetOutlineTextMetricsW(hdc, size, otm);
return otm;
}
#else
static OUTLINETEXTMETRICA *getOutlineTextMetric(HDC hdc)
{
int size;
size = GetOutlineTextMetricsA(hdc, 0, 0);
OUTLINETEXTMETRICA *otm = (OUTLINETEXTMETRICA *)malloc(size);
GetOutlineTextMetricsA(hdc, size, otm);
return otm;
}
#endif
void QFontEngineWin::getCMap()
{
QT_WA({
ttf = (bool)(tm.w.tmPitchAndFamily & TMPF_TRUETYPE);
} , {
ttf = (bool)(tm.a.tmPitchAndFamily & TMPF_TRUETYPE);
});
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
bool symb = false;
if (ttf) {
cmapTable = getSfntTable(qbswap<quint32>(MAKE_TAG('c', 'm', 'a', 'p')));
int size = 0;
cmap = QFontEngine::getCMap(reinterpret_cast<const uchar *>(cmapTable.constData()),
cmapTable.size(), &symb, &size);
}
if (!cmap) {
ttf = false;
symb = false;
}
symbol = symb;
designToDevice = 1;
_faceId.index = 0;
if(cmap) {
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
designToDevice = QFixed((int)otm->otmEMSquare)/int(otm->otmTextMetrics.tmHeight);
unitsPerEm = otm->otmEMSquare;
x_height = (int)otm->otmsXHeight;
loadKerningPairs(designToDevice);
_faceId.filename = (char *)otm + (int)otm->otmpFullName;
lineWidth = otm->otmsUnderscoreSize;
fsType = otm->otmfsType;
free(otm);
} else {
unitsPerEm = tm.w.tmHeight;
}
}
inline unsigned int getChar(const QChar *str, int &i, const int len)
{
unsigned int uc = str[i].unicode();
if (uc >= 0xd800 && uc < 0xdc00 && i < len-1) {
uint low = str[i+1].unicode();
if (low >= 0xdc00 && low < 0xe000) {
uc = (uc - 0xd800)*0x400 + (low - 0xdc00) + 0x10000;
++i;
}
}
return uc;
}
int QFontEngineWin::getGlyphIndexes(const QChar *str, int numChars, QGlyphLayout *glyphs, bool mirrored) const
{
QGlyphLayout *g = glyphs;
if (mirrored) {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, QChar::mirroredChar(uc));
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint ucs = QChar::mirroredChar(getChar(str, i, numChars));
if (ucs >= first && ucs <= last)
glyphs->glyph = ucs;
else
glyphs->glyph = 0;
glyphs++;
}
}
} else {
if (symbol) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
if(!glyphs->glyph && uc < 0x100)
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc + 0xf000);
glyphs++;
}
} else if (ttf) {
for (int i = 0; i < numChars; ++i) {
unsigned int uc = getChar(str, i, numChars);
glyphs->glyph = getTrueTypeGlyphIndex(cmap, uc);
glyphs++;
}
} else {
ushort first, last;
QT_WA({
first = tm.w.tmFirstChar;
last = tm.w.tmLastChar;
}, {
first = tm.a.tmFirstChar;
last = tm.a.tmLastChar;
});
for (int i = 0; i < numChars; ++i) {
uint uc = getChar(str, i, numChars);
if (uc >= first && uc <= last)
glyphs->glyph = uc;
else
glyphs->glyph = 0;
glyphs++;
}
}
}
return glyphs - g;
}
QFontEngineWin::QFontEngineWin(const QString &name, HFONT _hfont, bool stockFont, LOGFONT lf)
{
//qDebug("regular windows font engine created: font='%s', size=%d", name, lf.lfHeight);
_name = name;
cmap = 0;
hfont = _hfont;
logfont = lf;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
this->stockFont = stockFont;
fontDef.pixelSize = -lf.lfHeight;
lbearing = SHRT_MIN;
rbearing = SHRT_MIN;
synthesized_flags = -1;
lineWidth = -1;
x_height = -1;
BOOL res;
QT_WA({
res = GetTextMetricsW(hdc, &tm.w);
} , {
res = GetTextMetricsA(hdc, &tm.a);
});
fontDef.fixedPitch = !(tm.w.tmPitchAndFamily & TMPF_FIXED_PITCH);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
cache_cost = tm.w.tmHeight * tm.w.tmAveCharWidth * 2000;
getCMap();
useTextOutA = false;
#ifndef Q_OS_WINCE
// TextOutW doesn't work for symbol fonts on Windows 95!
// since we're using glyph indices we don't care for ttfs about this!
if (QSysInfo::WindowsVersion == QSysInfo::WV_95 && !ttf &&
(_name == QLatin1String("Marlett") || _name == QLatin1String("Symbol") ||
_name == QLatin1String("Webdings") || _name == QLatin1String("Wingdings")))
useTextOutA = true;
#endif
widthCache = 0;
widthCacheSize = 0;
designAdvances = 0;
designAdvancesSize = 0;
if (!resolvedGetCharWidthI)
resolveGetCharWidthI();
}
QFontEngineWin::~QFontEngineWin()
{
if (designAdvances)
free(designAdvances);
if (widthCache)
free(widthCache);
// make sure we aren't by accident still selected
SelectObject(shared_dc(), systemFont());
if (!stockFont) {
if (!DeleteObject(hfont))
qErrnoWarning("QFontEngineWin: failed to delete non-stock font...");
}
}
HGDIOBJ QFontEngineWin::selectDesignFont(QFixed *overhang) const
{
LOGFONT f = logfont;
f.lfHeight = unitsPerEm;
HFONT designFont;
QT_WA({
designFont = CreateFontIndirectW(&f);
}, {
LOGFONTA fa;
wa_copy_logfont(&f, &fa);
designFont = CreateFontIndirectA(&fa);
});
HGDIOBJ oldFont = SelectObject(shared_dc(), designFont);
if (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) {
BOOL res;
QT_WA({
TEXTMETRICW tm;
res = GetTextMetricsW(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
} , {
TEXTMETRICA tm;
res = GetTextMetricsA(shared_dc(), &tm);
if (!res)
qErrnoWarning("QFontEngineWin: GetTextMetrics failed");
*overhang = QFixed((int)tm.tmOverhang) / designToDevice;
});
} else {
*overhang = 0;
}
return oldFont;
}
bool QFontEngineWin::stringToCMap(const QChar *str, int len, QGlyphLayout *glyphs, int *nglyphs, QTextEngine::ShaperFlags flags) const
{
if (*nglyphs < len) {
*nglyphs = len;
return false;
}
*nglyphs = getGlyphIndexes(str, len, glyphs, flags & QTextEngine::RightToLeft);
if (flags & QTextEngine::GlyphIndicesOnly)
return true;
#if defined(Q_OS_WINCE)
HDC hdc = shared_dc();
if (flags & QTextEngine::DesignMetrics) {
HGDIOBJ oldFont = 0;
QFixed overhang = 0;
int glyph_pos = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)(str+i), surrogate ? 2 : 1, &size);
designAdvances[glyph] = QFixed((int)size.cx)/designToDevice;
}
glyphs[glyph_pos].advance.x = designAdvances[glyph];
glyphs[glyph_pos].advance.y = 0;
if (surrogate)
++i;
++glyph_pos;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
int glyph_pos = 0;
HGDIOBJ oldFont = 0;
for(register int i = 0; i < len; i++) {
bool surrogate = (str[i].unicode() >= 0xd800 && str[i].unicode() < 0xdc00 && i < len-1
&& str[i+1].unicode() >= 0xdc00 && str[i+1].unicode() < 0xe000);
unsigned int glyph = glyphs[glyph_pos].glyph;
glyphs[glyph_pos].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[glyph_pos].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[glyph_pos].advance.x == 0) {
SIZE size = {0, 0};
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
GetTextExtentPoint32W(hdc, (wchar_t *)str + i, surrogate ? 2 : 1, &size);
size.cx -= overhang;
glyphs[glyph_pos].advance.x = size.cx;
// if glyph's within cache range, store it for later
if (size.cx > 0 && size.cx < 0x100)
widthCache[glyph] = size.cx;
}
if (surrogate)
++i;
++glyph_pos;
}
if (oldFont)
SelectObject(hdc, oldFont);
}
#else
recalcAdvances(*nglyphs, glyphs, flags);
#endif
return true;
}
void QFontEngineWin::recalcAdvances(int len, QGlyphLayout *glyphs, QTextEngine::ShaperFlags flags) const
{
HGDIOBJ oldFont = 0;
HDC hdc = shared_dc();
if (ttf && (flags & QTextEngine::DesignMetrics)) {
QFixed overhang = 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
if(int(glyph) >= designAdvancesSize) {
int newSize = (glyph + 256) >> 8 << 8;
designAdvances = (QFixed *)realloc(designAdvances, newSize*sizeof(QFixed));
for(int i = designAdvancesSize; i < newSize; ++i)
designAdvances[i] = -1000000;
designAdvancesSize = newSize;
}
if(designAdvances[glyph] < -999999) {
if(!oldFont)
oldFont = selectDesignFont(&overhang);
if (ptrGetCharWidthI) {
int width = 0;
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
designAdvances[glyph] = QFixed(width) / designToDevice;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX|GGO_NATIVE, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
designAdvances[glyph] = QFixed(gm.gmCellIncX) / designToDevice;
}
#endif
}
}
glyphs[i].advance.x = designAdvances[glyph];
glyphs[i].advance.y = 0;
}
if(oldFont)
DeleteObject(SelectObject(hdc, oldFont));
} else {
int overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
for(int i = 0; i < len; i++) {
unsigned int glyph = glyphs[i].glyph;
glyphs[i].advance.y = 0;
if (glyph >= widthCacheSize) {
int newSize = (glyph + 256) >> 8 << 8;
widthCache = (unsigned char *)realloc(widthCache, newSize*sizeof(QFixed));
memset(widthCache + widthCacheSize, 0, newSize - widthCacheSize);
widthCacheSize = newSize;
}
glyphs[i].advance.x = widthCache[glyph];
// font-width cache failed
if (glyphs[i].advance.x == 0) {
int width = 0;
if (!oldFont)
oldFont = SelectObject(hdc, hfont);
if (!ttf) {
QChar ch[2] = { ushort(glyph), 0 };
int chrLen = 1;
if (glyph > 0xffff) {
ch[0] = QChar::highSurrogate(glyph);
ch[1] = QChar::lowSurrogate(glyph);
++chrLen;
}
SIZE size = {0, 0};
GetTextExtentPoint32W(hdc, (wchar_t *)ch, chrLen, &size);
width = size.cx;
} else if (ptrGetCharWidthI) {
ptrGetCharWidthI(hdc, glyph, 1, 0, &width);
width -= overhang;
} else {
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
DWORD res = GDI_ERROR;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR) {
width = gm.gmCellIncX;
}
#endif
}
glyphs[i].advance.x = width;
// if glyph's within cache range, store it for later
if (width > 0 && width < 0x100)
widthCache[glyph] = width;
}
}
if (oldFont)
SelectObject(hdc, oldFont);
}
}
glyph_metrics_t QFontEngineWin::boundingBox(const QGlyphLayout *glyphs, int numGlyphs)
{
if (numGlyphs == 0)
return glyph_metrics_t();
QFixed w = 0;
const QGlyphLayout *end = glyphs + numGlyphs;
while(end > glyphs) {
--end;
w += end->effectiveAdvance();
}
return glyph_metrics_t(0, -tm.w.tmAscent, w, tm.w.tmHeight, w, 0);
}
#ifndef Q_OS_WINCE
typedef HRESULT (WINAPI *pGetCharABCWidthsFloat)(HDC, UINT, UINT, LPABCFLOAT);
static pGetCharABCWidthsFloat qt_GetCharABCWidthsFloat = 0;
#endif
glyph_metrics_t QFontEngineWin::boundingBox(glyph_t glyph)
{
#ifndef Q_OS_WINCE
GLYPHMETRICS gm;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if(!ttf) {
SIZE s = {0, 0};
WCHAR ch = glyph;
int width;
int overhang = 0;
static bool resolved = false;
if (!resolved) {
QLibrary lib(QLatin1String("gdi32"));
qt_GetCharABCWidthsFloat = (pGetCharABCWidthsFloat) lib.resolve("GetCharABCWidthsFloatW");
resolved = true;
}
if (QT_WA_INLINE(true, false) && qt_GetCharABCWidthsFloat) {
ABCFLOAT abc;
qt_GetCharABCWidthsFloat(hdc, ch, ch, &abc);
width = qRound(abc.abcfB);
} else {
GetTextExtentPoint32W(hdc, &ch, 1, &s);
overhang = (QSysInfo::WindowsVersion & QSysInfo::WV_DOS_based) ? tm.a.tmOverhang : 0;
width = s.cx;
}
return glyph_metrics_t(0, -tm.a.tmAscent, width, tm.a.tmHeight, width-overhang, 0);
} else {
DWORD res = 0;
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
QT_WA({
res = GetGlyphOutlineW(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
} , {
res = GetGlyphOutlineA(hdc, glyph, GGO_METRICS|GGO_GLYPH_INDEX, &gm, 0, 0, &mat);
});
if (res != GDI_ERROR)
return glyph_metrics_t(gm.gmptGlyphOrigin.x, -gm.gmptGlyphOrigin.y,
(int)gm.gmBlackBoxX, (int)gm.gmBlackBoxY, gm.gmCellIncX, gm.gmCellIncY);
}
return glyph_metrics_t();
#else
SIZE s = {0, 0};
WCHAR ch = glyph;
HDC hdc = shared_dc();
BOOL res = GetTextExtentPoint32W(hdc, &ch, 1, &s);
Q_UNUSED(res);
return glyph_metrics_t(0, -tm.a.tmAscent, s.cx, tm.a.tmHeight, s.cx, 0);
#endif
}
QFixed QFontEngineWin::ascent() const
{
return tm.w.tmAscent;
}
QFixed QFontEngineWin::descent() const
{
return tm.w.tmDescent;
}
QFixed QFontEngineWin::leading() const
{
return tm.w.tmExternalLeading;
}
QFixed QFontEngineWin::xHeight() const
{
if(x_height >= 0)
return x_height;
return QFontEngine::xHeight();
}
QFixed QFontEngineWin::averageCharWidth() const
{
return tm.w.tmAveCharWidth;
}
qreal QFontEngineWin::maxCharWidth() const
{
return tm.w.tmMaxCharWidth;
}
enum { max_font_count = 256 };
static const ushort char_table[] = {
40,
67,
70,
75,
86,
88,
89,
91,
102,
114,
124,
127,
205,
645,
884,
922,
1070,
12386,
0
};
static const int char_table_entries = sizeof(char_table)/sizeof(ushort);
qreal QFontEngineWin::minLeftBearing() const
{
if (lbearing == SHRT_MIN)
minRightBearing(); // calculates both
return lbearing;
}
qreal QFontEngineWin::minRightBearing() const
{
#ifdef Q_OS_WINCE
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABC[char_table_entries+1];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
ml = 0;
mr = -tm.a.tmOverhang;
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#else
if (rbearing == SHRT_MIN) {
int ml = 0;
int mr = 0;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
if (ttf) {
ABC *abc = 0;
int n = QT_WA_INLINE(tm.w.tmLastChar - tm.w.tmFirstChar, tm.a.tmLastChar - tm.a.tmFirstChar);
if (n <= max_font_count) {
abc = new ABC[n+1];
QT_WA({
GetCharABCWidths(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
}, {
GetCharABCWidthsA(hdc,tm.a.tmFirstChar,tm.a.tmLastChar,abc);
});
} else {
abc = new ABC[char_table_entries+1];
QT_WA({
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidths(hdc, char_table[i], char_table[i], abc+i);
}, {
for(int i = 0; i < char_table_entries; i++) {
QByteArray w = QString(QChar(char_table[i])).toLocal8Bit();
if (w.length() == 1) {
uint ch8 = (uchar)w[0];
GetCharABCWidthsA(hdc, ch8, ch8, abc+i);
}
}
});
n = char_table_entries;
}
ml = abc[0].abcA;
mr = abc[0].abcC;
for (int i = 1; i < n; i++) {
if (abc[i].abcA + abc[i].abcB + abc[i].abcC != 0) {
ml = qMin(ml,abc[i].abcA);
mr = qMin(mr,abc[i].abcC);
}
}
delete [] abc;
} else {
QT_WA({
ABCFLOAT *abc = 0;
int n = tm.w.tmLastChar - tm.w.tmFirstChar+1;
if (n <= max_font_count) {
abc = new ABCFLOAT[n];
GetCharABCWidthsFloat(hdc, tm.w.tmFirstChar, tm.w.tmLastChar, abc);
} else {
abc = new ABCFLOAT[char_table_entries];
for(int i = 0; i < char_table_entries; i++)
GetCharABCWidthsFloat(hdc, char_table[i], char_table[i], abc+i);
n = char_table_entries;
}
float fml = abc[0].abcfA;
float fmr = abc[0].abcfC;
for (int i=1; i<n; i++) {
if (abc[i].abcfA + abc[i].abcfB + abc[i].abcfC != 0) {
fml = qMin(fml,abc[i].abcfA);
fmr = qMin(fmr,abc[i].abcfC);
}
}
ml = int(fml-0.9999);
mr = int(fmr-0.9999);
delete [] abc;
} , {
ml = 0;
mr = -tm.a.tmOverhang;
});
}
lbearing = ml;
rbearing = mr;
}
return rbearing;
#endif
}
const char *QFontEngineWin::name() const
{
return 0;
}
bool QFontEngineWin::canRender(const QChar *string, int len)
{
if (symbol) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0) {
if (uc < 0x100) {
if (getTrueTypeGlyphIndex(cmap, uc + 0xf000) == 0)
return false;
} else {
return false;
}
}
}
} else if (ttf) {
for (int i = 0; i < len; ++i) {
unsigned int uc = getChar(string, i, len);
if (getTrueTypeGlyphIndex(cmap, uc) == 0)
return false;
}
} else {
QT_WA({
while(len--) {
if (tm.w.tmFirstChar > string->unicode() || tm.w.tmLastChar < string->unicode())
return false;
}
}, {
while(len--) {
if (tm.a.tmFirstChar > string->unicode() || tm.a.tmLastChar < string->unicode())
return false;
}
});
}
return true;
}
QFontEngine::Type QFontEngineWin::type() const
{
return QFontEngine::Win;
}
static inline double qt_fixed_to_double(const FIXED &p) {
return ((p.value << 16) + p.fract) / 65536.0;
}
static inline QPointF qt_to_qpointf(const POINTFX &pt, qreal scale) {
return QPointF(qt_fixed_to_double(pt.x) * scale, -qt_fixed_to_double(pt.y) * scale);
}
#ifndef GGO_UNHINTED
#define GGO_UNHINTED 0x0100
#endif
static void addGlyphToPath(glyph_t glyph, const QFixedPoint &position, HDC hdc,
QPainterPath *path, bool ttf, glyph_metrics_t *metric = 0, qreal scale = 1)
{
#if defined(Q_OS_WINCE)
Q_UNUSED(glyph);
Q_UNUSED(hdc);
#endif
MAT2 mat;
mat.eM11.value = mat.eM22.value = 1;
mat.eM11.fract = mat.eM22.fract = 0;
mat.eM21.value = mat.eM12.value = 0;
mat.eM21.fract = mat.eM12.fract = 0;
uint glyphFormat = GGO_NATIVE;
if (ttf)
glyphFormat |= GGO_GLYPH_INDEX;
GLYPHMETRICS gMetric;
memset(&gMetric, 0, sizeof(GLYPHMETRICS));
int bufferSize = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
bufferSize = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
}, {
bufferSize = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, 0, 0, &mat);
});
#endif
if ((DWORD)bufferSize == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(1) failed");
return;
}
void *dataBuffer = new char[bufferSize];
DWORD ret = GDI_ERROR;
#if !defined(Q_OS_WINCE)
QT_WA( {
ret = GetGlyphOutlineW(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
}, {
ret = GetGlyphOutlineA(hdc, glyph, glyphFormat, &gMetric, bufferSize,
dataBuffer, &mat);
} );
#endif
if (ret == GDI_ERROR) {
qErrnoWarning("QFontEngineWin::addOutlineToPath: GetGlyphOutline(2) failed");
delete [](char *)dataBuffer;
return;
}
if(metric) {
// #### obey scale
*metric = glyph_metrics_t(gMetric.gmptGlyphOrigin.x, -gMetric.gmptGlyphOrigin.y,
(int)gMetric.gmBlackBoxX, (int)gMetric.gmBlackBoxY,
gMetric.gmCellIncX, gMetric.gmCellIncY);
}
int offset = 0;
int headerOffset = 0;
TTPOLYGONHEADER *ttph = 0;
QPointF oset = position.toPointF();
while (headerOffset < bufferSize) {
ttph = (TTPOLYGONHEADER*)((char *)dataBuffer + headerOffset);
QPointF lastPoint(qt_to_qpointf(ttph->pfxStart, scale));
path->moveTo(lastPoint + oset);
offset += sizeof(TTPOLYGONHEADER);
TTPOLYCURVE *curve;
while (offset<int(headerOffset + ttph->cb)) {
curve = (TTPOLYCURVE*)((char*)(dataBuffer) + offset);
switch (curve->wType) {
case TT_PRIM_LINE: {
for (int i=0; i<curve->cpfx; ++i) {
QPointF p = qt_to_qpointf(curve->apfx[i], scale) + oset;
path->lineTo(p);
}
break;
}
case TT_PRIM_QSPLINE: {
const QPainterPath::Element &elm = path->elementAt(path->elementCount()-1);
QPointF prev(elm.x, elm.y);
QPointF endPoint;
for (int i=0; i<curve->cpfx - 1; ++i) {
QPointF p1 = qt_to_qpointf(curve->apfx[i], scale) + oset;
QPointF p2 = qt_to_qpointf(curve->apfx[i+1], scale) + oset;
if (i < curve->cpfx - 2) {
endPoint = QPointF((p1.x() + p2.x()) / 2, (p1.y() + p2.y()) / 2);
} else {
endPoint = p2;
}
path->quadTo(p1, endPoint);
prev = endPoint;
}
break;
}
case TT_PRIM_CSPLINE: {
for (int i=0; i<curve->cpfx; ) {
QPointF p2 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p3 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
QPointF p4 = qt_to_qpointf(curve->apfx[i++], scale) + oset;
path->cubicTo(p2, p3, p4);
}
break;
}
default:
qWarning("QFontEngineWin::addOutlineToPath, unhandled switch case");
}
offset += sizeof(TTPOLYCURVE) + (curve->cpfx-1) * sizeof(POINTFX);
}
path->closeSubpath();
headerOffset += ttph->cb;
}
delete [] (char*)dataBuffer;
}
void QFontEngineWin::addGlyphsToPath(glyph_t *glyphs, QFixedPoint *positions, int nglyphs,
QPainterPath *path, QTextItem::RenderFlags)
{
LOGFONT lf = logfont;
// The sign must be negative here to make sure we match against character height instead of
// hinted cell height. This ensures that we get linear matching, and we need this for
// paths since we later on apply a scaling transform to the glyph outline to get the
// font at the correct pixel size.
lf.lfHeight = -unitsPerEm;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
for(int i = 0; i < nglyphs; ++i)
addGlyphToPath(glyphs[i], positions[i], hdc, path, ttf, /*metric*/0, qreal(fontDef.pixelSize) / unitsPerEm);
DeleteObject(SelectObject(hdc, oldfont));
}
void QFontEngineWin::addOutlineToPath(qreal x, qreal y, const QGlyphLayout *glyphs, int numGlyphs,
QPainterPath *path, QTextItem::RenderFlags flags)
{
#if !defined(Q_OS_WINCE)
if(tm.w.tmPitchAndFamily & (TMPF_TRUETYPE)) {
QFontEngine::addOutlineToPath(x, y, glyphs, numGlyphs, path, flags);
return;
}
#endif
QFontEngine::addBitmapFontToPath(x, y, glyphs, numGlyphs, path, flags);
}
QFontEngine::FaceId QFontEngineWin::faceId() const
{
return _faceId;
}
QT_BEGIN_INCLUDE_NAMESPACE
#include <qdebug.h>
QT_END_INCLUDE_NAMESPACE
int QFontEngineWin::synthesized() const
{
if(synthesized_flags == -1) {
synthesized_flags = 0;
if(ttf) {
const DWORD HEAD = MAKE_TAG('h', 'e', 'a', 'd');
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
uchar data[4];
GetFontData(hdc, HEAD, 44, &data, 4);
USHORT macStyle = getUShort(data);
if (tm.w.tmItalic && !(macStyle & 2))
synthesized_flags = SynthesizedItalic;
if (fontDef.stretch != 100 && ttf)
synthesized_flags |= SynthesizedStretch;
if (tm.w.tmWeight >= 500 && !(macStyle & 1))
synthesized_flags |= SynthesizedBold;
//qDebug() << "font is" << _name <<
// "it=" << (macStyle & 2) << fontDef.style << "flags=" << synthesized_flags;
}
}
return synthesized_flags;
}
QFixed QFontEngineWin::emSquareSize() const
{
return unitsPerEm;
}
QFontEngine::Properties QFontEngineWin::properties() const
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
#if defined(Q_OS_WINCE)
OUTLINETEXTMETRICW *otm = getOutlineTextMetric(hdc);
#else
OUTLINETEXTMETRICA *otm = getOutlineTextMetric(hdc);
#endif
Properties p;
p.emSquare = unitsPerEm;
p.italicAngle = otm->otmItalicAngle;
p.postscriptName = (char *)otm + (int)otm->otmpFamilyName;
p.postscriptName += (char *)otm + (int)otm->otmpStyleName;
#ifndef QT_NO_PRINTER
p.postscriptName = QPdf::stripSpecialCharacters(p.postscriptName);
#endif
p.boundingBox = QRectF(otm->otmrcFontBox.left, -otm->otmrcFontBox.top,
otm->otmrcFontBox.right - otm->otmrcFontBox.left,
otm->otmrcFontBox.top - otm->otmrcFontBox.bottom);
p.ascent = otm->otmAscent;
p.descent = -otm->otmDescent;
p.leading = (int)otm->otmLineGap;
p.capHeight = 0;
p.lineWidth = otm->otmsUnderscoreSize;
free(otm);
DeleteObject(SelectObject(hdc, oldfont));
return p;
}
void QFontEngineWin::getUnscaledGlyph(glyph_t glyph, QPainterPath *path, glyph_metrics_t *metrics)
{
LOGFONT lf = logfont;
lf.lfHeight = unitsPerEm;
int flags = synthesized();
if(flags & SynthesizedItalic)
lf.lfItalic = false;
lf.lfWidth = 0;
HFONT hf;
QT_WA({
hf = CreateFontIndirectW(&lf);
}, {
LOGFONTA lfa;
wa_copy_logfont(&lf, &lfa);
hf = CreateFontIndirectA(&lfa);
});
HDC hdc = shared_dc();
HGDIOBJ oldfont = SelectObject(hdc, hf);
QFixedPoint p;
p.x = 0;
p.y = 0;
addGlyphToPath(glyph, p, hdc, path, ttf, metrics);
DeleteObject(SelectObject(hdc, oldfont));
}
bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) const
{
if (!ttf)
return false;
HDC hdc = shared_dc();
SelectObject(hdc, hfont);
DWORD t = qbswap<quint32>(tag);
*length = GetFontData(hdc, t, 0, buffer, *length);
return *length != GDI_ERROR;
}
#if !defined(CLEARTYPE_QUALITY)
# define CLEARTYPE_QUALITY 5
#endif
QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph)
{
glyph_metrics_t gm = boundingBox(glyph);
int glyph_x = qFloor(gm.x.toReal());
int glyph_y = qFloor(gm.y.toReal());
int glyph_width = qCeil((gm.x + gm.width).toReal()) - glyph_x;
int glyph_height = qCeil((gm.y + gm.height).toReal()) - glyph_y;
if (glyph_width + glyph_x <= 0 || glyph_height <= 0)
return QImage();
QImage im(glyph_width, glyph_height, QImage::Format_ARGB32_Premultiplied);
im.fill(0);
QPainter p(&im);
HFONT oldHFont = hfont;
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
// try hard to disable cleartype rendering
static_cast<QRasterPaintEngine *>(p.paintEngine())->disableClearType();
LOGFONT nonCleartypeFont = logfont;
nonCleartypeFont.lfQuality = ANTIALIASED_QUALITY;
hfont = CreateFontIndirect(&nonCleartypeFont);
}
p.setPen(Qt::black);
p.setBrush(Qt::NoBrush);
QTextItemInt ti;
ti.ascent = ascent();
ti.descent = descent();
ti.width = glyph_width;
ti.fontEngine = this;
ti.num_glyphs = 1;
QGlyphLayout glyphLayout;
ti.glyphs = &glyphLayout;
glyphLayout.glyph = glyph;
memset(&glyphLayout.attributes, 0, sizeof(glyphLayout.attributes));
glyphLayout.advance.x = glyph_width;
p.drawTextItem(QPointF(-glyph_x, -glyph_y), ti);
if (QSysInfo::WindowsVersion >= QSysInfo::WV_XP) {
DeleteObject(hfont);
hfont = oldHFont;
}
p.end();
QImage indexed(im.width(), im.height(), QImage::Format_Indexed8);
QVector<QRgb> colors(256);
for (int i=0; i<256; ++i)
colors[i] = qRgba(0, 0, 0, i);
indexed.setColorTable(colors);
for (int y=0; y<im.height(); ++y) {
uchar *dst = (uchar *) indexed.scanLine(y);
uint *src = (uint *) im.scanLine(y);
for (int x=0; x<im.width(); ++x)
dst[x] = qAlpha(src[x]);
}
return indexed;
}
// -------------------------------------- Multi font engine
QFontEngineMultiWin::QFontEngineMultiWin(QFontEngineWin *first, const QStringList &fallbacks)
: QFontEngineMulti(fallbacks.size()+1),
fallbacks(fallbacks)
{
engines[0] = first;
first->ref.ref();
fontDef = engines[0]->fontDef;
}
void QFontEngineMultiWin::loadEngine(int at)
{
Q_ASSERT(at < engines.size());
Q_ASSERT(engines.at(at) == 0);
QString fam = fallbacks.at(at-1);
LOGFONT lf = static_cast<QFontEngineWin *>(engines.at(0))->logfont;
HFONT hfont;
QT_WA({
memcpy(lf.lfFaceName, fam.utf16(), sizeof(TCHAR)*qMin(fam.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectW(&lf);
} , {
// LOGFONTA and LOGFONTW are binary compatible
QByteArray lname = fam.toLocal8Bit();
memcpy(lf.lfFaceName,lname.data(),
qMin(lname.length()+1,32)); // 32 = Windows hard-coded
hfont = CreateFontIndirectA((LOGFONTA*)&lf);
});
bool stockFont = false;
if (hfont == 0) {
hfont = (HFONT)GetStockObject(ANSI_VAR_FONT);
stockFont = true;
}
engines[at] = new QFontEngineWin(fam, hfont, stockFont, lf);
engines[at]->ref.ref();
engines[at]->fontDef = fontDef;
}
QT_END_NAMESPACE
| liuyanghejerry/qtextended | qtopiacore/qt/src/gui/text/qfontengine_win.cpp | C++ | gpl-2.0 | 43,049 |
<?php defined( '_JEXEC') or die( 'Restricted Access' );
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: BinaryStream.php 23775 2011-03-01 17:25:24Z ralph $
*/
/**
* Utility class to walk through a data stream byte by byte with conventional names
*
* @package Zend_Amf
* @subpackage Util
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Amf_Util_BinaryStream
{
/**
* @var string Byte stream
*/
protected $_stream;
/**
* @var int Length of stream
*/
protected $_streamLength;
/**
* @var bool BigEndian encoding?
*/
protected $_bigEndian;
/**
* @var int Current position in stream
*/
protected $_needle;
/**
* Constructor
*
* Create a reference to a byte stream that is going to be parsed or created
* by the methods in the class. Detect if the class should use big or
* little Endian encoding.
*
* @param string $stream use '' if creating a new stream or pass a string if reading.
* @return void
*/
public function __construct($stream)
{
if (!is_string($stream)) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Inputdata is not of type String');
}
$this->_stream = $stream;
$this->_needle = 0;
$this->_streamLength = strlen($stream);
$this->_bigEndian = (pack('l', 1) === "\x00\x00\x00\x01");
}
/**
* Returns the current stream
*
* @return string
*/
public function getStream()
{
return $this->_stream;
}
/**
* Read the number of bytes in a row for the length supplied.
*
* @todo Should check that there are enough bytes left in the stream we are about to read.
* @param int $length
* @return string
* @throws Zend_Amf_Exception for buffer underrun
*/
public function readBytes($length)
{
if (($length + $this->_needle) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
$bytes = substr($this->_stream, $this->_needle, $length);
$this->_needle+= $length;
return $bytes;
}
/**
* Write any length of bytes to the stream
*
* Usually a string.
*
* @param string $bytes
* @return Zend_Amf_Util_BinaryStream
*/
public function writeBytes($bytes)
{
$this->_stream.= $bytes;
return $this;
}
/**
* Reads a signed byte
*
* @return int Value is in the range of -128 to 127.
*/
public function readByte()
{
if (($this->_needle + 1) > $this->_streamLength) {
require_once 'Zend/Amf/Exception.php';
throw new Zend_Amf_Exception('Buffer underrun at needle position: ' . $this->_needle . ' while requesting length: ' . $length);
}
return ord($this->_stream{$this->_needle++});
}
/**
* Writes the passed string into a signed byte on the stream.
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeByte($stream)
{
$this->_stream.= pack('c', $stream);
return $this;
}
/**
* Reads a signed 32-bit integer from the data stream.
*
* @return int Value is in the range of -2147483648 to 2147483647
*/
public function readInt()
{
return ($this->readByte() << 8) + $this->readByte();
}
/**
* Write an the integer to the output stream as a 32 bit signed integer
*
* @param int $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeInt($stream)
{
$this->_stream.= pack('n', $stream);
return $this;
}
/**
* Reads a UTF-8 string from the data stream
*
* @return string A UTF-8 string produced by the byte representation of characters
*/
public function readUtf()
{
$length = $this->readInt();
return $this->readBytes($length);
}
/**
* Wite a UTF-8 string to the outputstream
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeUtf($stream)
{
$this->writeInt(strlen($stream));
$this->_stream.= $stream;
return $this;
}
/**
* Read a long UTF string
*
* @return string
*/
public function readLongUtf()
{
$length = $this->readLong();
return $this->readBytes($length);
}
/**
* Write a long UTF string to the buffer
*
* @param string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLongUtf($stream)
{
$this->writeLong(strlen($stream));
$this->_stream.= $stream;
}
/**
* Read a long numeric value
*
* @return double
*/
public function readLong()
{
return ($this->readByte() << 24) + ($this->readByte() << 16) + ($this->readByte() << 8) + $this->readByte();
}
/**
* Write long numeric value to output stream
*
* @param int|string $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeLong($stream)
{
$this->_stream.= pack('N', $stream);
return $this;
}
/**
* Read a 16 bit unsigned short.
*
* @todo This could use the unpack() w/ S,n, or v
* @return double
*/
public function readUnsignedShort()
{
$byte1 = $this->readByte();
$byte2 = $this->readByte();
return (($byte1 << 8) | $byte2);
}
/**
* Reads an IEEE 754 double-precision floating point number from the data stream.
*
* @return double Floating point number
*/
public function readDouble()
{
$bytes = substr($this->_stream, $this->_needle, 8);
$this->_needle+= 8;
if (!$this->_bigEndian) {
$bytes = strrev($bytes);
}
$double = unpack('dflt', $bytes);
return $double['flt'];
}
/**
* Writes an IEEE 754 double-precision floating point number from the data stream.
*
* @param string|double $stream
* @return Zend_Amf_Util_BinaryStream
*/
public function writeDouble($stream)
{
$stream = pack('d', $stream);
if (!$this->_bigEndian) {
$stream = strrev($stream);
}
$this->_stream.= $stream;
return $this;
}
}
| kiennd146/nhazz.com | plugins/system/zend/Zend/Amf/Util/BinaryStream.php | PHP | gpl-2.0 | 7,414 |
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE_AFL.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2014 X.commerce, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
*/
var varienTabs = new Class.create();
varienTabs.prototype = {
initialize : function(containerId, destElementId, activeTabId, shadowTabs){
this.containerId = containerId;
this.destElementId = destElementId;
this.activeTab = null;
this.tabOnClick = this.tabMouseClick.bindAsEventListener(this);
this.tabs = $$('#'+this.containerId+' li a.tab-item-link');
this.hideAllTabsContent();
for (var tab=0; tab<this.tabs.length; tab++) {
Event.observe(this.tabs[tab],'click',this.tabOnClick);
// move tab contents to destination element
if($(this.destElementId)){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].contentMoved = true;
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
/*
// this code is pretty slow in IE, so lets do it in tabs*.phtml
// mark ajax tabs as not loaded
if (Element.hasClassName($(this.tabs[tab].id), 'ajax')) {
Element.addClassName($(this.tabs[tab].id), 'notloaded');
}
*/
// bind shadow tabs
if (this.tabs[tab].id && shadowTabs && shadowTabs[this.tabs[tab].id]) {
this.tabs[tab].shadowTabs = shadowTabs[this.tabs[tab].id];
}
}
this.displayFirst = activeTabId;
Event.observe(window,'load',this.moveTabContentInDest.bind(this));
},
setSkipDisplayFirstTab : function(){
this.displayFirst = null;
},
moveTabContentInDest : function(){
for(var tab=0; tab<this.tabs.length; tab++){
if($(this.destElementId) && !this.tabs[tab].contentMoved){
var tabContentElement = $(this.getTabContentElementId(this.tabs[tab]));
if(tabContentElement && tabContentElement.parentNode.id != this.destElementId){
$(this.destElementId).appendChild(tabContentElement);
tabContentElement.container = this;
tabContentElement.statusBar = this.tabs[tab];
tabContentElement.tabObject = this.tabs[tab];
this.tabs[tab].container = this;
this.tabs[tab].show = function(){
this.container.showTabContent(this);
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('moveTab', {tab:this.tabs[tab]});
}
}
}
}
if (this.displayFirst) {
this.showTabContent($(this.displayFirst));
this.displayFirst = null;
}
},
getTabContentElementId : function(tab){
if(tab){
return tab.id+'_content';
}
return false;
},
tabMouseClick : function(event) {
var tab = Event.findElement(event, 'a');
// go directly to specified url or switch tab
if ((tab.href.indexOf('#') != tab.href.length-1)
&& !(Element.hasClassName(tab, 'ajax'))
) {
location.href = tab.href;
}
else {
this.showTabContent(tab);
}
Event.stop(event);
},
hideAllTabsContent : function(){
for(var tab in this.tabs){
this.hideTabContent(this.tabs[tab]);
}
},
// show tab, ready or not
showTabContentImmediately : function(tab) {
this.hideAllTabsContent();
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
Element.show(tabContentElement);
Element.addClassName(tab, 'active');
// load shadow tabs, if any
if (tab.shadowTabs && tab.shadowTabs.length) {
for (var k in tab.shadowTabs) {
this.loadShadowTab($(tab.shadowTabs[k]));
}
}
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
this.activeTab = tab;
}
if (varienGlobalEvents) {
varienGlobalEvents.fireEvent('showTab', {tab:tab});
}
},
// the lazy show tab method
showTabContent : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement) {
if (this.activeTab != tab) {
if (varienGlobalEvents) {
if (varienGlobalEvents.fireEvent('tabChangeBefore', $(this.getTabContentElementId(this.activeTab))).indexOf('cannotchange') != -1) {
return;
};
}
}
// wait for ajax request, if defined
var isAjax = Element.hasClassName(tab, 'ajax');
var isEmpty = tabContentElement.innerHTML=='' && tab.href.indexOf('#')!=tab.href.length-1;
var isNotLoaded = Element.hasClassName(tab, 'notloaded');
if ( isAjax && (isEmpty || isNotLoaded) )
{
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
this.showTabContentImmediately(tab)
}
}.bind(this)
});
}
else {
this.showTabContentImmediately(tab);
}
}
},
loadShadowTab : function(tab) {
var tabContentElement = $(this.getTabContentElementId(tab));
if (tabContentElement && Element.hasClassName(tab, 'ajax') && Element.hasClassName(tab, 'notloaded')) {
new Ajax.Request(tab.href, {
parameters: {form_key: FORM_KEY},
evalScripts: true,
onSuccess: function(transport) {
try {
if (transport.responseText.isJSON()) {
var response = transport.responseText.evalJSON()
if (response.error) {
alert(response.message);
}
if(response.ajaxExpired && response.ajaxRedirect) {
setLocation(response.ajaxRedirect);
}
} else {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}
catch (e) {
$(tabContentElement.id).update(transport.responseText);
if (!Element.hasClassName(tab, 'ajax only')) {
Element.removeClassName(tab, 'notloaded');
}
}
}.bind(this)
});
}
},
hideTabContent : function(tab){
var tabContentElement = $(this.getTabContentElementId(tab));
if($(this.destElementId) && tabContentElement){
Element.hide(tabContentElement);
Element.removeClassName(tab, 'active');
}
if(varienGlobalEvents){
varienGlobalEvents.fireEvent('hideTab', {tab:tab});
}
}
}
| T0MM0R/magento | web/js/mage/adminhtml/tabs.js | JavaScript | gpl-2.0 | 10,013 |
#!/usr/bin/python2.4
# Copyright 2008 Google Inc.
# Author : Anoop Chandran <anoopj@google.com>
#
# openduckbill is a simple backup application. It offers support for
# transferring data to a local backup directory, NFS. It also provides
# file system monitoring of directories marked for backup. Please read
# the README file for more details.
#
# 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.
"""Helper class, does command execution and returns value.
This class has the method RunCommandPopen which executes commands passed to
it and returns the status.
"""
import os
import subprocess
import sys
class CommandHelper:
"""Run command and return status, either using Popen or call
"""
def __init__(self, log_handle=''):
"""Initialise logging state
Logging enabled in debug mode.
Args:
log_handle: Object - a handle to the logging subsystem.
"""
self.logmsg = log_handle
if self.logmsg.debug:
self.stdout_debug = None
self.stderr_debug = None
else:
self.stdout_debug = 1
self.stderr_debug = 1
def RunCommandPopen(self, runcmd):
"""Uses subprocess.Popen to run the command.
Also prints the command output if being run in debug mode.
Args:
runcmd: List - path to executable and its arguments.
Retuns:
runretval: Integer - exit value of the command, after execution.
"""
stdout_val=self.stdout_debug
stderr_val=self.stderr_debug
if stdout_val:
stdout_l = file(os.devnull, 'w')
else:
stdout_l=subprocess.PIPE
if stderr_val:
stderr_l = file(os.devnull, 'w')
else:
stderr_l=subprocess.STDOUT
try:
run_proc = subprocess.Popen(runcmd, bufsize=0,
executable=None, stdin=None,
stdout=stdout_l, stderr=stderr_l)
if self.logmsg.debug:
output = run_proc.stdout
while 1:
line = output.readline()
if not line:
break
line = line.rstrip()
self.logmsg.logger.debug("Command output: %s" % line)
run_proc.wait()
runretval = run_proc.returncode
except OSError, e:
self.logmsg.logger.error('%s', e)
runretval = 1
except KeyboardInterrupt, e:
self.logmsg.logger.error('User interrupt')
sys.exit(1)
if stdout_l:
pass
#stderr_l.close()
if stderr_l:
pass
#stderr_l.close()
return runretval
| xtao/openduckbill | src/helper.py | Python | gpl-2.0 | 3,110 |
<?php
/**
* -----------------------------------------------------------------------------
*
* Functions for TwitterZoid PHP Script
* Copyright (c) 2008 Philip Newborough <mail@philipnewborough.co.uk>
*
* http://crunchbang.org/archives/2008/02/20/twitterzoid-php-script/
*
* LICENSE: 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.
*
* http://www.gnu.org/licenses/
*
* -----------------------------------------------------------------------------
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted Access' );
function timesince($i,$date){
if($i >= time()){
$timeago = JText::_('JM_0_SECONDS_AGO');
return $timeago;
}
$seconds = time()-$i;
$units = array('JM_SECOND' => 1,'JM_MINUTE' => 60,'JM_HOUR' => 3600,'JM_DAY' => 86400,'JM_MONTH' => 2629743,'JM_YEAR' => 31556926);
foreach($units as $key => $val){
if($seconds >= $val){
$results = floor($seconds/$val);
if($key == 'JM_DAY' | $key == 'JM_MONTH' | $key == 'JM_YEAR'){
$timeago = $date;
}else{
$timeago = ($results >= 2) ? JText::_('JM_ABOUT').' ' . $results . ' ' . JText::_($key) . JText::_('JM_S_AGO') : JText::_('JM_ABOUT').' '. $results . ' ' . JText::_($key) .' '. JText::_('JM_AGO');
}
}
}
return $timeago;
}
function twitterit(&$text, $twitter_username, $target='_blank', $nofollow=true){
$urls = _autolink_find_URLS( $text );
if(!empty($urls)){
array_walk( $urls, '_autolink_create_html_tags', array('target'=>$target, 'nofollow'=>$nofollow) );
$text = strtr( $text, $urls );
}
$text = preg_replace("/(\s@|^@)([a-zA-Z0-9]{1,15})/","$1<a href=\"http://twitter.com/$2\" target=\"_blank\" rel=\"nofollow\">$2</a>",$text);
$text = preg_replace("/(\s#|^#)([a-zA-Z0-9]{1,15})/","$1<a href=\"http://twitter.com/#!/search?q=$2\" target=\"_blank\" rel=\"nofollow\">$2</a>",$text);
$text = str_replace($twitter_username.": ", "",$text);
return $text;
}
function _autolink_find_URLS($text){
$scheme = '(http:\/\/|https:\/\/)';
$www = 'www\.';
$ip = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
$subdomain = '[-a-z0-9_]+\.';
$name = '[a-z][-a-z0-9]+\.';
$tld = '[a-z]+(\.[a-z]{2,2})?';
$the_rest = '\/?[a-z0-9._\/~#&=;%+?-]+[a-z0-9\/#=?]{1,1}';
$pattern = "$scheme?(?(1)($ip|($subdomain)?$name$tld)|($www$name$tld))$the_rest";
$pattern = '/'.$pattern.'/is';
$c = preg_match_all($pattern, $text, $m);
unset($text, $scheme, $www, $ip, $subdomain, $name, $tld, $the_rest, $pattern);
if($c){
return(array_flip($m[0]));
}
return(array());
}
function _autolink_create_html_tags(&$value, $key, $other=null){
$target = $nofollow = null;
if(is_array($other)){
$target = ($other['target'] ? " target=\"$other[target]\"":null);
$nofollow = ($other['nofollow'] ? ' rel="nofollow"':null);
}
$value = "<a href=\"$key\"$target$nofollow>$key</a>";
}
?>
| cifren/opussalon | administrator/components/com_joomailermailchimpintegration/libraries/TwitterZoid.php | PHP | gpl-2.0 | 3,467 |
<?php
echo '<h2 class="paddingtop">' . $words->get('members') . '</h2>';
$User = new APP_User;
$words = new MOD_words();
$layoutbits = new MOD_layoutbits;
$url = '/places/' . htmlspecialchars($this->countryName) . '/' . $this->countryCode . '/';
if ($this->regionCode) {
$url .= htmlspecialchars($this->regionName) . '/' . $this->regionCode . '/';
}
if ($this->cityCode) {
$url .= htmlspecialchars($this->cityName) . '/' . $this->cityCode . '/';
}
$loginUrlOpen = '<a href="login' . $url . '#login-widget">';
$loginUrlClose = '</a>';
if (!$this->members) {
if ($this->totalMemberCount) {
echo $words->get('PlacesMoreMembers', $words->getSilent('PlacesMoreLogin'), $loginUrlOpen, $loginUrlClose) . $words->flushBuffer();
} else {
echo $words->get('PlacesNoMembersFound', htmlspecialchars($this->placeName));
}
} else {
if ($this->totalMemberCount != $this->memberCount) {
echo $words->get('PlacesMoreMembers', $words->getSilent('PlacesMoreLogin'), $loginUrlOpen, $loginUrlClose) . $words->flushBuffer();
}
// divide members into pages of Places::MEMBERS_PER_PAGE (20)
$params = new StdClass;
$params->strategy = new HalfPagePager('right');
$params->page_url = $url;
$params->page_url_marker = 'page';
$params->page_method = 'url';
$params->items = $this->memberCount;
$params->active_page = $this->pageNumber;
$params->items_per_page = Places::MEMBERS_PER_PAGE;
$pager = new PagerWidget($params);
// show members if there are any to show
echo '<ul class="clearfix">';
foreach ($this->members as $member) {
$image = new MOD_images_Image('',$member->username);
if ($member->HideBirthDate=="No") {
$member->age = floor($layoutbits->fage_value($member->BirthDate));
} else {
$member->age = $words->get("Hidden");
}
echo '<li class="userpicbox float_left">';
echo MOD_layoutbits::PIC_50_50($member->username,'',$style='framed float_left');
echo '<div class="userinfo">';
echo ' <a class="username" href="members/'.$member->username.'">'.
$member->username.'</a><br />';
echo ' <span class="small">'.$words->get("yearsold",$member->age).
'<br />'.$member->city.'</span>';
echo '</div>';
echo '</li>';
}
echo '</ul>';
$pager->render();
}
?>
| thisismeonmounteverest/rox | build/places/templates/memberlist.php | PHP | gpl-2.0 | 2,396 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\View;
use Magento\Framework\View\Design\ThemeInterface;
/**
* View file in the file system with context of its identity
*/
class File
{
/**
* File name
*
* @var string
*/
protected $filename;
/**
* Module
*
* @var string
*/
protected $module;
/**
* Theme
*
* @var ThemeInterface
*/
protected $theme;
/**
* Base flag
*
* @var string
*/
protected $isBase;
/**
* Identifier
*
* @var string
*/
protected $identifier;
/**
* Constructor
*
* @param string $filename
* @param string $module
* @param ThemeInterface $theme
* @param bool $isBase
*/
public function __construct($filename, $module, ThemeInterface $theme = null, $isBase = false)
{
$this->filename = $filename;
$this->module = $module;
$this->theme = $theme;
$this->isBase = $isBase;
}
/**
* Retrieve full filename
*
* @return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* Retrieve name of a file without a directory path
*
* @return string
*/
public function getName()
{
return basename($this->filename);
}
/**
* Retrieve fully-qualified name of a module a file belongs to
*
* @return string
*/
public function getModule()
{
return $this->module;
}
/**
* Retrieve instance of a theme a file belongs to
*
* @return ThemeInterface|null
*/
public function getTheme()
{
return $this->theme;
}
/**
* Whether file is a base one
*
* @return bool
*/
public function isBase()
{
return $this->theme === null;
}
/**
* Calculate unique identifier for a view file
*
* @return string
*/
public function getFileIdentifier()
{
if (null === $this->identifier) {
$theme = $this->getTheme() ? ('|theme:' . $this->theme->getFullPath()) : '';
$this->identifier = ($this->isBase ? 'base' : '')
. $theme . '|module:' . $this->getModule() . '|file:' . $this->getName();
}
return $this->identifier;
}
}
| FPLD/project0 | vendor/magento/framework/View/File.php | PHP | gpl-2.0 | 2,453 |
(function ($) {
/**
* Attaches double-click behavior to toggle full path of Krumo elements.
*/
Drupal.behaviors.devel = {
attach: function (context, settings) {
// Add hint to footnote
$('.krumo-footnote .krumo-call').once().before('<img style="vertical-align: middle;" title="Click to expand. Double-click to show path." src="' + settings.basePath + 'misc/help.png"/>');
var krumo_name = [];
var krumo_type = [];
function krumo_traverse(el) {
krumo_name.push($(el).html());
krumo_type.push($(el).siblings('em').html().match(/\w*/)[0]);
if ($(el).closest('.krumo-nest').length > 0) {
krumo_traverse($(el).closest('.krumo-nest').prev().find('.krumo-name'));
}
}
$('.krumo-child > div:first-child', context).dblclick(
function(e) {
if ($(this).find('> .krumo-php-path').length > 0) {
// Remove path if shown.
$(this).find('> .krumo-php-path').remove();
}
else {
// Get elements.
krumo_traverse($(this).find('> a.krumo-name'));
// Create path.
var krumo_path_string = '';
for (var i = krumo_name.length - 1; i >= 0; --i) {
// Start element.
if ((krumo_name.length - 1) == i)
krumo_path_string += '$' + krumo_name[i];
if (typeof krumo_name[(i-1)] !== 'undefined') {
if (krumo_type[i] == 'Array') {
krumo_path_string += "[";
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += krumo_name[(i-1)];
if (!/^\d*$/.test(krumo_name[(i-1)]))
krumo_path_string += "'";
krumo_path_string += "]";
}
if (krumo_type[i] == 'Object')
krumo_path_string += '->' + krumo_name[(i-1)];
}
}
$(this).append('<div class="krumo-php-path" style="font-family: Courier, monospace; font-weight: bold;">' + krumo_path_string + '</div>');
// Reset arrays.
krumo_name = [];
krumo_type = [];
}
}
);
}
};
})(jQuery);
;
(function ($) {
/**
* Attach the machine-readable name form element behavior.
*/
Drupal.behaviors.machineName = {
/**
* Attaches the behavior.
*
* @param settings.machineName
* A list of elements to process, keyed by the HTML ID of the form element
* containing the human-readable value. Each element is an object defining
* the following properties:
* - target: The HTML ID of the machine name form element.
* - suffix: The HTML ID of a container to show the machine name preview in
* (usually a field suffix after the human-readable name form element).
* - label: The label to show for the machine name preview.
* - replace_pattern: A regular expression (without modifiers) matching
* disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
* - replace: A character to replace disallowed characters with; e.g., '_'
* or '-'.
* - standalone: Whether the preview should stay in its own element rather
* than the suffix of the source element.
* - field_prefix: The #field_prefix of the form element.
* - field_suffix: The #field_suffix of the form element.
*/
attach: function (context, settings) {
var self = this;
$.each(settings.machineName, function (source_id, options) {
var $source = $(source_id, context).addClass('machine-name-source');
var $target = $(options.target, context).addClass('machine-name-target');
var $suffix = $(options.suffix, context);
var $wrapper = $target.closest('.form-item');
// All elements have to exist.
if (!$source.length || !$target.length || !$suffix.length || !$wrapper.length) {
return;
}
// Skip processing upon a form validation error on the machine name.
if ($target.hasClass('error')) {
return;
}
// Figure out the maximum length for the machine name.
options.maxlength = $target.attr('maxlength');
// Hide the form item container of the machine name form element.
$wrapper.hide();
// Determine the initial machine name value. Unless the machine name form
// element is disabled or not empty, the initial default value is based on
// the human-readable form element value.
if ($target.is(':disabled') || $target.val() != '') {
var machine = $target.val();
}
else {
var machine = self.transliterate($source.val(), options);
}
// Append the machine name preview to the source field.
var $preview = $('<span class="machine-name-value">' + options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix + '</span>');
$suffix.empty();
if (options.label) {
$suffix.append(' ').append('<span class="machine-name-label">' + options.label + ':</span>');
}
$suffix.append(' ').append($preview);
// If the machine name cannot be edited, stop further processing.
if ($target.is(':disabled')) {
return;
}
// If it is editable, append an edit link.
var $link = $('<span class="admin-link"><a href="#">' + Drupal.t('Edit') + '</a></span>')
.click(function () {
$wrapper.show();
$target.focus();
$suffix.hide();
$source.unbind('.machineName');
return false;
});
$suffix.append(' ').append($link);
// Preview the machine name in realtime when the human-readable name
// changes, but only if there is no machine name yet; i.e., only upon
// initial creation, not when editing.
if ($target.val() == '') {
$source.bind('keyup.machineName change.machineName input.machineName', function () {
machine = self.transliterate($(this).val(), options);
// Set the machine name to the transliterated value.
if (machine != '') {
if (machine != options.replace) {
$target.val(machine);
$preview.html(options.field_prefix + Drupal.checkPlain(machine) + options.field_suffix);
}
$suffix.show();
}
else {
$suffix.hide();
$target.val(machine);
$preview.empty();
}
});
// Initialize machine name preview.
$source.keyup();
}
});
},
/**
* Transliterate a human-readable name to a machine name.
*
* @param source
* A string to transliterate.
* @param settings
* The machine name settings for the corresponding field, containing:
* - replace_pattern: A regular expression (without modifiers) matching
* disallowed characters in the machine name; e.g., '[^a-z0-9]+'.
* - replace: A character to replace disallowed characters with; e.g., '_'
* or '-'.
* - maxlength: The maximum length of the machine name.
*
* @return
* The transliterated source string.
*/
transliterate: function (source, settings) {
var rx = new RegExp(settings.replace_pattern, 'g');
return source.toLowerCase().replace(rx, settings.replace).substr(0, settings.maxlength);
}
};
})(jQuery);
;
(function ($) {
Drupal.behaviors.textarea = {
attach: function (context, settings) {
$('.form-textarea-wrapper.resizable', context).once('textarea', function () {
var staticOffset = null;
var textarea = $(this).addClass('resizable-textarea').find('textarea');
var grippie = $('<div class="grippie"></div>').mousedown(startDrag);
grippie.insertAfter(textarea);
function startDrag(e) {
staticOffset = textarea.height() - e.pageY;
textarea.css('opacity', 0.25);
$(document).mousemove(performDrag).mouseup(endDrag);
return false;
}
function performDrag(e) {
textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
return false;
}
function endDrag(e) {
$(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
textarea.css('opacity', 1);
}
});
}
};
})(jQuery);
;
(function ($) {
Drupal.toolbar = Drupal.toolbar || {};
/**
* Attach toggling behavior and notify the overlay of the toolbar.
*/
Drupal.behaviors.toolbar = {
attach: function(context) {
// Set the initial state of the toolbar.
$('#toolbar', context).once('toolbar', Drupal.toolbar.init);
// Toggling toolbar drawer.
$('#toolbar a.toggle', context).once('toolbar-toggle').click(function(e) {
Drupal.toolbar.toggle();
// Allow resize event handlers to recalculate sizes/positions.
$(window).triggerHandler('resize');
return false;
});
}
};
/**
* Retrieve last saved cookie settings and set up the initial toolbar state.
*/
Drupal.toolbar.init = function() {
// Retrieve the collapsed status from a stored cookie.
var collapsed = $.cookie('Drupal.toolbar.collapsed');
// Expand or collapse the toolbar based on the cookie value.
if (collapsed == 1) {
Drupal.toolbar.collapse();
}
else {
Drupal.toolbar.expand();
}
};
/**
* Collapse the toolbar.
*/
Drupal.toolbar.collapse = function() {
var toggle_text = Drupal.t('Show shortcuts');
$('#toolbar div.toolbar-drawer').addClass('collapsed');
$('#toolbar a.toggle')
.removeClass('toggle-active')
.attr('title', toggle_text)
.html(toggle_text);
$('body').removeClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height());
$.cookie(
'Drupal.toolbar.collapsed',
1,
{
path: Drupal.settings.basePath,
// The cookie should "never" expire.
expires: 36500
}
);
};
/**
* Expand the toolbar.
*/
Drupal.toolbar.expand = function() {
var toggle_text = Drupal.t('Hide shortcuts');
$('#toolbar div.toolbar-drawer').removeClass('collapsed');
$('#toolbar a.toggle')
.addClass('toggle-active')
.attr('title', toggle_text)
.html(toggle_text);
$('body').addClass('toolbar-drawer').css('paddingTop', Drupal.toolbar.height());
$.cookie(
'Drupal.toolbar.collapsed',
0,
{
path: Drupal.settings.basePath,
// The cookie should "never" expire.
expires: 36500
}
);
};
/**
* Toggle the toolbar.
*/
Drupal.toolbar.toggle = function() {
if ($('#toolbar div.toolbar-drawer').hasClass('collapsed')) {
Drupal.toolbar.expand();
}
else {
Drupal.toolbar.collapse();
}
};
Drupal.toolbar.height = function() {
var $toolbar = $('#toolbar');
var height = $toolbar.outerHeight();
// In modern browsers (including IE9), when box-shadow is defined, use the
// normal height.
var cssBoxShadowValue = $toolbar.css('box-shadow');
var boxShadow = (typeof cssBoxShadowValue !== 'undefined' && cssBoxShadowValue !== 'none');
// In IE8 and below, we use the shadow filter to apply box-shadow styles to
// the toolbar. It adds some extra height that we need to remove.
if (!boxShadow && /DXImageTransform\.Microsoft\.Shadow/.test($toolbar.css('filter'))) {
height -= $toolbar[0].filters.item("DXImageTransform.Microsoft.Shadow").strength;
}
return height;
};
})(jQuery);
;
/**
* @file
* A JavaScript file for the theme.
* This file should be used as a template for your other js files.
* It defines a drupal behavior the "Drupal way".
*
*/
// JavaScript should be made compatible with libraries other than jQuery by
// wrapping it with an "anonymous closure". See:
// - https://drupal.org/node/1446420
// - http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
(function ($, Drupal, window, document, undefined) {
'use strict';
// To understand behaviors, see https://drupal.org/node/756722#behaviors
Drupal.behaviors.hideSubmitBlockit = {
attach: function(context) {
var timeoutId = null;
$('form', context).once('hideSubmitButton', function () {
var $form = $(this);
// Bind to input elements.
if (Drupal.settings.hide_submit.hide_submit_method === 'indicator') {
// Replace input elements with buttons.
$('input.form-submit', $form).each(function(index, el) {
var attrs = {};
$.each($(this)[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
$(this).replaceWith(function() {
return $("<button/>", attrs).append($(this).attr('value'));
});
});
// Add needed attributes to the submit buttons.
$('button.form-submit', $form).each(function(index, el) {
$(this).addClass('ladda-button button').attr({
'data-style': Drupal.settings.hide_submit.hide_submit_indicator_style,
'data-spinner-color': Drupal.settings.hide_submit.hide_submit_spinner_color,
'data-spinner-lines': Drupal.settings.hide_submit.hide_submit_spinner_lines
});
});
Ladda.bind('.ladda-button', $form, {
timeout: Drupal.settings.hide_submit.hide_submit_reset_time
});
}
else {
$('input.form-submit, button.form-submit', $form).click(function (e) {
var el = $(this);
el.after('<input type="hidden" name="' + el.attr('name') + '" value="' + el.attr('value') + '" />');
return true;
});
}
// Bind to form submit.
$('form', context).submit(function (e) {
var $inp;
if (!e.isPropagationStopped()) {
if (Drupal.settings.hide_submit.hide_submit_method === 'disable') {
$('input.form-submit, button.form-submit', $form).attr('disabled', 'disabled').each(function (i) {
var $button = $(this);
if (Drupal.settings.hide_submit.hide_submit_css) {
$button.addClass(Drupal.settings.hide_submit.hide_submit_css);
}
if (Drupal.settings.hide_submit.hide_submit_abtext) {
$button.val($button.val() + ' ' + Drupal.settings.hide_submit.hide_submit_abtext);
}
$inp = $button;
});
if ($inp && Drupal.settings.hide_submit.hide_submit_atext) {
$inp.after('<span class="hide-submit-text">' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_atext) + '</span>');
}
}
else if (Drupal.settings.hide_submit.hide_submit_method !== 'indicator'){
var pdiv = '<div class="hide-submit-text' + (Drupal.settings.hide_submit.hide_submit_hide_css ? ' ' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css) + '"' : '') + '>' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_text) + '</div>';
if (Drupal.settings.hide_submit.hide_submit_hide_fx) {
$('input.form-submit, button.form-submit', $form).addClass(Drupal.settings.hide_submit.hide_submit_css).fadeOut(100).eq(0).after(pdiv);
$('input.form-submit, button.form-submit', $form).next().fadeIn(100);
}
else {
$('input.form-submit, button.form-submit', $form).addClass(Drupal.settings.hide_submit.hide_submit_css).hide().eq(0).after(pdiv);
}
}
// Add a timeout to reset the buttons (if needed).
if (Drupal.settings.hide_submit.hide_submit_reset_time) {
timeoutId = window.setTimeout(function() {
hideSubmitResetButtons(null, $form);
}, Drupal.settings.hide_submit.hide_submit_reset_time);
}
}
return true;
});
});
// Bind to clientsideValidationFormHasErrors to support clientside validation.
// $(document).bind('clientsideValidationFormHasErrors', function(event, form) {
//hideSubmitResetButtons(event, form.form);
// });
// Reset all buttons.
function hideSubmitResetButtons(event, form) {
// Clear timer.
window.clearTimeout(timeoutId);
timeoutId = null;
switch (Drupal.settings.hide_submit.hide_submit_method) {
case 'disable':
$('input.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css) + ', button.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css), form)
.each(function (i, el) {
$(el).removeClass(Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css))
.removeAttr('disabled');
});
$('.hide-submit-text', form).remove();
break;
case 'indicator':
Ladda.stopAll();
break;
default:
$('input.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css) + ', button.' + Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_css), form)
.each(function (i, el) {
$(el).stop()
.removeClass(Drupal.checkPlain(Drupal.settings.hide_submit.hide_submit_hide_css))
.show();
});
$('.hide-submit-text', form).remove();
}
}
}
};
})(jQuery, Drupal, window, this.document);
;
| brharp/hjckrrh | profiles/ug/modules/ug/ug_demo/data/images/public/js/js_GWG8O3mHf8xRnabCEJIqQCLluQ1UIMRNp4CIToqq9Ow.js | JavaScript | gpl-2.0 | 17,330 |
<?php
class sigesp_snorh_c_diaferiado
{
var $io_sql;
var $io_mensajes;
var $io_funciones;
var $io_seguridad;
var $io_sno;
var $ls_codemp;
//-----------------------------------------------------------------------------------------------------------------------------------
function sigesp_snorh_c_diaferiado()
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: sigesp_snorh_c_diaferiado
// Access: public (sigesp_snorh_d_diaferiado)
// Description: Constructor de la Clase
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
require_once("../shared/class_folder/sigesp_include.php");
$io_include=new sigesp_include();
$io_conexion=$io_include->uf_conectar();
require_once("../shared/class_folder/class_sql.php");
$this->io_sql=new class_sql($io_conexion);
require_once("../shared/class_folder/class_mensajes.php");
$this->io_mensajes=new class_mensajes();
require_once("../shared/class_folder/class_funciones.php");
$this->io_funciones=new class_funciones();
require_once("../shared/class_folder/sigesp_c_seguridad.php");
$this->io_seguridad=new sigesp_c_seguridad();
require_once("sigesp_sno.php");
$this->io_sno=new sigesp_sno();
$this->ls_codemp=$_SESSION["la_empresa"]["codemp"];
}// end function sigesp_snorh_c_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_destructor()
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_destructor
// Access: public (sigesp_snorh_d_diaferiado)
// Description: Destructor de la Clase
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unset($io_include);
unset($io_conexion);
unset($this->io_sql);
unset($this->io_mensajes);
unset($this->io_funciones);
unset($this->io_seguridad);
unset($this->ls_codemp);
}// end function uf_destructor
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_select_diaferiado($as_campo,$as_valor)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_select_diaferiado
// Access: private
// Arguments: as_campo // Campo por el que se quiere filtrar
// as_valor // Valor del campo
// Returns: lb_existe True si existe ó False si no existe
// Description: Funcion que verifica si el día feriado está registrado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_existe=true;
$ls_sql="SELECT ".$as_campo." ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND ".$as_campo."='".$as_valor."'";
$rs_data=$this->io_sql->select($ls_sql);
if($rs_data===false)
{
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_select_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$lb_existe=false;
}
else
{
if(!$row=$this->io_sql->fetch_row($rs_data))
{
$lb_existe=false;
}
$this->io_sql->free_result($rs_data);
}
return $lb_existe;
}// end function uf_select_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_insert_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_insert_diaferiado
// Access: private
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el insert ó False si hubo error en el insert
// Description: Funcion que inserta en la tabla sno_diaferiado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="INSERT INTO sno_diaferiado".
"(codemp,fecfer,nomfer)VALUES('".$this->ls_codemp."','".$ad_fecfer."','".$as_nomfer."')";
$this->io_sql->begin_transaction() ;
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_insert_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="INSERT";
$ls_descripcion ="Insertó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Dia Feriado fue registrado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_insert_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}
return $lb_valido;
}// end function uf_insert_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_update_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_update_diaferiado
// Access: private
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el update ó False si hubo error en el update
// Description: Funcion que actualiza en la tabla sno_diaferiado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ls_sql="UPDATE sno_diaferiado ".
" SET nomfer='".$as_nomfer."' ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer='".$ad_fecfer."'";
$this->io_sql->begin_transaction();
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_update_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="UPDATE";
$ls_descripcion ="Actualizó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Día feriado fue Actualizado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_update_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}
return $lb_valido;
}// end function uf_update_diaferiado
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_guardar($as_existe,$ad_fecfer,$as_nomfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_guardar
// Access: public (sigesp_snorh_d_diaferiado)
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si guardo ó False si hubo error al guardar
// Description: Funcion que almacena el día feriado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$ad_fecfer=$this->io_funciones->uf_convertirdatetobd($ad_fecfer);
$lb_valido=false;
switch ($as_existe)
{
case "FALSE":
if($this->uf_select_diaferiado("fecfer",$ad_fecfer)===false)
{
$lb_valido=$this->uf_insert_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad);
}
else
{
$this->io_mensajes->message("El Dia Feriado ya existe, no lo puede incluir.");
}
break;
case "TRUE":
if(($this->uf_select_diaferiado("fecfer",$ad_fecfer)))
{
$lb_valido=$this->uf_update_diaferiado($ad_fecfer,$as_nomfer,$aa_seguridad);
}
else
{
$this->io_mensajes->message("El Dia Feriado no existe, no lo puede actualizar.");
}
break;
}
return $lb_valido;
}// end function uf_guardar
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_delete_diaferiado($ad_fecfer,$aa_seguridad)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_delete_diaferiado
// Access: public (sigesp_snorh_d_diaferiado)
// Arguments: ad_fecfer // Fecha del Feriado
// as_nomfer // Descripción del Feriado
// aa_seguridad // arreglo de las variables de seguridad
// Returns: lb_valido True si se ejecuto el delete ó False si hubo error en el delete
// Description: Funcion que elimina el día feriado
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 01/01/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$lb_valido=true;
$ad_fecfer=$this->io_funciones->uf_convertirdatetobd($ad_fecfer);
$ls_sql="DELETE ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer='".$ad_fecfer."'";
$this->io_sql->begin_transaction();
$li_row=$this->io_sql->execute($ls_sql);
if($li_row===false)
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_delete_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
else
{
///////////////////////////////// SEGURIDAD /////////////////////////////
$ls_evento="DELETE";
$ls_descripcion ="Eliminó el Día Feriado ".$ad_fecfer;
$lb_valido= $this->io_seguridad->uf_sss_insert_eventos_ventana($aa_seguridad["empresa"],
$aa_seguridad["sistema"],$ls_evento,$aa_seguridad["logusr"],
$aa_seguridad["ventanas"],$ls_descripcion);
///////////////////////////////// SEGURIDAD /////////////////////////////
if($lb_valido)
{
$this->io_mensajes->message("El Día feriado fue Eliminado.");
$this->io_sql->commit();
}
else
{
$lb_valido=false;
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_delete_diaferiado ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
$this->io_sql->rollback();
}
}// end function uf_delete_diaferiado
return $lb_valido;
}
//-----------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------
function uf_select_feriados($ad_fecdes,$ad_fechas)
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: uf_select_feriados
// Access: private
// Arguments: ad_fecdes // Fecha desde
// ad_fechas // Fecha Hasta
// Returns: li_total Toal de días feriados
// Description: Funcion que cuenta la cantidad de días feriados dada una fecha
// Creado Por: Ing. Yesenia Moreno
// Fecha Creación: 07/09/2006 Fecha Última Modificación :
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
$li_total=0;
$ls_sql="SELECT fecfer ".
" FROM sno_diaferiado ".
" WHERE codemp='".$this->ls_codemp."'".
" AND fecfer>='".$ad_fecdes."' ".
" AND fecfer<='".$ad_fechas."' ";
$rs_data=$this->io_sql->select($ls_sql);
if($rs_data===false)
{
$this->io_mensajes->message("CLASE->Dia Feriado MÉTODO->uf_select_feriados ERROR->".$this->io_funciones->uf_convertirmsg($this->io_sql->message));
}
else
{
while($row=$this->io_sql->fetch_row($rs_data))
{
$ld_fecfer=$row["fecfer"];
$ld_fecfer=$this->io_funciones->uf_convertirfecmostrar($ld_fecfer);
if($this->io_sno->uf_nro_sabydom($ld_fecfer,$ld_fecfer)==0)
{
$li_total=$li_total+1;
}
}
$this->io_sql->free_result($rs_data);
}
return $li_total;
}// end function uf_select_feriados
//-----------------------------------------------------------------------------------------------------------------------------------
}
?> | omerta/huayra | sno/sigesp_snorh_c_diaferiado.php | PHP | gpl-2.0 | 16,072 |
#!/usr/bin/env rspec
require_relative "test_helper"
require "yaml"
# Important: Loads data in constructor
Yast.import "Product"
Yast.import "Mode"
Yast.import "Stage"
Yast.import "OSRelease"
Yast.import "PackageSystem"
Yast.import "Pkg"
Yast.import "PackageLock"
Yast.import "Mode"
Yast.import "Stage"
include Yast::Logger
# Path to a test data - service file - mocking the default data path
DATA_PATH = File.join(File.expand_path(File.dirname(__FILE__)), "data")
def load_zypp(file_name)
file_name = File.join(DATA_PATH, "zypp", file_name)
raise "File not found: #{file_name}" unless File.exist?(file_name)
log.info "Loading file: #{file_name}"
YAML.load_file(file_name)
end
PRODUCTS_FROM_ZYPP = load_zypp("products.yml").freeze
def stub_defaults
log.info "--------- Running test ---------"
Yast::Product.send(:reset)
allow(Yast::PackageSystem).to receive(:EnsureTargetInit).and_return(true)
allow(Yast::PackageSystem).to receive(:EnsureSourceInit).and_return(true)
allow(Yast::Pkg).to receive(:PkgSolve).and_return(true)
allow(Yast::PackageLock).to receive(:Check).and_return(true)
allow(Yast::Pkg).to receive(:ResolvableProperties).with("", :product, "").and_return(PRODUCTS_FROM_ZYPP.dup)
end
# Describes Product handling as a whole (due to lazy loading and internal caching),
# methods descriptions are below
describe "Yast::Product (integration)" do
before(:each) do
stub_defaults
end
context "while called in installation system without os-release file" do
before(:each) do
allow(Yast::Stage).to receive(:stage).and_return("initial")
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
end
describe "when the mode is Installation" do
it "reads product information from zypp and fills up internal variables" do
allow(Yast::Mode).to receive(:mode).and_return("installation")
expect(Yast::Product.name).to eq("openSUSE (SELECTED)")
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
end
end
describe "when the mode is Update" do
it "reads product information from zypp and fills up internal variables" do
allow(Yast::Mode).to receive(:mode).and_return("update")
expect(Yast::Product.name).to eq("openSUSE (SELECTED)")
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
end
end
end
context "while called on a running system with os-release file" do
before(:each) do
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(true)
end
# This is the default behavior
context "OSRelease is complete" do
it "reads product information from OSRelease and fills up internal variables" do
release_info = "Happy Feet 2.0"
allow(Yast::OSRelease).to receive(:ReleaseName).and_return("anything")
allow(Yast::OSRelease).to receive(:ReleaseVersion).and_return("anything")
allow(Yast::OSRelease).to receive(:ReleaseInformation).and_return(release_info)
expect(Yast::Product.name).to eq(release_info)
end
end
# This is the fallback behavior
context "OSRelease is incomplete" do
it "reads product information from OSRelease and then zypp and fills up internal variables" do
release_name = "Happy Feet"
release_version = "1.0.1"
allow(Yast::OSRelease).to receive(:ReleaseName).and_return(release_name)
allow(Yast::OSRelease).to receive(:ReleaseVersion).and_return(release_version)
allow(Yast::OSRelease).to receive(:ReleaseInformation).and_return("")
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
expect(Yast::Product.name).to eq("openSUSE (INSTALLED)")
end
end
end
context "while called on a running system without os-release file" do
before(:each) do
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
end
it "reads product information from zypp and fills up internal variables" do
expect(Yast::Product.short_name).to eq("openSUSE")
expect(Yast::Product.version).to eq("13.1")
expect(Yast::Product.name).to eq("openSUSE (INSTALLED)")
end
end
end
# Describes Product methods
describe Yast::Product do
before(:each) do
stub_defaults
end
context "while called in installation without os-release file" do
before(:each) do
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
allow(Yast::Stage).to receive(:stage).and_return("initial")
allow(Yast::Mode).to receive(:mode).and_return("installation")
end
describe "#name" do
it "reads data from zypp and returns product name" do
expect(Yast::Product.name).to eq("openSUSE (SELECTED)")
end
end
describe "#short_name" do
it "reads data from zypp and returns short product name" do
expect(Yast::Product.short_name).to eq("openSUSE")
end
end
describe "#version" do
it "reads data from zypp and returns product version" do
expect(Yast::Product.version).to eq("13.1")
end
end
describe "#run_you" do
it "reads data from zypp and returns whether running online update is requested" do
expect(Yast::Product.run_you).to eq(false)
end
end
describe "#relnotesurl" do
it "reads data from zypp and returns URL to release notes" do
expect(Yast::Product.relnotesurl).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"
)
end
end
describe "#relnotesurl_all" do
it "reads data from zypp and returns list of all URLs to release notes" do
expect(Yast::Product.relnotesurl_all).to eq(
["http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"]
)
end
end
describe "#product_of_relnotes" do
it "reads data from zypp and returns hash of release notes URLs linking to their product names" do
expect(Yast::Product.product_of_relnotes).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm" => "openSUSE (SELECTED)"
)
end
end
describe "#FindBaseProducts" do
it "reads data from zypp and returns list of base products selected for installation" do
list_of_products = Yast::Product.FindBaseProducts
expect(list_of_products).to be_a_kind_of(Array)
expect(list_of_products[0]).to be_a_kind_of(Hash)
expect(list_of_products[0]["display_name"]).to eq("openSUSE (SELECTED)")
expect(list_of_products[0]["status"]).to eq(:selected)
end
end
it "reports that method has been dropped" do
[:vendor, :dist, :distproduct, :distversion, :shortlabel].each do |method_name|
expect { Yast::Product.send(method_name) }.to raise_error(/#{method_name}.*dropped/)
end
end
end
context "while called on running system with os-release file" do
release_name = "Mraky a Internety"
release_version = "44.6"
release_info = "#{release_name} #{release_version} (Banana Juice)"
before(:each) do
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(true)
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
allow(Yast::OSRelease).to receive(:ReleaseName).and_return(release_name)
allow(Yast::OSRelease).to receive(:ReleaseVersion).and_return(release_version)
allow(Yast::OSRelease).to receive(:ReleaseInformation).and_return(release_info)
end
describe "#name" do
it "reads data from os-release and returns product name" do
expect(Yast::Product.name).to eq(release_info)
end
end
describe "#short_name" do
it "reads data from os-release and returns short product name" do
expect(Yast::Product.short_name).to eq(release_name)
end
end
describe "#version" do
it "reads data from os-release and returns product version" do
expect(Yast::Product.version).to eq(release_version)
end
end
describe "#run_you" do
it "reads data from zypp and returns whether running online update is requested" do
expect(Yast::Product.run_you).to eq(false)
end
end
describe "#relnotesurl" do
it "reads data from zypp and returns URL to release notes" do
expect(Yast::Product.relnotesurl).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"
)
end
end
describe "#relnotesurl_all" do
it "reads data from zypp and returns list of all URLs to release notes" do
expect(Yast::Product.relnotesurl_all).to eq(
["http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm"]
)
end
end
describe "#product_of_relnotes" do
it "reads data from zypp and returns hash of release notes URLs linking to their product names" do
expect(Yast::Product.product_of_relnotes).to eq(
"http://doc.opensuse.org/release-notes/x86_64/openSUSE/13.1/release-notes-openSUSE.rpm" => "openSUSE (INSTALLED)"
)
end
end
it "reports that method has been dropped" do
[:vendor, :dist, :distproduct, :distversion, :shortlabel].each do |method_name|
expect { Yast::Product.send(method_name) }.to raise_error(/#{method_name}.*dropped/)
end
end
end
# Methods that do not allow empty result
SUPPORTED_METHODS = [:name, :short_name, :version, :run_you, :flags, :relnotesurl]
# Empty result is allowed
SUPPORTED_METHODS_ALLOWED_EMPTY = [:relnotesurl_all, :product_of_relnotes]
context "while called on a broken system (no os-release, no zypp information)" do
before(:each) do
allow(Yast::OSRelease).to receive(:os_release_exists?).and_return(false)
allow(Yast::Pkg).to receive(:ResolvableProperties).with("", :product, "").and_return([])
end
context "in installation" do
it "reports that no base product was found" do
allow(Yast::Stage).to receive(:stage).and_return("initial")
allow(Yast::Mode).to receive(:mode).and_return("installation")
SUPPORTED_METHODS.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect { Yast::Product.send(method_name) }.to raise_error(/no base product found/i)
end
SUPPORTED_METHODS_ALLOWED_EMPTY.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect(Yast::Product.send(method_name)).to be_empty
end
end
end
context "on a running system" do
it "reports that no base product was found" do
allow(Yast::Stage).to receive(:stage).and_return("normal")
allow(Yast::Mode).to receive(:mode).and_return("normal")
SUPPORTED_METHODS.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect { Yast::Product.send(method_name) }.to raise_error(/no base product found/i)
end
SUPPORTED_METHODS_ALLOWED_EMPTY.each do |method_name|
log.info "Yast::Product.#{method_name}"
expect(Yast::Product.send(method_name)).to be_empty
end
end
end
end
end
| gabi2/yast-yast2 | library/packages/test/product_test.rb | Ruby | gpl-2.0 | 11,801 |
var contextMenuObserving;
var contextMenuUrl;
function contextMenuRightClick(event) {
var target = $(event.target);
if (target.is('a')) {return;}
var tr = target.parents('tr').first();
if (!tr.hasClass('hascontextmenu')) {return;}
event.preventDefault();
if (!contextMenuIsSelected(tr)) {
contextMenuUnselectAll();
contextMenuAddSelection(tr);
contextMenuSetLastSelected(tr);
}
contextMenuShow(event);
}
function contextMenuClick(event) {
var target = $(event.target);
var lastSelected;
if (target.is('a') && target.hasClass('submenu')) {
event.preventDefault();
return;
}
contextMenuHide();
if (target.is('a') || target.is('img')) { return; }
if (event.which == 1 || (navigator.appVersion.match(/\bMSIE\b/))) {
var tr = target.parents('tr').first();
if (tr.length && tr.hasClass('hascontextmenu')) {
// a row was clicked, check if the click was on checkbox
if (target.is('input')) {
// a checkbox may be clicked
if (target.prop('checked')) {
tr.addClass('context-menu-selection');
} else {
tr.removeClass('context-menu-selection');
}
} else {
if (event.ctrlKey || event.metaKey) {
contextMenuToggleSelection(tr);
} else if (event.shiftKey) {
lastSelected = contextMenuLastSelected();
if (lastSelected.length) {
var toggling = false;
$('.hascontextmenu').each(function(){
if (toggling || $(this).is(tr)) {
contextMenuAddSelection($(this));
}
if ($(this).is(tr) || $(this).is(lastSelected)) {
toggling = !toggling;
}
});
} else {
contextMenuAddSelection(tr);
}
} else {
contextMenuUnselectAll();
contextMenuAddSelection(tr);
}
contextMenuSetLastSelected(tr);
}
} else {
// click is outside the rows
if (target.is('a') && (target.hasClass('disabled') || target.hasClass('submenu'))) {
event.preventDefault();
} else {
contextMenuUnselectAll();
}
}
}
}
function contextMenuCreate() {
if ($('#context-menu').length < 1) {
var menu = document.createElement("div");
menu.setAttribute("id", "context-menu");
menu.setAttribute("style", "display:none;");
document.getElementById("content").appendChild(menu);
}
}
function contextMenuShow(event) {
var mouse_x = event.pageX;
var mouse_y = event.pageY;
var render_x = mouse_x;
var render_y = mouse_y;
var dims;
var menu_width;
var menu_height;
var window_width;
var window_height;
var max_width;
var max_height;
$('#context-menu').css('left', (render_x + 'px'));
$('#context-menu').css('top', (render_y + 'px'));
$('#context-menu').html('');
$.ajax({
url: contextMenuUrl,
data: $(event.target).parents('form').first().serialize(),
success: function(data, textStatus, jqXHR) {
$('#context-menu').html(data);
menu_width = $('#context-menu').width();
menu_height = $('#context-menu').height();
max_width = mouse_x + 2*menu_width;
max_height = mouse_y + menu_height;
var ws = window_size();
window_width = ws.width;
window_height = ws.height;
/* display the menu above and/or to the left of the click if needed */
if (max_width > window_width) {
render_x -= menu_width;
$('#context-menu').addClass('reverse-x');
} else {
$('#context-menu').removeClass('reverse-x');
}
if (max_height > window_height) {
render_y -= menu_height;
$('#context-menu').addClass('reverse-y');
} else {
$('#context-menu').removeClass('reverse-y');
}
if (render_x <= 0) render_x = 1;
if (render_y <= 0) render_y = 1;
$('#context-menu').css('left', (render_x + 'px'));
$('#context-menu').css('top', (render_y + 'px'));
$('#context-menu').show();
//if (window.parseStylesheets) { window.parseStylesheets(); } // IE
}
});
}
function contextMenuSetLastSelected(tr) {
$('.cm-last').removeClass('cm-last');
tr.addClass('cm-last');
}
function contextMenuLastSelected() {
return $('.cm-last').first();
}
function contextMenuUnselectAll() {
$('.hascontextmenu').each(function(){
contextMenuRemoveSelection($(this));
});
$('.cm-last').removeClass('cm-last');
}
function contextMenuHide() {
$('#context-menu').hide();
}
function contextMenuToggleSelection(tr) {
if (contextMenuIsSelected(tr)) {
contextMenuRemoveSelection(tr);
} else {
contextMenuAddSelection(tr);
}
}
function contextMenuAddSelection(tr) {
tr.addClass('context-menu-selection');
contextMenuCheckSelectionBox(tr, true);
contextMenuClearDocumentSelection();
}
function contextMenuRemoveSelection(tr) {
tr.removeClass('context-menu-selection');
contextMenuCheckSelectionBox(tr, false);
}
function contextMenuIsSelected(tr) {
return tr.hasClass('context-menu-selection');
}
function contextMenuCheckSelectionBox(tr, checked) {
tr.find('input[type=checkbox]').prop('checked', checked);
}
function contextMenuClearDocumentSelection() {
// TODO
if (document.selection) {
document.selection.empty(); // IE
} else {
window.getSelection().removeAllRanges();
}
}
function contextMenuInit(url) {
contextMenuUrl = url;
contextMenuCreate();
contextMenuUnselectAll();
if (!contextMenuObserving) {
$(document).click(contextMenuClick);
$(document).contextmenu(contextMenuRightClick);
contextMenuObserving = true;
}
}
function toggleIssuesSelection(el) {
var boxes = $(el).parents('form').find('input[type=checkbox]');
var all_checked = true;
boxes.each(function(){ if (!$(this).prop('checked')) { all_checked = false; } });
boxes.each(function(){
if (all_checked) {
$(this).removeAttr('checked');
$(this).parents('tr').removeClass('context-menu-selection');
} else if (!$(this).prop('checked')) {
$(this).prop('checked', true);
$(this).parents('tr').addClass('context-menu-selection');
}
});
}
function window_size() {
var w;
var h;
if (window.innerWidth) {
w = window.innerWidth;
h = window.innerHeight;
} else if (document.documentElement) {
w = document.documentElement.clientWidth;
h = document.documentElement.clientHeight;
} else {
w = document.body.clientWidth;
h = document.body.clientHeight;
}
return {width: w, height: h};
}
| cvnhan/ncredmine | public/javascripts/context_menu.js | JavaScript | gpl-2.0 | 6,545 |
/********************************************************************************
Copyright (C) MixERP Inc. (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, version 2 of the License.
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 System;
using MixERP.Net.FrontEnd.Base;
namespace MixERP.Net.Core.Modules.BackOffice
{
public partial class CustomFields : MixERPUserControl
{
public override void OnControlLoad(object sender, EventArgs e)
{
}
}
} | gjms2000/mixerp | src/FrontEnd/MixERP.Net.FrontEnd/Modules/BackOffice/CustomFields.ascx.cs | C# | gpl-2.0 | 1,053 |
/* AbiWord
* Copyright (C) 2004 Luca Padovani <lpadovan@cs.unibo.it>
*
* 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., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include "gr_Graphics.h"
#include "gr_Abi_CharArea.h"
#include "gr_Abi_RenderingContext.h"
GR_Abi_CharArea::GR_Abi_CharArea(GR_Graphics* graphics, GR_Font* f, const scaled& /*size*/, UT_UCS4Char c)
: m_pFont(f), m_ch(c)
{
#if 0
UT_ASSERT(graphics);
graphics->setFont(m_pFont);
m_box = BoundingBox(GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->measureUnRemappedChar(m_ch)),
GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->getFontAscent()),
GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->getFontDescent()));
#else
UT_ASSERT(f);
UT_Rect glyphRect;
graphics->setFont(m_pFont);
f->glyphBox(m_ch, glyphRect, graphics);
GR_Abi_RenderingContext Context(graphics);
#if 0
fprintf(stderr, "getting glyph %d\n glyphBox [left=%d,width=%d,top=%d,height=%d]\n measureUnremappedChar=%d\n measureUnremappedCharForCache=%d\n ftlu=%f\n tdu=%f\n tlu=%f\n size=%d\n", c,
glyphRect.left, glyphRect.width, glyphRect.top, glyphRect.height,
graphics->measureUnRemappedChar(m_ch),
f->measureUnremappedCharForCache(m_ch),
graphics->ftluD(1.0),
graphics->tduD(1.0),
graphics->tluD(1.0),
size.getValue());
#endif
m_box = BoundingBox(Context.fromAbiLayoutUnits(glyphRect.width + glyphRect.left),
Context.fromAbiLayoutUnits(glyphRect.top),
Context.fromAbiLayoutUnits(glyphRect.height - glyphRect.top));
#endif
}
GR_Abi_CharArea::~GR_Abi_CharArea()
{ }
BoundingBox
GR_Abi_CharArea::box() const
{
return m_box;
}
scaled
GR_Abi_CharArea::leftEdge() const
{
return 0;
}
scaled
GR_Abi_CharArea::rightEdge() const
{
return m_box.width;
}
void
GR_Abi_CharArea::render(RenderingContext& c, const scaled& x, const scaled& y) const
{
GR_Abi_RenderingContext& context = dynamic_cast<GR_Abi_RenderingContext&>(c);
context.drawChar(x, y, m_pFont, m_ch);
//context.drawBox(x, y, m_box);
}
| tanya-guza/abiword | plugins/mathview/xp/gr_Abi_CharArea.cpp | C++ | gpl-2.0 | 2,657 |
<?php
/**
* @file
* Default theme implementation to display a region.
*
* Available variables:
* - $regions: Renderable array of regions associated with this zone
* - $enabled: Flag to detect if the zone was enabled/disabled via theme settings
* - $wrapper: Flag set to display a full browser width wrapper around the
* container zone allowing items/backgrounds to be themed outside the
* 960pixel container size.
* - $zid: the zone id of the zone being rendered. This is a text value.
* - $container_width: the container width (12, 16, 24) of the zone
* - $attributes: a string containing the relevant class & id data for a container
*
* Helper Variables
* - $attributes_array: an array of attributes for the container zone
*
* @see template_preprocess()
* @see template_preprocess_zone()
* @see template_process()
* @see template_process_zone()
*/
?>
<?php if($enabled && $populated): ?>
<?php if($wrapper): ?><div id="<?php print $zid;?>-outer-wrapper" class="clearfix"><?php endif; ?>
<div <?php print $attributes; ?>>
<?php print render($regions); ?>
</div>
<?php if($wrapper): ?></div><?php endif; ?>
<?php endif; ?> | 404pnf/d7sites | sites/csc.fltrp.com/themes/standard/omega/omega/templates/zone.tpl.php | PHP | gpl-2.0 | 1,173 |
package cc.wdcy.domain;
import cc.wdcy.infrastructure.DateUtils;
import cc.wdcy.domain.shared.GuidGenerator;
import java.io.Serializable;
import java.util.Date;
/**
* @author Shengzhao Li
*/
public abstract class AbstractDomain implements Serializable {
/**
* Database id
*/
protected int id;
protected boolean archived;
/**
* Domain business guid.
*/
protected String guid = GuidGenerator.generate();
/**
* The domain create time.
*/
protected Date createTime = DateUtils.now();
public AbstractDomain() {
}
public int id() {
return id;
}
public void id(int id) {
this.id = id;
}
public boolean archived() {
return archived;
}
public AbstractDomain archived(boolean archived) {
this.archived = archived;
return this;
}
public String guid() {
return guid;
}
public void guid(String guid) {
this.guid = guid;
}
public Date createTime() {
return createTime;
}
public boolean isNewly() {
return id == 0;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AbstractDomain)) {
return false;
}
AbstractDomain that = (AbstractDomain) o;
return guid.equals(that.guid);
}
@Override
public int hashCode() {
return guid.hashCode();
}
//For subclass override it
public void saveOrUpdate() {
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{id=").append(id);
sb.append(", archived=").append(archived);
sb.append(", guid='").append(guid).append('\'');
sb.append(", createTime=").append(createTime);
sb.append('}');
return sb.toString();
}
} | vFiv/spring-oauth-server | src/main/java/cc/wdcy/domain/AbstractDomain.java | Java | gpl-2.0 | 1,925 |
/*
Copyright (C) 2008 Paul Davis
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "ardour/analyser.h"
#include "ardour/audiofilesource.h"
#include "ardour/rc_configuration.h"
#include "ardour/session_event.h"
#include "ardour/transient_detector.h"
#include "pbd/compose.h"
#include "pbd/error.h"
#include "pbd/i18n.h"
using namespace std;
using namespace ARDOUR;
using namespace PBD;
Analyser* Analyser::the_analyser = 0;
Glib::Threads::Mutex Analyser::analysis_active_lock;
Glib::Threads::Mutex Analyser::analysis_queue_lock;
Glib::Threads::Cond Analyser::SourcesToAnalyse;
list<boost::weak_ptr<Source> > Analyser::analysis_queue;
Analyser::Analyser ()
{
}
Analyser::~Analyser ()
{
}
static void
analyser_work ()
{
Analyser::work ();
}
void
Analyser::init ()
{
Glib::Threads::Thread::create (sigc::ptr_fun (analyser_work));
}
void
Analyser::queue_source_for_analysis (boost::shared_ptr<Source> src, bool force)
{
if (!src->can_be_analysed()) {
return;
}
if (!force && src->has_been_analysed()) {
return;
}
Glib::Threads::Mutex::Lock lm (analysis_queue_lock);
analysis_queue.push_back (boost::weak_ptr<Source>(src));
SourcesToAnalyse.broadcast ();
}
void
Analyser::work ()
{
SessionEvent::create_per_thread_pool ("Analyser", 64);
while (true) {
analysis_queue_lock.lock ();
wait:
if (analysis_queue.empty()) {
SourcesToAnalyse.wait (analysis_queue_lock);
}
if (analysis_queue.empty()) {
goto wait;
}
boost::shared_ptr<Source> src (analysis_queue.front().lock());
analysis_queue.pop_front();
analysis_queue_lock.unlock ();
boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
if (afs && afs->length(afs->timeline_position())) {
Glib::Threads::Mutex::Lock lm (analysis_active_lock);
analyse_audio_file_source (afs);
}
}
}
void
Analyser::analyse_audio_file_source (boost::shared_ptr<AudioFileSource> src)
{
AnalysisFeatureList results;
try {
TransientDetector td (src->sample_rate());
td.set_sensitivity (3, Config->get_transient_sensitivity()); // "General purpose"
if (td.run (src->get_transients_path(), src.get(), 0, results) == 0) {
src->set_been_analysed (true);
} else {
src->set_been_analysed (false);
}
} catch (...) {
error << string_compose(_("Transient Analysis failed for %1."), _("Audio File Source")) << endmsg;;
src->set_been_analysed (false);
return;
}
}
void
Analyser::flush ()
{
Glib::Threads::Mutex::Lock lq (analysis_queue_lock);
Glib::Threads::Mutex::Lock la (analysis_active_lock);
analysis_queue.clear();
}
| johannes-mueller/ardour | libs/ardour/analyser.cc | C++ | gpl-2.0 | 3,246 |
<?php global $woocommerce, $yith_wcwl; ?>
<?php
$instance = jaw_template_get_var('instance');
?>
<ul>
<?php if (isset($instance['login_show']) && $instance['login_show'] == '1') { ?>
<li class="top-bar-login-content" aria-haspopup="true">
<?php
$myaccount_page_id = get_option('woocommerce_myaccount_page_id');
$myaccount_page_url = '';
if ($myaccount_page_id) {
$myaccount_page_url = get_permalink($myaccount_page_id);
}
if (is_user_logged_in()) {
$text = __('My account', 'jawtemplates');
} else {
$text = __('Log in', 'jawtemplates');
}
?>
<a href="<?php echo $myaccount_page_url; ?>">
<span class="topbar-title-icon icon-user-icon2"></span>
<span class="topbar-title-text">
<?php echo $text; ?>
</span>
</a>
<?php
$class = '';
if (class_exists('WooCommerce') && is_user_logged_in()) {
$class = 'woo-menu';
}
?>
<div class="top-bar-login-form <?php echo $class; ?>">
<?php echo jaw_get_template_part('login', array('header', 'top_bar')); ?>
<?php if (get_option('users_can_register') && !is_user_logged_in()) : ?>
<p class="regiter-button">
<?php
if (class_exists('WooCommerce') && get_option('woocommerce_enable_myaccount_registration') == 'yes') {
$register_link = get_permalink($myaccount_page_id);
} else {
$register_link = esc_url(wp_registration_url());
}
?>
<?php echo apply_filters('register', sprintf('<a class="btnregiter" href="%s">%s</a>', $register_link, __('Register', 'jawtemplates'))); ?>
</p>
<?php endif; ?>
</div>
</li>
<?php } ?>
<?php if (is_plugin_active('yith-woocommerce-wishlist/init.php') && class_exists('WooCommerce')) { ?>
<?php if (isset($instance['wishlist_show']) && $instance['wishlist_show'] == '1') { ?>
<li class="wishlist-contents">
<a href="<?php echo $yith_wcwl->get_wishlist_url(); ?>">
<span class="topbar-title-icon icon-wishlist-icon"></span>
<span class="topbar-title-text">
<?php _e('Wishlist', 'jawtemplates'); ?>
</span>
</a>
</li>
<?php } ?>
<?php } ?>
<?php if (class_exists('WooCommerce')) { ?>
<?php if (isset($instance['cart_show']) && $instance['cart_show'] == '1') { ?>
<li class="woo-bar-woo-cart woocommerce-page " aria-haspopup="true">
<?php echo jaw_get_template_part('woo_cart', array('widgets', 'ecommerce_widget')); ?>
</li>
<?php } ?>
<?php } ?>
</ul>
| thanhtrantv/car-wp | wp-content/themes/goodstore/templates/widgets/jaw_ecommerce_widget.php | PHP | gpl-2.0 | 3,151 |
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package Sketch
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php sketch_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | petrofcikmatus/wp-blog | wp-content/themes/sketch/index.php | PHP | gpl-2.0 | 1,208 |
// license:GPL-2.0+
// copyright-holders:Couriersud
/*
* nld_legacy.c
*
*/
#include "nld_legacy.h"
#include "nl_setup.h"
NETLIB_NAMESPACE_DEVICES_START()
NETLIB_START(nicRSFF)
{
register_input("S", m_S);
register_input("R", m_R);
register_output("Q", m_Q);
register_output("QQ", m_QQ);
}
NETLIB_RESET(nicRSFF)
{
m_Q.initial(0);
m_QQ.initial(1);
}
NETLIB_UPDATE(nicRSFF)
{
if (!INPLOGIC(m_S))
{
OUTLOGIC(m_Q, 1, NLTIME_FROM_NS(20));
OUTLOGIC(m_QQ, 0, NLTIME_FROM_NS(20));
}
else if (!INPLOGIC(m_R))
{
OUTLOGIC(m_Q, 0, NLTIME_FROM_NS(20));
OUTLOGIC(m_QQ, 1, NLTIME_FROM_NS(20));
}
}
NETLIB_START(nicDelay)
{
register_input("1", m_I);
register_output("2", m_Q);
register_param("L_TO_H", m_L_to_H, 10);
register_param("H_TO_L", m_H_to_L, 10);
save(NLNAME(m_last));
}
NETLIB_RESET(nicDelay)
{
m_Q.initial(0);
}
NETLIB_UPDATE_PARAM(nicDelay)
{
}
NETLIB_UPDATE(nicDelay)
{
netlist_sig_t nval = INPLOGIC(m_I);
if (nval && !m_last)
{
// L_to_H
OUTLOGIC(m_Q, 1, NLTIME_FROM_NS(m_L_to_H.Value()));
}
else if (!nval && m_last)
{
// H_to_L
OUTLOGIC(m_Q, 0, NLTIME_FROM_NS(m_H_to_L.Value()));
}
m_last = nval;
}
NETLIB_NAMESPACE_DEVICES_END()
| RJRetro/mame | src/lib/netlist/devices/nld_legacy.cpp | C++ | gpl-2.0 | 1,191 |
<?php
/*
* @version $Id: ruledictionnarynetworkequipmenttypecollection.class.php 22656 2014-02-12 16:15:25Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI 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.
GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
class RuleDictionnaryNetworkEquipmentTypeCollection extends RuleDictionnaryDropdownCollection {
public $item_table = "glpi_networkequipmenttypes";
public $menu_option = "type.networking";
/**
* @see RuleCollection::getTitle()
**/
function getTitle() {
return __('Dictionnary of network equipment types');
}
}
?>
| flavioleal/projeto-towb | inc/ruledictionnarynetworkequipmenttypecollection.class.php | PHP | gpl-2.0 | 1,510 |
// { dg-do compile { target c++14 } }
//
// Copyright (C) 2013-2021 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
//
// NB: This file is for testing type_traits with NO OTHER INCLUDES.
#include <type_traits>
using namespace std;
enum E : long { };
static_assert( is_same<typename underlying_type<E>::type,
underlying_type_t<E>>(),
"underlying_type_t" );
| Gurgel100/gcc | libstdc++-v3/testsuite/20_util/underlying_type/requirements/alias_decl.cc | C++ | gpl-2.0 | 1,091 |
<div class="wrap">
<div class="postbox-container" style="width:95%; margin-right: 5%">
<div class="metabox-holder">
<div class="meta-box-sortables" style="min-height:0;">
<div class="postbox">
<h3 class="hndle"><span><?php echo $tr_Deck_Builder; ?></span></h3>
<div class="inside">
<p style="width: 50%"><?php echo $tr_Select_Components; ?></p>
<form method="POST" action="" id="idmsg-settings" name="idmsg-settings">
<div class="form-select">
<p>
<label for="deck_select"><?php echo $tr_Create_Select; ?></label><br/>
<select name="deck_select" id="deck_select">
<option><?php echo $tr_New_Deck; ?></option>
</select>
</p>
</div>
<div class="form-input">
<p>
<label for="deck_title"><?php echo $tr_Deck_Title; ?></label><br/>
<input type="text" name="deck_title" id="deck_title" class="deck-attr-text" value="" />
</p>
</div>
<div class="form-check">
<input type="checkbox" name="project_title" id="project_title" class="deck-attr" value="1"/>
<label for="project_title"><?php echo $tr_Project_Title; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_image" id="project_image" class="deck-attr" value="1"/>
<label for="project_image"><?php echo $tr_Product_Image; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_bar" id="project_bar" class="deck-attr" value="1"/>
<label for="project_bar"><?php echo $tr_Percentage_Bar; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_pledged" id="project_pledged" class="deck-attr" value="1"/>
<label for="project_pledged"><?php echo $tr_Total_Raised; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_goal" id="project_goal" class="deck-attr" value="1"/>
<label for="project_goal"><?php echo $tr_Project_Goal; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_pledgers" id="project_pledgers" class="deck-attr" value="1"/>
<label for="project_pledgers"><?php echo $tr_Total_Orders; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="days_left" id="days_left" class="deck-attr" value="1"/>
<label for="days_left"><?php echo $tr_Days_To_Go; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_end" id="project_end" class="deck-attr" value="1"/>
<label for="project_end"><?php echo $tr_End_Date; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_button" id="project_button" class="deck-attr" value="1"/>
<label for="project_button"><?php echo $tr_Buy_Button; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_description" id="project_description" class="deck-attr" value="1"/>
<label for="project_description"><?php echo $tr_meta_project_description; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_levels" id="project_levels" class="deck-attr" value="1"/>
<label for="project_levels"><?php echo $tr_Levels; ?></label>
</div>
<div class="submit">
<input type="submit" name="deck_submit" id="submit" class="button button-primary"/>
<input type="submit" name="deck_delete" id="deck_delete" class="button" value="Delete Deck" style="display: none;"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div> | sharpmachine/unlikelyheroes.com | wp-content/plugins/ignitiondeck/templates/admin/_deckBuilder.php | PHP | gpl-2.0 | 3,759 |
;(function ($, window, document, undefined) {
'use strict';
var settings = {
callback: $.noop,
deep_linking: true,
init: false
},
methods = {
init : function (options) {
settings = $.extend({}, options, settings);
return this.each(function () {
if (!settings.init) methods.events();
if (settings.deep_linking) methods.from_hash();
});
},
events : function () {
$(document).on('click.fndtn', '.tabs a', function (e) {
methods.set_tab($(this).parent('dd, li'), e);
});
settings.init = true;
},
set_tab : function ($tab, e) {
var $activeTab = $tab.closest('dl, ul').find('.active'),
target = $tab.children('a').attr("href"),
hasHash = /^#/.test(target),
$content = $(target + 'Tab');
if (hasHash && $content.length > 0) {
// Show tab content
if (e && !settings.deep_linking) e.preventDefault();
$content.closest('.tabs-content').children('li').removeClass('active').hide();
$content.css('display', 'block').addClass('active');
}
// Make active tab
$activeTab.removeClass('active');
$tab.addClass('active');
settings.callback();
},
from_hash : function () {
var hash = window.location.hash,
$tab = $('a[href="' + hash + '"]');
$tab.trigger('click.fndtn');
}
}
$.fn.foundationTabs = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.foundationTabs');
}
};
}(jQuery, this, this.document)); | RemanenceStudio/intuisens | wp-content/themes/intuisens/js/foundation/jquery.foundation.tabs.js | JavaScript | gpl-2.0 | 1,977 |
<?php
/**
* ------------------------------------------------------------------------
* T3V2 Framework
* ------------------------------------------------------------------------
* Copyright (C) 2004-20011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
?>
<jdoc:include type="modules" name="<?php echo JRequest::getCmd ('name') ?>" /> | heqiaoliu/Viral-Dark-Matter | tmp/install_4f209c9de9bf1/plugins/system/jat3/base-themes/default/page/ajax.modules.php | PHP | gpl-2.0 | 657 |
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <deque>
#include <set>
#ifdef WIN32
#include "direct.h"
#else
#include <sys/stat.h>
#endif
#include "dbcfile.h"
#include "mpq_libmpq.h"
extern unsigned int iRes;
extern ArchiveSet gOpenArchives;
bool ConvertADT(char*,char*);
typedef struct{
char name[64];
unsigned int id;
}map_id;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
map_id * map_ids;
uint16 * areas;
char output_path[128]=".";
char input_path[128]=".";
enum Extract
{
EXTRACT_MAP = 1,
EXTRACT_DBC = 2
};
int extract = EXTRACT_MAP | EXTRACT_DBC;
#define ADT_RES 64
void CreateDir( const std::string& Path )
{
#ifdef WIN32
_mkdir( Path.c_str());
#else
mkdir( Path.c_str(), 0777 );
#endif
}
bool FileExists( const char* FileName )
{
if(FILE* fp = fopen( FileName, "rb" ))
{
fclose(fp);
return true;
}
return false;
}
void Usage(char* prg)
{
printf("Usage:\n%s -[var] [value]\n-i set input path\n-o set output path\n-r set resolution\n-e extract only MAP(1)/DBC(2) - standard: both(3)\nExample: %s -r 256 -i \"c:\\games\\game\"",
prg,prg);
exit(1);
}
void HandleArgs(int argc, char * arg[])
{
for(int c=1;c<argc;c++)
{
//i - input path
//o - output path
//r - resolution, array of (r * r) heights will be created
//e - extract only MAP(1)/DBC(2) - standard both(3)
if(arg[c][0] != '-')
Usage(arg[0]);
switch(arg[c][1])
{
case 'i':
if(c+1<argc)//all ok
strcpy(input_path,arg[(c++) +1]);
else
Usage(arg[0]);
break;
case 'o':
if(c+1<argc)//all ok
strcpy(output_path,arg[(c++) +1]);
else
Usage(arg[0]);
break;
case 'r':
if(c+1<argc)//all ok
iRes=atoi(arg[(c++) +1]);
else
Usage(arg[0]);
break;
case 'e':
if(c+1<argc)//all ok
{
extract=atoi(arg[(c++) +1]);
if(!(extract > 0 && extract < 4))
Usage(arg[0]);
}
else
Usage(arg[0]);
break;
}
}
}
uint32 ReadMapDBC()
{
printf("Read Map.dbc file... ");
DBCFile dbc("DBFilesClient\\Map.dbc");
dbc.open();
uint32 map_count=dbc.getRecordCount();
map_ids=new map_id[map_count];
for(unsigned int x=0;x<map_count;x++)
{
map_ids[x].id=dbc.getRecord(x).getUInt(0);
strcpy(map_ids[x].name,dbc.getRecord(x).getString(1));
}
printf("Done! (%u maps loaded)\n", map_count);
return map_count;
}
void ReadAreaTableDBC()
{
printf("Read AreaTable.dbc file... ");
DBCFile dbc("DBFilesClient\\AreaTable.dbc");
dbc.open();
unsigned int area_count=dbc.getRecordCount();
uint32 maxid = dbc.getMaxId();
areas=new uint16[maxid + 1];
memset(areas, 0xff, sizeof(areas));
for(unsigned int x=0; x<area_count;++x)
areas[dbc.getRecord(x).getUInt(0)] = dbc.getRecord(x).getUInt(3);
printf("Done! (%u areas loaded)\n", area_count);
}
void ExtractMapsFromMpq()
{
char mpq_filename[1024];
char output_filename[1024];
printf("Extracting maps...\n");
uint32 map_count = ReadMapDBC();
ReadAreaTableDBC();
unsigned int total=map_count*ADT_RES*ADT_RES;
unsigned int done=0;
std::string path = output_path;
path += "/maps/";
CreateDir(path);
for(unsigned int x = 0; x < ADT_RES; ++x)
{
for(unsigned int y = 0; y < ADT_RES; ++y)
{
for(unsigned int z = 0; z < map_count; ++z)
{
sprintf(mpq_filename,"World\\Maps\\%s\\%s_%u_%u.adt",map_ids[z].name,map_ids[z].name,x,y);
sprintf(output_filename,"%s/maps/%03u%02u%02u.map",output_path,map_ids[z].id,y,x);
ConvertADT(mpq_filename,output_filename);
done++;
}
//draw progess bar
printf("Processing........................%d%%\r",(100*done)/total);
}
}
delete [] areas;
delete [] map_ids;
}
//bool WMO(char* filename);
void ExtractDBCFiles()
{
printf("Extracting dbc files...\n");
set<string> dbcfiles;
// get DBC file list
for(ArchiveSet::iterator i = gOpenArchives.begin(); i != gOpenArchives.end();++i)
{
vector<string> files;
(*i)->GetFileListTo(files);
for (vector<string>::iterator iter = files.begin(); iter != files.end(); ++iter)
if (iter->rfind(".dbc") == iter->length() - strlen(".dbc"))
dbcfiles.insert(*iter);
}
string path = output_path;
path += "/dbc/";
CreateDir(path);
// extract DBCs
int count = 0;
for (set<string>::iterator iter = dbcfiles.begin(); iter != dbcfiles.end(); ++iter)
{
string filename = path;
filename += (iter->c_str() + strlen("DBFilesClient\\"));
FILE *output=fopen(filename.c_str(), "wb");
if(!output)
{
printf("Can't create the output file '%s'\n", filename.c_str());
continue;
}
MPQFile m(iter->c_str());
if(!m.isEof())
fwrite(m.getPointer(), 1, m.getSize(), output);
fclose(output);
++count;
}
printf("Extracted %u DBC files\n\n", count);
}
void LoadCommonMPQFiles()
{
char filename[512];
sprintf(filename,"%s/Data/terrain.MPQ", input_path);
new MPQArchive(filename);
sprintf(filename,"%s/Data/dbc.MPQ", input_path);
new MPQArchive(filename);
for(int i = 1; i < 5; ++i)
{
char ext[3] = "";
if(i > 1)
sprintf(ext, "-%i", i);
sprintf(filename,"%s/Data/patch%s.MPQ", input_path, ext);
if(FileExists(filename))
new MPQArchive(filename);
}
}
inline void CloseMPQFiles()
{
for(ArchiveSet::iterator j = gOpenArchives.begin(); j != gOpenArchives.end();++j) (*j)->close();
gOpenArchives.clear();
}
int main(int argc, char * arg[])
{
printf("Map & DBC Extractor\n");
printf("===================\n\n");
HandleArgs(argc, arg);
if (extract & EXTRACT_MAP)
{
printf("Loading files.. \n");
// Open MPQs
LoadCommonMPQFiles();
// Extract dbc
ExtractDBCFiles();
// Extract maps
ExtractMapsFromMpq();
// Close MPQs
CloseMPQFiles();
}
return 0;
}
| brotalnia/TrinityZero | contrib/extractor/System.cpp | C++ | gpl-2.0 | 6,690 |
#!/usr/bin/python
# pep8.py - Check Python source code formatting, according to PEP 8
# Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
"""
Check Python source code formatting, according to PEP 8:
http://www.python.org/dev/peps/pep-0008/
For usage and a list of options, try this:
$ python pep8.py -h
This program and its regression test suite live here:
http://svn.browsershots.org/trunk/devtools/pep8/
http://trac.browsershots.org/browser/trunk/devtools/pep8/
Groups of errors and warnings:
E errors
W warnings
100 indentation
200 whitespace
300 blank lines
400 imports
500 line length
600 deprecation
700 statements
You can add checks to this program by writing plugins. Each plugin is
a simple function that is called for each line of source code, either
physical or logical.
Physical line:
- Raw line of text from the input file.
Logical line:
- Multi-line statements converted to a single line.
- Stripped left and right.
- Contents of strings replaced with 'xxx' of same length.
- Comments removed.
The check function requests physical or logical lines by the name of
the first argument:
def maximum_line_length(physical_line)
def extraneous_whitespace(logical_line)
def blank_lines(logical_line, blank_lines, indent_level, line_number)
The last example above demonstrates how check plugins can request
additional information with extra arguments. All attributes of the
Checker object are available. Some examples:
lines: a list of the raw lines from the input file
tokens: the tokens that contribute to this logical line
line_number: line number in the input file
blank_lines: blank lines before this one
indent_char: first indentation character in this file (' ' or '\t')
indent_level: indentation (with tabs expanded to multiples of 8)
previous_indent_level: indentation on previous line
previous_logical: previous logical line
The docstring of each check function shall be the relevant part of
text from PEP 8. It is printed if the user enables --show-pep8.
"""
import os
import sys
import re
import time
import inspect
import tokenize
from optparse import OptionParser
from keyword import iskeyword
from fnmatch import fnmatch
from six import iteritems
__version__ = '0.2.0'
__revision__ = '$Rev$'
default_exclude = '.svn,CVS,*.pyc,*.pyo'
indent_match = re.compile(r'([ \t]*)').match
raise_comma_match = re.compile(r'raise\s+\w+\s*(,)').match
operators = """
+ - * / % ^ & | = < > >> <<
+= -= *= /= %= ^= &= |= == <= >= >>= <<=
!= <> :
in is or not and
""".split()
options = None
args = None
##############################################################################
# Plugins (check functions) for physical lines
##############################################################################
def tabs_or_spaces(physical_line, indent_char):
"""
Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
"""
indent = indent_match(physical_line).group(1)
for offset, char in enumerate(indent):
if char != indent_char:
return offset, "E101 indentation contains mixed spaces and tabs"
def tabs_obsolete(physical_line):
"""
For new projects, spaces-only are strongly recommended over tabs. Most
editors have features that make this easy to do.
"""
indent = indent_match(physical_line).group(1)
if indent.count('\t'):
return indent.index('\t'), "W191 indentation contains tabs"
def trailing_whitespace(physical_line):
"""
JCR: Trailing whitespace is superfluous.
"""
physical_line = physical_line.rstrip('\n') # chr(10), newline
physical_line = physical_line.rstrip('\r') # chr(13), carriage return
physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
stripped = physical_line.rstrip()
if physical_line != stripped:
return len(stripped), "W291 trailing whitespace"
def trailing_blank_lines(physical_line, lines, line_number):
"""
JCR: Trailing blank lines are superfluous.
"""
if physical_line.strip() == '' and line_number == len(lines):
return 0, "W391 blank line at end of file"
def missing_newline(physical_line):
"""
JCR: The last line should have a newline.
"""
if physical_line.rstrip() == physical_line:
return len(physical_line), "W292 no newline at end of file"
def maximum_line_length(physical_line):
"""
Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to have
several windows side-by-side. The default wrapping on such devices looks
ugly. Therefore, please limit all lines to a maximum of 79 characters.
For flowing long blocks of text (docstrings or comments), limiting the
length to 72 characters is recommended.
"""
length = len(physical_line.rstrip())
if length > 79:
return 79, "E501 line too long (%d characters)" % length
##############################################################################
# Plugins (check functions) for logical lines
##############################################################################
def blank_lines(logical_line, blank_lines, indent_level, line_number,
previous_logical):
"""
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related
functions. Blank lines may be omitted between a bunch of related
one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
"""
if line_number == 1:
return # Don't expect blank lines before the first line
if previous_logical.startswith('@'):
return # Don't expect blank lines after function decorator
if (logical_line.startswith('def ') or
logical_line.startswith('class ') or
logical_line.startswith('@')):
if indent_level > 0 and blank_lines != 1:
return 0, "E301 expected 1 blank line, found %d" % blank_lines
if indent_level == 0 and blank_lines != 2:
return 0, "E302 expected 2 blank lines, found %d" % blank_lines
if blank_lines > 2:
return 0, "E303 too many blank lines (%d)" % blank_lines
def extraneous_whitespace(logical_line):
"""
Avoid extraneous whitespace in the following situations:
- Immediately inside parentheses, brackets or braces.
- Immediately before a comma, semicolon, or colon.
"""
line = logical_line
for char in '([{':
found = line.find(char + ' ')
if found > -1:
return found + 1, "E201 whitespace after '%s'" % char
for char in '}])':
found = line.find(' ' + char)
if found > -1 and line[found - 1] != ',':
return found, "E202 whitespace before '%s'" % char
for char in ',;:':
found = line.find(' ' + char)
if found > -1:
return found, "E203 whitespace before '%s'" % char
def missing_whitespace(logical_line):
"""
JCR: Each comma, semicolon or colon should be followed by whitespace.
"""
line = logical_line
for index in range(len(line) - 1):
char = line[index]
if char in ',;:' and line[index + 1] != ' ':
before = line[:index]
if char == ':' and before.count('[') > before.count(']'):
continue # Slice syntax, no space required
return index, "E231 missing whitespace after '%s'" % char
def indentation(logical_line, previous_logical, indent_char,
indent_level, previous_indent_level):
"""
Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
"""
if indent_char == ' ' and indent_level % 4:
return 0, "E111 indentation is not a multiple of four"
indent_expect = previous_logical.endswith(':')
if indent_expect and indent_level <= previous_indent_level:
return 0, "E112 expected an indented block"
if indent_level > previous_indent_level and not indent_expect:
return 0, "E113 unexpected indentation"
def whitespace_before_parameters(logical_line, tokens):
"""
Avoid extraneous whitespace in the following situations:
- Immediately before the open parenthesis that starts the argument
list of a function call.
- Immediately before the open parenthesis that starts an indexing or
slicing.
"""
prev_type = tokens[0][0]
prev_text = tokens[0][1]
prev_end = tokens[0][3]
for index in range(1, len(tokens)):
token_type, text, start, end, line = tokens[index]
if (token_type == tokenize.OP and
text in '([' and
start != prev_end and
prev_type == tokenize.NAME and
(index < 2 or tokens[index - 2][1] != 'class') and
(not iskeyword(prev_text))):
return prev_end, "E211 whitespace before '%s'" % text
prev_type = token_type
prev_text = text
prev_end = end
def whitespace_around_operator(logical_line):
"""
Avoid extraneous whitespace in the following situations:
- More than one space around an assignment (or other) operator to
align it with another.
"""
line = logical_line
for operator in operators:
found = line.find(' ' + operator)
if found > -1:
return found, "E221 multiple spaces before operator"
found = line.find(operator + ' ')
if found > -1:
return found, "E222 multiple spaces after operator"
found = line.find('\t' + operator)
if found > -1:
return found, "E223 tab before operator"
found = line.find(operator + '\t')
if found > -1:
return found, "E224 tab after operator"
def whitespace_around_comma(logical_line):
"""
Avoid extraneous whitespace in the following situations:
- More than one space around an assignment (or other) operator to
align it with another.
JCR: This should also be applied around comma etc.
"""
line = logical_line
for separator in ',;:':
found = line.find(separator + ' ')
if found > -1:
return found + 1, "E241 multiple spaces after '%s'" % separator
found = line.find(separator + '\t')
if found > -1:
return found + 1, "E242 tab after '%s'" % separator
def imports_on_separate_lines(logical_line):
"""
Imports should usually be on separate lines.
"""
line = logical_line
if line.startswith('import '):
found = line.find(',')
if found > -1:
return found, "E401 multiple imports on one line"
def compound_statements(logical_line):
"""
Compound statements (multiple statements on the same line) are
generally discouraged.
"""
line = logical_line
found = line.find(':')
if -1 < found < len(line) - 1:
before = line[:found]
if (before.count('{') <= before.count('}') and # {'a': 1} (dict)
before.count('[') <= before.count(']') and # [1:2] (slice)
not re.search(r'\blambda\b', before)): # lambda x: x
return found, "E701 multiple statements on one line (colon)"
found = line.find(';')
if -1 < found:
return found, "E702 multiple statements on one line (semicolon)"
def python_3000_has_key(logical_line):
"""
The {}.has_key() method will be removed in the future version of
Python. Use the 'in' operation instead, like:
d = {"a": 1, "b": 2}
if "b" in d:
print d["b"]
"""
pos = logical_line.find('.has_key(')
if pos > -1:
return pos, "W601 .has_key() is deprecated, use 'in'"
def python_3000_raise_comma(logical_line):
"""
When raising an exception, use "raise ValueError('message')"
instead of the older form "raise ValueError, 'message'".
The paren-using form is preferred because when the exception arguments
are long or include string formatting, you don't need to use line
continuation characters thanks to the containing parentheses. The older
form will be removed in Python 3000.
"""
match = raise_comma_match(logical_line)
if match:
return match.start(1), "W602 deprecated form of raising exception"
##############################################################################
# Helper functions
##############################################################################
def expand_indent(line):
"""
Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
16
"""
result = 0
for char in line:
if char == '\t':
result = result / 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result
##############################################################################
# Framework to run all checks
##############################################################################
def message(text):
"""Print a message."""
# print >> sys.stderr, options.prog + ': ' + text
# print >> sys.stderr, text
print(text)
def find_checks(argument_name):
"""
Find all globally visible functions where the first argument name
starts with argument_name.
"""
checks = []
function_type = type(find_checks)
for name, function in iteritems(globals()):
if type(function) is function_type:
args = inspect.getargspec(function)[0]
if len(args) >= 1 and args[0].startswith(argument_name):
checks.append((name, function, args))
checks.sort()
return checks
def mute_string(text):
"""
Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"')
'"xxx"'
>>> mute_string("'''abc'''")
"'''xxx'''"
>>> mute_string("r'abc'")
"r'xxx'"
"""
start = 1
end = len(text) - 1
# String modifiers (e.g. u or r)
if text.endswith('"'):
start += text.index('"')
elif text.endswith("'"):
start += text.index("'")
# Triple quotes
if text.endswith('"""') or text.endswith("'''"):
start += 2
end -= 2
return text[:start] + 'x' * (end - start) + text[end:]
class Checker:
"""
Load a Python source file, tokenize it, check coding style.
"""
def __init__(self, filename):
self.filename = filename
self.lines = file(filename).readlines()
self.physical_checks = find_checks('physical_line')
self.logical_checks = find_checks('logical_line')
options.counters['physical lines'] = \
options.counters.get('physical lines', 0) + len(self.lines)
def readline(self):
"""
Get the next line from the input buffer.
"""
self.line_number += 1
if self.line_number > len(self.lines):
return ''
return self.lines[self.line_number - 1]
def readline_check_physical(self):
"""
Check and return the next physical line. This method can be
used to feed tokenize.generate_tokens.
"""
line = self.readline()
if line:
self.check_physical(line)
return line
def run_check(self, check, argument_names):
"""
Run a check plugin.
"""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments)
def check_physical(self, line):
"""
Run all physical checks on a raw input line.
"""
self.physical_line = line
if self.indent_char is None and len(line) and line[0] in ' \t':
self.indent_char = line[0]
for name, check, argument_names in self.physical_checks:
result = self.run_check(check, argument_names)
if result is not None:
offset, text = result
self.report_error(self.line_number, offset, text, check)
def build_tokens_line(self):
"""
Build a logical line from tokens.
"""
self.mapping = []
logical = []
length = 0
previous = None
for token in self.tokens:
token_type, text = token[0:2]
if token_type in (tokenize.COMMENT, tokenize.NL,
tokenize.INDENT, tokenize.DEDENT,
tokenize.NEWLINE):
continue
if token_type == tokenize.STRING:
text = mute_string(text)
if previous:
end_line, end = previous[3]
start_line, start = token[2]
if end_line != start_line: # different row
if self.lines[end_line - 1][end - 1] not in '{[(':
logical.append(' ')
length += 1
elif end != start: # different column
fill = self.lines[end_line - 1][end:start]
logical.append(fill)
length += len(fill)
self.mapping.append((length, token))
logical.append(text)
length += len(text)
previous = token
self.logical_line = ''.join(logical)
assert self.logical_line.lstrip() == self.logical_line
assert self.logical_line.rstrip() == self.logical_line
def check_logical(self):
"""
Build a line from tokens and run all logical checks on it.
"""
options.counters['logical lines'] = \
options.counters.get('logical lines', 0) + 1
self.build_tokens_line()
first_line = self.lines[self.mapping[0][1][2][0] - 1]
indent = first_line[:self.mapping[0][1][2][1]]
self.previous_indent_level = self.indent_level
self.indent_level = expand_indent(indent)
if options.verbose >= 2:
print(self.logical_line[:80].rstrip())
for name, check, argument_names in self.logical_checks:
if options.verbose >= 3:
print(' ', name)
result = self.run_check(check, argument_names)
if result is not None:
offset, text = result
if type(offset) is tuple:
original_number, original_offset = offset
else:
for token_offset, token in self.mapping:
if offset >= token_offset:
original_number = token[2][0]
original_offset = (token[2][1]
+ offset - token_offset)
self.report_error(original_number, original_offset,
text, check)
self.previous_logical = self.logical_line
def check_all(self):
"""
Run all checks on the input file.
"""
self.file_errors = 0
self.line_number = 0
self.indent_char = None
self.indent_level = 0
self.previous_logical = ''
self.blank_lines = 0
self.tokens = []
parens = 0
for token in tokenize.generate_tokens(self.readline_check_physical):
# print tokenize.tok_name[token[0]], repr(token)
self.tokens.append(token)
token_type, text = token[0:2]
if token_type == tokenize.OP and text in '([{':
parens += 1
if token_type == tokenize.OP and text in '}])':
parens -= 1
if token_type == tokenize.NEWLINE and not parens:
self.check_logical()
self.blank_lines = 0
self.tokens = []
if token_type == tokenize.NL and not parens:
self.blank_lines += 1
self.tokens = []
if token_type == tokenize.COMMENT:
source_line = token[4]
token_start = token[2][1]
if source_line[:token_start].strip() == '':
self.blank_lines = 0
return self.file_errors
def report_error(self, line_number, offset, text, check):
"""
Report an error, according to options.
"""
if options.quiet == 1 and not self.file_errors:
message(self.filename)
self.file_errors += 1
code = text[:4]
options.counters[code] = options.counters.get(code, 0) + 1
options.messages[code] = text[5:]
if options.quiet:
return
if options.testsuite:
base = os.path.basename(self.filename)[:4]
if base == code:
return
if base[0] == 'E' and code[0] == 'W':
return
if ignore_code(code):
return
if options.counters[code] == 1 or options.repeat:
message("%s:%s:%d: %s" %
(self.filename, line_number, offset + 1, text))
if options.show_source:
line = self.lines[line_number - 1]
message(line.rstrip())
message(' ' * offset + '^')
if options.show_pep8:
message(check.__doc__.lstrip('\n').rstrip())
def input_file(filename):
"""
Run all checks on a Python source file.
"""
if excluded(filename) or not filename_match(filename):
return {}
if options.verbose:
message('checking ' + filename)
options.counters['files'] = options.counters.get('files', 0) + 1
errors = Checker(filename).check_all()
if options.testsuite and not errors:
message("%s: %s" % (filename, "no errors found"))
def input_dir(dirname):
"""
Check all Python source files in this directory and all subdirectories.
"""
dirname = dirname.rstrip('/')
if excluded(dirname):
return
for root, dirs, files in os.walk(dirname):
if options.verbose:
message('directory ' + root)
options.counters['directories'] = \
options.counters.get('directories', 0) + 1
dirs.sort()
for subdir in dirs:
if excluded(subdir):
dirs.remove(subdir)
files.sort()
for filename in files:
input_file(os.path.join(root, filename))
def excluded(filename):
"""
Check if options.exclude contains a pattern that matches filename.
"""
basename = os.path.basename(filename)
for pattern in options.exclude:
if fnmatch(basename, pattern):
# print basename, 'excluded because it matches', pattern
return True
def filename_match(filename):
"""
Check if options.filename contains a pattern that matches filename.
If options.filename is unspecified, this always returns True.
"""
if not options.filename:
return True
for pattern in options.filename:
if fnmatch(filename, pattern):
return True
def ignore_code(code):
"""
Check if options.ignore contains a prefix of the error code.
"""
for ignore in options.ignore:
if code.startswith(ignore):
return True
def get_error_statistics():
"""Get error statistics."""
return get_statistics("E")
def get_warning_statistics():
"""Get warning statistics."""
return get_statistics("W")
def get_statistics(prefix=''):
"""
Get statistics for message codes that start with the prefix.
prefix='' matches all errors and warnings
prefix='E' matches all errors
prefix='W' matches all warnings
prefix='E4' matches all errors that have to do with imports
"""
stats = []
keys = options.messages.keys()
keys.sort()
for key in keys:
if key.startswith(prefix):
stats.append('%-7s %s %s' %
(options.counters[key], key, options.messages[key]))
return stats
def print_statistics(prefix=''):
"""Print overall statistics (number of errors and warnings)."""
for line in get_statistics(prefix):
print(line)
def print_benchmark(elapsed):
"""
Print benchmark numbers.
"""
print('%-7.2f %s' % (elapsed, 'seconds elapsed'))
keys = ['directories', 'files',
'logical lines', 'physical lines']
for key in keys:
if key in options.counters:
print('%-7d %s per second (%d total)' % (
options.counters[key] / elapsed, key,
options.counters[key]))
def process_options(arglist=None):
"""
Process options passed either via arglist or via command line args.
"""
global options, args
usage = "%prog [options] input ..."
parser = OptionParser(usage)
parser.add_option('-v', '--verbose', default=0, action='count',
help="print status messages, or debug with -vv")
parser.add_option('-q', '--quiet', default=0, action='count',
help="report only file names, or nothing with -qq")
parser.add_option('--exclude', metavar='patterns', default=default_exclude,
help="skip matches (default %s)" % default_exclude)
parser.add_option('--filename', metavar='patterns',
help="only check matching files (e.g. *.py)")
parser.add_option('--ignore', metavar='errors', default='',
help="skip errors and warnings (e.g. E4,W)")
parser.add_option('--repeat', action='store_true',
help="show all occurrences of the same error")
parser.add_option('--show-source', action='store_true',
help="show source code for each error")
parser.add_option('--show-pep8', action='store_true',
help="show text of PEP 8 for each error")
parser.add_option('--statistics', action='store_true',
help="count errors and warnings")
parser.add_option('--benchmark', action='store_true',
help="measure processing speed")
parser.add_option('--testsuite', metavar='dir',
help="run regression tests from dir")
parser.add_option('--doctest', action='store_true',
help="run doctest on myself")
options, args = parser.parse_args(arglist)
if options.testsuite:
args.append(options.testsuite)
if len(args) == 0:
parser.error('input not specified')
options.prog = os.path.basename(sys.argv[0])
options.exclude = options.exclude.split(',')
for index in range(len(options.exclude)):
options.exclude[index] = options.exclude[index].rstrip('/')
if options.filename:
options.filename = options.filename.split(',')
if options.ignore:
options.ignore = options.ignore.split(',')
else:
options.ignore = []
options.counters = {}
options.messages = {}
return options, args
def _main():
"""
Parse options and run checks on Python source.
"""
options, args = process_options()
if options.doctest:
import doctest
return doctest.testmod()
start_time = time.time()
for path in args:
if os.path.isdir(path):
input_dir(path)
else:
input_file(path)
elapsed = time.time() - start_time
if options.statistics:
print_statistics()
if options.benchmark:
print_benchmark(elapsed)
if __name__ == '__main__':
_main()
| MSusik/invenio | scripts/pep8.py | Python | gpl-2.0 | 29,318 |
<?php
/**
* @version $Id: ItemPrivacyPopulator.php 10887 2013-05-30 06:31:57Z btowles $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
class RokSprocket_Provider_EasyBlog_ItemPrivacyPopulator implements RokCommon_Filter_IPicklistPopulator
{
/**
*
* @return array;
*/
public function getPicklistOptions()
{
$options = array();
$options['private'] = "Private";
$options['public'] = "Public";
return $options;
}
}
| effortlesssites/template | components/com_roksprocket/lib/RokSprocket/Provider/EasyBlog/ItemPrivacyPopulator.php | PHP | gpl-2.0 | 616 |
require 'rexml/document'
module Ohcount
module Gestalt
class CsprojRule < FileRule
attr_accessor :import
def initialize(*args)
@import = args.shift || /.*/
@import = /^#{Regexp.escape(@import.to_s)}$/ unless @import.is_a? Regexp
super(args)
end
def process_source_file(source_file)
if source_file.filename =~ /\.csproj$/ && source_file.language_breakdown('xml')
callback = lambda do |import|
@count += 1 if import =~ @import
end
begin
REXML::Document.parse_stream(source_file.language_breakdown('xml').code, CsprojListener.new(callback))
rescue REXML::ParseException
# Malformed XML! -- ignore and move on
end
end
end
end
end
end
| scriptum/ohcount | ruby/gestalt/rules/csproj_rule.rb | Ruby | gpl-2.0 | 739 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="cs_CZ">
<context>
<name>AboutDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="134"/>
<source>About</source>
<translation type="unfinished">O</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="135"/>
<source><html><head/><body><p><span style=" font-size:16pt; font-weight:600;">PCManFM</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="137"/>
<source>Lightweight file manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="143"/>
<source>PCMan File Manager
Copyright (C) 2009 - 2014 洪任諭 (Hong Jen Yee)
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.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="139"/>
<source>Programming:
* Hong Jen Yee (PCMan) <pcman.tw@gmail.com>
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="138"/>
<source><html><head/><body><p><a href="http://lxqt.org/"><span style=" text-decoration: underline; color:#0000ff;">http://lxqt.org/</span></a></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="142"/>
<source>Authors</source>
<translation type="unfinished">Autoři</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="160"/>
<source>License</source>
<translation type="unfinished">Licence</translation>
</message>
</context>
<context>
<name>AutoRunDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="110"/>
<source>Removable medium is inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="112"/>
<source><b>Removable medium is inserted</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="113"/>
<source>Type of medium:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="114"/>
<source>Detecting...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="115"/>
<source>Please select the action you want to perform:</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DesktopFolder</name>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="75"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="76"/>
<source>Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="77"/>
<source>Desktop folder:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="79"/>
<source>Image file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="84"/>
<source>Folder path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="85"/>
<source>&Browse</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DesktopPreferencesDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="254"/>
<source>Desktop Preferences</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="255"/>
<source>Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="256"/>
<source>Wallpaper mode:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="257"/>
<source>Wallpaper image file:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="259"/>
<source>Select background color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="261"/>
<source>Image file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="266"/>
<source>Image file path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="267"/>
<source>&Browse</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="268"/>
<source>Label Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="271"/>
<source>Select text color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="272"/>
<source>Select shadow color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="273"/>
<source>Select font:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="275"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="276"/>
<source>Window Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="277"/>
<source>Show menus provided by window managers when desktop is clicked</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="278"/>
<source>Advanced</source>
<translation type="unfinished">Pokročilé</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="557"/>
<source>File Manager</source>
<translation type="unfinished">Správce souborů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="560"/>
<source>Go Up</source>
<translation type="unfinished">Nahoru</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="562"/>
<source>Alt+Up</source>
<translation type="unfinished">Alt+Nahoru</translation>
</message>
<message>
<source>Home</source>
<translation type="obsolete">Domů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="564"/>
<source>Alt+Home</source>
<translation type="unfinished">Alt+Home</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="583"/>
<source>Reload</source>
<translation type="unfinished">Obnovit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="566"/>
<source>F5</source>
<translation type="unfinished">F5</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="563"/>
<source>&Home</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="565"/>
<source>&Reload</source>
<translation type="unfinished">&Obnovit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="567"/>
<source>Go</source>
<translation type="unfinished">Jdi</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="568"/>
<source>Quit</source>
<translation type="unfinished">ukončit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="569"/>
<source>&About</source>
<translation type="unfinished">&O programu</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="572"/>
<source>New Window</source>
<translation type="unfinished">Nové okno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="574"/>
<source>Ctrl+N</source>
<translation type="unfinished">Ctrl+N</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="575"/>
<source>Show &Hidden</source>
<translation type="unfinished">Zobrazit &skryté</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="576"/>
<source>Ctrl+H</source>
<translation type="unfinished">Ctrl+H</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="577"/>
<source>&Computer</source>
<translation type="unfinished">Počítač</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="578"/>
<source>&Trash</source>
<translation type="unfinished">&Koš</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="579"/>
<source>&Network</source>
<translation type="unfinished">Síť</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="580"/>
<source>&Desktop</source>
<translation type="unfinished">Plocha</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="581"/>
<source>&Add to Bookmarks</source>
<translation type="unfinished">Přidat k záložkám</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="582"/>
<source>&Applications</source>
<translation type="unfinished">Programy</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="589"/>
<source>Ctrl+X</source>
<translation type="unfinished">Ctrl+X</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="590"/>
<source>&Copy</source>
<translation type="unfinished">Kopírovat</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="591"/>
<source>Ctrl+C</source>
<translation type="unfinished">Ctrl+C</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="592"/>
<source>&Paste</source>
<translation type="unfinished">Vložit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="593"/>
<source>Ctrl+V</source>
<translation type="unfinished">Ctrl+V</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="594"/>
<source>Select &All</source>
<translation type="unfinished">Vybrat všechno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="596"/>
<source>Pr&eferences</source>
<translation type="unfinished">&Nastavení</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="597"/>
<source>&Ascending</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="598"/>
<source>&Descending</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="599"/>
<source>&By File Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="600"/>
<source>By &Modification Time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="601"/>
<source>By File &Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="602"/>
<source>By &Owner</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="603"/>
<source>&Folder First</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="619"/>
<source>&Invert Selection</source>
<translation type="unfinished">Invertovat výběr</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="620"/>
<source>&Delete</source>
<translation type="unfinished">Smazat</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="622"/>
<source>&Rename</source>
<translation type="unfinished">Přejmenovat</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="629"/>
<source>&Case Sensitive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="630"/>
<source>By File &Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="631"/>
<source>&Close Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="595"/>
<source>Ctrl+A</source>
<translation type="unfinished">Ctrl+A</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="558"/>
<source>Go &Up</source>
<translation type="unfinished">Nahoru</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="570"/>
<source>&New Window</source>
<translation type="unfinished">Nové &okno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="584"/>
<source>&Icon View</source>
<translation type="unfinished">Pohled s ikonami</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="585"/>
<source>&Compact View</source>
<translation type="unfinished">Kompaktní pohled</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="586"/>
<source>&Detailed List</source>
<translation type="unfinished">Seznam s podrobnostmi</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="587"/>
<source>&Thumbnail View</source>
<translation type="unfinished">Pohled s náhledy</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="588"/>
<source>Cu&t</source>
<translation type="unfinished">Vyjmout</translation>
</message>
<message>
<source>Ascending</source>
<translation type="obsolete">Vzestupně</translation>
</message>
<message>
<source>Descending</source>
<translation type="obsolete">Sestupně</translation>
</message>
<message>
<source>By File Name</source>
<translation type="obsolete">Podle jména</translation>
</message>
<message>
<source>By Modification Time</source>
<translation type="obsolete">Podle času</translation>
</message>
<message>
<source>By File Type</source>
<translation type="obsolete">Podle typu</translation>
</message>
<message>
<source>By Owner</source>
<translation type="obsolete">Podle vlastníka</translation>
</message>
<message>
<source>Folder First</source>
<translation type="obsolete">Složky jako první</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="604"/>
<source>New &Tab</source>
<translation type="unfinished">Nový &panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="606"/>
<source>New Tab</source>
<translation type="unfinished">Nový panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="608"/>
<source>Ctrl+T</source>
<translation type="unfinished">Ctrl+T</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="609"/>
<source>Go &Back</source>
<translation type="unfinished">Zpět</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="611"/>
<source>Go Back</source>
<translation type="unfinished">Zpět</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="613"/>
<source>Alt+Left</source>
<translation type="unfinished">Alt+Vlevo</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="614"/>
<source>Go &Forward</source>
<translation type="unfinished">&Vpřed</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="616"/>
<source>Go Forward</source>
<translation type="unfinished">Vpřed</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="618"/>
<source>Alt+Right</source>
<translation type="unfinished">Alt+Vpravo</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="621"/>
<source>Del</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="623"/>
<source>F2</source>
<translation type="unfinished">F2</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="624"/>
<source>C&lose Tab</source>
<translation type="unfinished">Zavřít panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="626"/>
<source>File &Properties</source>
<translation type="unfinished">Vlastnosti souboru</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="628"/>
<source>&Folder Properties</source>
<translation type="unfinished">Vlastnosti složky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="638"/>
<source>Ctrl+Shift+N</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="640"/>
<source>Ctrl+Alt+N</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="643"/>
<source>Filter</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="646"/>
<source>C&reate New</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="649"/>
<source>&Sorting</source>
<translation type="unfinished">Řadit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="654"/>
<source>Main Toolbar</source>
<translation type="unfinished">Hlavní panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="625"/>
<source>Ctrl+W</source>
<translation type="unfinished">Ctrl+W</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="627"/>
<source>Alt+Return</source>
<translation type="unfinished">Alt+Return</translation>
</message>
<message>
<source>Case Sensitive</source>
<translation type="obsolete">Rozlišovat velikost písmen</translation>
</message>
<message>
<source>By File Size</source>
<translation type="obsolete">Podle velikosti</translation>
</message>
<message>
<source>Close Window</source>
<translation type="obsolete">Zavřít okno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="632"/>
<source>Edit Bookmarks</source>
<translation type="unfinished">Upravit záložky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="633"/>
<source>Open &Terminal</source>
<translation type="unfinished">Otevřít &terminál</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="634"/>
<source>F4</source>
<translation type="unfinished">F4</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="635"/>
<source>Open as &Root</source>
<translation type="unfinished">Otevřít jako &Root</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="636"/>
<source>&Edit Bookmarks</source>
<translation type="unfinished">Upravit záložky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="637"/>
<source>&Folder</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="639"/>
<source>&Blank File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="641"/>
<source>&Find Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="642"/>
<source>F3</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="644"/>
<source>Filter by string...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="645"/>
<source>&File</source>
<translation type="unfinished">&Soubor</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="647"/>
<source>&Help</source>
<translation type="unfinished">&Nápověda</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="648"/>
<source>&View</source>
<translation type="unfinished">&Zobrazení</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="650"/>
<source>&Edit</source>
<translation type="unfinished">Úpr&avy</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="651"/>
<source>&Bookmarks</source>
<translation type="unfinished">Zál&ožky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="652"/>
<source>&Go</source>
<translation type="unfinished">&Jdi</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="653"/>
<source>&Tool</source>
<translation type="unfinished">Nás&troje</translation>
</message>
</context>
<context>
<name>PCManFM::Application</name>
<message>
<location filename="../application.cpp" line="162"/>
<source>Name of configuration profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="162"/>
<source>PROFILE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="165"/>
<source>Run PCManFM as a daemon</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="168"/>
<source>Quit PCManFM</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="171"/>
<source>Launch desktop manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="174"/>
<source>Turn off desktop manager if it's running</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="177"/>
<source>Open desktop preference dialog on the page with the specified name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="177"/>
<location filename="../application.cpp" line="193"/>
<source>NAME</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="180"/>
<source>Open new window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="183"/>
<source>Open Find Files utility</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="186"/>
<source>Set desktop wallpaper from image FILE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="186"/>
<source>FILE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="190"/>
<source>Set mode of desktop wallpaper. MODE=(color|stretch|fit|center|tile)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="190"/>
<source>MODE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="193"/>
<source>Open Preferences dialog on the page with the specified name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="196"/>
<source>Files or directories to open</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="196"/>
<source>[FILE1, FILE2,...]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="500"/>
<location filename="../application.cpp" line="507"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="507"/>
<source>Terminal emulator is not set.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::AutoRunDialog</name>
<message>
<location filename="../autorundialog.cpp" line="43"/>
<source>Open in file manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../autorundialog.cpp" line="133"/>
<source>Removable Disk</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::DesktopPreferencesDialog</name>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="50"/>
<source>Fill with background color only</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="51"/>
<source>Stretch to fill the entire screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="52"/>
<source>Stretch to fit the screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="53"/>
<source>Center on the screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="54"/>
<source>Tile the image to fill the entire screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="157"/>
<source>Image Files</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::DesktopWindow</name>
<message>
<location filename="../desktopwindow.cpp" line="366"/>
<source>Stic&k to Current Position</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktopwindow.cpp" line="388"/>
<source>Desktop Preferences</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::MainWindow</name>
<message>
<location filename="../mainwindow.cpp" line="190"/>
<source>Clear text (Ctrl+K)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="455"/>
<source>Version: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="907"/>
<source>&Move to Trash</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="907"/>
<source>&Delete</source>
<translation type="unfinished">Smazat</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="969"/>
<location filename="../mainwindow.cpp" line="980"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="980"/>
<source>Switch user command is not set.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::PreferencesDialog</name>
<message>
<location filename="../preferencesdialog.cpp" line="190"/>
<source>Icon View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../preferencesdialog.cpp" line="191"/>
<source>Compact Icon View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../preferencesdialog.cpp" line="192"/>
<source>Thumbnail View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../preferencesdialog.cpp" line="193"/>
<source>Detailed List View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::TabPage</name>
<message>
<location filename="../tabpage.cpp" line="248"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../tabpage.cpp" line="261"/>
<source>Free space: %1 (Total: %2)</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location filename="../tabpage.cpp" line="276"/>
<source>%n item(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../tabpage.cpp" line="278"/>
<source> (%n hidden)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location filename="../tabpage.cpp" line="426"/>
<source>%1 item(s) selected</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::View</name>
<message>
<location filename="../view.cpp" line="103"/>
<source>Open in New T&ab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../view.cpp" line="107"/>
<source>Open in New Win&dow</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../view.cpp" line="114"/>
<source>Open in Termina&l</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PreferencesDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="706"/>
<source>Preferences</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="715"/>
<source>User Interface</source>
<translation type="unfinished">Uživatelské rozhraní</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="711"/>
<source>Behavior</source>
<translation type="unfinished">Chování</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="717"/>
<location filename="../../build/pcmanfm/ui_preferences.h" line="779"/>
<source>Thumbnail</source>
<translation type="unfinished">Náhled</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="719"/>
<source>Volume</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="721"/>
<source>Advanced</source>
<translation type="unfinished">Pokročilé</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="742"/>
<source>Icons</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="744"/>
<source>Size of big icons:</source>
<translation type="unfinished">Velikost velkých ikon:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="745"/>
<source>Size of small icons:</source>
<translation type="unfinished">Velikost malých ikon:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="746"/>
<source>Size of thumbnails:</source>
<translation type="unfinished">Velikost náhledů:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="747"/>
<source>Size of side pane icons:</source>
<translation type="unfinished">Velikost ikon v postranním panelu:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="743"/>
<source>Icon theme:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="753"/>
<source>Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="757"/>
<source>Default width of new windows:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="758"/>
<source>Default height of new windows:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="754"/>
<source>Always show the tab bar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="755"/>
<source>Show 'Close' buttons on tabs </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="756"/>
<source>Remember the size of the last closed window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="724"/>
<source>Browsing</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="725"/>
<source>Open files with single click</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="726"/>
<source>Delay of auto-selection in single click mode (0 to disable)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="727"/>
<source>Default view mode:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="728"/>
<source> sec</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="736"/>
<source>File Operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="737"/>
<source>Confirm before deleting files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="738"/>
<source>Move deleted files to "trash bin" instead of erasing from disk.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="783"/>
<source>Show thumbnails of files</source>
<translation type="unfinished">Zobrazovat náhledy souborů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="782"/>
<source>Only show thumbnails for local files</source>
<translation type="unfinished">Zobrazovat náhlet jen u lokálních souborů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="713"/>
<source>Display</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="729"/>
<source>Bookmarks:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="732"/>
<source>Open in current tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="733"/>
<source>Open in new tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="734"/>
<source>Open in new window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="739"/>
<source>Erase files on removable media instead of "trash can" creation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="740"/>
<source>Confirm before moving files into "trash can"</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="741"/>
<source>Don't ask options on launch executable file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="748"/>
<source>User interface</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="750"/>
<source>Treat backup files as hidden</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="751"/>
<source>Always show full file names</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="752"/>
<source>Show icons of hidden files shadowed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="759"/>
<source>Show in places</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="764"/>
<source>Home</source>
<translation type="unfinished">Domů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="766"/>
<source>Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="768"/>
<source>Trash can</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="770"/>
<source>Computer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="772"/>
<source>Applications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="774"/>
<source>Devices</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="776"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="780"/>
<source>Do not generate thumbnails for image files exceeding this size:</source>
<translation type="unfinished">Negenerovat náhledy obrázků přesahujících tuto velikost:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="781"/>
<source> KB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="784"/>
<source>Auto Mount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="785"/>
<source>Mount mountable volumes automatically on program startup</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="786"/>
<source>Mount removable media automatically when they are inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="787"/>
<source>Show available options for removable media when they are inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="788"/>
<source>When removable medium unmounted:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="789"/>
<source>Close &tab containing removable medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="790"/>
<source>Chan&ge folder in the tab to home folder</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="793"/>
<source>Switch &user command:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="796"/>
<source>Archiver in&tegration:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="797"/>
<source>Templates</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="798"/>
<source>Show only user defined templates in menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="799"/>
<source>Show only one template for each MIME type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="800"/>
<source>Run default application after creation from template</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="791"/>
<source>Programs</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="792"/>
<source>Terminal emulator:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="794"/>
<source>Examples: "xterm -e %s" for terminal or "gksu %s" for switching user.
%s = the command line you want to execute with terminal or su.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="749"/>
<source>Use SI decimal prefixes instead of IEC binary prefixes</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| rbazaud/pcmanfm-qt | pcmanfm/translations/pcmanfm-qt_cs_CZ.ts | TypeScript | gpl-2.0 | 53,147 |
/*
* Copyright 2007 Sun Microsystems, Inc.
*
* This file is part of jVoiceBridge.
*
* jVoiceBridge is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation and distributed hereunder
* to you.
*
* jVoiceBridge 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/>.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied this
* code.
*/
package com.sun.mc.softphone.media.coreaudio;
import com.sun.mc.softphone.media.NativeLibUtil;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.prefs.Preferences;
import java.util.ArrayList;
import com.sun.voip.Logger;
import com.sun.mc.softphone.media.AudioServiceProvider;
import com.sun.mc.softphone.media.Microphone;
import com.sun.mc.softphone.media.Speaker;
public class CoreAudioAudioServiceProvider implements AudioServiceProvider {
private static final String CORE_AUDIO_NAME = "libMediaFramework.jnilib";
private static AudioDriver audioDriver;
private Microphone microphone;
private Speaker speaker;
public CoreAudioAudioServiceProvider() throws IOException {
Logger.println("Loading CoreAudio provider");
// load the libarary
String arch = System.getProperty("os.arch");
String nativeLibraryName = CORE_AUDIO_NAME;
Logger.println("Loading native library: " + nativeLibraryName);
NativeLibUtil.loadLibrary(getClass(), nativeLibraryName);
return;
}
public void initialize(int sampleRate, int channels,
int microphoneSampleRate, int microphoneChannels,
int microphoneBufferSize, int speakerBufferSize)
throws IOException {
shutdown(); // stop old driver if running
audioDriver = new AudioDriverMac();
audioDriver.initialize(microphoneBufferSize, speakerBufferSize);
Logger.println("Initializing audio driver to " + sampleRate
+ "/" + channels + " microphoneBufferSize " + microphoneBufferSize
+ " speakerBufferSize " + speakerBufferSize);
/*
* The speaker is always set to 2 channels.
* Resampling is done if necessary.
*
* When set to 1 channel, sound only comes
* out of 1 channel instead of 2.
*/
audioDriver.start(
sampleRate, // speaker sample rate
2, // speaker channels
2*2, // speaker bytes per packet
1, // speaker frames per packet
2*2, // speaker frame size
16, // speaker bits per channel
microphoneSampleRate,// microphone sample rate
microphoneChannels, // microphone channels,
2*microphoneChannels,// microphone bytes per packet
1, // microphone frames per packet
2*microphoneChannels,// microphone bytes per frame
16); // microphone bits per channel
initializeMicrophone(microphoneSampleRate, microphoneChannels,
microphoneBufferSize);
initializeSpeaker(sampleRate, channels, speakerBufferSize);
}
public void shutdown() {
if (audioDriver != null) {
audioDriver.stop();
audioDriver = null;
}
}
public Microphone getMicrophone() {
return microphone;
}
public String[] getMicrophoneList() {
return new String[0];
}
private void initializeMicrophone(int sampleRate, int channels,
int microphoneBufferSize) throws IOException {
microphone = new MicrophoneCoreAudioImpl(sampleRate, channels,
microphoneBufferSize, audioDriver);
}
public Speaker getSpeaker() {
return speaker;
}
public String[] getSpeakerList() {
return new String[0];
}
private void initializeSpeaker(int sampleRate, int channels,
int speakerBufferSize) throws IOException {
speaker = new SpeakerCoreAudioImpl(sampleRate, channels,
speakerBufferSize, audioDriver);
}
}
| damirkusar/jvoicebridge | softphone/src/com/sun/mc/softphone/media/coreaudio/CoreAudioAudioServiceProvider.java | Java | gpl-2.0 | 4,493 |
<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/**
* Adminhtml catalog product edit action attributes update tab block
*
* @author Magento Core Team <core@magentocommerce.com>
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab;
use Magento\Framework\Data\Form\Element\AbstractElement;
/**
* @SuppressWarnings(PHPMD.DepthOfInheritance)
*/
class Attributes extends \Magento\Catalog\Block\Adminhtml\Form implements
\Magento\Backend\Block\Widget\Tab\TabInterface
{
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $_productFactory;
/**
* @var \Magento\Catalog\Helper\Product\Edit\Action\Attribute
*/
protected $_attributeAction;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Data\FormFactory $formFactory
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param \Magento\Catalog\Helper\Product\Edit\Action\Attribute $attributeAction
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Helper\Product\Edit\Action\Attribute $attributeAction,
array $data = []
) {
$this->_attributeAction = $attributeAction;
$this->_productFactory = $productFactory;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setShowGlobalIcon(true);
}
/**
* @return void
*/
protected function _prepareForm()
{
$this->setFormExcludedFieldList(
[
'category_ids',
'gallery',
'image',
'media_gallery',
'quantity_and_stock_status',
'tier_price',
]
);
$this->_eventManager->dispatch(
'adminhtml_catalog_product_form_prepare_excluded_field_list',
['object' => $this]
);
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$fieldset = $form->addFieldset('fields', ['legend' => __('Attributes')]);
$attributes = $this->getAttributes();
/**
* Initialize product object as form property
* for using it in elements generation
*/
$form->setDataObject($this->_productFactory->create());
$this->_setFieldset($attributes, $fieldset, $this->getFormExcludedFieldList());
$form->setFieldNameSuffix('attributes');
$this->setForm($form);
}
/**
* Retrieve attributes for product mass update
*
* @return \Magento\Framework\DataObject[]
*/
public function getAttributes()
{
return $this->_attributeAction->getAttributes()->getItems();
}
/**
* Additional element types for product attributes
*
* @return array
*/
protected function _getAdditionalElementTypes()
{
return [
'price' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Price',
'weight' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight',
'image' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Image',
'boolean' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Boolean'
];
}
/**
* Custom additional element html
*
* @param AbstractElement $element
* @return string
*/
protected function _getAdditionalElementHtml($element)
{
// Add name attribute to checkboxes that correspond to multiselect elements
$nameAttributeHtml = $element->getExtType() === 'multiple' ? 'name="' . $element->getId() . '_checkbox"' : '';
$elementId = $element->getId();
$dataAttribute = "data-disable='{$elementId}'";
$dataCheckboxName = "toggle_" . "{$elementId}";
$checkboxLabel = __('Change');
$html = <<<HTML
<span class="attribute-change-checkbox">
<input type="checkbox" id="$dataCheckboxName" name="$dataCheckboxName" class="checkbox" $nameAttributeHtml onclick="toogleFieldEditMode(this, '{$elementId}')" $dataAttribute />
<label class="label" for="$dataCheckboxName">
{$checkboxLabel}
</label>
</span>
HTML;
if ($elementId === 'weight') {
$html .= <<<HTML
<script>require(['Magento_Catalog/js/product/weight-handler'], function (weightHandle) {
weightHandle.hideWeightSwitcher();
});</script>
HTML;
}
return $html;
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabLabel()
{
return __('Attributes');
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabTitle()
{
return __('Attributes');
}
/**
* @return bool
*/
public function canShowTab()
{
return true;
}
/**
* @return bool
*/
public function isHidden()
{
return false;
}
}
| FPLD/project0 | vendor/magento/module-catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php | PHP | gpl-2.0 | 5,430 |
<?php
/**
* EasyRdf
*
* LICENSE
*
* Copyright (c) 2009-2010 Nicholas J Humfrey. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author 'Nicholas J Humfrey" may be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package EasyRdf
* @copyright Copyright (c) 2009-2010 Nicholas J Humfrey
* @license http://www.opensource.org/licenses/bsd-license.php
* @version $Id: Rapper.php 98993 2011-10-05 12:20:17Z bkaempgen $
*/
/**
* Class to serialise an EasyRdf_Graph to RDF
* using the 'rapper' command line tool.
*
* Note: the built-in N-Triples serialiser is used to pass data to Rapper.
*
* @package EasyRdf
* @copyright Copyright (c) 2009-2010 Nicholas J Humfrey
* @license http://www.opensource.org/licenses/bsd-license.php
*/
class EasyRdf_Serialiser_Rapper extends EasyRdf_Serialiser_Ntriples
{
private $_rapperCmd = null;
/**
* Constructor
*
* @param string $rapperCmd Optional path to the rapper command to use.
* @return object EasyRdf_Serialiser_Rapper
*/
public function __construct($rapperCmd='rapper')
{
exec("which ".escapeshellarg($rapperCmd), $output, $retval);
if ($retval == 0) {
$this->_rapperCmd = $rapperCmd;
} else {
throw new EasyRdf_Exception(
"The command '$rapperCmd' is not available on this system."
);
}
}
/**
* Serialise an EasyRdf_Graph to the RDF format of choice.
*
* @param object EasyRdf_Graph $graph An EasyRdf_Graph object.
* @param string $format The name of the format to convert to.
* @return string The RDF in the new desired format.
*/
public function serialise($graph, $format)
{
parent::checkSerialiseParams($graph, $format);
$ntriples = parent::serialise($graph, 'ntriples');
// Open a pipe to the rapper command
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
// Hack to produce more concise RDF/XML
if ($format == 'rdfxml') $format = 'rdfxml-abbrev';
$process = proc_open(
escapeshellcmd($this->_rapperCmd).
" --quiet ".
" --input ntriples ".
" --output " . escapeshellarg($format).
" - ". 'unknown://', # FIXME: how can this be improved?
$descriptorspec, $pipes, '/tmp', null
);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// 2 => readable handle connected to child stderr
fwrite($pipes[0], $ntriples);
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[2]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$returnValue = proc_close($process);
if ($returnValue) {
throw new EasyRdf_Exception(
"Failed to convert RDF: ".$error
);
}
} else {
throw new EasyRdf_Exception(
"Failed to execute rapper command."
);
}
return $output;
}
}
// FIXME: do this automatically
EasyRdf_Format::register('dot', 'Graphviz');
EasyRdf_Format::register('json-triples', 'RDF/JSON Triples');
EasyRdf_Format::registerSerialiser('dot', 'EasyRdf_Serialiser_Rapper');
EasyRdf_Format::registerSerialiser('json-triples', 'EasyRdf_Serialiser_Rapper');
EasyRdf_Format::registerSerialiser('rdfxml', 'EasyRdf_Serialiser_Rapper');
EasyRdf_Format::registerSerialiser('turtle', 'EasyRdf_Serialiser_Rapper');
| SuriyaaKudoIsc/wikia-app-test | extensions/SemanticWebBrowser/lib/EasyRdf/Serialiser/Rapper.php | PHP | gpl-2.0 | 5,338 |
#!/usr/bin/env python3
import os
import sys
import subprocess
if os.getenv("MSYSTEM") == "MINGW32":
mingw_dir = "/mingw32"
elif os.getenv("MSYSTEM") == "MINGW64":
mingw_dir = "/mingw64"
p = subprocess.Popen([
"sh", "-c",
"cp {}/bin/{} {}".format(mingw_dir, sys.argv[1], sys.argv[2])])
sys.exit(p.wait())
| cnvogelg/fs-uae | dist/windows/clib.py | Python | gpl-2.0 | 323 |
package net.minecraft.util.text;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.util.EnumTypeAdapterFactory;
import net.minecraft.util.JsonUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public interface ITextComponent extends Iterable<ITextComponent>
{
ITextComponent setChatStyle(Style style);
Style getChatStyle();
/**
* Appends the given text to the end of this component.
*/
ITextComponent appendText(String text);
/**
* Appends the given component to the end of this one.
*/
ITextComponent appendSibling(ITextComponent component);
/**
* Gets the text of this component, without any special formatting codes added, for chat. TODO: why is this two
* different methods?
*/
String getUnformattedTextForChat();
/**
* Get the text of this component, <em>and all child components</em>, with all special formatting codes removed.
*/
String getUnformattedText();
/**
* Gets the text of this component, with formatting codes added for rendering.
*/
String getFormattedText();
List<ITextComponent> getSiblings();
/**
* Creates a copy of this component. Almost a deep copy, except the style is shallow-copied.
*/
ITextComponent createCopy();
public static class Serializer implements JsonDeserializer<ITextComponent>, JsonSerializer<ITextComponent>
{
private static final Gson GSON;
public ITextComponent deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
if (p_deserialize_1_.isJsonPrimitive())
{
return new TextComponentString(p_deserialize_1_.getAsString());
}
else if (!p_deserialize_1_.isJsonObject())
{
if (p_deserialize_1_.isJsonArray())
{
JsonArray jsonarray1 = p_deserialize_1_.getAsJsonArray();
ITextComponent itextcomponent1 = null;
for (JsonElement jsonelement : jsonarray1)
{
ITextComponent itextcomponent2 = this.deserialize(jsonelement, jsonelement.getClass(), p_deserialize_3_);
if (itextcomponent1 == null)
{
itextcomponent1 = itextcomponent2;
}
else
{
itextcomponent1.appendSibling(itextcomponent2);
}
}
return itextcomponent1;
}
else
{
throw new JsonParseException("Don\'t know how to turn " + p_deserialize_1_.toString() + " into a Component");
}
}
else
{
JsonObject jsonobject = p_deserialize_1_.getAsJsonObject();
ITextComponent itextcomponent;
if (jsonobject.has("text"))
{
itextcomponent = new TextComponentString(jsonobject.get("text").getAsString());
}
else if (jsonobject.has("translate"))
{
String s = jsonobject.get("translate").getAsString();
if (jsonobject.has("with"))
{
JsonArray jsonarray = jsonobject.getAsJsonArray("with");
Object[] aobject = new Object[jsonarray.size()];
for (int i = 0; i < aobject.length; ++i)
{
aobject[i] = this.deserialize(jsonarray.get(i), p_deserialize_2_, p_deserialize_3_);
if (aobject[i] instanceof TextComponentString)
{
TextComponentString textcomponentstring = (TextComponentString)aobject[i];
if (textcomponentstring.getChatStyle().isEmpty() && textcomponentstring.getSiblings().isEmpty())
{
aobject[i] = textcomponentstring.getChatComponentText_TextValue();
}
}
}
itextcomponent = new TextComponentTranslation(s, aobject);
}
else
{
itextcomponent = new TextComponentTranslation(s, new Object[0]);
}
}
else if (jsonobject.has("score"))
{
JsonObject jsonobject1 = jsonobject.getAsJsonObject("score");
if (!jsonobject1.has("name") || !jsonobject1.has("objective"))
{
throw new JsonParseException("A score component needs a least a name and an objective");
}
itextcomponent = new TextComponentScore(JsonUtils.getString(jsonobject1, "name"), JsonUtils.getString(jsonobject1, "objective"));
if (jsonobject1.has("value"))
{
((TextComponentScore)itextcomponent).setValue(JsonUtils.getString(jsonobject1, "value"));
}
}
else
{
if (!jsonobject.has("selector"))
{
throw new JsonParseException("Don\'t know how to turn " + p_deserialize_1_.toString() + " into a Component");
}
itextcomponent = new TextComponentSelector(JsonUtils.getString(jsonobject, "selector"));
}
if (jsonobject.has("extra"))
{
JsonArray jsonarray2 = jsonobject.getAsJsonArray("extra");
if (jsonarray2.size() <= 0)
{
throw new JsonParseException("Unexpected empty array of components");
}
for (int j = 0; j < jsonarray2.size(); ++j)
{
itextcomponent.appendSibling(this.deserialize(jsonarray2.get(j), p_deserialize_2_, p_deserialize_3_));
}
}
itextcomponent.setChatStyle((Style)p_deserialize_3_.deserialize(p_deserialize_1_, Style.class));
return itextcomponent;
}
}
private void serializeChatStyle(Style style, JsonObject object, JsonSerializationContext ctx)
{
JsonElement jsonelement = ctx.serialize(style);
if (jsonelement.isJsonObject())
{
JsonObject jsonobject = (JsonObject)jsonelement;
for (Entry<String, JsonElement> entry : jsonobject.entrySet())
{
object.add((String)entry.getKey(), (JsonElement)entry.getValue());
}
}
}
public JsonElement serialize(ITextComponent p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
JsonObject jsonobject = new JsonObject();
if (!p_serialize_1_.getChatStyle().isEmpty())
{
this.serializeChatStyle(p_serialize_1_.getChatStyle(), jsonobject, p_serialize_3_);
}
if (!p_serialize_1_.getSiblings().isEmpty())
{
JsonArray jsonarray = new JsonArray();
for (ITextComponent itextcomponent : p_serialize_1_.getSiblings())
{
jsonarray.add(this.serialize((ITextComponent)itextcomponent, itextcomponent.getClass(), p_serialize_3_));
}
jsonobject.add("extra", jsonarray);
}
if (p_serialize_1_ instanceof TextComponentString)
{
jsonobject.addProperty("text", ((TextComponentString)p_serialize_1_).getChatComponentText_TextValue());
}
else if (p_serialize_1_ instanceof TextComponentTranslation)
{
TextComponentTranslation textcomponenttranslation = (TextComponentTranslation)p_serialize_1_;
jsonobject.addProperty("translate", textcomponenttranslation.getKey());
if (textcomponenttranslation.getFormatArgs() != null && textcomponenttranslation.getFormatArgs().length > 0)
{
JsonArray jsonarray1 = new JsonArray();
for (Object object : textcomponenttranslation.getFormatArgs())
{
if (object instanceof ITextComponent)
{
jsonarray1.add(this.serialize((ITextComponent)((ITextComponent)object), object.getClass(), p_serialize_3_));
}
else
{
jsonarray1.add(new JsonPrimitive(String.valueOf(object)));
}
}
jsonobject.add("with", jsonarray1);
}
}
else if (p_serialize_1_ instanceof TextComponentScore)
{
TextComponentScore textcomponentscore = (TextComponentScore)p_serialize_1_;
JsonObject jsonobject1 = new JsonObject();
jsonobject1.addProperty("name", textcomponentscore.getName());
jsonobject1.addProperty("objective", textcomponentscore.getObjective());
jsonobject1.addProperty("value", textcomponentscore.getUnformattedTextForChat());
jsonobject.add("score", jsonobject1);
}
else
{
if (!(p_serialize_1_ instanceof TextComponentSelector))
{
throw new IllegalArgumentException("Don\'t know how to serialize " + p_serialize_1_ + " as a Component");
}
TextComponentSelector textcomponentselector = (TextComponentSelector)p_serialize_1_;
jsonobject.addProperty("selector", textcomponentselector.getSelector());
}
return jsonobject;
}
public static String componentToJson(ITextComponent component)
{
return GSON.toJson((Object)component);
}
public static ITextComponent jsonToComponent(String json)
{
return (ITextComponent)JsonUtils.gsonDeserialize(GSON, json, ITextComponent.class, false);
}
public static ITextComponent fromJsonLenient(String json)
{
return (ITextComponent)JsonUtils.gsonDeserialize(GSON, json, ITextComponent.class, true);
}
static
{
GsonBuilder gsonbuilder = new GsonBuilder();
gsonbuilder.registerTypeHierarchyAdapter(ITextComponent.class, new ITextComponent.Serializer());
gsonbuilder.registerTypeHierarchyAdapter(Style.class, new Style.Serializer());
gsonbuilder.registerTypeAdapterFactory(new EnumTypeAdapterFactory());
GSON = gsonbuilder.create();
}
}
} | aebert1/BigTransport | build/tmp/recompileMc/sources/net/minecraft/util/text/ITextComponent.java | Java | gpl-3.0 | 12,605 |
/* Refresh.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
* With the widget refresh, the visu is added a switch, which allows the visu to reload the displayed data.
*
* @author Christian Mayer
* @since 2014
*/
qx.Class.define('cv.ui.structure.pure.Refresh', {
extend: cv.ui.structure.AbstractWidget,
include: [cv.ui.common.Operate, cv.ui.common.HasAnimatedButton, cv.ui.common.BasicUpdate],
/*
******************************************************
PROPERTIES
******************************************************
*/
properties: {
sendValue: { check: "String", nullable: true }
},
/*
******************************************************
MEMBERS
******************************************************
*/
members: {
// overridden
_onDomReady: function() {
this.base(arguments);
this.defaultUpdate(undefined, this.getSendValue());
},
// overridden
_getInnerDomString: function () {
return '<div class="actor switchUnpressed"><div class="value">-</div></div>';
},
_action: function() {
cv.TemplateEngine.getInstance().visu.restart(true);
}
}
}); | robert1978/CometVisu | source/class/cv/ui/structure/pure/Refresh.js | JavaScript | gpl-3.0 | 1,913 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ContactRole'
db.create_table('base_contactrole', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('resource', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.ResourceBase'])),
('contact', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['people.Profile'])),
('role', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['people.Role'])),
))
db.send_create_signal('base', ['ContactRole'])
# Adding unique constraint on 'ContactRole', fields ['contact', 'resource', 'role']
db.create_unique('base_contactrole', ['contact_id', 'resource_id', 'role_id'])
# Adding model 'TopicCategory'
db.create_table('base_topiccategory', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=50)),
('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal('base', ['TopicCategory'])
# Adding model 'Thumbnail'
db.create_table('base_thumbnail', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('thumb_file', self.gf('django.db.models.fields.files.FileField')(max_length=100)),
('thumb_spec', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('version', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0, null=True)),
))
db.send_create_signal('base', ['Thumbnail'])
# Adding model 'ResourceBase'
db.create_table('base_resourcebase', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('uuid', self.gf('django.db.models.fields.CharField')(max_length=36)),
('owner', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('date_type', self.gf('django.db.models.fields.CharField')(default='publication', max_length=255)),
('edition', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('abstract', self.gf('django.db.models.fields.TextField')(blank=True)),
('purpose', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('maintenance_frequency', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('keywords_region', self.gf('django.db.models.fields.CharField')(default='USA', max_length=3)),
('constraints_use', self.gf('django.db.models.fields.CharField')(default='copyright', max_length=255)),
('constraints_other', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('spatial_representation_type', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('language', self.gf('django.db.models.fields.CharField')(default='eng', max_length=3)),
('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.TopicCategory'], null=True, blank=True)),
('temporal_extent_start', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
('temporal_extent_end', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
('supplemental_information', self.gf('django.db.models.fields.TextField')(default=u'No information provided')),
('distribution_url', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('distribution_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('data_quality_statement', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('bbox_x0', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('bbox_x1', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('bbox_y0', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('bbox_y1', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('srid', self.gf('django.db.models.fields.CharField')(default='EPSG:4326', max_length=255)),
('csw_typename', self.gf('django.db.models.fields.CharField')(default='gmd:MD_Metadata', max_length=32)),
('csw_schema', self.gf('django.db.models.fields.CharField')(default='http://www.isotc211.org/2005/gmd', max_length=64)),
('csw_mdsource', self.gf('django.db.models.fields.CharField')(default='local', max_length=256)),
('csw_insert_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
('csw_type', self.gf('django.db.models.fields.CharField')(default='dataset', max_length=32)),
('csw_anytext', self.gf('django.db.models.fields.TextField')(null=True)),
('csw_wkt_geometry', self.gf('django.db.models.fields.TextField')(default='SRID=4326;POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))')),
('metadata_uploaded', self.gf('django.db.models.fields.BooleanField')(default=False)),
('metadata_xml', self.gf('django.db.models.fields.TextField')(default='<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>', null=True, blank=True)),
('thumbnail', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.Thumbnail'], null=True, blank=True)),
))
db.send_create_signal('base', ['ResourceBase'])
# Adding model 'Link'
db.create_table('base_link', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('resource', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.ResourceBase'])),
('extension', self.gf('django.db.models.fields.CharField')(max_length=255)),
('link_type', self.gf('django.db.models.fields.CharField')(max_length=255)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('mime', self.gf('django.db.models.fields.CharField')(max_length=255)),
('url', self.gf('django.db.models.fields.TextField')(unique=True, max_length=1000)),
))
db.send_create_signal('base', ['Link'])
def backwards(self, orm):
# Removing unique constraint on 'ContactRole', fields ['contact', 'resource', 'role']
db.delete_unique('base_contactrole', ['contact_id', 'resource_id', 'role_id'])
# Deleting model 'ContactRole'
db.delete_table('base_contactrole')
# Deleting model 'TopicCategory'
db.delete_table('base_topiccategory')
# Deleting model 'Thumbnail'
db.delete_table('base_thumbnail')
# Deleting model 'ResourceBase'
db.delete_table('base_resourcebase')
# Deleting model 'Link'
db.delete_table('base_link')
models = {
'actstream.action': {
'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'},
'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}),
'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 384488)'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 388268)'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 388203)'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'relationships': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_to'", 'symmetrical': 'False', 'through': "orm['relationships.Relationship']", 'to': "orm['auth.User']"}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'base.contactrole': {
'Meta': {'unique_together': "(('contact', 'resource', 'role'),)", 'object_name': 'ContactRole'},
'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Profile']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.ResourceBase']"}),
'role': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Role']"})
},
'base.link': {
'Meta': {'object_name': 'Link'},
'extension': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'link_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'mime': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.ResourceBase']"}),
'url': ('django.db.models.fields.TextField', [], {'unique': 'True', 'max_length': '1000'})
},
'base.resourcebase': {
'Meta': {'object_name': 'ResourceBase'},
'abstract': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'bbox_x0': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'bbox_x1': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'bbox_y0': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'bbox_y1': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.TopicCategory']", 'null': 'True', 'blank': 'True'}),
'constraints_other': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'constraints_use': ('django.db.models.fields.CharField', [], {'default': "'copyright'", 'max_length': '255'}),
'contacts': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['people.Profile']", 'through': "orm['base.ContactRole']", 'symmetrical': 'False'}),
'csw_anytext': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'csw_insert_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'csw_mdsource': ('django.db.models.fields.CharField', [], {'default': "'local'", 'max_length': '256'}),
'csw_schema': ('django.db.models.fields.CharField', [], {'default': "'http://www.isotc211.org/2005/gmd'", 'max_length': '64'}),
'csw_type': ('django.db.models.fields.CharField', [], {'default': "'dataset'", 'max_length': '32'}),
'csw_typename': ('django.db.models.fields.CharField', [], {'default': "'gmd:MD_Metadata'", 'max_length': '32'}),
'csw_wkt_geometry': ('django.db.models.fields.TextField', [], {'default': "'SRID=4326;POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))'"}),
'data_quality_statement': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_type': ('django.db.models.fields.CharField', [], {'default': "'publication'", 'max_length': '255'}),
'distribution_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'distribution_url': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'edition': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keywords_region': ('django.db.models.fields.CharField', [], {'default': "'USA'", 'max_length': '3'}),
'language': ('django.db.models.fields.CharField', [], {'default': "'eng'", 'max_length': '3'}),
'maintenance_frequency': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'metadata_uploaded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'metadata_xml': ('django.db.models.fields.TextField', [], {'default': '\'<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>\'', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'purpose': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'spatial_representation_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'srid': ('django.db.models.fields.CharField', [], {'default': "'EPSG:4326'", 'max_length': '255'}),
'supplemental_information': ('django.db.models.fields.TextField', [], {'default': "u'No information provided'"}),
'temporal_extent_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'temporal_extent_start': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'thumbnail': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.Thumbnail']", 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36'})
},
'base.thumbnail': {
'Meta': {'object_name': 'Thumbnail'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'thumb_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'thumb_spec': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'version': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'null': 'True'})
},
'base.topiccategory': {
'Meta': {'ordering': "('name',)", 'object_name': 'TopicCategory'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'people.profile': {
'Meta': {'object_name': 'Profile'},
'area': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}),
'delivery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'organization': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'position': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'profile': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'profile'", 'unique': 'True', 'null': 'True', 'to': "orm['auth.User']"}),
'voice': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'zipcode': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'people.role': {
'Meta': {'object_name': 'Role'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'relationships.relationship': {
'Meta': {'ordering': "('created',)", 'unique_together': "(('from_user', 'to_user', 'status', 'site'),)", 'object_name': 'Relationship'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'from_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'from_users'", 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'related_name': "'relationships'", 'to': "orm['sites.Site']"}),
'status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['relationships.RelationshipStatus']"}),
'to_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'to_users'", 'to': "orm['auth.User']"}),
'weight': ('django.db.models.fields.FloatField', [], {'default': '1.0', 'null': 'True', 'blank': 'True'})
},
'relationships.relationshipstatus': {
'Meta': {'ordering': "('name',)", 'object_name': 'RelationshipStatus'},
'from_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'symmetrical_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'to_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'taggit.tag': {
'Meta': {'object_name': 'Tag'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'})
},
'taggit.taggeditem': {
'Meta': {'object_name': 'TaggedItem'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"})
}
}
complete_apps = ['base']
| dwoods/gn-maps | geonode/base/migrations/0001_initial.py | Python | gpl-3.0 | 25,336 |
/* Avuna HTTPD - General Server Applications Copyright (C) 2015 Maxwell Bruce 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.avuna.httpd.mail.imap.command;
import java.io.IOException;
import org.avuna.httpd.hosts.HostMail;
import org.avuna.httpd.mail.imap.IMAPCommand;
import org.avuna.httpd.mail.imap.IMAPWork;
import org.avuna.httpd.mail.mailbox.Mailbox;
public class IMAPCommandCreate extends IMAPCommand {
public IMAPCommandCreate(String comm, int minState, int maxState, HostMail host) {
super(comm, minState, maxState, host);
}
@Override
public void run(IMAPWork focus, String letters, String[] args) throws IOException {
if (args.length >= 1) {
String ms = args[0];
if (ms.startsWith("\"")) {
ms = ms.substring(1);
}
if (ms.endsWith("\"")) {
ms = ms.substring(0, ms.length() - 1);
}
if (focus.authUser.getMailbox(ms) != null) {
focus.writeLine(letters, "NO Mailbox Exists.");
}else {
focus.authUser.mailboxes.add(new Mailbox(focus.authUser, ms));
focus.writeLine(letters, "OK Mailbox created.");
}
}else {
focus.writeLine(letters, "BAD No mailbox.");
}
}
}
| JavaProphet/AvunaHTTPD-Java | src/org/avuna/httpd/mail/imap/command/IMAPCommandCreate.java | Java | gpl-3.0 | 1,747 |
/*
* This file is part of the dSploit.
*
* Copyleft of Simone Margaritelli aka evilsocket <evilsocket@gmail.com>
*
* dSploit 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.
*
* dSploit 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 dSploit. If not, see <http://www.gnu.org/licenses/>.
*/
package it.evilsocket.dsploit.gui.dialogs;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class ChoiceDialog extends AlertDialog
{
public interface ChoiceDialogListener
{
public void onChoice( int choice );
}
public ChoiceDialog( final Activity activity, String title, String[] choices, final ChoiceDialogListener listener ) {
super( activity );
this.setTitle( title );
LinearLayout layout = new LinearLayout( activity );
layout.setPadding( 10, 10, 10, 10 );
for( int i = 0; i < choices.length; i++ )
{
Button choice = new Button( activity );
choice.setLayoutParams( new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0.5f ) );
choice.setTag( "" + i );
choice.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
ChoiceDialog.this.dismiss();
listener.onChoice( Integer.parseInt( (String)v.getTag() ) );
}
});
choice.setText( choices[i] );
layout.addView( choice );
}
setView( layout );
this.setButton( "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
}
| zabubaev/dsploit | src/it/evilsocket/dsploit/gui/dialogs/ChoiceDialog.java | Java | gpl-3.0 | 2,193 |
<?php
/**
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Benchmark
* @author Timo Tijhof
*/
require_once __DIR__ . '/Benchmarker.php';
/**
* Maintenance script that benchmarks CSSMin.
*
* @ingroup Benchmark
*/
class BenchmarkCSSMin extends Benchmarker {
public function __construct() {
parent::__construct();
$this->addDescription( 'Benchmarks CSSMin.' );
$this->addOption( 'file', 'Path to CSS file (may be gzipped)', false, true );
$this->addOption( 'out', 'Echo output of one run to stdout for inspection', false, false );
}
public function execute() {
$file = $this->getOption( 'file', __DIR__ . '/cssmin/styles.css' );
$filename = basename( $file );
$css = $this->loadFile( $file );
if ( $this->hasOption( 'out' ) ) {
echo "## minify\n\n",
CSSMin::minify( $css ),
"\n\n";
echo "## remap\n\n",
CSSMin::remap( $css, dirname( $file ), 'https://example.org/test/', true ),
"\n";
return;
}
$this->bench( [
"minify ($filename)" => [
'function' => [ CSSMin::class, 'minify' ],
'args' => [ $css ]
],
"remap ($filename)" => [
'function' => [ CSSMin::class, 'remap' ],
'args' => [ $css, dirname( $file ), 'https://example.org/test/', true ]
],
] );
}
}
$maintClass = BenchmarkCSSMin::class;
require_once RUN_MAINTENANCE_IF_MAIN;
| kylethayer/bioladder | wiki/maintenance/benchmarks/benchmarkCSSMin.php | PHP | gpl-3.0 | 2,049 |
package org.zeromq;
import java.io.Closeable;
import java.io.IOException;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
/**
* ZeroMQ Queue Device implementation.
*
* @author Alois Belaska <alois.belaska@gmail.com>
*/
public class ZMQQueue implements Runnable, Closeable {
private final ZMQ.Poller poller;
private final ZMQ.Socket inSocket;
private final ZMQ.Socket outSocket;
/**
* Class constructor.
*
* @param context a 0MQ context previously created.
* @param inSocket input socket
* @param outSocket output socket
*/
public ZMQQueue(Context context, Socket inSocket, Socket outSocket) {
this.inSocket = inSocket;
this.outSocket = outSocket;
this.poller = context.poller(2);
this.poller.register(inSocket, ZMQ.Poller.POLLIN);
this.poller.register(outSocket, ZMQ.Poller.POLLIN);
}
/**
* Queuing of requests and replies.
*/
@Override
public void run() {
byte[] msg = null;
boolean more = true;
while (!Thread.currentThread().isInterrupted()) {
try {
// wait while there are either requests or replies to process
if (poller.poll(-1) < 0) {
break;
}
// process a request
if (poller.pollin(0)) {
more = true;
while (more) {
msg = inSocket.recv(0);
more = inSocket.hasReceiveMore();
if (msg != null) {
outSocket.send(msg, more ? ZMQ.SNDMORE : 0);
}
}
}
// process a reply
if (poller.pollin(1)) {
more = true;
while (more) {
msg = outSocket.recv(0);
more = outSocket.hasReceiveMore();
if (msg != null) {
inSocket.send(msg, more ? ZMQ.SNDMORE : 0);
}
}
}
} catch (ZMQException e) {
// context destroyed, exit
if (ZMQ.Error.ETERM.getCode() == e.getErrorCode()) {
break;
}
throw e;
}
}
}
/**
* Unregisters input and output sockets.
*/
@Override
public void close() throws IOException {
poller.unregister(this.inSocket);
poller.unregister(this.outSocket);
}
}
| aol/jzmq | src/org/zeromq/ZMQQueue.java | Java | gpl-3.0 | 2,634 |
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './ModalFooter.css';
class ModalFooter extends Component {
//
// Render
render() {
const {
children,
...otherProps
} = this.props;
return (
<div
className={styles.modalFooter}
{...otherProps}
>
{children}
</div>
);
}
}
ModalFooter.propTypes = {
children: PropTypes.node
};
export default ModalFooter;
| Radarr/Radarr | frontend/src/Components/Modal/ModalFooter.js | JavaScript | gpl-3.0 | 485 |
<?php
/**
* @file
* This file is part of the PdfParser library.
*
* @author Sébastien MALOT <sebastien@malot.fr>
* @date 2017-01-03
* @license LGPLv3
* @url <https://github.com/smalot/pdfparser>
*
* PdfParser is a pdf library written in PHP, extraction oriented.
* Copyright (C) 2017 - Sébastien MALOT <sebastien@malot.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program.
* If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
*
*/
namespace Smalot\PdfParser\Font;
use Smalot\PdfParser\Font;
/**
* Class FontType3
*
* @package Smalot\PdfParser\Font
*/
class FontType3 extends Font
{
}
| j0k3r/pdfparser | src/Smalot/PdfParser/Font/FontType3.php | PHP | gpl-3.0 | 1,227 |
package de.btu.openinfra.backend.db.rbac;
import java.util.UUID;
import de.btu.openinfra.backend.db.OpenInfraSchemas;
import de.btu.openinfra.backend.db.daos.TopicCharacteristicToAttributeTypeGroupDao;
import de.btu.openinfra.backend.db.jpa.model.AttributeTypeGroup;
import de.btu.openinfra.backend.db.jpa.model.AttributeTypeGroupToTopicCharacteristic;
import de.btu.openinfra.backend.db.jpa.model.TopicCharacteristic;
import de.btu.openinfra.backend.db.pojos.TopicCharacteristicToAttributeTypeGroupPojo;
public class TopicCharacteristicToAttributeTypeGroupRbac extends
OpenInfraValueValueRbac<TopicCharacteristicToAttributeTypeGroupPojo,
AttributeTypeGroupToTopicCharacteristic, AttributeTypeGroup,
TopicCharacteristic, TopicCharacteristicToAttributeTypeGroupDao> {
public TopicCharacteristicToAttributeTypeGroupRbac(
UUID currentProjectId,
OpenInfraSchemas schema) {
super(currentProjectId, schema, AttributeTypeGroup.class,
TopicCharacteristic.class,
TopicCharacteristicToAttributeTypeGroupDao.class);
}
}
| OpenInfRA/core | openinfra_core/src/main/java/de/btu/openinfra/backend/db/rbac/TopicCharacteristicToAttributeTypeGroupRbac.java | Java | gpl-3.0 | 1,063 |
/*
* Thresher IRC client library
* Copyright (C) 2002 Aaron Hunter <thresher@sharkbite.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 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* See the gpl.txt file located in the top-level-directory of
* the archive of this library for complete text of license.
*/
using System;
using System.Diagnostics;
using System.Globalization;
namespace Sharkbite.Irc
{
/// <summary>
/// Constants and utility methods to support CTCP.
/// </summary>
/// <remarks>The CTCP constants should be used to test incoming
/// CTCP queries for their type and as the CTCP command
/// for outgoing ones.</remarks>
public sealed class CtcpUtil
{
/// <summary>CTCP Finger.</summary>
public const string Finger = "FINGER";
/// <summary>CTCP USERINFO.</summary>
public const string UserInfo = "USERINFO";
/// <summary>CTCP VERSION.</summary>
public const string Version = "VERSION";
/// <summary>CTCP SOURCE.</summary>
public const string Source = "SOURCE";
/// <summary>CTCP CLIENTINFO.</summary>
public const string ClientInfo = "CLIENTINFO";
/// <summary>CTCP ERRMSG.</summary>
public const string ErrorMessage = "ERRMSG";
/// <summary>CTCP PING.</summary>
public const string Ping = "PING";
/// <summary>CTCP TIME.</summary>
public const string Time = "TIME";
internal static TraceSwitch CtcpTrace = new TraceSwitch("CtcpTraceSwitch", "Debug level for CTCP classes.");
//Should never be called so make it private
private CtcpUtil(){}
/// <summary>
/// Generate a timestamp string suitable for the CTCP Ping command.
/// </summary>
/// <returns>The current time as a string.</returns>
public static string CreateTimestamp()
{
return DateTime.Now.ToFileTime().ToString( CultureInfo.InvariantCulture );
}
}
}
| Dmitchell94/MCForge-Vanilla-Original | sharkbite.thresher/Ctcp/CtcpUtil.cs | C# | gpl-3.0 | 2,431 |
# encoding: UTF-8
# This file contains data derived from the IANA Time Zone Database
# (http://www.iana.org/time-zones).
module TZInfo
module Data
module Definitions
module Europe
module Minsk
include TimezoneDefinition
timezone 'Europe/Minsk' do |tz|
tz.offset :o0, 6616, 0, :LMT
tz.offset :o1, 6600, 0, :MMT
tz.offset :o2, 7200, 0, :EET
tz.offset :o3, 10800, 0, :MSK
tz.offset :o4, 3600, 3600, :CEST
tz.offset :o5, 3600, 0, :CET
tz.offset :o6, 10800, 3600, :MSD
tz.offset :o7, 7200, 3600, :EEST
tz.offset :o8, 10800, 0, :'+03'
tz.transition 1879, 12, :o1, -2840147416, 26003326573, 10800
tz.transition 1924, 5, :o2, -1441158600, 349042669, 144
tz.transition 1930, 6, :o3, -1247536800, 29113781, 12
tz.transition 1941, 6, :o4, -899780400, 19441387, 8
tz.transition 1942, 11, :o5, -857257200, 58335973, 24
tz.transition 1943, 3, :o4, -844556400, 58339501, 24
tz.transition 1943, 10, :o5, -828226800, 58344037, 24
tz.transition 1944, 4, :o4, -812502000, 58348405, 24
tz.transition 1944, 7, :o3, -804650400, 29175293, 12
tz.transition 1981, 3, :o6, 354920400
tz.transition 1981, 9, :o3, 370728000
tz.transition 1982, 3, :o6, 386456400
tz.transition 1982, 9, :o3, 402264000
tz.transition 1983, 3, :o6, 417992400
tz.transition 1983, 9, :o3, 433800000
tz.transition 1984, 3, :o6, 449614800
tz.transition 1984, 9, :o3, 465346800
tz.transition 1985, 3, :o6, 481071600
tz.transition 1985, 9, :o3, 496796400
tz.transition 1986, 3, :o6, 512521200
tz.transition 1986, 9, :o3, 528246000
tz.transition 1987, 3, :o6, 543970800
tz.transition 1987, 9, :o3, 559695600
tz.transition 1988, 3, :o6, 575420400
tz.transition 1988, 9, :o3, 591145200
tz.transition 1989, 3, :o6, 606870000
tz.transition 1989, 9, :o3, 622594800
tz.transition 1991, 3, :o7, 670374000
tz.transition 1991, 9, :o2, 686102400
tz.transition 1992, 3, :o7, 701827200
tz.transition 1992, 9, :o2, 717552000
tz.transition 1993, 3, :o7, 733276800
tz.transition 1993, 9, :o2, 749001600
tz.transition 1994, 3, :o7, 764726400
tz.transition 1994, 9, :o2, 780451200
tz.transition 1995, 3, :o7, 796176000
tz.transition 1995, 9, :o2, 811900800
tz.transition 1996, 3, :o7, 828230400
tz.transition 1996, 10, :o2, 846374400
tz.transition 1997, 3, :o7, 859680000
tz.transition 1997, 10, :o2, 877824000
tz.transition 1998, 3, :o7, 891129600
tz.transition 1998, 10, :o2, 909273600
tz.transition 1999, 3, :o7, 922579200
tz.transition 1999, 10, :o2, 941328000
tz.transition 2000, 3, :o7, 954028800
tz.transition 2000, 10, :o2, 972777600
tz.transition 2001, 3, :o7, 985478400
tz.transition 2001, 10, :o2, 1004227200
tz.transition 2002, 3, :o7, 1017532800
tz.transition 2002, 10, :o2, 1035676800
tz.transition 2003, 3, :o7, 1048982400
tz.transition 2003, 10, :o2, 1067126400
tz.transition 2004, 3, :o7, 1080432000
tz.transition 2004, 10, :o2, 1099180800
tz.transition 2005, 3, :o7, 1111881600
tz.transition 2005, 10, :o2, 1130630400
tz.transition 2006, 3, :o7, 1143331200
tz.transition 2006, 10, :o2, 1162080000
tz.transition 2007, 3, :o7, 1174780800
tz.transition 2007, 10, :o2, 1193529600
tz.transition 2008, 3, :o7, 1206835200
tz.transition 2008, 10, :o2, 1224979200
tz.transition 2009, 3, :o7, 1238284800
tz.transition 2009, 10, :o2, 1256428800
tz.transition 2010, 3, :o7, 1269734400
tz.transition 2010, 10, :o2, 1288483200
tz.transition 2011, 3, :o8, 1301184000
end
end
end
end
end
end
| somniumio/Somnium | vendor/cache/ruby/2.3.0/gems/tzinfo-data-1.2017.2/lib/tzinfo/data/definitions/Europe/Minsk.rb | Ruby | gpl-3.0 | 4,340 |
<?php
/**
* Déclarations relatives à la base de données
*
* @plugin SVP pour SPIP
* @license GPL
* @package SPIP\SVP\Pipelines
**/
/**
* Déclarer les objets éditoriaux de SVP
*
* - Dépot : table spip_depots
* - Plugin : table spip_plugins
* - Paquet : table spip_paquets
*
* @pipeline declarer_tables_objets_sql
* @param array $tables
* Description des tables
* @return array
* Description complétée des tables
*/
function svp_declarer_tables_objets_sql($tables) {
include_spip('inc/config');
// Table des depots
$tables['spip_depots'] = array(
// Base de donnees
'table_objet' => 'depots',
'type' => 'depot',
'field' => array(
"id_depot" => "bigint(21) NOT NULL",
"titre" => "text DEFAULT '' NOT NULL",
"descriptif" => "text DEFAULT '' NOT NULL",
"type" => "varchar(10) DEFAULT '' NOT NULL",
"url_serveur" => "varchar(255) DEFAULT '' NOT NULL",
// url du serveur svn ou git
"url_brouteur" => "varchar(255) DEFAULT '' NOT NULL",
// url de l'interface de gestion du repository (trac, redmine...)
"url_archives" => "varchar(255) DEFAULT '' NOT NULL",
// url de base des zips
"url_commits" => "varchar(255) DEFAULT '' NOT NULL",
// url du flux rss des commits du serveur svn ou git
"xml_paquets" => "varchar(255) DEFAULT '' NOT NULL",
// chemin complet du fichier xml du depot
"sha_paquets" => "varchar(40) DEFAULT '' NOT NULL",
"nbr_paquets" => "integer DEFAULT 0 NOT NULL",
"nbr_plugins" => "integer DEFAULT 0 NOT NULL",
"nbr_autres" => "integer DEFAULT 0 NOT NULL",
// autres contributions, non plugin
"maj" => "timestamp"
),
'key' => array(
"PRIMARY KEY" => "id_depot"
),
'tables_jointures' => array('id_plugin' => 'depots_plugins'),
'principale' => 'oui',
// Titre, date et gestion du statut
'titre' => "titre, '' AS lang",
// Edition, affichage et recherche
'page' => 'depot',
'url_voir' => 'depot',
'url_edit' => 'depot_edit',
'editable' => lire_config('svp/depot_editable', 'non'),
'champs_editables' => array('titre', 'descriptif'),
'icone_objet' => 'depot',
// Textes standard
'texte_retour' => 'icone_retour',
'texte_modifier' => 'svp:bouton_modifier_depot',
'texte_creer' => '',
'texte_creer_associer' => '',
'texte_signale_edition' => '',
'texte_objet' => 'svp:titre_depot',
'texte_objets' => 'svp:titre_depots',
'info_aucun_objet' => 'svp:info_aucun_depot',
'info_1_objet' => 'svp:info_1_depot',
'info_nb_objets' => 'svp:info_nb_depots',
'texte_logo_objet' => 'svp:titre_logo_depot',
);
// Table des plugins
$tables['spip_plugins'] = array(
// Base de donnees
'table_objet' => 'plugins',
'type' => 'plugin',
'field' => array(
"id_plugin" => "bigint(21) NOT NULL",
"prefixe" => "varchar(30) DEFAULT '' NOT NULL",
"nom" => "text DEFAULT '' NOT NULL",
"slogan" => "text DEFAULT '' NOT NULL",
"categorie" => "varchar(100) DEFAULT '' NOT NULL",
"tags" => "text DEFAULT '' NOT NULL",
"vmax" => "varchar(24) DEFAULT '' NOT NULL", // version la plus elevee des paquets du plugin
"date_crea" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // la plus ancienne des paquets du plugin
"date_modif" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // la plus recente des paquets du plugin
"compatibilite_spip" => "varchar(24) DEFAULT '' NOT NULL", // union des intervalles des paquets du plugin
"branches_spip" => "varchar(255) DEFAULT '' NOT NULL"
), // union des branches spip supportees par les paquets du plugin
'key' => array(
"PRIMARY KEY" => "id_plugin",
"KEY prefixe" => "prefixe"
),
'tables_jointures' => array('id_depot' => 'depots_plugins'),
'principale' => 'oui',
// Titre, date et gestion du statut
'titre' => "prefixe AS titre, '' AS lang",
// Edition, affichage et recherche
'page' => 'plugin',
'url_voir' => 'plugin',
'editable' => 'non',
'champs_editables' => array(),
'rechercher_champs' => array('prefixe' => 8, 'nom' => 8, 'slogan' => 4),
'rechercher_jointures' => array('paquet' => array('auteur' => 8, 'description' => 2)),
'icone_objet' => 'plugin',
// Textes standard
'texte_retour' => 'icone_retour',
'texte_modifier' => '',
'texte_creer' => '',
'texte_creer_associer' => '',
'texte_signale_edition' => '',
'texte_objet' => 'svp:titre_plugin',
'texte_objets' => 'svp:titre_plugins',
'info_aucun_objet' => 'svp:info_aucun_plugin',
'info_1_objet' => 'svp:info_1_plugin',
'info_nb_objets' => 'svp:info_nb_plugins',
'texte_logo_objet' => 'svp:titre_logo_plugin',
);
$tables['spip_paquets'] = array(
// Base de donnees
'table_objet' => 'paquets',
'type' => 'paquet',
'field' => array(
"id_paquet" => "bigint(21) NOT NULL",
"id_plugin" => "bigint(21) NOT NULL",
"prefixe" => "varchar(30) DEFAULT '' NOT NULL",
"logo" => "varchar(255) DEFAULT '' NOT NULL",
// chemin du logo depuis la racine du plugin
"version" => "varchar(24) DEFAULT '' NOT NULL",
"version_base" => "varchar(24) DEFAULT '' NOT NULL",
"compatibilite_spip" => "varchar(24) DEFAULT '' NOT NULL",
"branches_spip" => "varchar(255) DEFAULT '' NOT NULL",
// branches spip supportees (cf meta)
"description" => "text DEFAULT '' NOT NULL",
"auteur" => "text DEFAULT '' NOT NULL",
"credit" => "text DEFAULT '' NOT NULL",
"licence" => "text DEFAULT '' NOT NULL",
"copyright" => "text DEFAULT '' NOT NULL",
"lien_doc" => "text DEFAULT '' NOT NULL",
// lien vers la documentation
"lien_demo" => "text DEFAULT '' NOT NULL",
// lien vers le site de demo
"lien_dev" => "text DEFAULT '' NOT NULL",
// lien vers le site de dev
"etat" => "varchar(16) DEFAULT '' NOT NULL",
"etatnum" => "int(1) DEFAULT 0 NOT NULL",
// 0 aucune indication - 1 exp - 2 dev - 3 test - 4 stable
"dependances" => "text DEFAULT '' NOT NULL",
"procure" => "text DEFAULT '' NOT NULL",
"date_crea" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
"date_modif" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
"id_depot" => "bigint(21) DEFAULT 0 NOT NULL",
// 0 pour un paquet local
"nom_archive" => "VARCHAR(255) DEFAULT '' NOT NULL",
// nom du zip du paquet, depuis l'adresse de la zone
"nbo_archive" => "integer DEFAULT 0 NOT NULL",
// taille de l'archive en octets
"maj_archive" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
// date de mise a jour de l'archive
"src_archive" => "VARCHAR(255) DEFAULT '' NOT NULL",
// source de l'archive sur le depot
"traductions" => "text DEFAULT '' NOT NULL",
// tableau serialise par module des langues traduites et de leurs traducteurs
"actif" => "varchar(3) DEFAULT 'non' NOT NULL",
// est actif ? oui / non
"installe" => "varchar(3) DEFAULT 'non' NOT NULL",
// est desinstallable ? oui / non
"recent" => "int(2) DEFAULT 0 NOT NULL",
// a ete utilise recemment ? > 0 : oui
"maj_version" => "VARCHAR(255) DEFAULT '' NOT NULL",
// version superieure existante (mise a jour possible)
"superieur" => "varchar(3) DEFAULT 'non' NOT NULL",
// superieur : version plus recente disponible (distant) d'un plugin (actif?) existant
"obsolete" => "varchar(3) DEFAULT 'non' NOT NULL",
// obsolete : version plus ancienne (locale) disponible d'un plugin local existant
"attente" => "varchar(3) DEFAULT 'non' NOT NULL",
// attente : plugin semi actif (il etait actif, mais il lui manque maintenant une dependance : il reste coche actif jusqu'a resolution ou desactivation manuelle)
"constante" => "VARCHAR(30) DEFAULT '' NOT NULL",
// nom de la constante _DIR_(PLUGINS|EXTENSIONS|PLUGINS_SUPP)
"signature" => "VARCHAR(32) DEFAULT '' NOT NULL"
), // hash MD5 d'un paquet
'key' => array(
"PRIMARY KEY" => "id_paquet",
"KEY id_plugin" => "id_plugin"
),
'join' => array(
"id_paquet" => "id_paquet",
"id_plugin" => "id_plugin"
),
'principale' => 'oui',
// Titre, date et gestion du statut
'titre' => "nom_archive AS titre, '' AS lang",
// Edition, affichage et recherche
'page' => 'paquet',
'url_voir' => '',
'editable' => 'non',
'champs_editables' => array(),
'rechercher_champs' => array(),
'rechercher_jointures' => array(),
'icone_objet' => 'paquet',
// Textes standard
'texte_retour' => '',
'texte_modifier' => '',
'texte_creer' => '',
'texte_creer_associer' => '',
'texte_signale_edition' => '',
'texte_objet' => 'svp:titre_paquet',
'texte_objets' => 'svp:titre_paquets',
'info_aucun_objet' => 'svp:info_aucun_paquet',
'info_1_objet' => 'svp:info_1_paquet',
'info_nb_objets' => 'svp:info_nb_paquets',
'texte_logo_objet' => '',
);
return $tables;
}
/**
* Déclarer les tables de liaisons de SVP
*
* Déclare la table spip_depots_plugins
*
* @pipeline declarer_tables_auxiliaires
* @param array $tables_auxiliaires
* Description des tables auxiliaires
* @return array
* Description complétée des tables auxiliaires
*/
function svp_declarer_tables_auxiliaires($tables_auxiliaires) {
// Tables de liens entre plugins et depots : spip_depots_plugins
$spip_depots_plugins = array(
"id_depot" => "bigint(21) NOT NULL",
"id_plugin" => "bigint(21) NOT NULL"
);
$spip_depots_plugins_key = array(
"PRIMARY KEY" => "id_depot, id_plugin"
);
$tables_auxiliaires['spip_depots_plugins'] =
array('field' => &$spip_depots_plugins, 'key' => &$spip_depots_plugins_key);
return $tables_auxiliaires;
}
/**
* Déclare les alias de boucle et traitements automatiques de certaines balises
*
* @pipeline declarer_tables_interfaces
* @param array $interface
* Déclarations d'interface pour le compilateur
* @return array
* Déclarations d'interface pour le compilateur
*/
function svp_declarer_tables_interfaces($interface) {
// Les tables : permet d'appeler une boucle avec le *type* de la table uniquement
$interface['table_des_tables']['depots'] = 'depots';
$interface['table_des_tables']['plugins'] = 'plugins';
$interface['table_des_tables']['paquets'] = 'paquets';
$interface['table_des_tables']['depots_plugins'] = 'depots_plugins';
// Les traitements
// - table spip_plugins
$interface['table_des_traitements']['SLOGAN']['plugins'] = _TRAITEMENT_RACCOURCIS;
$interface['table_des_traitements']['VMAX']['plugins'] = 'denormaliser_version(%s)';
// - table spip_paquets
$interface['table_des_traitements']['DESCRIPTION']['paquets'] = _TRAITEMENT_RACCOURCIS;
$interface['table_des_traitements']['VERSION']['paquets'] = 'denormaliser_version(%s)';
$interface['table_des_traitements']['MAJ_VERSION']['paquets'] = 'denormaliser_version(%s)';
return $interface;
}
| ernestovi/ups | spip/plugins-dist/svp/base/svp_declarer.php | PHP | gpl-3.0 | 10,636 |
#include <stdio.h>
#include "license_hash.hh"
#ifdef DMALLOC
#include <dmalloc.h>
#endif
#define STRLONG 4096
int main(int argc, const char* argv[])
{
char license[STRLONG];
if (argc > 1)
{
if (GenerateTempKey(license, 4096, argv[1]) == 0)
printf("%s", license);
}
else
{
printf("Usage: %s <hardware ID>\n", argv[0]);
}
return 0;
}
| Zengwn/ViewTouch-POS-System | main/temphash.cc | C++ | gpl-3.0 | 401 |
<?php
/* Copyright (C) 2002-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2004 Eric Seigne <eric.seigne@ryxeo.com>
* Copyright (C) 2003 Brian Fraval <brian@fraval.org>
* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
* Copyright (C) 2005-2016 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2008 Patrick Raguin <patrick.raguin@auguria.net>
* Copyright (C) 2010-2014 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro>
* Copyright (C) 2013 Alexandre Spangaro <aspangaro.dolibarr@gmail.com>
* Copyright (C) 2013 Peter Fontaine <contact@peterfontaine.fr>
* Copyright (C) 2014-2015 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.fr>
*
* 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/>.
*/
/**
* \file htdocs/societe/class/societe.class.php
* \ingroup societe
* \brief File for third party class
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
/**
* Class to manage third parties objects (customers, suppliers, prospects...)
*/
class Societe extends CommonObject
{
public $element='societe';
public $table_element = 'societe';
public $fk_element='fk_soc';
protected $childtables=array("supplier_proposal","propal","commande","facture","contrat","facture_fourn","commande_fournisseur","projet","expedition"); // To test if we can delete object
/**
* 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
* @var int
*/
protected $ismultientitymanaged = 1;
public $entity;
/**
* Thirdparty name
* @var string
* @deprecated Use $name instead
* @see name
*/
public $nom;
/**
* Alias names (commercial, trademark or alias names)
* @var string
*/
public $name_alias;
public $particulier;
public $address;
public $zip;
public $town;
/**
* Thirdparty status : 0=activity ceased, 1= in activity
* @var int
*/
var $status;
/**
* Id of department
* @var int
*/
var $state_id;
var $state_code;
var $state;
/**
* State code
* @var string
* @deprecated Use state_code instead
* @see state_code
*/
var $departement_code;
/**
* @var string
* @deprecated Use state instead
* @see state
*/
var $departement;
/**
* @var string
* @deprecated Use country instead
* @see country
*/
var $pays;
/**
* Phone number
* @var string
*/
var $phone;
/**
* Fax number
* @var string
*/
var $fax;
/**
* Email
* @var string
*/
var $email;
/**
* Skype username
* @var string
*/
var $skype;
/**
* Webpage
* @var string
*/
var $url;
//! barcode
/**
* Barcode value
* @var string
*/
var $barcode;
// 6 professional id (usage depends on country)
/**
* Professional ID 1 (Ex: Siren in France)
* @var string
*/
var $idprof1;
/**
* Professional ID 2 (Ex: Siret in France)
* @var string
*/
var $idprof2;
/**
* Professional ID 3 (Ex: Ape in France)
* @var string
*/
var $idprof3;
/**
* Professional ID 4 (Ex: RCS in France)
* @var string
*/
var $idprof4;
/**
* Professional ID 5
* @var string
*/
var $idprof5;
/**
* Professional ID 6
* @var string
*/
var $idprof6;
var $prefix_comm;
var $tva_assuj;
/**
* Intracommunitary VAT ID
* @var string
*/
var $tva_intra;
// Local taxes
var $localtax1_assuj;
var $localtax1_value;
var $localtax2_assuj;
var $localtax2_value;
var $managers;
var $capital;
var $typent_id;
var $typent_code;
var $effectif;
var $effectif_id;
var $forme_juridique_code;
var $forme_juridique;
var $remise_percent;
var $mode_reglement_supplier_id;
var $cond_reglement_supplier_id;
var $fk_prospectlevel;
var $name_bis;
//Log data
/**
* Date of last update
* @var string
*/
var $date_modification;
/**
* User that made last update
* @var string
*/
var $user_modification;
/**
* Date of creation
* @var string
*/
var $date_creation;
/**
* User that created the thirdparty
* @var User
*/
var $user_creation;
var $specimen;
/**
* 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
* @var int
*/
var $client;
/**
* 0=no prospect, 1=prospect
* @var int
*/
var $prospect;
/**
* 0=no supplier, 1=supplier
* @var int
*/
var $fournisseur;
/**
* Client code. E.g: CU2014-003
* @var string
*/
var $code_client;
/**
* Supplier code. E.g: SU2014-003
* @var string
*/
var $code_fournisseur;
/**
* Accounting code for client
* @var string
*/
var $code_compta;
/**
* Accounting code for suppliers
* @var string
*/
var $code_compta_fournisseur;
/**
* @var string
* @deprecated Note is split in public and private notes
* @see note_public, note_private
*/
var $note;
/**
* Private note
* @var string
*/
var $note_private;
/**
* Public note
* @var string
*/
var $note_public;
//! code statut prospect
var $stcomm_id;
var $statut_commercial;
/**
* Assigned price level
* @var int
*/
var $price_level;
var $outstanding_limit;
/**
* Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
* @var int
*/
var $commercial_id;
/**
* Id of parent thirdparty (if one)
* @var int
*/
var $parent;
/**
* Default language code of thirdparty (en_US, ...)
* @var string
*/
var $default_lang;
var $ref;
var $ref_int;
/**
* External user reference.
* This is to allow external systems to store their id and make self-developed synchronizing functions easier to
* build.
* @var string
*/
var $ref_ext;
/**
* Import key.
* Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
* to an import process
* @var string
*/
var $import_key;
/**
* Supplier WebServices URL
* @var string
*/
var $webservices_url;
/**
* Supplier WebServices Key
* @var string
*/
var $webservices_key;
var $logo;
var $logo_small;
var $logo_mini;
var $array_options;
// Incoterms
var $fk_incoterms;
var $location_incoterms;
var $libelle_incoterms; //Used into tooltip
// Multicurrency
var $fk_multicurrency;
var $multicurrency_code;
/**
* To contains a clone of this when we need to save old properties of object
* @var Societe
*/
var $oldcopy;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
$this->client = 0;
$this->prospect = 0;
$this->fournisseur = 0;
$this->typent_id = 0;
$this->effectif_id = 0;
$this->forme_juridique_code = 0;
$this->tva_assuj = 1;
$this->status = 1;
return 1;
}
/**
* Create third party in database
*
* @param User $user Object of user that ask creation
* @return int >= 0 if OK, < 0 if KO
*/
function create($user)
{
global $langs,$conf;
$error=0;
// Clean parameters
if (empty($this->status)) $this->status=0;
$this->name=$this->name?trim($this->name):trim($this->nom);
if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
$this->nom=$this->name; // For backward compatibility
if (empty($this->client)) $this->client=0;
if (empty($this->fournisseur)) $this->fournisseur=0;
$this->import_key = trim($this->import_key);
if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
if (empty($this->fk_multicurrency))
{
$this->multicurrency_code = '';
$this->fk_multicurrency = 0;
}
dol_syslog(get_class($this)."::create ".$this->name);
// Check parameters
if (! empty($conf->global->SOCIETE_MAIL_REQUIRED) && ! isValidEMail($this->email))
{
$langs->load("errors");
$this->error = $langs->trans("ErrorBadEMail",$this->email);
return -1;
}
$now=dol_now();
$this->db->begin();
// For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
if ($this->code_client == -1) $this->get_codeclient($this,0);
if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
// Check more parameters
// If error, this->errors[] is filled
$result = $this->verify();
if ($result >= 0)
{
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
$sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'";
$sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
$sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
$sql.= ", ".$this->status;
$sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
$sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
$sql.= ", 0";
$sql.= ", ".(int) $this->fk_incoterms;
$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
$sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
$sql.= ", ".(int) $this->fk_multicurrency;
$sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
dol_syslog(get_class($this)."::create", LOG_DEBUG);
$result=$this->db->query($sql);
if ($result)
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
$ret = $this->update($this->id,$user,0,1,1,'add');
// Ajout du commercial affecte
if ($this->commercial_id != '' && $this->commercial_id != -1)
{
$this->add_commercial($user, $this->commercial_id);
}
// si un commercial cree un client il lui est affecte automatiquement
else if (empty($user->rights->societe->client->voir))
{
$this->add_commercial($user, $user->id);
}
if ($ret >= 0)
{
// Call trigger
$result=$this->call_trigger('COMPANY_CREATE',$user);
if ($result < 0) $error++;
// End call triggers
}
else $error++;
if (! $error)
{
dol_syslog(get_class($this)."::Create success id=".$this->id);
$this->db->commit();
return $this->id;
}
else
{
dol_syslog(get_class($this)."::Create echec update ".$this->error, LOG_ERR);
$this->db->rollback();
return -3;
}
}
else
{
if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
{
$this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);
$result=-1;
}
else
{
$this->error=$this->db->lasterror();
$result=-2;
}
$this->db->rollback();
return $result;
}
}
else
{
$this->db->rollback();
dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
return -3;
}
}
/**
* Create a contact/address from thirdparty
*
* @param User $user Object user
* @return int <0 if KO, >0 if OK
*/
function create_individual(User $user)
{
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
$contact=new Contact($this->db);
$contact->name = $this->name_bis;
$contact->firstname = $this->firstname;
$contact->civility_id = $this->civility_id;
$contact->socid = $this->id; // fk_soc
$contact->statut = 1;
$contact->priv = 0;
$contact->country_id = $this->country_id;
$contact->state_id = $this->state_id;
$contact->address = $this->address;
$contact->email = $this->email;
$contact->zip = $this->zip;
$contact->town = $this->town;
$contact->phone_pro = $this->phone;
$result = $contact->create($user);
if ($result < 0)
{
$this->error = $contact->error;
$this->errors = $contact->errors;
dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
}
return $result;
}
/**
* Check properties of third party are ok (like name, third party codes, ...)
* Used before an add or update.
*
* @return int 0 if OK, <0 if KO
*/
function verify()
{
$this->errors=array();
$result = 0;
$this->name = trim($this->name);
$this->nom=$this->name; // For backward compatibility
if (! $this->name)
{
$this->errors[] = 'ErrorBadThirdPartyName';
$result = -2;
}
if ($this->client)
{
$rescode = $this->check_codeclient();
if ($rescode <> 0)
{
if ($rescode == -1)
{
$this->errors[] = 'ErrorBadCustomerCodeSyntax';
}
if ($rescode == -2)
{
$this->errors[] = 'ErrorCustomerCodeRequired';
}
if ($rescode == -3)
{
$this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
}
if ($rescode == -4)
{
$this->errors[] = 'ErrorPrefixRequired';
}
$result = -3;
}
}
if ($this->fournisseur)
{
$rescode = $this->check_codefournisseur();
if ($rescode <> 0)
{
if ($rescode == -1)
{
$this->errors[] = 'ErrorBadSupplierCodeSyntax';
}
if ($rescode == -2)
{
$this->errors[] = 'ErrorSupplierCodeRequired';
}
if ($rescode == -3)
{
$this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
}
if ($rescode == -5)
{
$this->errors[] = 'ErrorprefixRequired';
}
$result = -3;
}
}
return $result;
}
/**
* Update parameters of third party
*
* @param int $id id societe
* @param User $user Utilisateur qui demande la mise a jour
* @param int $call_trigger 0=non, 1=oui
* @param int $allowmodcodeclient Inclut modif code client et code compta
* @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur
* @param string $action 'add' or 'update'
* @param int $nosyncmember Do not synchronize info of linked member
* @return int <0 if KO, >=0 if OK
*/
function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
{
global $langs,$conf,$hookmanager;
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$error=0;
dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
$now=dol_now();
// Clean parameters
$this->id = $id;
$this->name = $this->name?trim($this->name):trim($this->nom);
$this->nom = $this->name; // For backward compatibility
$this->name_alias = trim($this->name_alias);
$this->ref_ext = trim($this->ref_ext);
$this->address = $this->address?trim($this->address):trim($this->address);
$this->zip = $this->zip?trim($this->zip):trim($this->zip);
$this->town = $this->town?trim($this->town):trim($this->town);
$this->state_id = trim($this->state_id);
$this->country_id = ($this->country_id > 0)?$this->country_id:0;
$this->phone = trim($this->phone);
$this->phone = preg_replace("/\s/","",$this->phone);
$this->phone = preg_replace("/\./","",$this->phone);
$this->fax = trim($this->fax);
$this->fax = preg_replace("/\s/","",$this->fax);
$this->fax = preg_replace("/\./","",$this->fax);
$this->email = trim($this->email);
$this->skype = trim($this->skype);
$this->url = $this->url?clean_url($this->url,0):'';
$this->idprof1 = trim($this->idprof1);
$this->idprof2 = trim($this->idprof2);
$this->idprof3 = trim($this->idprof3);
$this->idprof4 = trim($this->idprof4);
$this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):'');
$this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):'');
$this->prefix_comm = trim($this->prefix_comm);
$this->outstanding_limit = price2num($this->outstanding_limit);
$this->tva_assuj = trim($this->tva_assuj);
$this->tva_intra = dol_sanitizeFileName($this->tva_intra,'');
if (empty($this->status)) $this->status = 0;
if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
if (empty($this->fk_multicurrency))
{
$this->multicurrency_code = '';
$this->fk_multicurrency = 0;
}
// Local taxes
$this->localtax1_assuj=trim($this->localtax1_assuj);
$this->localtax2_assuj=trim($this->localtax2_assuj);
$this->localtax1_value=trim($this->localtax1_value);
$this->localtax2_value=trim($this->localtax2_value);
if ($this->capital != '') $this->capital=price2num(trim($this->capital));
if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef
$this->effectif_id=trim($this->effectif_id);
$this->forme_juridique_code=trim($this->forme_juridique_code);
//Gencod
$this->barcode=trim($this->barcode);
// For automatic creation
if ($this->code_client == -1) $this->get_codeclient($this,0);
if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
$this->code_compta=trim($this->code_compta);
$this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
// Check parameters
if (! empty($conf->global->SOCIETE_MAIL_REQUIRED) && ! isValidEMail($this->email))
{
$langs->load("errors");
$this->error = $langs->trans("ErrorBadEMail",$this->email);
return -1;
}
if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
{
$langs->load("errors");
$this->error = $langs->trans("BadValueForParameterClientOrSupplier");
return -1;
}
$customer=false;
if (! empty($allowmodcodeclient) && ! empty($this->client))
{
// Attention get_codecompta peut modifier le code suivant le module utilise
if (empty($this->code_compta))
{
$ret=$this->get_codecompta('customer');
if ($ret < 0) return -1;
}
$customer=true;
}
$supplier=false;
if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
{
// Attention get_codecompta peut modifier le code suivant le module utilise
if (empty($this->code_compta_fournisseur))
{
$ret=$this->get_codecompta('supplier');
if ($ret < 0) return -1;
}
$supplier=true;
}
//Web services
$this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
$this->webservices_key = trim($this->webservices_key);
//Incoterms
$this->fk_incoterms = (int) $this->fk_incoterms;
$this->location_incoterms = trim($this->location_incoterms);
$this->db->begin();
// Check name is required and codes are ok or unique.
// If error, this->errors[] is filled
$result = 0;
if ($action != 'add') $result = $this->verify(); // We don't check when update called during a create because verify was already done
if ($result >= 0)
{
dol_syslog(get_class($this)."::update verify ok or not done");
$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
$sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
$sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
$sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
$sql .= ",address = '" . $this->db->escape($this->address) ."'";
$sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
$sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
$sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
$sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
$sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
$sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
$sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
$sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
$sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
$sql .= ",siren = '". $this->db->escape($this->idprof1) ."'";
$sql .= ",siret = '". $this->db->escape($this->idprof2) ."'";
$sql .= ",ape = '". $this->db->escape($this->idprof3) ."'";
$sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
$sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
$sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
$sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->tva_assuj."'":"null");
$sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
$sql .= ",status = " .$this->status;
// Local taxes
$sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->localtax1_assuj."'":"null");
$sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->localtax2_assuj."'":"null");
if($this->localtax1_assuj==1)
{
if($this->localtax1_value!='')
{
$sql .=",localtax1_value =".$this->localtax1_value;
}
else $sql .=",localtax1_value =0.000";
}
else $sql .=",localtax1_value =0.000";
if($this->localtax2_assuj==1)
{
if($this->localtax2_value!='')
{
$sql .=",localtax2_value =".$this->localtax2_value;
}
else $sql .=",localtax2_value =0.000";
}
else $sql .=",localtax2_value =0.000";
$sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
$sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
$sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
if (isset($this->stcomm_id))
{
$sql .= ",fk_stcomm='".$this->stcomm_id."'";
}
$sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
$sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
$sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
$sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
$sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
$sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
$sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
$sql .= ",client = " . (! empty($this->client)?$this->client:0);
$sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
$sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
$sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
$sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
$sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
$sql .= ",fk_prospectlevel='".$this->fk_prospectlevel."'";
$sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
$sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
//Incoterms
$sql.= ", fk_incoterms = ".$this->fk_incoterms;
$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
if ($customer)
{
$sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
$sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
}
if ($supplier)
{
$sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
$sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
}
$sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
$sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'";
$sql .= " WHERE rowid = '" . $id ."'";
dol_syslog(get_class($this)."::Update", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
unset($this->country_code); // We clean this because it may have been changed after an update of country_id
unset($this->country);
unset($this->state_code);
unset($this->state);
$nbrowsaffected = $this->db->affected_rows($resql);
if (! $error && $nbrowsaffected)
{
// Update information on linked member if it is an update
if (! $nosyncmember && ! empty($conf->adherent->enabled))
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
dol_syslog(get_class($this)."::update update linked member");
$lmember=new Adherent($this->db);
$result=$lmember->fetch(0, 0, $this->id);
if ($result > 0)
{
$lmember->societe=$this->name;
//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
$lmember->address=$this->address;
$lmember->email=$this->email;
$lmember->skype=$this->skype;
$lmember->phone=$this->phone;
$result=$lmember->update($user,0,1,1,1); // Use nosync to 1 to avoid cyclic updates
if ($result < 0)
{
$this->error=$lmember->error;
dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
$error++;
}
}
else if ($result < 0)
{
$this->error=$lmember->error;
$error++;
}
}
}
$action='update';
// Actions on extra fields (by external module or standard code)
// TODO le hook fait double emploi avec le trigger !!
$hookmanager->initHooks(array('thirdpartydao'));
$parameters=array('socid'=>$this->id);
$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if (empty($reshook))
{
if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
{
$result=$this->insertExtraFields();
if ($result < 0)
{
$error++;
}
}
}
else if ($reshook < 0) $error++;
if (! $error && $call_trigger)
{
// Call trigger
$result=$this->call_trigger('COMPANY_MODIFY',$user);
if ($result < 0) $error++;
// End call triggers
}
if (! $error)
{
dol_syslog(get_class($this)."::Update success");
$this->db->commit();
return 1;
}
else
{
$this->db->rollback();
return -1;
}
}
else
{
if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
{
// Doublon
$this->error = $langs->trans("ErrorDuplicateField");
$result = -1;
}
else
{
$result = -2;
}
$this->db->rollback();
return $result;
}
}
else
{
$this->db->rollback();
dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
return -3;
}
}
/**
* Load a third party from database into memory
*
* @param int $rowid Id of third party to load
* @param string $ref Reference of third party, name (Warning, this can return several records)
* @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
* @param string $ref_int Internal reference of third party
* @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
* @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
* @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
* @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
* @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
* @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
* @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
*/
function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='')
{
global $langs;
global $conf;
if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6)) return -1;
$sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
$sql .= ', s.status';
$sql .= ', s.price_level';
$sql .= ', s.tms as date_modification';
$sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
$sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
$sql .= ', s.capital, s.tva_intra';
$sql .= ', s.fk_typent as typent_id';
$sql .= ', s.fk_effectif as effectif_id';
$sql .= ', s.fk_forme_juridique as forme_juridique_code';
$sql .= ', s.webservices_url, s.webservices_key';
$sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
$sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
$sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
$sql .= ', s.fk_shipping_method';
$sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
$sql .= ', s.fk_multicurrency, s.multicurrency_code';
$sql .= ', fj.libelle as forme_juridique';
$sql .= ', e.libelle as effectif';
$sql .= ', c.code as country_code, c.label as country';
$sql .= ', d.code_departement as state_code, d.nom as state';
$sql .= ', st.libelle as stcomm';
$sql .= ', te.code as typent_code';
$sql .= ', i.libelle as libelle_incoterms';
$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
if ($rowid) $sql .= ' WHERE s.rowid = '.$rowid;
else if ($ref) $sql .= " WHERE s.nom = '".$this->db->escape($ref)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($ref_ext) $sql .= " WHERE s.ref_ext = '".$this->db->escape($ref_ext)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($ref_int) $sql .= " WHERE s.ref_int = '".$this->db->escape($ref_int)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof1) $sql .= " WHERE s.siren = '".$this->db->escape($idprof1)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof2) $sql .= " WHERE s.siret = '".$this->db->escape($idprof2)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof3) $sql .= " WHERE s.ape = '".$this->db->escape($idprof3)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof4) $sql .= " WHERE s.idprof4 = '".$this->db->escape($idprof4)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof5) $sql .= " WHERE s.idprof5 = '".$this->db->escape($idprof5)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof6) $sql .= " WHERE s.idprof6 = '".$this->db->escape($idprof6)."' AND s.entity IN (".getEntity($this->element, 1).")";
$resql=$this->db->query($sql);
dol_syslog(get_class($this)."::fetch ".$sql);
if ($resql)
{
$num=$this->db->num_rows($resql);
if ($num > 1)
{
$this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
dol_syslog($this->error, LOG_ERR);
$result = -2;
}
elseif ($num) // $num = 1
{
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->entity = $obj->entity;
$this->canvas = $obj->canvas;
$this->ref = $obj->rowid;
$this->name = $obj->name;
$this->nom = $obj->name; // deprecated
$this->name_alias = $obj->name_alias;
$this->ref_ext = $obj->ref_ext;
$this->ref_int = $obj->ref_int;
$this->date_creation = $this->db->jdate($obj->date_creation);
$this->date_modification = $this->db->jdate($obj->date_modification);
$this->address = $obj->address;
$this->zip = $obj->zip;
$this->town = $obj->town;
$this->country_id = $obj->country_id;
$this->country_code = $obj->country_id?$obj->country_code:'';
$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
$this->state_id = $obj->fk_departement;
$this->state_code = $obj->state_code;
$this->state = ($obj->state!='-'?$obj->state:'');
$transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
$libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
$this->stcomm_id = $obj->fk_stcomm; // id statut commercial
$this->statut_commercial = $libelle; // libelle statut commercial
$this->email = $obj->email;
$this->skype = $obj->skype;
$this->url = $obj->url;
$this->phone = $obj->phone;
$this->fax = $obj->fax;
$this->parent = $obj->parent;
$this->idprof1 = $obj->idprof1;
$this->idprof2 = $obj->idprof2;
$this->idprof3 = $obj->idprof3;
$this->idprof4 = $obj->idprof4;
$this->idprof5 = $obj->idprof5;
$this->idprof6 = $obj->idprof6;
$this->capital = $obj->capital;
$this->code_client = $obj->code_client;
$this->code_fournisseur = $obj->code_fournisseur;
$this->code_compta = $obj->code_compta;
$this->code_compta_fournisseur = $obj->code_compta_fournisseur;
$this->barcode = $obj->barcode;
$this->tva_assuj = $obj->tva_assuj;
$this->tva_intra = $obj->tva_intra;
$this->status = $obj->status;
// Local Taxes
$this->localtax1_assuj = $obj->localtax1_assuj;
$this->localtax2_assuj = $obj->localtax2_assuj;
$this->localtax1_value = $obj->localtax1_value;
$this->localtax2_value = $obj->localtax2_value;
$this->typent_id = $obj->typent_id;
$this->typent_code = $obj->typent_code;
$this->effectif_id = $obj->effectif_id;
$this->effectif = $obj->effectif_id?$obj->effectif:'';
$this->forme_juridique_code= $obj->forme_juridique_code;
$this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:'';
$this->fk_prospectlevel = $obj->fk_prospectlevel;
$this->prefix_comm = $obj->prefix_comm;
$this->remise_percent = $obj->remise_client;
$this->mode_reglement_id = $obj->mode_reglement;
$this->cond_reglement_id = $obj->cond_reglement;
$this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
$this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
$this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
$this->fk_account = $obj->fk_account;
$this->client = $obj->client;
$this->fournisseur = $obj->fournisseur;
$this->note = $obj->note_private; // TODO Deprecated for backward comtability
$this->note_private = $obj->note_private;
$this->note_public = $obj->note_public;
$this->modelpdf = $obj->model_pdf;
$this->default_lang = $obj->default_lang;
$this->logo = $obj->logo;
$this->webservices_url = $obj->webservices_url;
$this->webservices_key = $obj->webservices_key;
$this->outstanding_limit = $obj->outstanding_limit;
// multiprix
$this->price_level = $obj->price_level;
$this->import_key = $obj->import_key;
//Incoterms
$this->fk_incoterms = $obj->fk_incoterms;
$this->location_incoterms = $obj->location_incoterms;
$this->libelle_incoterms = $obj->libelle_incoterms;
// multicurrency
$this->fk_multicurrency = $obj->fk_multicurrency;
$this->multicurrency_code = $obj->multicurrency_code;
$result = 1;
// Retreive all extrafield for thirdparty
// fetch optionals attributes and labels
require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
$extrafields=new ExtraFields($this->db);
$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
$this->fetch_optionals($this->id,$extralabels);
}
else
{
$result = 0;
}
$this->db->free($resql);
}
else
{
$this->error=$this->db->lasterror();
$result = -3;
}
// Use first price level if level not defined for third party
if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
return $result;
}
/**
* Search and fetch thirparties by name
*
* @param string $name Name
* @param int $type Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier)
* @param array $filters Array of couple field name/value to filter the companies with the same name
* @param boolean $exact Exact string search (true/false)
* @param boolean $case Case sensitive (true/false)
* @param boolean $similar Add test if string inside name into database, or name into database inside string. Do not use this: Not compatible with other database.
* @param string $clause Clause for filters
* @return array|int <0 if KO, array of thirdparties object if OK
*/
function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
{
$thirdparties = array();
dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact);
// Check parameter
if (empty($name))
{
$this->errors[]='ErrorBadValueForParameter';
return -1;
}
// Generation requete recherche
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
$sql.= " WHERE entity IN (".getEntity('category',1).")";
if (! empty($type))
{
if ($type == 1 || $type == 2)
$sql.= " AND client = ".$type;
elseif ($type == 3)
$sql.= " AND fournisseur = 1";
}
if (! empty($name))
{
if (! $exact)
{
if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
{
$name = str_replace('*', '%', $name);
}
else
{
$name = '%'.$name.'%';
}
}
$sql.= " AND ";
if (is_array($filters) && ! empty($filters))
$sql.= "(";
if ($similar)
{
// For test similitude (string inside name into database, or name into database inside string)
// Do not use this. Not compatible with other database.
$sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
}
else
{
if (! $case)
$sql.= "nom LIKE '".$this->db->escape($name)."'";
else
$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
}
}
if (is_array($filters) && ! empty($filters))
{
foreach($filters as $field => $value)
{
if (! $exact)
{
if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
{
$value = str_replace('*', '%', $value);
}
else
{
$value = '%'.$value.'%';
}
}
if (! $case)
$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
else
$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
}
if (! empty($name))
$sql.= ")";
}
$res = $this->db->query($sql);
if ($res)
{
while ($rec = $this->db->fetch_array($res))
{
$soc = new Societe($this->db);
$soc->fetch($rec['rowid']);
$thirdparties[] = $soc;
}
return $thirdparties;
}
else
{
$this->error=$this->db->lasterror();
return -1;
}
}
/**
* Delete a third party from database and all its dependencies (contacts, rib...)
*
* @param int $id Id of third party to delete
* @param User $fuser User who ask to delete thirparty
* @param int $call_trigger 0=No, 1=yes
* @return int <0 if KO, 0 if nothing done, >0 if OK
*/
function delete($id, User $fuser=null, $call_trigger=1)
{
global $langs, $conf, $user;
if (empty($fuser)) $fuser=$user;
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$entity=isset($this->entity)?$this->entity:$conf->entity;
dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$error = 0;
// Test if child exists
$objectisused = $this->isObjectUsed($id);
if (empty($objectisused))
{
$this->db->begin();
// User is mandatory for trigger call
if (! $error && $call_trigger)
{
// Call trigger
$result=$this->call_trigger('COMPANY_DELETE',$fuser);
if ($result < 0) $error++;
// End call triggers
}
if (! $error)
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
$static_cat = new Categorie($this->db);
$toute_categs = array();
// Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
if ($this->client || $this->prospect)
{
$toute_categs ['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
}
if ($this->fournisseur)
{
$toute_categs ['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
}
// Remove each "Categorie"
foreach ($toute_categs as $type => $categs_type)
{
foreach ($categs_type as $cat)
{
$cat->del_type($this, $type);
}
}
}
// Remove contacts
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error .= $this->db->lasterror();
}
}
// Update link in member table
if (! $error)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
$sql.= " SET fk_soc = NULL WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error .= $this->db->lasterror();
dol_syslog(get_class($this)."::delete erreur -1 ".$this->error, LOG_ERR);
}
}
// Remove ban
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Remove societe_remise
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Remove societe_remise_except
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Remove associated users
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Removed extrafields
if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
{
$result=$this->deleteExtraFields();
if ($result < 0)
{
$error++;
dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
}
}
// Remove third party
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
$sql.= " WHERE rowid = " . $id;
dol_syslog(get_class($this)."::delete", LOG_DEBUG);
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
if (! $error)
{
$this->db->commit();
// Delete directory
if (! empty($conf->societe->multidir_output[$entity]))
{
$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
if (dol_is_dir($docdir))
{
dol_delete_dir_recursive($docdir);
}
}
return 1;
}
else
{
dol_syslog($this->error, LOG_ERR);
$this->db->rollback();
return -1;
}
}
else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
return 0;
}
/**
* Define third party as a customer
*
* @return int <0 if KO, >0 if OK
*/
function set_as_client()
{
if ($this->id)
{
$newclient=1;
if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag
$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
$sql.= " SET client = ".$newclient;
$sql.= " WHERE rowid = " . $this->id;
$resql=$this->db->query($sql);
if ($resql)
{
$this->client = $newclient;
return 1;
}
else return -1;
}
return 0;
}
/**
* Definit la societe comme un client
*
* @param float $remise Valeur en % de la remise
* @param string $note Note/Motif de modification de la remise
* @param User $user Utilisateur qui definie la remise
* @return int <0 if KO, >0 if OK
*/
function set_remise_client($remise, $note, User $user)
{
global $conf, $langs;
// Nettoyage parametres
$note=trim($note);
if (! $note)
{
$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Note"));
return -2;
}
dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
if ($this->id)
{
$this->db->begin();
$now=dol_now();
// Positionne remise courante
$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
$sql.= " SET remise_client = '".$this->db->escape($remise)."'";
$sql.= " WHERE rowid = " . $this->id .";";
$resql=$this->db->query($sql);
if (! $resql)
{
$this->db->rollback();
$this->error=$this->db->error();
return -1;
}
// Ecrit trace dans historique des remises
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
$sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
$sql.= " '".$this->db->escape($note)."',";
$sql.= " ".$user->id;
$sql.= ")";
$resql=$this->db->query($sql);
if (! $resql)
{
$this->db->rollback();
$this->error=$this->db->lasterror();
return -1;
}
$this->db->commit();
return 1;
}
}
/**
* Add a discount for third party
*
* @param float $remise Amount of discount
* @param User $user User adding discount
* @param string $desc Reason of discount
* @param float $tva_tx VAT rate
* @return int <0 if KO, id of discount record if OK
*/
function set_remise_except($remise, User $user, $desc, $tva_tx=0)
{
global $langs;
// Clean parameters
$remise = price2num($remise);
$desc = trim($desc);
// Check parameters
if (! $remise > 0)
{
$this->error=$langs->trans("ErrorWrongValueForParameter","1");
return -1;
}
if (! $desc)
{
$this->error=$langs->trans("ErrorWrongValueForParameter","3");
return -2;
}
if ($this->id)
{
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discount = new DiscountAbsolute($this->db);
$discount->fk_soc=$this->id;
$discount->amount_ht=price2num($remise,'MT');
$discount->amount_tva=price2num($remise*$tva_tx/100,'MT');
$discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
$discount->tva_tx=price2num($tva_tx,'MT');
$discount->description=$desc;
$result=$discount->create($user);
if ($result > 0)
{
return $result;
}
else
{
$this->error=$discount->error;
return -3;
}
}
else return 0;
}
/**
* Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
*
* @param User $user Filtre sur un user auteur des remises
* @param string $filter Filtre autre
* @param integer $maxvalue Filter on max value for discount
* @return int <0 if KO, Credit note amount otherwise
*/
function getAvailableDiscounts($user='',$filter='',$maxvalue=0)
{
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discountstatic=new DiscountAbsolute($this->db);
$result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue);
if ($result >= 0)
{
return $result;
}
else
{
$this->error=$discountstatic->error;
return -1;
}
}
/**
* Return array of sales representatives
*
* @param User $user Object user
* @return array Array of sales representatives of third party
*/
function getSalesRepresentatives(User $user)
{
global $conf;
$reparray=array();
$sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
$sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
if (! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode))
{
$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
$sql.= " WHERE ((ug.fk_user = sc.fk_user";
$sql.= " AND ug.entity = ".$conf->entity.")";
$sql.= " OR u.admin = 1)";
}
else
$sql.= " WHERE entity in (0, ".$conf->entity.")";
$sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc =".$this->id;
$resql = $this->db->query($sql);
if ($resql)
{
$num = $this->db->num_rows($resql);
$i=0;
while ($i < $num)
{
$obj = $this->db->fetch_object($resql);
$reparray[$i]['id']=$obj->rowid;
$reparray[$i]['lastname']=$obj->lastname;
$reparray[$i]['firstname']=$obj->firstname;
$reparray[$i]['email']=$obj->email;
$reparray[$i]['statut']=$obj->statut;
$reparray[$i]['entity']=$obj->entity;
$reparray[$i]['login']=$obj->login;
$reparray[$i]['photo']=$obj->photo;
$i++;
}
return $reparray;
}
else {
dol_print_error($this->db);
return -1;
}
}
/**
* Set the price level
*
* @param int $price_level Level of price
* @param User $user Use making change
* @return int <0 if KO, >0 if OK
*/
function set_price_level($price_level, User $user)
{
if ($this->id)
{
$now=dol_now();
$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
$sql .= " SET price_level = '".$this->db->escape($price_level)."'";
$sql .= " WHERE rowid = " . $this->id;
if (! $this->db->query($sql))
{
dol_print_error($this->db);
return -1;
}
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
$sql .= " (datec, fk_soc, price_level, fk_user_author)";
$sql .= " VALUES ('".$this->db->idate($now)."',".$this->id.",'".$this->db->escape($price_level)."',".$user->id.")";
if (! $this->db->query($sql))
{
dol_print_error($this->db);
return -1;
}
return 1;
}
return -1;
}
/**
* Add link to sales representative
*
* @param User $user Object user
* @param int $commid Id of user
* @return void
*/
function add_commercial(User $user, $commid)
{
if ($this->id > 0 && $commid > 0)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
$sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
$this->db->query($sql);
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
$sql.= " ( fk_soc, fk_user )";
$sql.= " VALUES (".$this->id.",".$commid.")";
if (! $this->db->query($sql) )
{
dol_syslog(get_class($this)."::add_commercial Erreur");
}
}
}
/**
* Add link to sales representative
*
* @param User $user Object user
* @param int $commid Id of user
* @return void
*/
function del_commercial(User $user, $commid)
{
if ($this->id > 0 && $commid > 0)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
$sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
if (! $this->db->query($sql) )
{
dol_syslog(get_class($this)."::del_commercial Erreur");
}
}
}
/**
* Return a link on thirdparty (with picto)
*
* @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
* @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project')
* @param int $maxlen Max length of name
* @param int $notooltip 1=Disable tooltip
* @return string String with URL
*/
function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0)
{
global $conf, $langs, $hookmanager;
if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
$name=$this->name?$this->name:$this->nom;
if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
{
if (($this->client) && (! empty ( $this->code_client ))) {
$code = $this->code_client . ' - ';
}
if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))) {
$code .= $this->code_fournisseur . ' - ';
}
$name =$code.' '.$name;
}
if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
$result=''; $label='';
$linkstart=''; $linkend='';
$label.= '<div width="100%">';
if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
{
$label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
}
else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
{
$label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
}
else if ($option == 'supplier')
{
$label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
}
else if ($option == 'agenda')
{
$label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
}
else if ($option == 'project')
{
$label.= '<u>' . $langs->trans("ShowProject") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
}
else if ($option == 'margin')
{
$label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
}
// By default
if (empty($linkstart))
{
$label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/soc.php?socid='.$this->id;
}
if (! empty($this->name))
{
$label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
}
if (! empty($this->code_client) && $this->client)
$label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
if (! empty($this->code_fournisseur) && $this->fournisseur)
$label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
if (! empty($conf->accounting->enabled) && $this->client)
$label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
if (! empty($conf->accounting->enabled) && $this->fournisseur)
$label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
if (! empty($this->logo))
{
$label.= '</br><div class="photointooltip">';
//if (! is_object($form)) $form = new Form($db);
$label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini');
$label.= '</div><div style="clear: both;"></div>';
}
$label.= '</div>';
// Add type of canvas
$linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'').'"';
$linkclose='';
if (empty($notooltip))
{
if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label=$langs->trans("ShowCompany");
$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
}
$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose.=' class="classfortooltip"';
if (! is_object($hookmanager))
{
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager=new HookManager($this->db);
}
$hookmanager->initHooks(array('societedao'));
$parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint;
}
$linkstart.=$linkclose.'>';
$linkend='</a>';
if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
if ($withpicto && $withpicto != 2) $result.=' ';
if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
return $result;
}
/**
* Return label of status (activity, closed)
*
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
* @return string Libelle
*/
function getLibStatut($mode=0)
{
return $this->LibStatut($this->status,$mode);
}
/**
* Renvoi le libelle d'un statut donne
*
* @param int $statut Id statut
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
* @return string Libelle du statut
*/
function LibStatut($statut,$mode=0)
{
global $langs;
$langs->load('companies');
if ($mode == 0)
{
if ($statut==0) return $langs->trans("ActivityCeased");
if ($statut==1) return $langs->trans("InActivity");
}
if ($mode == 1)
{
if ($statut==0) return $langs->trans("ActivityCeased");
if ($statut==1) return $langs->trans("InActivity");
}
if ($mode == 2)
{
if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
}
if ($mode == 3)
{
if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
}
if ($mode == 4)
{
if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
}
if ($mode == 5)
{
if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
}
}
/**
* Return list of contacts emails existing for third party
*
* @param int $addthirdparty 1=Add also a record for thirdparty email
* @return array Array of contacts emails
*/
function thirdparty_and_contact_email_array($addthirdparty=0)
{
global $langs;
$contact_emails = $this->contact_property_array('email',1);
if ($this->email && $addthirdparty)
{
if (empty($this->name)) $this->name=$this->nom;
$contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">";
}
return $contact_emails;
}
/**
* Return list of contacts mobile phone existing for third party
*
* @return array Array of contacts emails
*/
function thirdparty_and_contact_phone_array()
{
global $langs;
$contact_phone = $this->contact_property_array('mobile');
if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts
{
if (empty($this->name)) $this->name=$this->nom;
// TODO: Tester si tel non deja present dans tableau contact
$contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">";
}
return $contact_phone;
}
/**
* Return list of contacts emails or mobile existing for third party
*
* @param string $mode 'email' or 'mobile'
* @param int $hidedisabled 1=Hide contact if disabled
* @return array Array of contacts emails or mobile array(id=>'Name <email>')
*/
function contact_property_array($mode='email', $hidedisabled=0)
{
global $langs;
$contact_property = array();
$sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
$sql.= " WHERE fk_soc = '".$this->id."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$sepa="("; $sepb=")";
if ($mode == 'email')
{
$sepa="<"; $sepb=">";
}
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
if ($mode == 'email') $property=$obj->email;
else if ($mode == 'mobile') $property=$obj->phone_mobile;
else $property=$obj->$mode;
// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
if ($obj->statut == 1 || empty($hidedisabled))
{
if (empty($property))
{
if ($mode == 'email') $property=$langs->trans("NoEMail");
else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone");
}
if (!empty($obj->poste))
{
$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
}
else
{
$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
}
}
$i++;
}
}
}
else
{
dol_print_error($this->db);
}
return $contact_property;
}
/**
* Renvoie la liste des contacts de cette societe
*
* @return array tableau des contacts
*/
function contact_array()
{
$contacts = array();
$sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = '".$this->id."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
$contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
$i++;
}
}
}
else
{
dol_print_error($this->db);
}
return $contacts;
}
/**
* Renvoie la liste des contacts de cette societe
*
* @return array $contacts tableau des contacts
*/
function contact_array_objects()
{
require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
$contacts = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = '".$this->id."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
$contact = new Contact($this->db);
$contact->fetch($obj->rowid);
$contacts[] = $contact;
$i++;
}
}
}
else
{
dol_print_error($this->db);
}
return $contacts;
}
/**
* Return property of contact from its id
*
* @param int $rowid id of contact
* @param string $mode 'email' or 'mobile'
* @return string Email of contact with format: "Full name <email>"
*/
function contact_get_property($rowid,$mode)
{
$contact_property='';
if (empty($rowid)) return '';
$sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
$sql.= " WHERE rowid = '".$rowid."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$obj = $this->db->fetch_object($resql);
if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
}
return $contact_property;
}
else
{
dol_print_error($this->db);
}
}
/**
* Return bank number property of thirdparty (label or rum)
*
* @param string $mode 'label' or 'rum'
* @return string Bank number
*/
function display_rib($mode='label')
{
require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
$bac = new CompanyBankAccount($this->db);
$bac->fetch(0,$this->id);
if ($mode == 'label')
{
return $bac->getRibLabel(true);
}
elseif ($mode == 'rum')
{
if (empty($bac->rum))
{
require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
$prelevement = new BonPrelevement($this->db);
$bac->fetch_thirdparty();
$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
}
return $bac->rum;
}
return 'BadParameterToFunctionDisplayRib';
}
/**
* Return Array of RIB
*
* @return array|int 0 if KO, Array of CompanyBanckAccount if OK
*/
function get_all_rib()
{
require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id;
$result = $this->db->query($sql);
if (!$result) {
$this->error++;
$this->errors[] = $this->db->lasterror;
return 0;
} else {
$num_rows = $this->db->num_rows($result);
$rib_array = array();
if ($num_rows) {
while ($obj = $this->db->fetch_object($result)) {
$rib = new CompanyBankAccount($this->db);
$rib->fetch($obj->rowid);
$rib_array[] = $rib;
}
}
return $rib_array;
}
}
/**
* Attribut un code client a partir du module de controle des codes.
* Return value is stored into this->code_client
*
* @param Societe $objsoc Object thirdparty
* @param int $type Should be 0 to say customer
* @return void
*/
function get_codeclient($objsoc=0,$type=0)
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
$this->code_client = $mod->getNextValue($objsoc,$type);
$this->prefixCustomerIsRequired = $mod->prefixIsRequired;
dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
}
}
/**
* Attribut un code fournisseur a partir du module de controle des codes.
* Return value is stored into this->code_fournisseur
*
* @param Societe $objsoc Object thirdparty
* @param int $type Should be 1 to say supplier
* @return void
*/
function get_codefournisseur($objsoc=0,$type=1)
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
$this->code_fournisseur = $mod->getNextValue($objsoc,$type);
dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
}
}
/**
* Verifie si un code client est modifiable en fonction des parametres
* du module de controle des codes.
*
* @return int 0=No, 1=Yes
*/
function codeclient_modifiable()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
if ($mod->code_modifiable_null && ! $this->code_client) return 1;
if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
if ($mod->code_modifiable) return 1; // A mettre en dernier
return 0;
}
else
{
return 0;
}
}
/**
* Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
*
* @return int 0=No, 1=Yes
*/
function codefournisseur_modifiable()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
if ($mod->code_modifiable) return 1; // A mettre en dernier
return 0;
}
else
{
return 0;
}
}
/**
* Check customer code
*
* @return int 0 if OK
* -1 ErrorBadCustomerCodeSyntax
* -2 ErrorCustomerCodeRequired
* -3 ErrorCustomerCodeAlreadyUsed
* -4 ErrorPrefixRequired
*/
function check_codeclient()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
$result = $mod->verif($this->db, $this->code_client, $this, 0);
return $result;
}
else
{
return 0;
}
}
/**
* Check supplier code
*
* @return int 0 if OK
* -1 ErrorBadCustomerCodeSyntax
* -2 ErrorCustomerCodeRequired
* -3 ErrorCustomerCodeAlreadyUsed
* -4 ErrorPrefixRequired
*/
function check_codefournisseur()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
$result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
return $result;
}
else
{
return 0;
}
}
/**
* Renvoie un code compta, suivant le module de code compta.
* Peut etre identique a celui saisit ou genere automatiquement.
* A ce jour seule la generation automatique est implementee
*
* @param string $type Type of thirdparty ('customer' or 'supplier')
* @return string Code compta si ok, 0 si aucun, <0 si ko
*/
function get_codecompta($type)
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
{
$file='';
$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
{
$file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
break;
}
}
if (! empty($file))
{
dol_include_once($file);
$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
$mod = new $classname;
// Defini code compta dans $mod->code
$result = $mod->get_code($this->db, $this, $type);
if ($type == 'customer') $this->code_compta = $mod->code;
else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
return $result;
}
else
{
$this->error = 'ErrorAccountancyCodeNotDefined';
return -1;
}
}
else
{
if ($type == 'customer') $this->code_compta = '';
else if ($type == 'supplier') $this->code_compta_fournisseur = '';
return 0;
}
}
/**
* Define parent commany of current company
*
* @param int $id Id of thirdparty to set or '' to remove
* @return int <0 if KO, >0 if OK
*/
function set_parent($id)
{
if ($this->id)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
$sql.= " SET parent = ".($id > 0 ? $id : "null");
$sql.= " WHERE rowid = " . $this->id;
dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$this->parent = $id;
return 1;
}
else
{
return -1;
}
}
else return -1;
}
/**
* Returns if a profid sould be verified
*
* @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
* @return boolean true , false
*/
function id_prof_verifiable($idprof)
{
global $conf;
switch($idprof)
{
case 1:
$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
break;
case 2:
$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
break;
case 3:
$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
break;
case 4:
$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
break;
default:
$ret=false;
}
return $ret;
}
/**
* Verify if a profid exists into database for others thirds
*
* @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
* @param string $value Value of profid
* @param int $socid Id of thirdparty if update
* @return boolean true if exists, false if not
*/
function id_prof_exists($idprof,$value,$socid=0)
{
switch($idprof)
{
case 1:
$field="siren";
break;
case 2:
$field="siret";
break;
case 3:
$field="ape";
break;
case 4:
$field="idprof4";
break;
}
//Verify duplicate entries
$sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe',1).")";
if($socid) $sql .= " AND rowid <> ".$socid;
$resql = $this->db->query($sql);
if ($resql)
{
$obj = $this->db->fetch_object($resql);
$count = $obj->idprof;
}
else
{
$count = 0;
print $this->db->error();
}
$this->db->free($resql);
if ($count > 0) return true;
else return false;
}
/**
* Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
*
* @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
* @param Societe $soc Objet societe
* @return int <=0 if KO, >0 if OK
* TODO better to have this in a lib than into a business class
*/
function id_prof_check($idprof,$soc)
{
global $conf;
$ok=1;
if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
// Verifie SIREN si pays FR
if ($idprof == 1 && $soc->country_code == 'FR')
{
$chaine=trim($this->idprof1);
$chaine=preg_replace('/(\s)/','',$chaine);
if (dol_strlen($chaine) != 9) return -1;
$sum = 0;
for ($i = 0 ; $i < 10 ; $i = $i+2)
{
$sum = $sum + substr($this->idprof1, (8 - $i), 1);
}
for ($i = 1 ; $i < 9 ; $i = $i+2)
{
$ps = 2 * substr($this->idprof1, (8 - $i), 1);
if ($ps > 9)
{
$ps = substr($ps, 0,1) + substr($ps, 1, 1);
}
$sum = $sum + $ps;
}
if (substr($sum, -1) != 0) return -1;
}
// Verifie SIRET si pays FR
if ($idprof == 2 && $soc->country_code == 'FR')
{
$chaine=trim($this->idprof2);
$chaine=preg_replace('/(\s)/','',$chaine);
if (dol_strlen($chaine) != 14) return -1;
}
//Verify CIF/NIF/NIE if pays ES
//Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
if ($idprof == 1 && $soc->country_code == 'ES')
{
$string=trim($this->idprof1);
$string=preg_replace('/(\s)/','',$string);
$string = strtoupper($string);
for ($i = 0; $i < 9; $i ++)
$num[$i] = substr($string, $i, 1);
//Check format
if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
return 0;
//Check NIF
if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
return 1;
else
return -1;
//algorithm checking type code CIF
$sum = $num[2] + $num[4] + $num[6];
for ($i = 1; $i < 8; $i += 2)
$sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
$n = 10 - substr($sum, strlen($sum) - 1, 1);
//Chek special NIF
if (preg_match('/^[KLM]{1}/', $string))
if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
return 1;
else
return -1;
//Check CIF
if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
return 2;
else
return -2;
//Check NIE T
if (preg_match('/^[T]{1}/', $string))
if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
return 3;
else
return -3;
//Check NIE XYZ
if (preg_match('/^[XYZ]{1}/', $string))
if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
return 3;
else
return -3;
//Can not be verified
return -4;
}
return $ok;
}
/**
* Return an url to check online a professional id or empty string
*
* @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
* @param Societe $thirdparty Object thirdparty
* @return string Url or empty string if no URL known
* TODO better in a lib than into business class
*/
function id_prof_url($idprof,$thirdparty)
{
global $conf,$langs,$hookmanager;
$url='';
$action = '';
$hookmanager->initHooks(array('idprofurl'));
$parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
$reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if (empty($reshook))
{
if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
// TODO Move links to validate professional ID into a dictionary table "country" + "link"
if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1; // See also http://avis-situation-sirene.insee.fr/
//if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/'; // Link no more valid
if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
}
else
{
return $hookmanager->resPrint;
}
return '';
}
/**
* Indique si la societe a des projets
*
* @return bool true si la societe a des projets, false sinon
*/
function has_projects()
{
$sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
$resql = $this->db->query($sql);
if ($resql)
{
$obj = $this->db->fetch_object($resql);
$count = $obj->numproj;
}
else
{
$count = 0;
print $this->db->error();
}
$this->db->free($resql);
return ($count > 0);
}
/**
* Load information for tab info
*
* @param int $id Id of thirdparty to load
* @return void
*/
function info($id)
{
$sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
$sql.= " fk_user_creat, fk_user_modif";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql.= " WHERE s.rowid = ".$id;
$result=$this->db->query($sql);
if ($result)
{
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result);
$this->id = $obj->rowid;
if ($obj->fk_user_creat) {
$cuser = new User($this->db);
$cuser->fetch($obj->fk_user_creat);
$this->user_creation = $cuser;
}
if ($obj->fk_user_modif) {
$muser = new User($this->db);
$muser->fetch($obj->fk_user_modif);
$this->user_modification = $muser;
}
$this->ref = $obj->name;
$this->date_creation = $this->db->jdate($obj->date_creation);
$this->date_modification = $this->db->jdate($obj->date_modification);
}
$this->db->free($result);
}
else
{
dol_print_error($this->db);
}
}
/**
* Return if third party is a company (Business) or an end user (Consumer)
*
* @return boolean true=is a company, false=a and user
*/
function isACompany()
{
global $conf;
// Define if third party is treated as company (or not) when nature is unknown
$isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
if (! empty($this->tva_intra)) $isacompany=1;
else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE'))) $isacompany=1;
return $isacompany;
}
/**
* Charge la liste des categories fournisseurs
*
* @return int 0 if success, <> 0 if error
*/
function LoadSupplierCateg()
{
$this->SupplierCategories = array();
$sql = "SELECT rowid, label";
$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
$sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
$resql=$this->db->query($sql);
if ($resql)
{
while ($obj = $this->db->fetch_object($resql) )
{
$this->SupplierCategories[$obj->rowid] = $obj->label;
}
return 0;
}
else
{
return -1;
}
}
/**
* Charge la liste des categories fournisseurs
*
* @param int $categorie_id Id of category
* @return int 0 if success, <> 0 if error
*/
function AddFournisseurInCategory($categorie_id)
{
if ($categorie_id > 0)
{
$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
$sql.= " VALUES ('".$categorie_id."','".$this->id."');";
if ($resql=$this->db->query($sql)) return 0;
}
else
{
return 0;
}
return -1;
}
/**
* Create a third party into database from a member object
*
* @param Adherent $member Object member
* @param string $socname Name of third party to force
* @return int <0 if KO, id of created account if OK
*/
function create_from_member(Adherent $member,$socname='')
{
global $user,$langs;
$name = $socname?$socname:$member->societe;
if (empty($name)) $name=$member->getFullName($langs);
// Positionne parametres
$this->nom=$name; // TODO deprecated
$this->name=$name;
$this->address=$member->address;
$this->zip=$member->zip;
$this->town=$member->town;
$this->country_code=$member->country_code;
$this->country_id=$member->country_id;
$this->phone=$member->phone; // Prof phone
$this->email=$member->email;
$this->skype=$member->skype;
$this->client = 1; // A member is a customer by default
$this->code_client = -1;
$this->code_fournisseur = -1;
$this->db->begin();
// Cree et positionne $this->id
$result=$this->create($user);
if ($result >= 0)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
$sql.= " SET fk_soc=".$this->id;
$sql.= " WHERE rowid=".$member->id;
dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$this->db->commit();
return $this->id;
}
else
{
$this->error=$this->db->error();
$this->db->rollback();
return -1;
}
}
else
{
// $this->error deja positionne
dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
$this->db->rollback();
return $result;
}
}
/**
* Set properties with value into $conf
*
* @param Conf $conf Conf object (possibility to use another entity)
* @return void
*/
function setMysoc(Conf $conf)
{
global $langs;
$this->id=0;
$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
$this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
/* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only.
If we need label, label must be loaded by output that need it from id (label depends on output language)
require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
$this->state_id= $conf->global->MAIN_INFO_SOCIETE_STATE;
$this->state = getState($this->state_id);
}
*/
$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
$this->nom=$this->name; // deprecated
// We define country_id, country_code and country
$country_id=$country_code=$country_label='';
if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
{
$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
$country_id=$tmp[0];
if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
{
$country_code=$tmp[1];
$country_label=$tmp[2];
}
else // For backward compatibility
{
dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
$country_code=getCountry($country_id,2,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore
$country_label=getCountry($country_id,0,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore
}
}
$this->country_id=$country_id;
$this->country_code=$country_code;
$this->country=$country_label;
if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
// Id prof generiques
$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
// Define if company use vat or not
$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
// Define if company use local taxes
$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
}
/**
* Initialise an instance with random values.
* Used to build previews or test instances.
* id must be 0 if object instance is a specimen.
*
* @return void
*/
function initAsSpecimen()
{
$now=dol_now();
// Initialize parameters
$this->id=0;
$this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
$this->nom = $this->name; // For backward compatibility
$this->ref_ext = 'Ref ext';
$this->specimen=1;
$this->address='21 jump street';
$this->zip='99999';
$this->town='MyTown';
$this->state_id=1;
$this->state_code='AA';
$this->state='MyState';
$this->country_id=1;
$this->country_code='FR';
$this->email='specimen@specimen.com';
$this->skype='tom.hanson';
$this->url='http://www.specimen.com';
$this->phone='0909090901';
$this->fax='0909090909';
$this->code_client='CC-'.dol_print_date($now,'dayhourlog');
$this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
$this->capital=10000;
$this->client=1;
$this->prospect=1;
$this->fournisseur=1;
$this->tva_assuj=1;
$this->tva_intra='EU1234567';
$this->note_public='This is a comment (public)';
$this->note_private='This is a comment (private)';
$this->idprof1='idprof1';
$this->idprof2='idprof2';
$this->idprof3='idprof3';
$this->idprof4='idprof4';
$this->idprof5='idprof5';
$this->idprof6='idprof6';
}
/**
* Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
*
* @param int $localTaxNum To get info for only localtax1 or localtax2
* @return boolean true or false
*/
function useLocalTax($localTaxNum=0)
{
$sql = "SELECT t.localtax1, t.localtax2";
$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->country_code."'";
$sql .= " AND t.active = 1";
if (empty($localTaxNum)) $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
dol_syslog("useLocalTax", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
return ($this->db->num_rows($resql) > 0);
}
else return false;
}
/**
* Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
*
* @return boolean true or false
*/
function useNPR()
{
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->country_code."'";
$sql .= " AND t.active = 1 AND t.recuperableonly = 1";
dol_syslog("useNPR", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
return ($this->db->num_rows($resql) > 0);
}
else return false;
}
/**
* Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
*
* @return boolean true or false
*/
function useRevenueStamp()
{
$sql = "SELECT COUNT(*) as nb";
$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
$sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->country_code."'";
$sql .= " AND r.active = 1";
dol_syslog("useRevenueStamp", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$obj=$this->db->fetch_object($resql);
return (($obj->nb > 0)?true:false);
}
else
{
$this->error=$this->db->lasterror();
return false;
}
}
/**
* Return prostect level
*
* @return string Libelle
*/
function getLibProspLevel()
{
return $this->LibProspLevel($this->fk_prospectlevel);
}
/**
* Return label of prospect level
*
* @param int $fk_prospectlevel Prospect level
* @return string label of level
*/
function LibProspLevel($fk_prospectlevel)
{
global $langs;
$lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
// If lib not found in language file, we get label from cache/databse
if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
{
$lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
}
return $lib;
}
/**
* Set prospect level
*
* @param User $user Utilisateur qui definie la remise
* @return int <0 if KO, >0 if OK
* @deprecated Use update function instead
*/
function set_prospect_level(User $user)
{
return $this->update($this->id, $user);
}
/**
* Return status of prospect
*
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
* @param string $label Label to use for status for added status
* @return string Libelle
*/
function getLibProspCommStatut($mode=0, $label='')
{
return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
}
/**
* Return label of a given status
*
* @param int|string $statut Id or code for prospection status
* @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
* @param string $label Label to use for status for added status
* @return string Libelle du statut
*/
function LibProspCommStatut($statut, $mode=0, $label='')
{
global $langs;
$langs->load('customers');
if ($mode == 2)
{
if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
else
{
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
}
}
if ($mode == 3)
{
if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1);
elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1);
elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2);
elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3);
else
{
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
}
}
if ($mode == 4)
{
if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
else
{
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
}
}
return "Error, mode/status not found";
}
/**
* Set commnunication level
*
* @param User $user User making change
* @return int <0 if KO, >0 if OK
* @deprecated Use update function instead
*/
function set_commnucation_level($user)
{
return $this->update($this->id, $user);
}
/**
* Set outstanding value
*
* @param User $user User making change
* @return int <0 if KO, >0 if OK
* @deprecated Use update function instead
*/
function set_OutstandingBill(User $user)
{
return $this->update($this->id, $user);
}
/**
* Return amount of bill not paid
*
* @return int Amount in debt for thirdparty
*/
function get_OutstandingBill()
{
/* Accurate value of remain to pay is to sum remaintopay for each invoice
$paiement = $invoice->getSommePaiement();
$creditnotes=$invoice->getSumCreditNotesUsed();
$deposits=$invoice->getSumDepositsUsed();
$alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
$remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
*/
$sql = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
$sql .= " WHERE fk_soc = ". $this->id;
$sql .= " AND paye = 0";
$sql .= " AND fk_statut <> 0"; // Not a draft
//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
$sql .= " AND fk_statut <> 3"; // Not abandonned
$sql .= " AND fk_statut <> 2"; // Not clasified as paid
dol_syslog("get_OutstandingBill", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$outstandingBill = 0;
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$facturestatic=new Facture($this->db);
while($obj=$this->db->fetch_object($resql)) {
$facturestatic->id=$obj->rowid;
$paiement = $facturestatic->getSommePaiement();
$creditnotes = $facturestatic->getSumCreditNotesUsed();
$deposits = $facturestatic->getSumDepositsUsed();
$outstandingBill+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
}
return $outstandingBill;
}
else
return 0;
}
/**
* Return label of status customer is prospect/customer
*
* @return string Label
*/
function getLibCustProspStatut()
{
return $this->LibCustProspStatut($this->client);
}
/**
* Renvoi le libelle d'un statut donne
*
* @param int $statut Id statut
* @return string Libelle du statut
*/
function LibCustProspStatut($statut)
{
global $langs;
$langs->load('companies');
if ($statut==0) return $langs->trans("NorProspectNorCustomer");
if ($statut==1) return $langs->trans("Customer");
if ($statut==2) return $langs->trans("Prospect");
if ($statut==3) return $langs->trans("ProspectCustomer");
}
/**
* Create a document onto disk according to template module.
*
* @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
* @param Translate $outputlangs objet lang a utiliser pour traduction
* @param int $hidedetails Hide details of lines
* @param int $hidedesc Hide description
* @param int $hideref Hide ref
* @param null|array $moreparams Array to provide more information
* @return int <0 if KO, >0 if OK
*/
public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
{
global $conf,$user,$langs;
if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
{
$modelpath = "core/modules/bank/doc/";
include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
$companybankaccount = new CompanyBankAccount($this->db);
$result = $companybankaccount->fetch($moreparams['use_companybankid']);
if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
$result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
}
else
{
// Positionne le modele sur le nom du modele a utiliser
if (! dol_strlen($modele))
{
if (! empty($conf->global->COMPANY_ADDON_PDF))
{
$modele = $conf->global->COMPANY_ADDON_PDF;
}
else
{
print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
return 0;
}
}
$modelpath = "core/modules/societe/doc/";
$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
}
return $result;
}
/**
* Sets object to supplied categories.
*
* Deletes object from existing categories not supplied.
* Adds it to non existing supplied categories.
* Existing categories are left untouch.
*
* @param int[]|int $categories Category or categories IDs
* @param string $type Category type (customer or supplier)
*/
public function setCategories($categories, $type)
{
// Decode type
if ($type == 'customer') {
$type_id = Categorie::TYPE_CUSTOMER;
$type_text = 'customer';
} elseif ($type == 'supplier') {
$type_id = Categorie::TYPE_SUPPLIER;
$type_text = 'supplier';
} else {
dol_syslog(__METHOD__ . ': Type ' . $type . 'is an unknown company category type. Done nothing.', LOG_ERR);
return;
}
// Handle single category
if (!is_array($categories)) {
$categories = array($categories);
}
// Get current categories
require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
$c = new Categorie($this->db);
$existing = $c->containing($this->id, $type_id, 'id');
// Diff
if (is_array($existing)) {
$to_del = array_diff($existing, $categories);
$to_add = array_diff($categories, $existing);
} else {
$to_del = array(); // Nothing to delete
$to_add = $categories;
}
// Process
foreach ($to_del as $del) {
if ($c->fetch($del) > 0) {
$c->del_type($this, $type_text);
}
}
foreach ($to_add as $add) {
if ($c->fetch($add) > 0) {
$c->add_type($this, $type_text);
}
}
return;
}
/**
* Function used to replace a thirdparty id with another one.
* It must be used within a transaction to avoid trouble
*
* @param DoliDB $db Database handler
* @param int $origin_id Old thirdparty id
* @param int $dest_id New thirdparty id
* @return bool
*/
public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
{
/**
* Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some
* Because this function is meant to be executed within a transaction, we won't take care of it.
*/
$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
$sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
$sql .= ' SELECT fk_user ';
$sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
$sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
$query = $db->query($sql);
while ($result = $db->fetch_object($query)) {
$db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
}
/**
* llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
* Do not include llx_societe because it will be replaced later
*/
$tables = array(
'societe_address',
'societe_commerciaux',
'societe_log',
'societe_prices',
'societe_remise',
'societe_remise_except',
'societe_rib'
);
return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
}
}
| Franck-MOREAU/dolibarr | htdocs/societe/class/societe.class.php | PHP | gpl-3.0 | 125,850 |
#! /usr/bin/env python
import sys
from aubio import source, pitch, freqtomidi
if len(sys.argv) < 2:
print "Usage: %s <filename> [samplerate]" % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
downsample = 1
samplerate = 44100 / downsample
if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
win_s = 4096 / downsample # fft size
hop_s = 512 / downsample # hop size
s = source(filename, samplerate, hop_s)
samplerate = s.samplerate
tolerance = 0.8
pitch_o = pitch("yin", win_s, hop_s, samplerate)
pitch_o.set_unit("midi")
pitch_o.set_tolerance(tolerance)
pitches = []
confidences = []
# total number of frames read
total_frames = 0
while True:
samples, read = s()
pitch = pitch_o(samples)[0]
#pitch = int(round(pitch))
confidence = pitch_o.get_confidence()
#if confidence < 0.8: pitch = 0.
#print "%f %f %f" % (total_frames / float(samplerate), pitch, confidence)
pitches += [pitch]
confidences += [confidence]
total_frames += read
if read < hop_s: break
if 0: sys.exit(0)
#print pitches
from numpy import array, ma
import matplotlib.pyplot as plt
from demo_waveform_plot import get_waveform_plot, set_xlabels_sample2time
skip = 1
pitches = array(pitches[skip:])
confidences = array(confidences[skip:])
times = [t * hop_s for t in range(len(pitches))]
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax1 = get_waveform_plot(filename, samplerate = samplerate, block_size = hop_s, ax = ax1)
plt.setp(ax1.get_xticklabels(), visible = False)
ax1.set_xlabel('')
def array_from_text_file(filename, dtype = 'float'):
import os.path
from numpy import array
filename = os.path.join(os.path.dirname(__file__), filename)
return array([line.split() for line in open(filename).readlines()],
dtype = dtype)
ax2 = fig.add_subplot(312, sharex = ax1)
import sys, os.path
ground_truth = os.path.splitext(filename)[0] + '.f0.Corrected'
if os.path.isfile(ground_truth):
ground_truth = array_from_text_file(ground_truth)
true_freqs = ground_truth[:,2]
true_freqs = ma.masked_where(true_freqs < 2, true_freqs)
true_times = float(samplerate) * ground_truth[:,0]
ax2.plot(true_times, true_freqs, 'r')
ax2.axis( ymin = 0.9 * true_freqs.min(), ymax = 1.1 * true_freqs.max() )
# plot raw pitches
ax2.plot(times, pitches, '.g')
# plot cleaned up pitches
cleaned_pitches = pitches
#cleaned_pitches = ma.masked_where(cleaned_pitches < 0, cleaned_pitches)
#cleaned_pitches = ma.masked_where(cleaned_pitches > 120, cleaned_pitches)
cleaned_pitches = ma.masked_where(confidences < tolerance, cleaned_pitches)
ax2.plot(times, cleaned_pitches, '.-')
#ax2.axis( ymin = 0.9 * cleaned_pitches.min(), ymax = 1.1 * cleaned_pitches.max() )
#ax2.axis( ymin = 55, ymax = 70 )
plt.setp(ax2.get_xticklabels(), visible = False)
ax2.set_ylabel('f0 (midi)')
# plot confidence
ax3 = fig.add_subplot(313, sharex = ax1)
# plot the confidence
ax3.plot(times, confidences)
# draw a line at tolerance
ax3.plot(times, [tolerance]*len(confidences))
ax3.axis( xmin = times[0], xmax = times[-1])
ax3.set_ylabel('condidence')
set_xlabels_sample2time(ax3, times[-1], samplerate)
plt.show()
#plt.savefig(os.path.basename(filename) + '.svg')
| madmouser1/aubio | python/demos/demo_pitch.py | Python | gpl-3.0 | 3,193 |
/*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <philipp.heckel@gmail.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.syncany.plugins.transfer.oauth;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.syncany.plugins.transfer.TransferSettings;
/**
* This annotation is used to identify OAuth plugins by marking the corresponding
* {@link TransferSettings} class. An OAuth plugin will provide a 'token' field
* during the initialization process and the {@link OAuthGenerator} (provided via the
* help of the {@link #value()} field) will be able to check that token.
*
* @author Philipp Heckel <philipp.heckel@gmail.com>
* @author Christian Roth <christian.roth@port17.de>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface OAuth {
String PLUGIN_ID = "%pluginid%";
int RANDOM_PORT = -1;
/**
* @see OAuthGenerator
*/
Class<? extends OAuthGenerator> value();
/**
* The default Mode is {@link OAuthMode#SERVER}
*
* @see OAuthMode
*/
OAuthMode mode() default OAuthMode.SERVER;
/**
* If no specific port is provided (or {@value #RANDOM_PORT} is used), the {@link OAuthTokenWebListener} will choose a
* random port from the range of {@value OAuthTokenWebListener#PORT_LOWER} and
* {@value OAuthTokenWebListener#PORT_UPPER}.<br/>
* Needed if an OAuth provider uses preset and strict redirect URLs.
*/
int callbackPort() default RANDOM_PORT; // -1 is random
/**
* If no specific name is provided (or {@value #PLUGIN_ID} is used), the {@link OAuthTokenWebListener} will choose a
* random identifier for the OAuth process.<br/>
* Needed if an OAuth provider uses preset and strict redirect URLs.
*/
String callbackId() default PLUGIN_ID; // equals plugin id
}
| brogowski/syncany-plugin-azureblobstorage | core/syncany-lib/src/main/java/org/syncany/plugins/transfer/oauth/OAuth.java | Java | gpl-3.0 | 2,506 |
/*
* Copyright (c) 2007 by Fraunhofer IML, Dortmund.
* All rights reserved.
*
* Project: myWMS
*/
package org.mywms.cactustest;
import java.io.NotSerializableException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.mywms.model.ClearingItem;
import org.mywms.model.ClearingItemOption;
import org.mywms.model.ClearingItemOptionRetval;
import org.mywms.model.Client;
import org.mywms.res.BundleResolver;
/**
* @author aelbaz
* @version $Revision: 599 $ provided by $Author: trautm $
*/
public class ClearingItemServiceTest
extends CactusTestInit
{
private ClearingItem clearingItem1 = null, clearingItem11 = null,
clearingItem2 = null;
public void testCreateItem() throws NotSerializableException {
Client client = clientService.getSystemClient();
String host = "localhost";
String source1 = "Robot1";
String user1 = "Guest";
String messageResourceKey1 = "CLEARING_ITEM_MESSAGE_KEY";
String shortMessageResourceKey1 = "CLEARING_ITEM_SHORT_MESSAGE_KEY";
String[] messageParameters1 = {
"f_001", "f_002"
};
String[] shortMessageParameters1 = {
"f_001", "f_002"
};
ArrayList<ClearingItemOption> optionList =
new ArrayList<ClearingItemOption>();
ArrayList<ClearingItemOptionRetval> retvalList =
new ArrayList<ClearingItemOptionRetval>();
String[] messageParameters = {
"eins", "zwei"
};
ClearingItemOptionRetval retval1 = new ClearingItemOptionRetval();
ClearingItemOptionRetval retval2 = new ClearingItemOptionRetval();
retval1.setNameResourceKey("Date");
retval1.setType(Date.class);
retvalList.add(retval1);
retval2.setNameResourceKey("Dezimal");
retval2.setType(Integer.class);
retvalList.add(retval2);
ClearingItemOption options = new ClearingItemOption();
options.setMessageResourceKey("CLEARING_ITEM_OPTION_MESSAGE_KEY_1");
options.setMessageParameters(messageParameters);
options.setRetvals(retvalList);
optionList.add(options);
String boundleName1 = "org.mywms.res.mywms-clearing";
String boundleName2 = "org.mywms.res.mywms-clear";
clearingItem1 =
clearingItemService.create(
client,
host,
source1,
user1,
messageResourceKey1,
shortMessageResourceKey1,
boundleName1,
BundleResolver.class,
shortMessageParameters1,
messageParameters1,
optionList);
clearingItem1.setSolution("admin", options);
clearingItem1 = clearingItemService.merge(clearingItem1);
assertNotNull("Das Object wurde nicht erzeugt", clearingItem1);
String source2 = "Robot2";
String user2 = "Guest2";
String message2 = "Das Problem liegt am Fach2";
String shortMessage2 = "Problem Nummer 2";
String messageResourceKey2 = "CLEARING_ITEM_MESSAGE_";
String shortMessageResourceKey2 = "CLEARING_ITEM_SHORT_MESSAGE_KEY";
String[] messageParameters2 = {
"f_001", "f_002"
};
String[] shortMessageParameters2 = {
"f_001", "f_002"
};
clearingItem11 =
clearingItemService.create(
client,
host,
source1,
user1,
messageResourceKey1,
shortMessageResourceKey1,
boundleName1,
BundleResolver.class,
shortMessageParameters1,
messageParameters1,
optionList);
assertNotNull("Das Object wurde nicht erzeugt", clearingItem11);
clearingItem2 =
clearingItemService.create(
client,
host,
source2,
user2,
messageResourceKey2,
shortMessageResourceKey2,
boundleName2,
BundleResolver.class,
shortMessageParameters2,
messageParameters2,
optionList);
assertNotNull("Das Object wurde nicht erzeugt", clearingItem2);
}
public void testGetUser() {
List<String> listUsers = clearingItemService.getUser(null);
assertEquals("Guest", listUsers.get(0));
}
public void testGetSource() {
List<String> listSources = clearingItemService.getSources(null);
assertEquals("Robot1", listSources.get(0));
}
public void testGetHosts() {
List<String> listHosts = clearingItemService.getHosts(null);
assertEquals("localhost", listHosts.get(0));
}
public void testGetChronologicalLiVoidst() {
String client = clientService.getSystemClient().getNumber();
List<ClearingItem> list =
clearingItemService.getChronologicalList(
client,
"localhost",
"Robot1",
"user1",
3);
assertEquals("falsche Nummer", 0, list.size());
list =
clearingItemService.getChronologicalList(
client,
"localhost",
"Robot1",
"Guest",
2);
assertEquals("falsche Nummer", 2, list.size());
}
public void testGetNondealChronologicalList() {
String client = clientService.getSystemClient().getNumber();
List<ClearingItem> list =
clearingItemService.getNondealChronologicalList(
client,
"localhost",
"Robot1",
"Guest",
5);
assertEquals("falsche Nummer", 1, list.size());
}
}
| tedvals/mywms | server.app/mywms.as/cactus/src/org/mywms/cactustest/ClearingItemServiceTest.java | Java | gpl-3.0 | 6,345 |
# Phatch - Photo Batch Processor
# Copyright (C) 2007-2008 www.stani.be
#
# 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/
#
# Phatch recommends SPE (http://pythonide.stani.be) for editing python files.
# Embedded icon is taken from www.openclipart.org (public domain)
# Follows PEP8
from core import models
from lib.reverse_translation import _t
#---PIL
def init():
global Image, imtools
from PIL import Image
from lib import imtools
def transpose(image, method, amount=100):
transposed = image.transpose(getattr(Image, method))
if amount < 100:
transposed = imtools.blend(image, transposed, amount / 100.0)
return transposed
#---Phatch
class Action(models.Action):
""""""
label = _t('Transpose')
author = 'Stani'
email = 'spe.stani.be@gmail.com'
init = staticmethod(init)
pil = staticmethod(transpose)
version = '0.1'
tags = [_t('default'), _t('transform')]
__doc__ = _t('Flip or rotate 90 degrees')
def interface(self, fields):
fields[_t('Method')] = self.ImageTransposeField(
'Orientation')
fields[_t('Amount')] = self.SliderField(100, 1, 100)
def apply(self, photo, setting, cache):
#get info
info = photo.info
#dpi
method = self.get_field('Method', info)
#special case turn to its orientation
if method == 'ORIENTATION':
photo._exif_transposition_reverse = ()
info['orientation'] = 1
else:
amount = self.get_field('Amount', info)
layer = photo.get_layer()
layer.image = transpose(layer.image, method, amount)
return photo
icon = \
'x\xda\x01`\t\x9f\xf6\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x000\x00\
\x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\x00\x00\x00\x04sBIT\x08\x08\x08\
\x08|\x08d\x88\x00\x00\t\x17IDATh\x81\xed\xd9{\x8c\x9c\xd5y\x06\xf0\xdf\x99o\
\xee3{\xb7Y_\xd6\xd8\xd8\xa6\xc4.\x94\xe2[q\xa0\x01\n\xa8n\xa4\xc4$\xa2T\t\
\xa9ZE\x15\x94^\x94J\xf9\xa3\x89Z\xb5RD\xa4\xa4Q/\x8a\x8aZH\xa2DjU\x13\xa5\
\x8dTTD\x1b \x89"\x07\x1a\xb0MK|\xc7\xb0x\xb1\x8d\xbd\xbe\xad\xed\xf5\xce^f\
\xe6\xeb\x1f\xdf7\xde\xf5\xb2\xbe\x82eU\xf2;:\xfaFG\xe7;\xf3<\xefy\xcf{\x9e\
\xf7L\x88\xe3\xd8\xffg\xcb\\m\x00\xef\xd7\xae\x11\xb8\xdav\x8d\xc0\xd5\xb6\
\x0f\x8c@\x08!\x84\xef\x85(\xbc\x1bz\xc2\xa9\xb0$\x8c\x86\x15\xeb\xeb\xf7\
\xaf\xfe\xa0\xe6?\x97e/\xf7\xc5 T5\xdd#\xb6J\xb0R\xc3J\x19\xbd\x08\xad1\x1d\
\xa7\xdb\x07C.\xf4\xa1\x1e_\xa1|}I\x04\x82P\xc4G\xc5>-\xf8\xa8\x8c\xd2L\xe3\
\xf2r\xe6\x98-;\x92\x9b\x85v\x9c\xc4\xc4\xfb\x87\xfb^\xbb(\x02A\xc8\xe3Q\xfc\
\x19z\'}\xccrK\xac\xf3\x11\xd7\x9b\xaf\xcf\\\x9d\xcd\x0ec\x13\x13\xf6\xd7\
\x06m;\xb2;\xc6,\xd4B\x08Wd\x15.H \x08\x0f\xe1k\xb8~\xf2\xa5\xc8}\xd6\xfa\
\x8c\x8f\xcb\xd5r\xbe\xfb\xf3\xe7\xfc\xd7\xde\x8d\xf6\xed?\xe8\xc4\x89S\x93/\
\x1f7\x81N\x1cD\xed\x83\x06\x9f`97\xf0\x02\xfe\x0e\xbf?\xb5\xff~\xb7\xfb|\
\xfc\xbb\xb6\x1c\xde\xe1+?\xf9\x86\xad\xdb\xde8\xdf\xfc\x01EW0\xdb\xcdH \x08\
\x1dx\x01\xab\xa6\xf6?\xe0\x1e\x9f\xac\xdd\xe7\xe1o\x7f\xc1\xd1\xc3C\x17\x9e\
=N\xa7\xbb\x82\xf6\x1e\x02A\xc8\xe2_M\x03\xff)\xeb\xdc3\xbc\xdacO>\xee\xf4\
\xf0EF\xc3\x15\x85\x9e\xd8L+\xf0\xb7\xb8oj\xc7\x1dn\xb5v\xe8\x16\x7f\xfc\x8f\
_566~\xfe\x19\x9b\x92h\x1f\xc5\x90Q\xd4\xb5\xd6\xe2\n\xd8Y\x04\x82\xb0\x04\
\x8fM\x1f\xf4[\xf5\xfb}\xf1\xa9\xbf\x9f\x19\xfc)\xec\x17;\xa6\xee\xa4\x9a\
\x13F\x8c9i\xdc~M\x9b1\x82\xc6\x95\x81?}\x05b\x7f*\x88\xa6v\x95\x15m\xdb\xf3\
\x96\xd3\'k\xe4\xce\x8c\xe30\xde2a\xa7~\xfblWw\x14\xc3)\xe0S\xe9\x88~\x1c\
\xc5\xc4\xe5\xa4\xd0^\xe1\x96X\xe6\xf7\xb2\xc2my\xe1\x95\xa0\xfe\xe7\xfd\xe2\
\xd1s\x13\x08>9}\x929\xbam\xdd\xb3\'\t\r)\xc4\x97\x9d\xb2\xc7v\x87\xbc\x86\
\xfdx\x17\xc7qZ\x12<\xa3\xe9\xf7!\x9cp\x89\x87\xd8RaiS\xf4\xe5\xaa\xdc\x839!\
\x93\x93\x91\x13~U\x9c_\x182\xe1\xa1\xa9\xce8C \x0c\x86\xeb\\\xa7g\xfad\x03\
\x0ei\x1cl&^?\x81\xe7\xf5\xdb\xea9\xbc\x89\xbd)\xf8\x96\xf7\xc7%1\xdfL\x9fu\
\x89\x8c\xb8\xa8\x10\xbaSh\x1b\x92\xfbRI\xe1\xb1\x9cL\xa1 \x92\x13\xc9\xc9\
\xc8\xca\xc8\x86\xcc\x83\x85\xc3\x85;B\x08/\xc5q\xdc<\x8b\x80\xa6\x1bg\x9a\
\xb4\xaea\xa82\x9c\xf8\xf2G\xb6\xdb\xe5\xdf\xb0U\x12\x1e\x83\x12\x99\xd0\xda\
\xacM\x93\x1b6\x86\x8b\x0b\x9d\x10~E\xf1\xb3\xb1\xf2\xe3\x1d\xa29\x05Yy\x91\
\x82lJ \x92\x15\x89d\xc4\x13\xe3Or|U\x08a,\x8e\xe3f\x88\xe3X\x08!\xe3\x9f\
\xfd\x82\x87\xed\x98i\xfa\xcc\xcf\x82\xe6\xef\xc4[\xed\xf24\xb6`\x0f\x8eH\
\xe2\xbd\x8e\xe6\xe5\xca\x84{t\xdc>!\xfezV\xb4\xba(+iyy\xd9\xb4\xe5\xe4R\xf8\
\x91H\xdc\x08\xf1\xe6\'FV\xff\xf8s[\x7f\x1e\xc7\xf1x\x8b@\x1e\xbdF\xecU\x9a!\
{7\xb1\xce\x13\x9e\xf7\x1f\xd8\x99\x82\xaf\xbd\x1f\xe0\x0f=\x14\xa2#O\xb7\
\x7f=\x93\x89\x1e-\xcaE%yE9EyE\x05\x05yy\xb9\x94J\xf2\xc9\x88dd\x1c\xec\xcf\
\xbc\xfa\xd7\x8b\x9f\xb9\x0f\xc3Ar\xdc\x94\xb1\xc4F\xff\xeb\x8es\xfc\xe2\x88\
c\xbe\xe9S>\xe7\xa7\xa8\xb5b\xf0R-\x84\x10\x10=\xbc\x7f\xc5\xf7F\xe6\r>\x90E\
YAIAIQIQQQ!]\x87|\x1aHUU\x19\x19e%\xcdS\x1d\x8dO\xb4\xff\xc5B\x0cfS\x02y7X\
\x9e\xdd\x10\x89\xee\xc8\x18\x9b)i\x94u\xfb#\xff\xe2\xb3\xd6\xc5\xd5x\xd3\
\xe5\x80O-B[c\xdb\xdc_\x7f\xa4\xf33\x0e4\xf6\xdb1\xb1]\xb1kX9\x94\x94\x94S\
\x1ae\xf9t=\x96[.;1\xcb\xc9\xc6)\x13\x1a\xfef\xf3\x86 \x11\x89\xc7\'\t\xcc\
\xf2\xe1\xfa\xf6\x86y\x9bz\x1cXuT}\xa6\xb3\'\xa3G\xd5\x8bA\xf8C|7\x16_RzL\
\xbd\x9f\xc7\xac\xa7\xff\xf3\xd9\xf0\xf4K\xcfZ\xbc\xac\xcb\'~\xe3\x17\xcd\n\
\xb3\x95U\x95T\x94T\x15U\x14\x94\xcd\xb7\xc0\xe9Z\xd1\x9aG\x1f\x10\xb7\xc5\
\x898\x1f\x03\x1d\xc8g%J1\xabfL\x89\x81\xc7\x07\xad\xfd\x87\xe5^\x9e\xbb\xfd\
\\8\xda\xf1O\xf8Z\x10\x9e\xc2\x93\xb1\xf8\xc0\xc5r@\xae\xef\x97\xab\xf3f\xdf\
U\xce\xae\xbc\xbd\xcf\x87\xae\x9b\xaf\xa2\xaa\xa2]Y\x9b\x8a\x0ee\x1dJ\xdau\
\x99\xad\xd4\xe8\xb1\xe6K\xf7\x8a\'\xe2$\xaf\xb5Z\xa2r\xa3 9_\xe7(\xfa5\xb7\
\xfb\x8e<mK\xca\xee\xfd\xca\n\xcf\xb6\xff\xb7\t\xf5\x0b\x81\xaa\xe3Y\xbc\x8e\
\xfe\x0e\x06\xe6)\x0c\xfc\x81\xeb\x07F\x1d\xcf\xffT\xbc\xac){sQvY).\xddTi\
\x94\x96\xb6\x87\xca\r\x95\xa8R\xacjS\xd5\xae\xa2]U\xa7\x8aNU\xdd*\xba\xf5\
\x98\xab\x14\xf7X\xf5\xed\xfb\xed\xd9\xdc\x9f\xa4\x8d\x1e\xad\x15h\xfa+\xeb\
\xb0%\x9b\xf2i\x18uRAS\x909u`\xc4\x0f\xbe\xb8\xc9\x83_\xb8\xdb\xce\x05{\xbd\
\xe6\xbc\x9a?\x8b\xf5X_AQ\xc6\xb8\xa6o\xd9\xd7\xa8\xca\x85\x8a|\xa6*\xab\xa4\
\xa8\x1aJ\xaa\xd9\x8a\x8a\x8a\x16\xf8\xaa\x0eU]\xaa\xbaTt\xe94\xc7<\x8b\x1d\
\xa9\x8f\xfa\xd8\xf7\x7f\xd3\x9e\x81\xfed\xdd\xc2\x14\xef7\'\xc5a&\xed\x1a\
\xc7\xb0!\xbbEI\xef\xc8\xb1Q\x1b\xfe\xf2\x05\x85\x8d9\x8f4\xd6\xebT=\xef2\
\x94P\x96Q\x96Q\x12)\x8a\xa2\xa2l\xa6$\xa7$?-\xcb\x94\xcel\xd4\xc2\x946W\x9f\
\xde\xb8\xcfWw>\xe5\x86/\xdfj\xd3\x8e\xd7\xce\xfe\x91Q\x89\x1ax\xd3q\x89<\
\x89[\xc2-\x8b\x8a\xe3\xc6,u\xb7\xac \x97\xf4\xee\xdbq\xd8\xae\xd7\x07\xfc\
\xf6\x82u\xee\xec\xb8U\x1cb\x87\x1c\x9b\xea\x049\x94\x84\x94@\xa4,\xab,\xa7$\
7%E\x16\x14\x15\x94\xce\x80Ozg\xbb\xce"\x8b,\xb4\xd8\xff\x9c\x1cp\xf77>\xed\
\xb9M/L\x82\x0e\x92\xf0\xd9\xe8m\xbb\xbdm\x97\xedv\xda`\xcc6\x1ci\x1ddE\xcc\
\xc5j\xcb|\xde\xcd\xd6(pV+R\x99_t\xd7\x9d+\xac]\xfaK\xc6+u?\xf1\x9aWl\x951\
\xa6"\xa3*R\x15\xa9\xc8\xa9\xc8\xa9*\xa8(\xa8\xa4\xb9\xa5\xa2\xac\xaaj\x91\
\x85nt\xa3\xf9\x16zg\xac\xe6\x99\xbd/\xfb\xe6\x0f\xbf\xef\xddC\x87\xde\xbb\
\xb4\xa7\xf1\xef\xb6\xd9\xedE\x89\xee:$\x911o\xe2p\x8b@$\xc9.7\xe2\xc3V\xf9\
\x13\x1f\xb2Pi\x1a\x89\xfc\xe4\xbc\x9d}m\xee]\xb5\xc6G\xfan\xd3\xddV\xaaG\
\xf9\x89l\xc6\xb8a\'\x8c\x186\xa6\xa6K\xd5l]ztj\xd7)\x8a\xcbq\xa3\x19\xc5\
\xfbF\x872\xcf\xecy\xd5\x86\x1f\xfd\xe0\xecK\x80\xe96\x8e\xe7\rx\xd5\xb7$\
\xfa\xeb\xdd4\x88Z*w\xb4E\xe0L~\xc6r\xac\xb5\xc2#n1_\xc7\x14\x02\xe7\xbb\xc3\
(P\xe8\xcc\xea\xed\xea1\xaf\xb3[_\xc7\xacf\xbd!\x1c8z,\xbcsh\xd0\xe0\xe01\
\x8d\xfa%\xd45\'\xb1\xc9Q\x1b=\xa1\xe9g\xd8%\x91\xecc\x92\xf8\xaf\x9f\x11sH\
\x04]\x92[\xe7`\x19VZd\xbd\xb5n\xb3@\xb8\xb2w\x0bS\xac\x8e74\xbd\xe2u\xfd\
\x9e\xc1\xab\xd8!\t\x9d\x9a\xb42ii\xb03>\x8d\xe3\xb8\x19B\x18\x93H\xe4d\xaa\
\xb7\x8d\x18\xf2\x8e\xe5\xeer\xb3Ns]\xd9B\xfd 6;l\xab\x17\xd5l\x91\x84\xcd\
\xee\x14Sm\xa6\xba"L\x17\x93\xe9~(\xa2[r\x99u\x13n2\xcb\x1a\xcb\xac\xb4X\x9b\
^\x89\xfc{\xbf\xd6*\x92\x06\xc5\xf6\x1a\xb6\xdb\x16\x87\xbd$\t\x977\xb0OR,\
\x8d\x9e\xab(z\x0f\x81\x94DF\xb2\'\xda\xd0\x8b\x05X\x8cE*n\xd2k\xb9\xc5\xfa\
\xccU\xd0\x9e\x8e*^\x04\xe0\x86dc\x8e\xe0\xb0X\xbfS\x0e\x180h\x871\xfdx\x1bo\
a@RS\x0fc\xfc|\xcawF\x02)\x89 \t\xb1b\nq\xb6$\xd5\xceK[\xaf\xb2>\xed\xfaT\
\xcc\xd6\xadS\xbb\xa2\x82HR\x0b\x06M\xb1\x11\r\xa7M\x186\xe6\xb4\x9a\t55\xc7\
\x1d\xf1\x86q\x07$\xb1}\xd0d\x8a<b\xb2\xcak\\\xa8\xde8\'\x81)D2)\x91\x02*\
\x12\x15\xd8-Q&\xdd\xe8\x92H\xdb\xaa$\xb0\xf2\xe9\xf8H\xe2\xf3\xba\xc4\xef\
\xadb\x7f$\x05xtJ\x1b\x92\xdcd\x8cH\xb2L\xfdb\xeb\x8d\x0b\x12\x98F$\x92\x1c\
\xbcy\x89z\xa8LiE\x93\xa7E\x94\xb6Vq?\x91\x92\x18O\x01\x8e\x98\xbc\x82\xa9\
\x99r\x19p\xa9\x85\xd2E\x13\x98B\xa4%\xadZ \xb3&=\x9e*\xa93-\x11\x8a\t\x91\
\xd6s\xea\x8dE\xab/\xbe\xdc\xd2\xf4\x92\t\xcc@\x86I\xbdh\x86\xe7\xa4\x82\xbf\
\xac\x1b\x8b\x0b`\xb8\xf6O\xfdU\xb6k\x04\xae\xb6]#p\xb5\xed\xff\x00\xffpD!\
\x93;\xfd \x00\x00\x00\x00IEND\xaeB`\x82j\x88\xbf\xb5'
| anish/phatch | phatch/actions/transpose.py | Python | gpl-3.0 | 9,462 |
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { DatePipe, Location } from '@angular/common';
import { addYears, subYears, addDays, startOfMonth, endOfMonth, getMonth, getYear, isToday, isValid } from 'date-fns';
import { CalendarDateFormatter, CalendarMonthViewDay, CalendarEvent } from 'angular-calendar';
import { CustomDateFormatter } from './custom-date-formatter.provider';
import { Observable, BehaviorSubject, Subject } from 'rxjs/Rx';
import { AdminApi } from '../../remote';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MatSnackBar } from '@angular/material';
@Component({
selector: 'app-holidays',
templateUrl: './holidays.component.html',
styleUrls: ['./holidays.component.css'],
providers: [
{
provide: CalendarDateFormatter,
useClass: CustomDateFormatter
}
],
encapsulation: ViewEncapsulation.None
})
export class HolidaysComponent implements OnInit {
public showLoadSpinner = true;
@ViewChild('picker')
public picker1: any;
// calendar properties https://mattlewis92.github.io/angular-calendar/
public view: string = 'month';
public viewYear: BehaviorSubject<Date> = new BehaviorSubject<Date>(new Date());
public viewYearNumber: number;
public locale: string = 'en';
public yearMonths: Date[] = [];
public refresh: Subject<any> = new Subject();
public holidaysSaveDisabled: boolean = false;
private sub: any;
//public holidays: CalendarMonthViewDay[] = [];
public holidays: Map<String, CalendarMonthViewDay> = new Map<String, CalendarMonthViewDay>();
constructor(private adminService: AdminApi, private datePipe: DatePipe,
private route: ActivatedRoute,
private location: Location,
public snackBar: MatSnackBar
//private router: Router
) { }
ngOnInit() {
this.viewYear.subscribe(date => {
this.showLoadSpinner = true;
this.viewYearNumber = date.getFullYear();
this.getHolidays(this.viewYearNumber);
})
this.sub = this.route.params.subscribe(params => {
let yearDate = new Date(+params['year'], 0, 1, 0, 0, 0); // (+) converts string 'year' to a number
if (isValid(yearDate)) {
this.viewYear.next(yearDate);
}
});
}
public getHolidays(year) {
this.location.replaceState("admin/globalSettings/holidays/"+year);
this.adminService.globalsettingsHolidaysYearGet(year).subscribe(holidays => {
// console.log(holidays);
this.holidays = new Map<String, CalendarMonthViewDay>();
for (let holiday of holidays) {
let dtStr = this.datePipe.transform(holiday, 'yyyy-MM-dd');
let calDay: CalendarMonthViewDayImp = new CalendarMonthViewDayImp();
calDay.date = holiday;
this.holidays.set(dtStr, calDay);
}
this.buildMonths(year);
this.refresh.next();
this.showLoadSpinner = false;
});
}
public setHolidays() {
this.holidaysSaveDisabled = true;
this.showLoadSpinner = true;
let holidays: string[] = Array.from(this.holidays, x => this.datePipe.transform(x[1].date, 'yyyy-MM-dd'));
this.adminService.globalsettingsHolidaysYearPost(this.viewYearNumber, holidays).subscribe(response => {
//console.log(response);
this.holidaysSaveDisabled = false;
this.showLoadSpinner = false;
this.openSnackBar('Holidays saved!', 'ok', true);
},
error => {
this.openSnackBar('Holidays could not be saved!', 'ok', false);
});
}
ngAfterViewInit() { }
buildMonths(year: number) {
for (let i = 0; i < 12; i++) {
this.yearMonths[i] = new Date(year, i);
}
//console.log("build");
}
prevYear() {
this.viewYear.next(subYears(this.viewYear.getValue(), 1));
}
nextYear() {
this.viewYear.next(addYears(this.viewYear.getValue(), 1));
}
clickedDate(day: CalendarMonthViewDay, monthDate: Date) {
if (monthDate.getMonth() !== day.date.getMonth()) {
return;
}
let dtStr = this.datePipe.transform(day.date, 'yyyy-MM-dd');
let holiday: CalendarMonthViewDay = this.holidays.get(dtStr);
if (!holiday) {
day.cssClass = 'cal-day-selected';
this.holidays.set(dtStr, day);
} else {
delete day.cssClass;
this.holidays.delete(dtStr);
}
//console.log(this.holidays);
}
beforeMonthViewRender({ body }: { body: CalendarMonthViewDay[] }): void {
body.forEach(day => {
let dtStr = this.datePipe.transform(day.date, 'yyyy-MM-dd');
let holiday: CalendarMonthViewDay = this.holidays.get(dtStr);
if (holiday) {
day.cssClass = 'cal-day-selected';
}
});
}
// success and error snackBars
private openSnackBar(message: string, action: string, timeOut: boolean) {
if (timeOut) {
this.snackBar.open(message, action, {
duration: 5000,
extraClasses: ['success-snack-bar']
});
} else {
this.snackBar.open(message, action, {
extraClasses: ['error-snack-bar']
});
}
}
}
class CalendarMonthViewDayImp implements CalendarMonthViewDay {
inMonth: boolean;
events: CalendarEvent[];
backgroundColor?: string;
badgeTotal: number;
meta?: any;
date: Date;
isPast: any;
isToday;
isFuture;
isWeekend;
} | jrtdev/yum | yumfe/src/app/admin/holidays/holidays.component.ts | TypeScript | gpl-3.0 | 5,296 |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipaySecurityProdFingerprintApplyResponse.
/// </summary>
public class AlipaySecurityProdFingerprintApplyResponse : AopResponse
{
/// <summary>
/// IFAA标准中的校验类型,目前1为指纹
/// </summary>
[XmlElement("auth_type")]
public string AuthType { get; set; }
/// <summary>
/// 设备的唯一ID,IFAA标准体系中的设备的唯一标识,用于关联设备的开通状态
/// </summary>
[XmlElement("device_id")]
public string DeviceId { get; set; }
/// <summary>
/// IFAA标准中用于关联IFAA Server和业务方Server开通状态的token,此token用于后续校验和注销操作。
/// </summary>
[XmlElement("token")]
public string Token { get; set; }
}
}
| ColgateKas/cms | source/BaiRong.Core/ThirdParty/Alipay/openapi/Response/AlipaySecurityProdFingerprintApplyResponse.cs | C# | gpl-3.0 | 926 |
/* Avuna HTTPD - General Server Applications Copyright (C) 2015 Maxwell Bruce 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.avuna.httpd.http;
import java.text.SimpleDateFormat;
import org.avuna.httpd.AvunaHTTPD;
import org.avuna.httpd.http.event.EventMethodLookup;
import org.avuna.httpd.http.networking.RequestPacket;
import org.avuna.httpd.http.networking.ResponsePacket;
/** Creates a http response coming from the server. */
public class ResponseGenerator {
/** Our constructor */
public ResponseGenerator() {
}
/** Date format that isn't being used. */
public static final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
/** Processes a request and fills in the ResponsePacket
*
* @param request the request
* @param response the response to fill in
* @return returns the success of handling the request. */
public static boolean process(RequestPacket request, ResponsePacket response) {
// Check if httpVersion is compatible
if (!request.httpVersion.equals("HTTP/1.1")) {
// NOTE: StatusCode.NEEDS_HTTP_1_1??
if (request.httpVersion.equals("HTTP/1.0")) {
request.headers.addHeader("Host", "");
}
}
try {
// Logger.log("rg");
// response.headers.addHeader("Date", sdf.format(new Date())); timeless for optimization
response.headers.addHeader("Server", "Avuna/" + AvunaHTTPD.VERSION);
if (request.headers.hasHeader("Connection")) {
response.headers.addHeader("Connection", request.headers.getHeader("Connection"));
}
if (request.host == null) {
ResponseGenerator.generateDefaultResponse(response, StatusCode.INTERNAL_SERVER_ERROR);
response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.INTERNAL_SERVER_ERROR, "The requested host was not found on this server. Please contratc your server administrator.");
return false;
}
EventMethodLookup elm = new EventMethodLookup(request.method, request, response);
request.host.eventBus.callEvent(elm);
if (!elm.isCanceled()) {
generateDefaultResponse(response, StatusCode.NOT_YET_IMPLEMENTED);
response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.NOT_YET_IMPLEMENTED, "The requested URL " + request.target + " via " + request.method.name + " is not yet implemented.");
return false;
}else {
// System.out.println((ah - start) / 1000000D + " start-ah");
// System.out.println((ah2 - ah) / 1000000D + " ah-ah2");
// System.out.println((ah3 - ah2) / 1000000D + " ah2-ah3");
// System.out.println((cur - ah3) / 1000000D + " ah3-cur");
return true;
}
}catch (Exception e) {
request.host.logger.logError(e);
generateDefaultResponse(response, StatusCode.INTERNAL_SERVER_ERROR);
response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.INTERNAL_SERVER_ERROR, "The requested URL " + request.target + " caused a server failure.");
return false;
}
}
/** Generates the stausCode, httpVersion and reasonPhrase for the response
*
* @param response the response packet
* @param status the status to set. */
public static void generateDefaultResponse(ResponsePacket response, StatusCode status) {
response.statusCode = status.getStatus();
response.httpVersion = "HTTP/1.1";
response.reasonPhrase = status.getPhrase();
}
}
| JavaProphet/AvunaHTTPD-Java | src/org/avuna/httpd/http/ResponseGenerator.java | Java | gpl-3.0 | 4,004 |
<?php
$graph_type = "toner_usage";
$toners = dbFetchRows("SELECT * FROM `toner` WHERE device_id = ?", array($device['device_id']));
if (count($toners))
{
echo("<div style='background-color: #eeeeee; margin: 5px; padding: 5px;'>");
echo("<p style='padding: 0px 5px 5px;' class=sectionhead>");
echo('<a class="sectionhead" href="device/device='.$device['device_id'].'/tab=toner/">');
echo("<img align='absmiddle' src='images/icons/toner.png'> Toner</a></p>");
echo("<table width=100% cellspacing=0 cellpadding=5>");
foreach ($toners as $toner)
{
$percent = round($toner['toner_current'], 0);
$total = formatStorage($toner['toner_size']);
$free = formatStorage($toner['toner_free']);
$used = formatStorage($toner['toner_used']);
$background = toner2colour($toner['toner_descr'], $percent);
$graph_array = array();
$graph_array['height'] = "100";
$graph_array['width'] = "210";
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $toner['toner_id'];
$graph_array['type'] = $graph_type;
$graph_array['from'] = $config['time']['day'];
$graph_array['legend'] = "no";
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link = generate_url($link_array);
$overlib_content = generate_overlib_content($graph_array, $device['hostname'] . " - " . $toner['toner_descr']);
$graph_array['width'] = 80; $graph_array['height'] = 20; $graph_array['bg'] = 'ffffff00'; # the 00 at the end makes the area transparent.
$minigraph = generate_graph_tag($graph_array);
echo("<tr class=device-overview>
<td class=tablehead>".overlib_link($link, $toner['toner_descr'], $overlib_content)."</td>
<td width=90>".overlib_link($link, $minigraph, $overlib_content)."</td>
<td width=200>".overlib_link($link, print_percentage_bar (200, 20, $percent, NULL, "ffffff", $background['left'], $percent . "%", "ffffff", $background['right']), $overlib_content)."
</a></td>
</tr>");
}
echo("</table>");
echo("</div>");
}
unset ($toner_rows);
?>
| zylon-internet/librenms | html/pages/device/overview/toner.inc.php | PHP | gpl-3.0 | 2,200 |
#include "testapi.h"
#include "spark_wiring_i2c.h"
#include "Serial2/Serial2.h"
#include "Serial3/Serial3.h"
#include "Serial4/Serial4.h"
#include "Serial5/Serial5.h"
test(api_i2c)
{
int buffer;
API_COMPILE(buffer=I2C_BUFFER_LENGTH);
(void)buffer;
}
test(api_wiring_pinMode) {
PinMode mode = PIN_MODE_NONE;
API_COMPILE(mode=getPinMode(D0));
API_COMPILE(pinMode(D0, mode));
(void)mode;
}
test(api_wiring_analogWrite) {
API_COMPILE(analogWrite(D0, 50));
API_COMPILE(analogWrite(D0, 50, 10000));
}
test(api_wiring_wire_setSpeed)
{
API_COMPILE(Wire.setSpeed(CLOCK_SPEED_100KHZ));
}
void D0_callback()
{
}
test(api_wiring_interrupt) {
API_COMPILE(interrupts());
API_COMPILE(noInterrupts());
API_COMPILE(attachInterrupt(D0, D0_callback, RISING));
API_COMPILE(detachInterrupt(D0));
class MyClass {
public:
void handler() { }
} myObj;
API_COMPILE(attachInterrupt(D0, &MyClass::handler, &myObj, RISING));
API_COMPILE(attachSystemInterrupt(SysInterrupt_TIM1_CC_IRQ, D0_callback));
API_COMPILE(attachInterrupt(D0, D0_callback, RISING, 14));
API_COMPILE(attachInterrupt(D0, D0_callback, RISING, 14, 0));
API_COMPILE(attachInterrupt(D0, &MyClass::handler, &myObj, RISING, 14));
API_COMPILE(attachInterrupt(D0, &MyClass::handler, &myObj, RISING, 14, 0));
}
test(api_wiring_usartserial) {
API_COMPILE(Serial1.halfduplex(true));
API_COMPILE(Serial1.halfduplex(false));
API_COMPILE(Serial1.blockOnOverrun(false));
API_COMPILE(Serial1.blockOnOverrun(true));
API_COMPILE(Serial1.availableForWrite());
API_COMPILE(Serial1.begin(9600, SERIAL_8N1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8N2));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8E1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8E2));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8O1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8O2));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_9N1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_9N2));
API_COMPILE(Serial1.end());
}
test(api_wiring_usbserial) {
API_COMPILE(Serial.blockOnOverrun(false));
API_COMPILE(Serial.blockOnOverrun(true));
API_COMPILE(Serial.availableForWrite());
}
void TIM3_callback()
{
}
#if PLATFORM_ID>=6
// system interrupt not available for the core yet.
test(api_wiring_system_interrupt) {
API_COMPILE(attachSystemInterrupt(SysInterrupt_TIM3_IRQ, TIM3_callback));
API_COMPILE(detachSystemInterrupt(SysInterrupt_TIM3_IRQ));
}
#endif
void externalLEDHandler(uint8_t r, uint8_t g, uint8_t b) {
}
class ExternalLed {
public:
void handler(uint8_t r, uint8_t g, uint8_t b) {
}
} externalLed;
test(api_rgb) {
bool flag; uint8_t value;
API_COMPILE(RGB.brightness(50));
API_COMPILE(RGB.brightness(50, false));
API_COMPILE(flag=RGB.controlled());
API_COMPILE(RGB.control(true));
API_COMPILE(RGB.color(255,255,255));
API_COMPILE(RGB.color(RGB_COLOR_WHITE));
API_COMPILE(flag=RGB.brightness());
API_COMPILE(RGB.onChange(externalLEDHandler));
API_COMPILE(RGB.onChange(&ExternalLed::handler, &externalLed));
(void)flag; (void)value; // unused
}
test(api_servo_trim)
{
Servo servo;
servo.setTrim(234);
}
test(api_wire)
{
API_COMPILE(Wire.begin());
API_COMPILE(Wire.reset());
API_COMPILE(Wire.end());
}
test(api_map)
{
map(0x01,0x00,0xFF,0,255);
}
/**
* Ensures that we can stil take the address of the global instances.
*
*/
test(api_wiring_globals)
{
void* ptrs[] = {
&SPI,
#if Wiring_SPI1
&SPI1,
#endif
#if Wiring_SPI2
&SPI2,
#endif
&Serial,
&Wire,
#if Wiring_Wire1
&Wire1,
#endif
#if Wiring_Wire3
&Wire3,
#endif
&Serial1,
#if Wiring_Serial2
&Serial2,
#endif
#if Wiring_Serial3
&Serial3,
#endif
#if Wiring_Serial4
&Serial4,
#endif
#if Wiring_Serial5
&Serial5,
#endif
&EEPROM,
};
(void)ptrs;
}
| bluzDK/bluzDK-firmware | user/tests/wiring/api/wiring.cpp | C++ | gpl-3.0 | 4,116 |
/*
* This file is part of MUSIC.
* Copyright (C) 2009 INCF
*
* MUSIC 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.
*
* MUSIC 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 "music/distributor.hh"
#include "music/debug.hh"
#if MUSIC_USE_MPI
// distributor.hh needs to be included first since it causes inclusion
// of mpi.h (in data_map.hh). mpi.h must be included before other
// header files on BG/L
#include <algorithm>
#include <cstring>
#include "music/event.hh"
namespace MUSIC {
Distributor::Interval::Interval (IndexInterval& interval)
{
setBegin (interval.begin ());
setLength (interval.end () - interval.begin ());
}
void
Distributor::configure (DataMap* dmap)
{
dataMap = dmap;
}
IntervalTree<int, MUSIC::Interval, int>*
Distributor::buildTree ()
{
IntervalTree<int, MUSIC::Interval, int>* tree
= new IntervalTree<int, MUSIC::Interval, int> ();
IndexMap* indices = dataMap->indexMap ();
for (IndexMap::iterator i = indices->begin ();
i != indices->end ();
++i)
{
MUSIC_LOGR ("adding (" << i->begin () << ", " << i->end ()
<< ", " << i->local () << ") to tree");
tree->add (*i, i->local ());
}
tree->build ();
return tree;
}
void
Distributor::addRoutingInterval (IndexInterval interval, FIBO* buffer)
{
BufferMap::iterator b = buffers.find (buffer);
if (b == buffers.end ())
{
buffers.insert (std::make_pair (buffer, Intervals ()));
b = buffers.find (buffer);
}
Intervals& intervals = b->second;
intervals.push_back (Interval (interval));
}
void
Distributor::IntervalCalculator::operator() (int& offset)
{
interval_.setBegin (elementSize_
* (interval_.begin () - offset));
interval_.setLength (elementSize_ * interval_.length ());
}
void
Distributor::initialize ()
{
IntervalTree<int, MUSIC::Interval, int>* tree = buildTree ();
for (BufferMap::iterator b = buffers.begin (); b != buffers.end (); ++b)
{
FIBO* buffer = b->first;
Intervals& intervals = b->second;
sort (intervals.begin (), intervals.end ());
int elementSize = dataMap->type ().Get_size ();
int size = 0;
for (Intervals::iterator i = intervals.begin ();
i != intervals.end ();
++i)
{
IntervalCalculator calculator (*i, elementSize);
tree->search (i->begin (), &calculator);
size += i->length ();
}
buffer->configure (size);
}
delete tree;
}
void
Distributor::distribute ()
{
for (BufferMap::iterator b = buffers.begin (); b != buffers.end (); ++b)
{
FIBO* buffer = b->first;
Intervals& intervals = b->second;
ContDataT* src = static_cast<ContDataT*> (dataMap->base ());
ContDataT* dest = static_cast<ContDataT*> (buffer->insert ());
for (Intervals::iterator i = intervals.begin ();
i != intervals.end ();
++i)
{
MUSIC_LOGR ("src = " << static_cast<void*> (src)
<< ", begin = " << i->begin ()
<< ", length = " << i->length ());
memcpy (dest, src + i->begin (), i->length ());
dest += i->length ();
}
}
}
}
#endif
| weidel-p/MUSIC | src/distributor.cc | C++ | gpl-3.0 | 3,675 |
<?php
/**
* rasp_settings
* Parses the rasp_settings.xml and store the result in the well known rasp settings
* XML file created and restructured php 2012 by Lukas Kremsmayr
*/
/* Please don't make any changes in this file!!
Please make all your changes in the following file:
configs/plugins/rasp/rasp_settings.xml */
$config_file = 'configs/plugins/rasp/rasp_settings.xml'; //Settings XML File
require_once('includes/xmlparser.inc.php'); //XML-Parser
$xml_parser = new Examsly();
if (file_exists($config_file)) {
// $aseco->console('Load rasp Config [' . $config_file . ']');
if ($rasp_settings = $xml_parser->parseXml($config_file)){
/***************************** FEATURES **************************************/
$feature_ranks = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_RANKS'][0]);
$nextrank_show_rp = text2bool($rasp_settings['RASP_SETTINGS']['NEXTRANK_SHOW_POINTS'][0]);
$feature_karma = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_KARMA'][0]);
$allow_public_karma = text2bool($rasp_settings['RASP_SETTINGS']['ALLOW_PUBLIC_KARMA'][0]);
$karma_show_start = text2bool($rasp_settings['RASP_SETTINGS']['KARMA_SHOW_START'][0]);
$karma_show_details = text2bool($rasp_settings['RASP_SETTINGS']['KARMA_SHOW_DETAILS'][0]);
$karma_show_votes = text2bool($rasp_settings['RASP_SETTINGS']['KARMA_SHOW_VOTES'][0]);
$karma_require_finish = $rasp_settings['RASP_SETTINGS']['KARMA_REQUIRE_FINISH'][0];
$remind_karma = $rasp_settings['RASP_SETTINGS']['REMIND_KARMA'][0];
$feature_jukebox = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_JUKEBOX'][0]);
$feature_mxadd = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_MXADD'][0]);
$jukebox_skipleft = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_SKIPLEFT'][0]);
$jukebox_adminnoskip= text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_ADMINNOSKIP'][0]);
$jukebox_permadd = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_PERMADD'][0]);
$jukebox_adminadd = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_ADMINADD'][0]);
$jukebox_in_window = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_IN_WINDOW'][0]);
$admin_contact = $rasp_settings['RASP_SETTINGS']['ADMIN_CONTACT'][0];
$autosave_matchsettings = $rasp_settings['RASP_SETTINGS']['AUTOSAVE_MATCHSETTINGS'][0];
$feature_votes = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_VOTES'][0]);
$uptodate_check = text2bool($rasp_settings['RASP_SETTINGS']['UPTODATE_CHECK'][0]);
$globalbl_merge = text2bool($rasp_settings['RASP_SETTINGS']['GLOBALBL_MERGE'][0]);
$globalbl_url = $rasp_settings['RASP_SETTINGS']['GLOBALBL_URL'][0];
/* unused Settings in MPAseco: */
$feature_stats = true;
$always_show_pb = true;
$prune_records_times = false;
/***************************** PERFORMANCE VARIABLES ***************************/
$minpoints = $rasp_settings['RASP_SETTINGS']['MIN_POINTS'][0];
if(isset($rasp_settings['RASP_SETTINGS']['MIN_RANK'][0]))
$minrank = $rasp_settings['RASP_SETTINGS']['MIN_RANK'][0];
else
$minrank = 3;
if(isset($rasp_settings['RASP_SETTINGS']['MAX_RECS'][0]))
$maxrecs = $rasp_settings['RASP_SETTINGS']['MAX_RECS'][0];
else
$maxrecs = 50;
if(isset($rasp_settings['RASP_SETTINGS']['MAX_AVG'][0]))
$maxavg = $rasp_settings['RASP_SETTINGS']['MAX_AVG'][0];
else
$maxavg = 10;
/***************************** JUKEBOX VARIABLES *******************************/
$buffersize = $rasp_settings['RASP_SETTINGS']['BUFFER_SIZE'][0];
$mxvoteratio = $rasp_settings['RASP_SETTINGS']['MX_VOTERATIO'][0];
$mxdir = $rasp_settings['RASP_SETTINGS']['MX_DIR'][0];
$mxtmpdir = $rasp_settings['RASP_SETTINGS']['MX_TMPDIR'][0];
/******************************* IRC VARIABLES *********************************/
$CONFIG = array();
$CONFIG['server'] = $rasp_settings['RASP_SETTINGS']['IRC_SERVER'][0];
$CONFIG['nick'] = $rasp_settings['RASP_SETTINGS']['IRC_BOTNICK'][0];
$CONFIG['port'] = $rasp_settings['RASP_SETTINGS']['IRC_PORT'][0];
$CONFIG['channel']= $rasp_settings['RASP_SETTINGS']['IRC_CHANNEL'][0];
$CONFIG['name'] = $rasp_settings['RASP_SETTINGS']['IRC_BOTNAME'][0];
$show_connect = text2bool($rasp_settings['RASP_SETTINGS']['IRC_SHOW_CONNECT'][0]);
$linesbuffer = array();
$ircmsgs = array();
$outbuffer = array();
$con = array();
$jukebox = array();
$jb_buffer = array();
$mxadd = array();
$mxplaying = false;
$mxplayed = false;
} else {
trigger_error('Could not read/parse rasp config file ' . $config_file . ' !', E_USER_WARNING);
}
} else {
trigger_error('Could not find rasp config file ' . $config_file . ' !', E_USER_WARNING);
}
?>
| ManiaAseco/MPAseco | update/update_v05x-080/includes/rasp.settings.php | PHP | gpl-3.0 | 5,100 |
(function($){
// Search
var $searchWrap = $('#search-form-wrap'),
isSearchAnim = false,
searchAnimDuration = 200;
var startSearchAnim = function(){
isSearchAnim = true;
};
var stopSearchAnim = function(callback){
setTimeout(function(){
isSearchAnim = false;
callback && callback();
}, searchAnimDuration);
};
var s = [
'<div style="display: none;">',
'<script src="https://s11.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>',
'</div>'
].join('');
var di = $(s);
$('#container').append(di);
$('#nav-search-btn').on('click', function(){
if (isSearchAnim) return;
startSearchAnim();
$searchWrap.addClass('on');
stopSearchAnim(function(){
$('.search-form-input').focus();
});
});
$('.search-form-input').on('blur', function(){
startSearchAnim();
$searchWrap.removeClass('on');
stopSearchAnim();
});
// Share
$('body').on('click', function(){
$('.article-share-box.on').removeClass('on');
}).on('click', '.article-share-link', function(e){
e.stopPropagation();
var $this = $(this),
url = $this.attr('data-url'),
encodedUrl = encodeURIComponent(url),
id = 'article-share-box-' + $this.attr('data-id'),
offset = $this.offset();
if ($('#' + id).length){
var box = $('#' + id);
if (box.hasClass('on')){
box.removeClass('on');
return;
}
} else {
var html = [
'<div id="' + id + '" class="article-share-box">',
'<input class="article-share-input" value="' + url + '">',
'<div class="article-share-links">',
'<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
'<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
'<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>',
'<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>',
'</div>',
'</div>'
].join('');
var box = $(html);
$('body').append(box);
}
$('.article-share-box.on').hide();
box.css({
top: offset.top + 25,
left: offset.left
}).addClass('on');
}).on('click', '.article-share-box', function(e){
e.stopPropagation();
}).on('click', '.article-share-box-input', function(){
$(this).select();
}).on('click', '.article-share-box-link', function(e){
e.preventDefault();
e.stopPropagation();
window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
});
// Caption
$('.article-entry').each(function(i){
$(this).find('img').each(function(){
if ($(this).parent().hasClass('fancybox')) return;
var alt = this.alt;
if (alt) $(this).after('<span class="caption">' + alt + '</span>');
$(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
});
$(this).find('.fancybox').each(function(){
$(this).attr('rel', 'article' + i);
});
});
if ($.fancybox){
$('.fancybox').fancybox();
}
// Mobile nav
var $container = $('#container'),
isMobileNavAnim = false,
mobileNavAnimDuration = 200;
var startMobileNavAnim = function(){
isMobileNavAnim = true;
};
var stopMobileNavAnim = function(){
setTimeout(function(){
isMobileNavAnim = false;
}, mobileNavAnimDuration);
}
$('#main-nav-toggle').on('click', function(){
if (isMobileNavAnim) return;
startMobileNavAnim();
$container.toggleClass('mobile-nav-on');
stopMobileNavAnim();
});
$('#wrap').on('click', function(){
if (isMobileNavAnim || !$container.hasClass('mobile-nav-on')) return;
$container.removeClass('mobile-nav-on');
});
})(jQuery); | NiroDu/nirodu.github.io | themes/hiker/source/js/scripts.js | JavaScript | gpl-3.0 | 4,098 |
// I18N constants
// LANG: "es-ar", ENCODING: UTF-8 | ISO-8859-1
// Author: Mihai Bazon, <mishoo@infoiasi.ro>
// FOR TRANSLATORS:
//
// 1. PLEASE PUT YOUR CONTACT INFO IN THE ABOVE LINE
// (at least a valid email address)
//
// 2. PLEASE TRY TO USE UTF-8 FOR ENCODING;
// (if this is not possible, please include a comment
// that states what encoding is necessary.)
//
// Traduccion al español - argentino
// Juan Rossano <jrossano@care2x.org.ar> (2005) Grupo Biolinux
SpellChecker.I18N = {
"CONFIRM_LINK_CLICK" : "Por favor confirme que quiere abrir este enlace",
"Cancel" : "Cancelar",
"Dictionary" : "Diccionario",
"Finished list of mispelled words" : "Terminada la lista de palabras sugeridas",
"I will open it in a new page." : "Debe abrirse una nueva pagina.",
"Ignore all" : "Ignorar todo",
"Ignore" : "Ignorar",
"NO_ERRORS" : "No se han hallado errores con este diccionario.",
"NO_ERRORS_CLOSING" : "Correccion ortrografica completa, no se hallaron palabras erroneas. Cerrando ahora...",
"OK" : "OK",
"Original word" : "Palabra original",
"Please wait. Calling spell checker." : "Por favor espere. Llamando al diccionario.",
"Please wait: changing dictionary to" : "Por favor espere: Cambiando el diccionario a",
"QUIT_CONFIRMATION" : "Esto deshace los cambios y quita el corrector. Por favor confirme.",
"Re-check" : "Volver a corregir",
"Replace all" : "Reemplazar todo",
"Replace with" : "Reemplazar con",
"Replace" : "Reemplazar",
"SC-spell-check" : "Corregir ortografia",
"Suggestions" : "Sugerencias",
"pliz weit ;-)" : "Espere por favor ;-)"
};
| care2x/2.7 | js/html_editor/plugins/SpellChecker/lang/es-ar.js | JavaScript | gpl-3.0 | 2,070 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parsePairs = parsePairs;
exports.createPairs = createPairs;
exports.default = void 0;
var _errors = require("../../errors");
var _Map = _interopRequireDefault(require("../../schema/Map"));
var _Pair = _interopRequireDefault(require("../../schema/Pair"));
var _parseSeq = _interopRequireDefault(require("../../schema/parseSeq"));
var _Seq = _interopRequireDefault(require("../../schema/Seq"));
function parsePairs(doc, cst) {
var seq = (0, _parseSeq.default)(doc, cst);
for (var i = 0; i < seq.items.length; ++i) {
var item = seq.items[i];
if (item instanceof _Pair.default) continue;else if (item instanceof _Map.default) {
if (item.items.length > 1) {
var msg = 'Each pair must have its own sequence indicator';
throw new _errors.YAMLSemanticError(cst, msg);
}
var pair = item.items[0] || new _Pair.default();
if (item.commentBefore) pair.commentBefore = pair.commentBefore ? "".concat(item.commentBefore, "\n").concat(pair.commentBefore) : item.commentBefore;
if (item.comment) pair.comment = pair.comment ? "".concat(item.comment, "\n").concat(pair.comment) : item.comment;
item = pair;
}
seq.items[i] = item instanceof _Pair.default ? item : new _Pair.default(item);
}
return seq;
}
function createPairs(schema, iterable, ctx) {
var pairs = new _Seq.default();
pairs.tag = 'tag:yaml.org,2002:pairs';
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var it = _step.value;
var key = void 0,
value = void 0;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = it[1];
} else throw new TypeError("Expected [key, value] tuple: ".concat(it));
} else if (it && it instanceof Object) {
var keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value = it[key];
} else throw new TypeError("Expected { key: value } tuple: ".concat(it));
} else {
key = it;
}
var pair = schema.createPair(key, value, ctx);
pairs.items.push(pair);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return pairs;
}
var _default = {
default: false,
tag: 'tag:yaml.org,2002:pairs',
resolve: parsePairs,
createNode: createPairs
};
exports.default = _default; | mdranger/mytest | node_modules/yaml/browser/dist/tags/yaml-1.1/pairs.js | JavaScript | mpl-2.0 | 2,962 |
package common
import (
"reflect"
"testing"
)
func TestVBoxBundleConfigPrepare_VBoxBundle(t *testing.T) {
// Test with empty
c := new(VBoxBundleConfig)
errs := c.Prepare(testConfigTemplate(t))
if len(errs) > 0 {
t.Fatalf("err: %#v", errs)
}
if !reflect.DeepEqual(*c, VBoxBundleConfig{BundleISO: false}) {
t.Fatalf("bad: %#v", c)
}
// Test with a good one
c = new(VBoxBundleConfig)
c.BundleISO = true
errs = c.Prepare(testConfigTemplate(t))
if len(errs) > 0 {
t.Fatalf("err: %#v", errs)
}
expected := VBoxBundleConfig{
BundleISO: true,
}
if !reflect.DeepEqual(*c, expected) {
t.Fatalf("bad: %#v", c)
}
}
| bryson/packer | builder/virtualbox/common/vboxbundle_config_test.go | GO | mpl-2.0 | 638 |
// Copyright (C) 2008-2015 Conrad Sanderson
// Copyright (C) 2008-2015 NICTA (www.nicta.com.au)
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//! \addtogroup operator_cube_minus
//! @{
//! unary -
template<typename T1>
arma_inline
const eOpCube<T1, eop_neg>
operator-
(
const BaseCube<typename T1::elem_type,T1>& X
)
{
arma_extra_debug_sigprint();
return eOpCube<T1, eop_neg>(X.get_ref());
}
//! cancellation of two consecutive negations: -(-T1)
template<typename T1>
arma_inline
const typename ProxyCube<T1>::stored_type&
operator-
(
const eOpCube<T1, eop_neg>& X
)
{
arma_extra_debug_sigprint();
return X.P.Q;
}
//! BaseCube - scalar
template<typename T1>
arma_inline
const eOpCube<T1, eop_scalar_minus_post>
operator-
(
const BaseCube<typename T1::elem_type,T1>& X,
const typename T1::elem_type k
)
{
arma_extra_debug_sigprint();
return eOpCube<T1, eop_scalar_minus_post>(X.get_ref(), k);
}
//! scalar - BaseCube
template<typename T1>
arma_inline
const eOpCube<T1, eop_scalar_minus_pre>
operator-
(
const typename T1::elem_type k,
const BaseCube<typename T1::elem_type,T1>& X
)
{
arma_extra_debug_sigprint();
return eOpCube<T1, eop_scalar_minus_pre>(X.get_ref(), k);
}
//! complex scalar - non-complex BaseCube (experimental)
template<typename T1>
arma_inline
const mtOpCube<typename std::complex<typename T1::pod_type>, T1, op_cx_scalar_minus_pre>
operator-
(
const std::complex<typename T1::pod_type>& k,
const BaseCube<typename T1::pod_type, T1>& X
)
{
arma_extra_debug_sigprint();
return mtOpCube<typename std::complex<typename T1::pod_type>, T1, op_cx_scalar_minus_pre>('j', X.get_ref(), k);
}
//! non-complex BaseCube - complex scalar (experimental)
template<typename T1>
arma_inline
const mtOpCube<typename std::complex<typename T1::pod_type>, T1, op_cx_scalar_minus_post>
operator-
(
const BaseCube<typename T1::pod_type, T1>& X,
const std::complex<typename T1::pod_type>& k
)
{
arma_extra_debug_sigprint();
return mtOpCube<typename std::complex<typename T1::pod_type>, T1, op_cx_scalar_minus_post>('j', X.get_ref(), k);
}
//! subtraction of BaseCube objects with same element type
template<typename T1, typename T2>
arma_inline
const eGlueCube<T1, T2, eglue_minus>
operator-
(
const BaseCube<typename T1::elem_type,T1>& X,
const BaseCube<typename T1::elem_type,T2>& Y
)
{
arma_extra_debug_sigprint();
return eGlueCube<T1, T2, eglue_minus>(X.get_ref(), Y.get_ref());
}
//! subtraction of BaseCube objects with different element types
template<typename T1, typename T2>
inline
const mtGlueCube<typename promote_type<typename T1::elem_type, typename T2::elem_type>::result, T1, T2, glue_mixed_minus>
operator-
(
const BaseCube< typename force_different_type<typename T1::elem_type, typename T2::elem_type>::T1_result, T1>& X,
const BaseCube< typename force_different_type<typename T1::elem_type, typename T2::elem_type>::T2_result, T2>& Y
)
{
arma_extra_debug_sigprint();
typedef typename T1::elem_type eT1;
typedef typename T2::elem_type eT2;
typedef typename promote_type<eT1,eT2>::result out_eT;
promote_type<eT1,eT2>::check();
return mtGlueCube<out_eT, T1, T2, glue_mixed_minus>( X.get_ref(), Y.get_ref() );
}
template<typename eT, typename T2>
arma_inline
Cube<eT>
operator-
(
const subview_cube_each1<eT>& X,
const Base<eT,T2>& Y
)
{
arma_extra_debug_sigprint();
return subview_cube_each1_aux::operator_minus(X, Y.get_ref());
}
template<typename T1, typename eT>
arma_inline
Cube<eT>
operator-
(
const Base<eT,T1>& X,
const subview_cube_each1<eT>& Y
)
{
arma_extra_debug_sigprint();
return subview_cube_each1_aux::operator_minus(X.get_ref(), Y);
}
template<typename eT, typename TB, typename T2>
arma_inline
Cube<eT>
operator-
(
const subview_cube_each2<eT,TB>& X,
const Base<eT,T2>& Y
)
{
arma_extra_debug_sigprint();
return subview_cube_each2_aux::operator_minus(X, Y.get_ref());
}
template<typename T1, typename eT, typename TB>
arma_inline
Cube<eT>
operator-
(
const Base<eT,T1>& X,
const subview_cube_each2<eT,TB>& Y
)
{
arma_extra_debug_sigprint();
return subview_cube_each2_aux::operator_minus(X.get_ref(), Y);
}
//! @}
| adevress/armadillo | include/armadillo_bits/operator_cube_minus.hpp | C++ | mpl-2.0 | 4,562 |
package ro.code4.czl.scrape.client.representation;
import java.util.List;
/**
* @author Ionut-Maxim Margelatu (ionut.margelatu@gmail.com)
*/
public class PublicationRepresentation {
private String identifier;
private String title;
private String type;
private String institution;
private String date;
private String description;
private int feedback_days;
private ContactRepresentation contact;
private List<DocumentRepresentation> documents;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getInstitution() {
return institution;
}
public void setInstitution(String institution) {
this.institution = institution;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getFeedback_days() {
return feedback_days;
}
public void setFeedback_days(int feedback_days) {
this.feedback_days = feedback_days;
}
public ContactRepresentation getContact() {
return contact;
}
public void setContact(ContactRepresentation contact) {
this.contact = contact;
}
public List<DocumentRepresentation> getDocuments() {
return documents;
}
public void setDocuments(List<DocumentRepresentation> documents) {
this.documents = documents;
}
public static final class PublicationRepresentationBuilder {
private String identifier;
private String title;
private String type;
private String institution;
private String date;
private String description;
private int feedback_days;
private ContactRepresentation contact;
private List<DocumentRepresentation> documents;
private PublicationRepresentationBuilder() {
}
public static PublicationRepresentationBuilder aPublicationRepresentation() {
return new PublicationRepresentationBuilder();
}
public PublicationRepresentationBuilder withIdentifier(String identifier) {
this.identifier = identifier;
return this;
}
public PublicationRepresentationBuilder withTitle(String title) {
this.title = title;
return this;
}
public PublicationRepresentationBuilder withType(String type) {
this.type = type;
return this;
}
public PublicationRepresentationBuilder withInstitution(String institution) {
this.institution = institution;
return this;
}
public PublicationRepresentationBuilder withDate(String date) {
this.date = date;
return this;
}
public PublicationRepresentationBuilder withDescription(String description) {
this.description = description;
return this;
}
public PublicationRepresentationBuilder withFeedback_days(int feedback_days) {
this.feedback_days = feedback_days;
return this;
}
public PublicationRepresentationBuilder withContact(ContactRepresentation contact) {
this.contact = contact;
return this;
}
public PublicationRepresentationBuilder withDocuments(List<DocumentRepresentation> documents) {
this.documents = documents;
return this;
}
public PublicationRepresentation build() {
PublicationRepresentation publicationRepresentation = new PublicationRepresentation();
publicationRepresentation.setIdentifier(identifier);
publicationRepresentation.setTitle(title);
publicationRepresentation.setType(type);
publicationRepresentation.setInstitution(institution);
publicationRepresentation.setDate(date);
publicationRepresentation.setDescription(description);
publicationRepresentation.setFeedback_days(feedback_days);
publicationRepresentation.setContact(contact);
publicationRepresentation.setDocuments(documents);
return publicationRepresentation;
}
}
}
| mgax/czl-scrape | munca/src/main/java/ro/code4/czl/scrape/client/representation/PublicationRepresentation.java | Java | mpl-2.0 | 4,287 |
# -*- coding: utf-8 -*-
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import re, os, shutil, cgi
from anki.utils import checksum, call, namedtmp, tmpdir, isMac, stripHTML
from anki.hooks import addHook
from anki.lang import _
# if you modify these in an add-on, you must make sure to take tmp.tex as the
# input, and output tmp.png as the output file
latexCmds = [
["latex", "-interaction=nonstopmode", "tmp.tex"],
["dvipng", "-D", "200", "-T", "tight", "tmp.dvi", "-o", "tmp.png"]
# ["dvipng", "-D", "600", "-T", "tight", "-bg", "Transparent", "tmp.dvi", "-o", "tmp.png"]
]
build = True # if off, use existing media but don't create new
regexps = {
"standard": re.compile(r"\[latex\](.+?)\[/latex\]", re.DOTALL | re.IGNORECASE),
"expression": re.compile(r"\[\$\](.+?)\[/\$\]", re.DOTALL | re.IGNORECASE),
"math": re.compile(r"\[\$\$\](.+?)\[/\$\$\]", re.DOTALL | re.IGNORECASE),
}
# add standard tex install location to osx
if isMac:
os.environ['PATH'] += ":/usr/texbin"
def stripLatex(text):
for match in regexps['standard'].finditer(text):
text = text.replace(match.group(), "")
for match in regexps['expression'].finditer(text):
text = text.replace(match.group(), "")
for match in regexps['math'].finditer(text):
text = text.replace(match.group(), "")
return text
def mungeQA(html, type, fields, model, data, col):
"Convert TEXT with embedded latex tags to image links."
for match in regexps['standard'].finditer(html):
html = html.replace(match.group(), _imgLink(col, match.group(1), model))
for match in regexps['expression'].finditer(html):
html = html.replace(match.group(), _imgLink(
col, "$" + match.group(1) + "$", model))
for match in regexps['math'].finditer(html):
html = html.replace(match.group(), _imgLink(
col,
"\\begin{displaymath}" + match.group(1) + "\\end{displaymath}", model))
return html
def _imgLink(col, latex, model):
"Return an img link for LATEX, creating if necesssary."
txt = _latexFromHtml(col, latex)
fname = "latex-%s.png" % checksum(txt.encode("utf8"))
link = '<img class=latex src="%s">' % fname
if os.path.exists(fname):
return link
elif not build:
return u"[latex]%s[/latex]" % latex
else:
err = _buildImg(col, txt, fname, model)
if err:
return err
else:
return link
def _latexFromHtml(col, latex):
"Convert entities and fix newlines."
latex = re.sub("<br( /)?>|<div>", "\n", latex)
latex = stripHTML(latex)
return latex
def _buildImg(col, latex, fname, model):
# add header/footer & convert to utf8
latex = (model["latexPre"] + "\n" +
latex + "\n" +
model["latexPost"])
latex = latex.encode("utf8")
# it's only really secure if run in a jail, but these are the most common
tmplatex = latex.replace("\\includegraphics", "")
for bad in ("\\write18", "\\readline", "\\input", "\\include",
"\\catcode", "\\openout", "\\write", "\\loop",
"\\def", "\\shipout"):
# don't mind if the sequence is only part of a command
bad_re = "\\" + bad + "[^a-zA-Z]"
if re.search(bad_re, tmplatex):
return _("""\
For security reasons, '%s' is not allowed on cards. You can still use \
it by placing the command in a different package, and importing that \
package in the LaTeX header instead.""") % bad
# write into a temp file
log = open(namedtmp("latex_log.txt"), "w")
texpath = namedtmp("tmp.tex")
texfile = file(texpath, "w")
texfile.write(latex)
texfile.close()
mdir = col.media.dir()
oldcwd = os.getcwd()
png = namedtmp("tmp.png")
try:
# generate png
os.chdir(tmpdir())
for latexCmd in latexCmds:
if call(latexCmd, stdout=log, stderr=log):
return _errMsg(latexCmd[0], texpath)
# add to media
shutil.copyfile(png, os.path.join(mdir, fname))
return
finally:
os.chdir(oldcwd)
def _errMsg(type, texpath):
msg = (_("Error executing %s.") % type) + "<br>"
msg += (_("Generated file: %s") % texpath) + "<br>"
try:
log = open(namedtmp("latex_log.txt", rm=False)).read()
if not log:
raise Exception()
msg += "<small><pre>" + cgi.escape(log) + "</pre></small>"
except:
msg += _("Have you installed latex and dvipng?")
pass
return msg
# setup q/a filter
addHook("mungeQA", mungeQA)
| sunclx/anki | anki/latex.py | Python | agpl-3.0 | 4,659 |
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "average_onto_faces.h"
template <typename T, typename I>
IGL_INLINE void igl::average_onto_faces(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &V,
const Eigen::Matrix<I, Eigen::Dynamic, Eigen::Dynamic> &F,
const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &S,
Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> &SF)
{
SF = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>::Zero(F.rows(),S.cols());
for (int i = 0; i <F.rows(); ++i)
for (int j = 0; j<F.cols(); ++j)
SF.row(i) += S.row(F(i,j));
SF.array() /= F.cols();
};
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
#endif
| prusa3d/Slic3r | src/libigl/igl/average_onto_faces.cpp | C++ | agpl-3.0 | 1,017 |
<?php
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.
return [
'promote' => [
'pin' => 'Sei sicuro di voler promuovere questa trasmissione in diretta?',
'unpin' => "Sei sicuro di voler rimuovere la promozione di questa trasmissione in diretta?",
],
'top-headers' => [
'headline' => 'Livestream',
'description' => 'I dati vengono reperiti da twitch.tv ogni cinque minuti. Sei libero di porter avviare una diretta e di comparire sulla lista! Per maggiori informazioni su come iniziare, controlla :link.',
'link' => 'la pagina della wiki riguardante le trasmissioni',
],
];
| ppy/osu-web | resources/lang/it/livestreams.php | PHP | agpl-3.0 | 759 |
class ModeratedGradingForeignKeyIndexes < ActiveRecord::Migration[4.2]
tag :postdeploy
disable_ddl_transaction!
def change
add_index :submission_comments, :provisional_grade_id, where: "provisional_grade_id IS NOT NULL", algorithm: :concurrently
add_index :moderated_grading_provisional_grades, :source_provisional_grade_id, name: 'index_provisional_grades_on_source_grade', where: "source_provisional_grade_id IS NOT NULL", algorithm: :concurrently
add_index :moderated_grading_selections, :selected_provisional_grade_id, name: 'index_moderated_grading_selections_on_selected_grade', where: "selected_provisional_grade_id IS NOT NULL", algorithm: :concurrently
# this index is useless; the index on [assignment_id, student_id] already covers it
remove_index :moderated_grading_selections, column: :assignment_id
add_index :moderated_grading_selections, :student_id, algorithm: :concurrently
end
end
| matematikk-mooc/canvas-lms | db/migrate/20160616151853_moderated_grading_foreign_key_indexes.rb | Ruby | agpl-3.0 | 933 |
package dlug
// 0,1,2,3,4,5,6,7,8
var ByteLen []int = []int{1,2,3,4,5,6,8,9,17}
var PfxBitLen []int = []int{1,2,3,5,5,5,8,8,8}
var BitLen []uint = []uint{7,14,21,27,35,43,56,64,128}
var Pfx []byte = []byte{0,0x80,0xc0,0xe0,0xe8,0xf0,0xf8,0xf9,0xfa,0xff}
func Check(d []byte) bool {
if len(d)==0 { return false }
idx := GetDlugIndex(d)
if idx<0 { return false }
if idx>= len(ByteLen) { return false }
if len(d) != ByteLen[idx] { return false }
return true
}
func CheckCode(d []byte) int {
if len(d)==0 { return -1 }
idx := GetDlugIndex(d)
if idx<0 { return -2 }
if idx>= len(ByteLen) { return -3 }
if len(d) != ByteLen[idx] { return -4 }
return 0
}
func EqualByte(d []byte, b byte) bool {
if len(d)==0 { return false }
if len(d)==1 {
if (d[0]&(0x80)) != 0 { return false }
if (d[0]&0x7f) == b { return true }
return false
}
k := GetDlugIndex(d)
if k<0 { return false }
if d[0]&byte(0xff << (8-byte(PfxBitLen[k]))) != Pfx[k] { return false }
n:=len(d)
if d[n-1]!=b {return false}
for i:=1; i<(n-1); i++ { if d[i]!=0 { return false } }
return true
}
func GetDlugIndex(d []byte) int {
if len(d)==0 { return -1 }
for i:=0; i<len(ByteLen); i++ {
if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] {
return i
}
}
return -2
}
func GetByteLen(d []byte) int {
if len(d)==0 { return -1 }
for i:=0; i<len(ByteLen); i++ {
if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] {
return ByteLen[i]
}
}
return -2
}
func GetDataBitLen(d []byte) int {
if len(d)==0 { return -1 }
for i:=0; i<len(ByteLen); i++ {
if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] {
return int(BitLen[i])
}
}
return -2
}
func GetPrefixBitLen(d []byte) int {
if len(d)==0 { return -1 }
for i:=0; i<len(ByteLen); i++ {
if (d[0] & byte(0xff << (8-byte(PfxBitLen[i])))) == Pfx[i] {
return PfxBitLen[i]
}
}
return -2
}
//-----------------------
// Marshal Byte Functions
//-----------------------
func MarshalByte(b byte) []byte {
if b<(1<<BitLen[0]) { return []byte{b} }
return []byte{ 0x80, b }
}
func MarshalUint32(u uint32) []byte {
if u<(1<<BitLen[0]) { return []byte{ byte(u&0xff) } }
if u<(1<<BitLen[1]) {
return []byte{ byte(Pfx[1] | byte(0xff & (u>>8))), byte(0xff & u) }
}
if u<(1<<BitLen[2]) {
return []byte{ byte(Pfx[2] | byte(0xff & (u>>16))), byte(0xff & (u>>8)), byte(0xff & u) }
}
if u<(1<<BitLen[3]) {
return []byte{ byte(Pfx[3] | byte(0xff & (u>>24))), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
return []byte{ Pfx[4], byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
func MarshalUint64(u uint64) []byte {
if u<(1<<BitLen[0]) { return []byte{ byte(u&0xff) } }
if u<(1<<BitLen[1]) {
return []byte{ byte(Pfx[1] | byte(0xff & (u>>8))), byte(0xff & u) }
}
if u<(1<<BitLen[2]) {
return []byte{ byte(Pfx[2] | byte(0xff & (u>>16))), byte(0xff & (u>>8)), byte(0xff & u) }
}
if u<(1<<BitLen[3]) {
return []byte{ byte(Pfx[3] | byte(0xff & (u>>24))), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
if u<(1<<BitLen[4]) {
return []byte{ byte(Pfx[4] | byte(0xff & (u>>32))), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
if u<(1<<uint64(BitLen[5])) {
return []byte{ byte(Pfx[5] | byte(0xff & (u>>40))), byte(0xff & (u>>32)), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
if u<(1<<uint64(BitLen[6])) {
return []byte{ Pfx[6], byte(0xff & (u>>48)), byte(0xff & (u>>40)), byte(0xff & (u>>32)), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
return []byte{ Pfx[7], byte(0xff & (u>>56)), byte(0xff & (u>>48)), byte(0xff & (u>>40)), byte(0xff & (u>>32)), byte(0xff & (u>>24)), byte(0xff & (u>>16)), byte(0xff & (u>>8)), byte(0xff & u) }
}
//---------------------
// Fill Slice Functions
//---------------------
func FillSliceByte(s []byte, b byte) int {
if len(s) == 0 { return -1 }
if b<(1<<BitLen[0]) { s[0] = b; return 1 }
if len(s) < 2 { return -1 }
s[0] = 0x80
s[1] = b
return 2
}
func FillSliceUint32(s []byte, u uint32) int {
if len(s)==0 { return -1 }
if u<(1<<BitLen[0]) {
s[0] = byte(u&0xff)
return 1
}
if len(s)<int(ByteLen[1]) { return -1 }
if u<(1<<BitLen[1]) {
s[0] = byte(Pfx[1] | byte(0xff & (u>>8)))
s[1] = byte(0xff & u)
return ByteLen[1]
}
if len(s)<ByteLen[2] { return -1 }
if u<(1<<BitLen[2]) {
s[0] = byte(Pfx[2] | byte(0xff & (u>>16)))
s[1] = byte(0xff & (u>>8))
s[2] = byte(0xff & u)
return ByteLen[2]
}
if len(s)<ByteLen[3] { return -1 }
if u<(1<<BitLen[3]) {
s[0] = byte(Pfx[3] | byte(0xff & (u>>24)))
s[1] = byte(0xff & (u>>16))
s[2] = byte(0xff & (u>>8))
s[3] = byte(0xff & u)
return ByteLen[3]
}
if len(s)<ByteLen[4] { return -1 }
s[0] = Pfx[4]
s[1] = byte(0xff & (u>>24))
s[2] = byte(0xff & (u>>16))
s[3] = byte(0xff & (u>>8))
s[4] = byte(0xff & u)
return ByteLen[4]
}
func FillSliceUint64(s []byte, u uint64) int {
if len(s)==0 { return -1 }
if u<(1<<BitLen[0]) {
s[0] = byte(u&0xff)
return 1
}
if len(s)<ByteLen[1] { return -1 }
if u<(1<<BitLen[1]) {
s[0] = byte(Pfx[1] | byte(0xff & (u>>8)))
s[1] = byte(0xff & u)
return ByteLen[1]
}
if len(s)<ByteLen[2] { return -1 }
if u<(1<<BitLen[2]) {
s[0] = byte(Pfx[2] | byte(0xff & (u>>16)))
s[1] = byte(0xff & (u>>8))
s[2] = byte(0xff & u)
return ByteLen[2]
}
if len(s)<ByteLen[3] { return -1 }
if u<(1<<BitLen[3]) {
s[0] = byte(Pfx[3] | byte(0xff & (u>>24)))
s[1] = byte(0xff & (u>>16))
s[2] = byte(0xff & (u>>8))
s[3] = byte(0xff & u)
return ByteLen[3]
}
if len(s)<ByteLen[4] { return -1 }
if u<(1<<BitLen[4]) {
s[0] = Pfx[4] | byte(0xff & (u>>32))
s[1] = byte(0xff & (u>>24))
s[2] = byte(0xff & (u>>16))
s[3] = byte(0xff & (u>>8))
s[4] = byte(0xff & u)
return ByteLen[4]
}
if len(s)<ByteLen[5] { return -1 }
if u<(1<<uint64(BitLen[5])) {
s[0] = Pfx[5] | byte(0xff & (u>>40))
s[1] = byte(0xff & (u>>32))
s[2] = byte(0xff & (u>>24))
s[3] = byte(0xff & (u>>16))
s[4] = byte(0xff & (u>>8))
s[5] = byte(0xff & u)
return ByteLen[5]
}
if len(s)<ByteLen[6] { return -1 }
if u<(1<<uint64(BitLen[6])) {
s[0] = Pfx[6]
s[1] = byte(0xff & (u>>48))
s[2] = byte(0xff & (u>>40))
s[3] = byte(0xff & (u>>32))
s[4] = byte(0xff & (u>>24))
s[5] = byte(0xff & (u>>16))
s[6] = byte(0xff & (u>>8))
s[7] = byte(0xff & u)
return ByteLen[6]
}
if len(s)<ByteLen[7] { return -1 }
s[0] = Pfx[7]
s[1] = byte(0xff & (u>>56))
s[2] = byte(0xff & (u>>48))
s[3] = byte(0xff & (u>>40))
s[4] = byte(0xff & (u>>32))
s[5] = byte(0xff & (u>>24))
s[6] = byte(0xff & (u>>16))
s[7] = byte(0xff & (u>>8))
s[8] = byte(0xff & u)
return ByteLen[7]
}
//------------------
// Convert Functions
//------------------
func ConvertByte(b []byte) (byte, int) {
idx := GetDlugIndex(b)
if idx<0 { return 0,idx }
if idx==0 { return b[0]&0x7f,1 }
if len(b) < ByteLen[idx] { return 0,-1 }
return b[ByteLen[idx]-1], ByteLen[idx]
}
func ConvertUint32(b []byte) (uint32, int) {
idx := GetDlugIndex(b)
if idx<0 { return 0,idx }
if idx==0 { return uint32(b[0]&0x7f),1 }
if len(b) < ByteLen[idx] { return 0,-1 }
if idx==1 { return (uint32(b[0]&(^Pfx[1])) << 8) + uint32(b[1]), 2 }
if idx==2 { return (uint32(b[0]&(^Pfx[2])) << 16) + (uint32(b[1])<<8) + uint32(b[2]), 3 }
if idx==3 { return (uint32(b[0]&(^Pfx[3])) << 24) + (uint32(b[1])<<16) + (uint32(b[2])<<8) + uint32(b[3]), 4 }
n := ByteLen[idx]
return (uint32(b[n-4])<<24) + (uint32(b[n-3])<<16) + (uint32(b[n-2])<<8) + uint32(b[n-1]), n
}
func ConvertUint64(b []byte) (uint64, int) {
idx := GetDlugIndex(b)
if idx<0 { return 0,idx }
if idx==0 { return uint64(b[0]&0x7f),1 }
if len(b) < ByteLen[idx] { return 0,-1 }
if idx==1 { return (uint64(b[0]&(^Pfx[1]))<<8) + uint64(b[1]), 2 }
if idx==2 { return (uint64(b[0]&(^Pfx[2])) << 16) + (uint64(b[1])<<8) + uint64(b[2]), 3 }
if idx==3 { return (uint64(b[0]&(^Pfx[3])) << 24) + (uint64(b[1])<<16) + (uint64(b[2])<<8) + uint64(b[3]), 4 }
if idx==4 { return (uint64(b[0]&(^Pfx[4])) << 32) + (uint64(b[1])<<24) + (uint64(b[2])<<16) + (uint64(b[3])<<8) + uint64(b[4]), 5 }
if idx==5 { return (uint64(b[0]&(^Pfx[5])) << 40) + (uint64(b[1])<<32) + (uint64(b[2])<<24) + (uint64(b[3])<<16) + (uint64(b[4])<<8) + uint64(b[5]), 6 }
if idx==6 { return (uint64(b[1])<<48) + (uint64(b[2])<<40) + (uint64(b[3])<<32) + (uint64(b[4])<<24) + (uint64(b[5])<<16) + (uint64(b[6])<<8) + uint64(b[7]), 8 }
if idx==6 { return (uint64(b[1])<<48) + (uint64(b[2])<<40) + (uint64(b[3])<<32) + (uint64(b[4])<<24) + (uint64(b[5])<<16) + (uint64(b[6])<<8) + uint64(b[7]), 8 }
n := ByteLen[idx]
return (uint64(b[n-8])<<56) + (uint64(b[n-7])<<48) + (uint64(b[n-6])<<40) + (uint64(b[n-5])<<32) +
(uint64(b[n-4])<<24) + (uint64(b[n-3])<<16) + (uint64(b[n-2])<<8) + uint64(b[n-1]), n
}
| curoverse/l7g | tools/cglf-tools/dlug/.save/cp2/dlug.go | GO | agpl-3.0 | 9,203 |
/*
* Copyright 2010-2012 Fabric Engine Inc. All rights reserved.
*/
#include <Fabric/Core/MR/ConstArray.h>
#include <Fabric/Core/RT/FixedArrayDesc.h>
#include <Fabric/Core/RT/Manager.h>
#include <Fabric/Core/RT/VariableArrayDesc.h>
#include <Fabric/Base/JSON/Decoder.h>
#include <Fabric/Base/JSON/Encoder.h>
#include <Fabric/Base/Exception.h>
namespace Fabric
{
namespace MR
{
RC::Handle<ConstArray> ConstArray::Create(
RC::ConstHandle<RT::Manager> const &rtManager,
RC::ConstHandle<RT::Desc> const &elementDesc,
JSON::Entity const &entity
)
{
return new ConstArray( rtManager, elementDesc, entity );
}
RC::Handle<ConstArray> ConstArray::Create(
RC::ConstHandle<RT::Manager> const &rtManager,
RC::ConstHandle<RT::ArrayDesc> const &arrayDesc,
void const *data
)
{
return new ConstArray( rtManager, arrayDesc, data );
}
ConstArray::ConstArray(
RC::ConstHandle<RT::Manager> const &rtManager,
RC::ConstHandle<RT::Desc> const &elementDesc,
JSON::Entity const &entity
)
{
entity.requireArray();
m_fixedArrayDesc = rtManager->getFixedArrayOf( elementDesc, entity.value.array.size );
m_data.resize( m_fixedArrayDesc->getAllocSize(), 0 );
m_fixedArrayDesc->decodeJSON( entity, &m_data[0] );
}
ConstArray::ConstArray(
RC::ConstHandle<RT::Manager> const &rtManager,
RC::ConstHandle<RT::ArrayDesc> const &arrayDesc,
void const *data
)
{
RC::ConstHandle<RT::Desc> elementDesc = arrayDesc->getMemberDesc();
size_t count = arrayDesc->getNumMembers( data );
m_fixedArrayDesc = rtManager->getFixedArrayOf( elementDesc, count );
m_data.resize( m_fixedArrayDesc->getAllocSize(), 0 );
for ( size_t i=0; i<count; ++i )
elementDesc->setData( arrayDesc->getImmutableMemberData( data, i ), m_fixedArrayDesc->getMutableMemberData( &m_data[0], i ) );
}
ConstArray::~ConstArray()
{
m_fixedArrayDesc->disposeData( &m_data[0] );
}
RC::ConstHandle<RT::Desc> ConstArray::getElementDesc() const
{
return m_fixedArrayDesc->getMemberDesc();
}
const RC::Handle<ArrayProducer::ComputeState> ConstArray::createComputeState() const
{
return ComputeState::Create( this );
}
RC::Handle<ConstArray::ComputeState> ConstArray::ComputeState::Create( RC::ConstHandle<ConstArray> const &constArray )
{
return new ComputeState( constArray );
}
ConstArray::ComputeState::ComputeState( RC::ConstHandle<ConstArray> const &constArray )
: ArrayProducer::ComputeState( constArray )
, m_constArray( constArray )
{
setCount( m_constArray->m_fixedArrayDesc->getNumMembers() );
}
void ConstArray::ComputeState::produce( size_t index, void *data ) const
{
return m_constArray->getElementDesc()->setData( m_constArray->m_fixedArrayDesc->getImmutableMemberData( &m_constArray->m_data[0], index ), data );
}
void ConstArray::ComputeState::produceJSON( size_t index, JSON::Encoder &jg ) const
{
return m_constArray->getElementDesc()->encodeJSON( m_constArray->m_fixedArrayDesc->getImmutableMemberData( &m_constArray->m_data[0], index ), jg );
}
RC::ConstHandle<RT::ArrayDesc> ConstArray::getArrayDesc() const
{
return m_fixedArrayDesc;
}
void const *ConstArray::getImmutableData() const
{
return &m_data[0];
}
void ConstArray::flush()
{
}
}
}
| ghostx2013/FabricEngine_Backup | Native/Core/MR/ConstArray.cpp | C++ | agpl-3.0 | 3,557 |
/*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2011-2014 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
/**
* This class was original generated with Castor, but is no longer.
*/
package org.opennms.netmgt.config.service;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
/**
* Class Value.
*
* @version $Revision$ $Date$
*/
@XmlRootElement(name = "value")
@XmlAccessorType(XmlAccessType.FIELD)
public class Value implements Serializable {
private static final long serialVersionUID = 8678345448589083586L;
// --------------------------/
// - Class/Member Variables -/
// --------------------------/
/**
* internal content storage
*/
@XmlValue
private String _content = "";
/**
* Field _type.
*/
@XmlAttribute(name = "type")
private String _type;
// ----------------/
// - Constructors -/
// ----------------/
public Value() {
super();
setContent("");
}
public Value(final String type, final String content) {
super();
setType(type);
setContent(content);
}
// -----------/
// - Methods -/
// -----------/
/**
* Overrides the java.lang.Object.equals method.
*
* @param obj
* @return true if the objects are equal.
*/
@Override()
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj instanceof Value) {
Value temp = (Value) obj;
if (this._content != null) {
if (temp._content == null)
return false;
else if (!(this._content.equals(temp._content)))
return false;
} else if (temp._content != null)
return false;
if (this._type != null) {
if (temp._type == null)
return false;
else if (!(this._type.equals(temp._type)))
return false;
} else if (temp._type != null)
return false;
return true;
}
return false;
}
/**
* Returns the value of field 'content'. The field 'content' has the
* following description: internal content storage
*
* @return the value of field 'Content'.
*/
public String getContent() {
return this._content;
}
/**
* Returns the value of field 'type'.
*
* @return the value of field 'Type'.
*/
public String getType() {
return this._type;
}
/**
* Overrides the java.lang.Object.hashCode method.
* <p>
* The following steps came from <b>Effective Java Programming Language
* Guide</b> by Joshua Bloch, Chapter 3
*
* @return a hash code value for the object.
*/
public int hashCode() {
int result = 17;
if (_content != null) {
result = 37 * result + _content.hashCode();
}
if (_type != null) {
result = 37 * result + _type.hashCode();
}
return result;
}
/**
* Sets the value of field 'content'. The field 'content' has the
* following description: internal content storage
*
* @param content
* the value of field 'content'.
*/
public void setContent(final String content) {
this._content = content;
}
/**
* Sets the value of field 'type'.
*
* @param type
* the value of field 'type'.
*/
public void setType(final String type) {
this._type = type;
}
}
| roskens/opennms-pre-github | opennms-config-model/src/main/java/org/opennms/netmgt/config/service/Value.java | Java | agpl-3.0 | 5,047 |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/privacy/dlp/v2beta1/dlp.proto
namespace Google\Cloud\Dlp\V2beta1;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* Buckets represented as ranges, along with replacement values. Ranges must
* be non-overlapping.
*
* Generated from protobuf message <code>google.privacy.dlp.v2beta1.BucketingConfig.Bucket</code>
*/
class BucketingConfig_Bucket extends \Google\Protobuf\Internal\Message
{
/**
* Lower bound of the range, inclusive. Type should be the same as max if
* used.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value min = 1;</code>
*/
private $min = null;
/**
* Upper bound of the range, exclusive; type must match min.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value max = 2;</code>
*/
private $max = null;
/**
* Replacement value for this bucket. If not provided
* the default behavior will be to hyphenate the min-max range.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value replacement_value = 3;</code>
*/
private $replacement_value = null;
public function __construct() {
\GPBMetadata\Google\Privacy\Dlp\V2Beta1\Dlp::initOnce();
parent::__construct();
}
/**
* Lower bound of the range, inclusive. Type should be the same as max if
* used.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value min = 1;</code>
* @return \Google\Cloud\Dlp\V2beta1\Value
*/
public function getMin()
{
return $this->min;
}
/**
* Lower bound of the range, inclusive. Type should be the same as max if
* used.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value min = 1;</code>
* @param \Google\Cloud\Dlp\V2beta1\Value $var
* @return $this
*/
public function setMin($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\Value::class);
$this->min = $var;
return $this;
}
/**
* Upper bound of the range, exclusive; type must match min.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value max = 2;</code>
* @return \Google\Cloud\Dlp\V2beta1\Value
*/
public function getMax()
{
return $this->max;
}
/**
* Upper bound of the range, exclusive; type must match min.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value max = 2;</code>
* @param \Google\Cloud\Dlp\V2beta1\Value $var
* @return $this
*/
public function setMax($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\Value::class);
$this->max = $var;
return $this;
}
/**
* Replacement value for this bucket. If not provided
* the default behavior will be to hyphenate the min-max range.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value replacement_value = 3;</code>
* @return \Google\Cloud\Dlp\V2beta1\Value
*/
public function getReplacementValue()
{
return $this->replacement_value;
}
/**
* Replacement value for this bucket. If not provided
* the default behavior will be to hyphenate the min-max range.
*
* Generated from protobuf field <code>.google.privacy.dlp.v2beta1.Value replacement_value = 3;</code>
* @param \Google\Cloud\Dlp\V2beta1\Value $var
* @return $this
*/
public function setReplacementValue($var)
{
GPBUtil::checkMessage($var, \Google\Cloud\Dlp\V2beta1\Value::class);
$this->replacement_value = $var;
return $this;
}
}
| wlwwt/shopware | vendor/google/proto-client/src/Google/Cloud/Dlp/V2beta1/BucketingConfig_Bucket.php | PHP | agpl-3.0 | 3,854 |
# -*- coding: utf-8 -*-
# (c) 2016 Alfredo de la Fuente - AvanzOSC
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from openerp import models, fields, api
from dateutil.relativedelta import relativedelta
class saleOrderLine(models.Model):
_inherit = 'sale.order.line'
@api.multi
@api.depends('order_id', 'order_id.date_order', 'delay')
def _compute_date_planned(self):
for line in self:
new_date = fields.Date.context_today(self)
if line.order_id and line.order_id.date_order:
new_date = fields.Datetime.from_string(
line.order_id.date_order).date()
if line.delay:
new_date = (new_date +
(relativedelta(days=line.delay)))
line.date_planned = new_date
date_planned = fields.Date(
'Date planned', compute='_compute_date_planned', store=True,
default=_compute_date_planned)
def _find_sale_lines_from_stock_information(
self, company, to_date, product, location, from_date=None):
cond = [('company_id', '=', company.id),
('product_id', '=', product.id),
('date_planned', '<=', to_date),
('state', '=', 'draft')]
if from_date:
cond.append(('date_planned', '>=', from_date))
sale_lines = self.search(cond)
sale_lines = sale_lines.filtered(
lambda x: x.order_id.state not in ('cancel', 'except_picking',
'except_invoice', 'done',
'approved'))
sale_lines = sale_lines.filtered(
lambda x: x.order_id.warehouse_id.lot_stock_id.id == location.id)
return sale_lines
| alfredoavanzosc/odoo-addons | stock_information/models/sale_order_line.py | Python | agpl-3.0 | 1,803 |
<?php
namespace wcf\data\bbcode;
use wcf\data\DatabaseObjectEditor;
use wcf\data\IEditableCachedObject;
use wcf\system\cache\builder\BBCodeCacheBuilder;
/**
* Provides functions to edit bbcodes.
*
* @author Alexander Ebert
* @copyright 2001-2015 WoltLab GmbH
* @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
* @package com.woltlab.wcf
* @subpackage data.bbcode
* @category Community Framework
*/
class BBCodeEditor extends DatabaseObjectEditor implements IEditableCachedObject {
/**
* @see \wcf\data\DatabaseObjectDecorator::$baseClass
*/
public static $baseClass = 'wcf\data\bbcode\BBCode';
/**
* @see \wcf\data\IEditableCachedObject::resetCache()
*/
public static function resetCache() {
BBCodeCacheBuilder::getInstance()->reset();
}
}
| ramiusGitHub/WCF | wcfsetup/install/files/lib/data/bbcode/BBCodeEditor.class.php | PHP | lgpl-2.1 | 812 |
<?php
/*
* Copyright © 2010 - 2013 Modo Labs Inc. All rights reserved.
*
* The license governing the contents of this file is located in the LICENSE
* file located at the root directory of this distribution. If the LICENSE file
* is missing, please contact sales@modolabs.com.
*
*/
includePackage('News');
includePackage('DateTime');
class AthleticsShellModule extends ShellModule {
protected $id = 'athletics';
protected static $defaultEventModel = 'AthleticEventsDataModel';
protected $feeds = array();
protected $navFeeds = array();
public function loadScheduleData() {
$scheduleFeeds = $this->getModuleSections('schedule');
$default = $this->getOptionalModuleSection('schedule','module');
foreach ($scheduleFeeds as $index=>&$feedData) {
$feedData = array_merge($default, $feedData);
}
return $scheduleFeeds;
}
protected function getScheduleFeed($sport) {
$scheduleData = $this->loadScheduleData();
if ($feedData = Kurogo::arrayVal($scheduleData, $sport)) {
$dataModel = Kurogo::arrayVal($feedData, 'MODEL_CLASS', self::$defaultEventModel);
$this->scheduleFeed = AthleticEventsDataModel::factory($dataModel, $feedData);
return $this->scheduleFeed;
}
return null;
}
protected function getNewsFeed($sport, $gender=null) {
if ($sport=='topnews') {
$feedData = $this->getNavData('topnews');
} elseif (isset($this->feeds[$sport])) {
$feedData = $this->feeds[$sport];
} else {
throw new KurogoDataException($this->getLocalizedString('ERROR_INVALID_SPORT', $sport));
}
if (isset($feedData['DATA_RETRIEVER']) || isset($feedData['BASE_URL'])) {
$dataModel = isset($feedData['MODEL_CLASS']) ? $feedData['MODEL_CLASS'] : 'AthleticNewsDataModel';
$newsFeed = DataModel::factory($dataModel, $feedData);
return $newsFeed;
}
return null;
}
protected function getNavData($tab) {
$data = isset($this->navFeeds[$tab]) ? $this->navFeeds[$tab] : '';
if (!$data) {
throw new KurogoDataException($this->getLocalizedString('ERROR_NAV', $tab));
}
return $data;
}
protected function getSportsForGender($gender) {
$feeds = array();
foreach ($this->feeds as $key=>$feed) {
if (isset($feed['GENDER']) && $feed['GENDER'] == $gender) {
$feeds[$key] = $feed;
}
}
return $feeds;
}
public function getAllControllers() {
$controllers = array();
$controllers[] = $this->getNewsFeed('topnews');
foreach (array('men', 'women', 'coed') as $gender) {
if ($sportsConfig = $this->getSportsForGender($gender)) {
foreach ($sportsConfig as $key => $sportData) {
if ($newsFeed = $this->getNewsFeed($key)) {
$controllers[] = $newsFeed;
}
if ($scheduleFeed = $this->getScheduleFeed($key)) {
$controllers[] = $scheduleFeed;
}
}
}
}
return $controllers;
}
protected function initializeForCommand() {
$this->feeds = $this->loadFeedData();
$this->navFeeds = $this->getModuleSections('page-index');
switch($this->command) {
case 'fetchAllData':
$this->preFetchAllData();
return 0;
break;
default:
$this->invalidCommand();
break;
}
}
}
| modolabs/Kurogo-Mobile-Web | app/modules/athletics/AthleticsShellModule.php | PHP | lgpl-2.1 | 3,854 |
/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "packageuploader.h"
#include <utils/qtcassert.h>
#include <ssh/sftpchannel.h>
#include <ssh/sshconnection.h>
using namespace QSsh;
namespace RemoteLinux {
namespace Internal {
PackageUploader::PackageUploader(QObject *parent) :
QObject(parent), m_state(Inactive), m_connection(0)
{
}
PackageUploader::~PackageUploader()
{
}
void PackageUploader::uploadPackage(SshConnection *connection,
const QString &localFilePath, const QString &remoteFilePath)
{
QTC_ASSERT(m_state == Inactive, return);
setState(InitializingSftp);
emit progress(tr("Preparing SFTP connection..."));
m_localFilePath = localFilePath;
m_remoteFilePath = remoteFilePath;
m_connection = connection;
connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(handleConnectionFailure()));
m_uploader = m_connection->createSftpChannel();
connect(m_uploader.data(), SIGNAL(initialized()), this,
SLOT(handleSftpChannelInitialized()));
connect(m_uploader.data(), SIGNAL(channelError(QString)), this,
SLOT(handleSftpChannelError(QString)));
connect(m_uploader.data(), SIGNAL(finished(QSsh::SftpJobId,QString)),
this, SLOT(handleSftpJobFinished(QSsh::SftpJobId,QString)));
m_uploader->initialize();
}
void PackageUploader::cancelUpload()
{
QTC_ASSERT(m_state == InitializingSftp || m_state == Uploading, return);
cleanup();
}
void PackageUploader::handleConnectionFailure()
{
if (m_state == Inactive)
return;
const QString errorMsg = m_connection->errorString();
setState(Inactive);
emit uploadFinished(tr("Connection failed: %1").arg(errorMsg));
}
void PackageUploader::handleSftpChannelError(const QString &errorMsg)
{
QTC_ASSERT(m_state == InitializingSftp || m_state == Inactive, return);
if (m_state == Inactive)
return;
setState(Inactive);
emit uploadFinished(tr("SFTP error: %1").arg(errorMsg));
}
void PackageUploader::handleSftpChannelInitialized()
{
QTC_ASSERT(m_state == InitializingSftp || m_state == Inactive, return);
if (m_state == Inactive)
return;
const SftpJobId job = m_uploader->uploadFile(m_localFilePath,
m_remoteFilePath, SftpOverwriteExisting);
if (job == SftpInvalidJob) {
setState(Inactive);
emit uploadFinished(tr("Package upload failed: Could not open file."));
} else {
emit progress(tr("Starting upload..."));
setState(Uploading);
}
}
void PackageUploader::handleSftpJobFinished(SftpJobId, const QString &errorMsg)
{
QTC_ASSERT(m_state == Uploading || m_state == Inactive, return);
if (m_state == Inactive)
return;
if (!errorMsg.isEmpty())
emit uploadFinished(tr("Failed to upload package: %2").arg(errorMsg));
else
emit uploadFinished();
cleanup();
}
void PackageUploader::cleanup()
{
m_uploader->closeChannel();
setState(Inactive);
}
void PackageUploader::setState(State newState)
{
if (m_state == newState)
return;
if (newState == Inactive) {
if (m_uploader) {
disconnect(m_uploader.data(), 0, this, 0);
m_uploader.clear();
}
if (m_connection) {
disconnect(m_connection, 0, this, 0);
m_connection = 0;
}
}
m_state = newState;
}
} // namespace Internal
} // namespace RemoteLinux
| maui-packages/qt-creator | src/plugins/remotelinux/packageuploader.cpp | C++ | lgpl-2.1 | 4,820 |
/* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------------
* DefaultDrawingSupplier.java
* ---------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): Jeremy Bowman;
*
* Changes
* -------
* 16-Jan-2003 : Version 1 (DG);
* 17-Jan-2003 : Added stroke method, renamed DefaultPaintSupplier
* --> DefaultDrawingSupplier (DG)
* 27-Jan-2003 : Incorporated code from SeriesShapeFactory, originally
* contributed by Jeremy Bowman (DG);
* 25-Mar-2003 : Implemented Serializable (DG);
* 20-Aug-2003 : Implemented Cloneable and PublicCloneable (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 13-Jun-2007 : Added fillPaintSequence (DG);
*
*/
package org.jfree.chart.plot;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Polygon;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import org.jfree.chart.ChartColor;
import org.jfree.io.SerialUtilities;
import org.jfree.util.PublicCloneable;
import org.jfree.util.ShapeUtilities;
/**
* A default implementation of the {@link DrawingSupplier} interface. All
* {@link Plot} instances have a new instance of this class installed by
* default.
*/
public class DefaultDrawingSupplier implements DrawingSupplier, Cloneable,
PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = -7339847061039422538L;
/** The default fill paint sequence. */
public static final Paint[] DEFAULT_PAINT_SEQUENCE
= ChartColor.createDefaultPaintArray();
/** The default outline paint sequence. */
public static final Paint[] DEFAULT_OUTLINE_PAINT_SEQUENCE = new Paint[] {
Color.lightGray};
/** The default fill paint sequence. */
public static final Paint[] DEFAULT_FILL_PAINT_SEQUENCE = new Paint[] {
Color.white};
/** The default stroke sequence. */
public static final Stroke[] DEFAULT_STROKE_SEQUENCE = new Stroke[] {
new BasicStroke(1.0f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL)};
/** The default outline stroke sequence. */
public static final Stroke[] DEFAULT_OUTLINE_STROKE_SEQUENCE
= new Stroke[] {new BasicStroke(1.0f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL)};
/** The default shape sequence. */
public static final Shape[] DEFAULT_SHAPE_SEQUENCE
= createStandardSeriesShapes();
/** The paint sequence. */
private transient Paint[] paintSequence;
/** The current paint index. */
private int paintIndex;
/** The outline paint sequence. */
private transient Paint[] outlinePaintSequence;
/** The current outline paint index. */
private int outlinePaintIndex;
/** The fill paint sequence. */
private transient Paint[] fillPaintSequence;
/** The current fill paint index. */
private int fillPaintIndex;
/** The stroke sequence. */
private transient Stroke[] strokeSequence;
/** The current stroke index. */
private int strokeIndex;
/** The outline stroke sequence. */
private transient Stroke[] outlineStrokeSequence;
/** The current outline stroke index. */
private int outlineStrokeIndex;
/** The shape sequence. */
private transient Shape[] shapeSequence;
/** The current shape index. */
private int shapeIndex;
/**
* Creates a new supplier, with default sequences for fill paint, outline
* paint, stroke and shapes.
*/
public DefaultDrawingSupplier() {
this(DEFAULT_PAINT_SEQUENCE, DEFAULT_FILL_PAINT_SEQUENCE,
DEFAULT_OUTLINE_PAINT_SEQUENCE,
DEFAULT_STROKE_SEQUENCE,
DEFAULT_OUTLINE_STROKE_SEQUENCE,
DEFAULT_SHAPE_SEQUENCE);
}
/**
* Creates a new supplier.
*
* @param paintSequence the fill paint sequence.
* @param outlinePaintSequence the outline paint sequence.
* @param strokeSequence the stroke sequence.
* @param outlineStrokeSequence the outline stroke sequence.
* @param shapeSequence the shape sequence.
*/
public DefaultDrawingSupplier(Paint[] paintSequence,
Paint[] outlinePaintSequence,
Stroke[] strokeSequence,
Stroke[] outlineStrokeSequence,
Shape[] shapeSequence) {
this.paintSequence = paintSequence;
this.fillPaintSequence = DEFAULT_FILL_PAINT_SEQUENCE;
this.outlinePaintSequence = outlinePaintSequence;
this.strokeSequence = strokeSequence;
this.outlineStrokeSequence = outlineStrokeSequence;
this.shapeSequence = shapeSequence;
}
/**
* Creates a new supplier.
*
* @param paintSequence the paint sequence.
* @param fillPaintSequence the fill paint sequence.
* @param outlinePaintSequence the outline paint sequence.
* @param strokeSequence the stroke sequence.
* @param outlineStrokeSequence the outline stroke sequence.
* @param shapeSequence the shape sequence.
*
* @since 1.0.6
*/
public DefaultDrawingSupplier(Paint[] paintSequence,
Paint[] fillPaintSequence, Paint[] outlinePaintSequence,
Stroke[] strokeSequence, Stroke[] outlineStrokeSequence,
Shape[] shapeSequence) {
this.paintSequence = paintSequence;
this.fillPaintSequence = fillPaintSequence;
this.outlinePaintSequence = outlinePaintSequence;
this.strokeSequence = strokeSequence;
this.outlineStrokeSequence = outlineStrokeSequence;
this.shapeSequence = shapeSequence;
}
/**
* Returns the next paint in the sequence.
*
* @return The paint.
*/
public Paint getNextPaint() {
Paint result
= this.paintSequence[this.paintIndex % this.paintSequence.length];
this.paintIndex++;
return result;
}
/**
* Returns the next outline paint in the sequence.
*
* @return The paint.
*/
public Paint getNextOutlinePaint() {
Paint result = this.outlinePaintSequence[
this.outlinePaintIndex % this.outlinePaintSequence.length];
this.outlinePaintIndex++;
return result;
}
/**
* Returns the next fill paint in the sequence.
*
* @return The paint.
*
* @since 1.0.6
*/
public Paint getNextFillPaint() {
Paint result = this.fillPaintSequence[this.fillPaintIndex
% this.fillPaintSequence.length];
this.fillPaintIndex++;
return result;
}
/**
* Returns the next stroke in the sequence.
*
* @return The stroke.
*/
public Stroke getNextStroke() {
Stroke result = this.strokeSequence[
this.strokeIndex % this.strokeSequence.length];
this.strokeIndex++;
return result;
}
/**
* Returns the next outline stroke in the sequence.
*
* @return The stroke.
*/
public Stroke getNextOutlineStroke() {
Stroke result = this.outlineStrokeSequence[
this.outlineStrokeIndex % this.outlineStrokeSequence.length];
this.outlineStrokeIndex++;
return result;
}
/**
* Returns the next shape in the sequence.
*
* @return The shape.
*/
public Shape getNextShape() {
Shape result = this.shapeSequence[
this.shapeIndex % this.shapeSequence.length];
this.shapeIndex++;
return result;
}
/**
* Creates an array of standard shapes to display for the items in series
* on charts.
*
* @return The array of shapes.
*/
public static Shape[] createStandardSeriesShapes() {
Shape[] result = new Shape[10];
double size = 6.0;
double delta = size / 2.0;
int[] xpoints = null;
int[] ypoints = null;
// square
result[0] = new Rectangle2D.Double(-delta, -delta, size, size);
// circle
result[1] = new Ellipse2D.Double(-delta, -delta, size, size);
// up-pointing triangle
xpoints = intArray(0.0, delta, -delta);
ypoints = intArray(-delta, delta, delta);
result[2] = new Polygon(xpoints, ypoints, 3);
// diamond
xpoints = intArray(0.0, delta, 0.0, -delta);
ypoints = intArray(-delta, 0.0, delta, 0.0);
result[3] = new Polygon(xpoints, ypoints, 4);
// horizontal rectangle
result[4] = new Rectangle2D.Double(-delta, -delta / 2, size, size / 2);
// down-pointing triangle
xpoints = intArray(-delta, +delta, 0.0);
ypoints = intArray(-delta, -delta, delta);
result[5] = new Polygon(xpoints, ypoints, 3);
// horizontal ellipse
result[6] = new Ellipse2D.Double(-delta, -delta / 2, size, size / 2);
// right-pointing triangle
xpoints = intArray(-delta, delta, -delta);
ypoints = intArray(-delta, 0.0, delta);
result[7] = new Polygon(xpoints, ypoints, 3);
// vertical rectangle
result[8] = new Rectangle2D.Double(-delta / 2, -delta, size / 2, size);
// left-pointing triangle
xpoints = intArray(-delta, delta, delta);
ypoints = intArray(0.0, -delta, +delta);
result[9] = new Polygon(xpoints, ypoints, 3);
return result;
}
/**
* Tests this object for equality with another object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof DefaultDrawingSupplier)) {
return false;
}
DefaultDrawingSupplier that = (DefaultDrawingSupplier) obj;
if (!Arrays.equals(this.paintSequence, that.paintSequence)) {
return false;
}
if (this.paintIndex != that.paintIndex) {
return false;
}
if (!Arrays.equals(this.outlinePaintSequence,
that.outlinePaintSequence)) {
return false;
}
if (this.outlinePaintIndex != that.outlinePaintIndex) {
return false;
}
if (!Arrays.equals(this.strokeSequence, that.strokeSequence)) {
return false;
}
if (this.strokeIndex != that.strokeIndex) {
return false;
}
if (!Arrays.equals(this.outlineStrokeSequence,
that.outlineStrokeSequence)) {
return false;
}
if (this.outlineStrokeIndex != that.outlineStrokeIndex) {
return false;
}
if (!equalShapes(this.shapeSequence, that.shapeSequence)) {
return false;
}
if (this.shapeIndex != that.shapeIndex) {
return false;
}
return true;
}
/**
* A utility method for testing the equality of two arrays of shapes.
*
* @param s1 the first array (<code>null</code> permitted).
* @param s2 the second array (<code>null</code> permitted).
*
* @return A boolean.
*/
private boolean equalShapes(Shape[] s1, Shape[] s2) {
if (s1 == null) {
return s2 == null;
}
if (s2 == null) {
return false;
}
if (s1.length != s2.length) {
return false;
}
for (int i = 0; i < s1.length; i++) {
if (!ShapeUtilities.equal(s1[i], s2[i])) {
return false;
}
}
return true;
}
/**
* Handles serialization.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O problem.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
int paintCount = this.paintSequence.length;
stream.writeInt(paintCount);
for (int i = 0; i < paintCount; i++) {
SerialUtilities.writePaint(this.paintSequence[i], stream);
}
int outlinePaintCount = this.outlinePaintSequence.length;
stream.writeInt(outlinePaintCount);
for (int i = 0; i < outlinePaintCount; i++) {
SerialUtilities.writePaint(this.outlinePaintSequence[i], stream);
}
int strokeCount = this.strokeSequence.length;
stream.writeInt(strokeCount);
for (int i = 0; i < strokeCount; i++) {
SerialUtilities.writeStroke(this.strokeSequence[i], stream);
}
int outlineStrokeCount = this.outlineStrokeSequence.length;
stream.writeInt(outlineStrokeCount);
for (int i = 0; i < outlineStrokeCount; i++) {
SerialUtilities.writeStroke(this.outlineStrokeSequence[i], stream);
}
int shapeCount = this.shapeSequence.length;
stream.writeInt(shapeCount);
for (int i = 0; i < shapeCount; i++) {
SerialUtilities.writeShape(this.shapeSequence[i], stream);
}
}
/**
* Restores a serialized object.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O problem.
* @throws ClassNotFoundException if there is a problem loading a class.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
int paintCount = stream.readInt();
this.paintSequence = new Paint[paintCount];
for (int i = 0; i < paintCount; i++) {
this.paintSequence[i] = SerialUtilities.readPaint(stream);
}
int outlinePaintCount = stream.readInt();
this.outlinePaintSequence = new Paint[outlinePaintCount];
for (int i = 0; i < outlinePaintCount; i++) {
this.outlinePaintSequence[i] = SerialUtilities.readPaint(stream);
}
int strokeCount = stream.readInt();
this.strokeSequence = new Stroke[strokeCount];
for (int i = 0; i < strokeCount; i++) {
this.strokeSequence[i] = SerialUtilities.readStroke(stream);
}
int outlineStrokeCount = stream.readInt();
this.outlineStrokeSequence = new Stroke[outlineStrokeCount];
for (int i = 0; i < outlineStrokeCount; i++) {
this.outlineStrokeSequence[i] = SerialUtilities.readStroke(stream);
}
int shapeCount = stream.readInt();
this.shapeSequence = new Shape[shapeCount];
for (int i = 0; i < shapeCount; i++) {
this.shapeSequence[i] = SerialUtilities.readShape(stream);
}
}
/**
* Helper method to avoid lots of explicit casts in getShape(). Returns
* an array containing the provided doubles cast to ints.
*
* @param a x
* @param b y
* @param c z
*
* @return int[3] with converted params.
*/
private static int[] intArray(double a, double b, double c) {
return new int[] {(int) a, (int) b, (int) c};
}
/**
* Helper method to avoid lots of explicit casts in getShape(). Returns
* an array containing the provided doubles cast to ints.
*
* @param a x
* @param b y
* @param c z
* @param d t
*
* @return int[4] with converted params.
*/
private static int[] intArray(double a, double b, double c, double d) {
return new int[] {(int) a, (int) b, (int) c, (int) d};
}
/**
* Returns a clone.
*
* @return A clone.
*
* @throws CloneNotSupportedException if a component of the supplier does
* not support cloning.
*/
public Object clone() throws CloneNotSupportedException {
DefaultDrawingSupplier clone = (DefaultDrawingSupplier) super.clone();
return clone;
}
}
| apetresc/JFreeChart | src/main/java/org/jfree/chart/plot/DefaultDrawingSupplier.java | Java | lgpl-2.1 | 18,055 |
/*
* Copyright (c) 2010-2012 Grid Dynamics Consulting Services, Inc, All Rights Reserved
* http://www.griddynamics.com
*
* 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 any later version.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.griddynamics.jagger.invoker.http;
import com.google.common.collect.Maps;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.springframework.beans.factory.annotation.Required;
import java.io.Serializable;
import java.util.Map;
/**
* @author Alexey Kiselyov
* Date: 04.08.11
*/
public class HttpQuery implements Serializable {
public static enum Method {
POST,
PUT,
GET,
DELETE,
TRACE,
HEAD,
OPTIONS
}
private Method method = Method.GET;
private Map<String, String> methodParams = Maps.newHashMap();
private Map<String, Object> clientParams = Maps.newHashMap();
public HttpQuery() {
}
public Method getMethod() {
return this.method;
}
@Required
public void setMethod(Method method) {
this.method = method;
}
public Map<String, String> getMethodParams() {
return this.methodParams;
}
public void setMethodParams(Map<String, String> params) {
this.methodParams = params;
}
public Map<String, Object> getClientParams() {
return this.clientParams;
}
public void setClientParams(Map<String, Object> clientParams) {
this.clientParams = clientParams;
}
@Override
public String toString() {
return "HttpQuery{" +
"method=" + method +
", methodParams=" + methodParams +
", clientParams=" + clientParams +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HttpQuery httpQuery = (HttpQuery) o;
if (!clientParams.equals(httpQuery.clientParams)) return false;
if (method != httpQuery.method) return false;
if (!methodParams.equals(httpQuery.methodParams)) return false;
return true;
}
@Override
public int hashCode() {
int result = method.hashCode();
result = 31 * result + methodParams.hashCode();
result = 31 * result + clientParams.hashCode();
return result;
}
}
| dlatnikov/jagger | chassis/invokers/src/main/java/com/griddynamics/jagger/invoker/http/HttpQuery.java | Java | lgpl-2.1 | 3,338 |
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "addressbook.h"
//! [main function]
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
AddressBook addressBook;
addressBook.show();
return app.exec();
}
//! [main function]
| sunblithe/qt-everywhere-opensource-src-4.7.1 | examples/tutorials/addressbook/part2/main.cpp | C++ | lgpl-2.1 | 2,274 |
#ifndef SJTU_STATION_HPP
#define SJTU_STATION_HPP
#include <string>
#include "Date.hpp"
#include "lib/pair.hpp"
#include "lib/vector.hpp"
using std::string;
namespace sjtu {
class Station {
public:
const static int MAXN = 2000;
struct Node {
double price;
string level;
int left_n;
Node(double _price, const string &_level, int _left_n):
price(_price), level(_level), left_n(_left_n) {
}
};
private:
string location;
Date arrival_time, departure_time;
vector<Node> types;
int dist;
public:
Station(const string &_location, const Date &_arrival_time, const Date &_departure_time, const vector<Node> &_types, int _dist):
location(_location), arrival_time(_arrival_time),
departure_time(_departure_time), types(_types), dist(_dist) {
}
Station(const string &_location, const Date &_arrival_time, const Date &_departure_time, const vector<string> &_type, const vector<double> &_price, int _dist):
location(_location), arrival_time(_arrival_time),
departure_time(_departure_time), dist(_dist) {
types.clear();
for (int i = 0; i < (int)_price.size(); ++i) {
types.push_back(Node(_price[i], _type[i], MAXN));
}
}
const string query_location() const {
return location;
}
const Date query_arrival_time() const {
return arrival_time;
}
const Date query_departure_time() const {
return departure_time;
}
const int query_single_number(const string &request) const {
for (int i = 0; i < types.size(); ++i) {
if (types[i].level == request) {
return types[i].left_n;
}
}
throw Exception("未找到" + request + "票");
}
const double query_single_price(const string &request) const {
for (int i = 0; i < types.size(); ++i) {
if (types[i].level == request) {
return types[i].price;
}
}
throw Exception("未找到" + request + "票");
}
vector<Node> query_types() {
return types;
}
vector<double> query_specified_price(const vector<string> &request) {
vector<double> ret;
for (int i = 0; i < (int)request.size(); ++i) {
try {
ret.push_back(query_single_price(request[i]));
}
catch (const Exception &exp) {
throw exp;
}
}
return ret;
}
const bool is_same_location(const string &another) const {
for (int i = 0; i < 6 && i < location.size() && i < another.size(); ++i) {
if (another[i] != location[i]) {
return false;
}
}
return true;
}
const bool modify_number(const string &request, int delta) {
for (int i = 0; i < types.size(); ++i) {
if (types[i].level == request) {
if (types[i].left_n + delta < 0)
{
throw Exception(request+"票数目不够");
return false;
}
types[i].left_n += delta;
return true;
}
}
throw Exception("未找到" + request + "票");
return false;
}
const int query_distance() const { return dist; }
void go_one_day() { arrival_time.go_one_day(); departure_time.go_one_day(); }
};
}
#endif
| pascalprimer/DataStructure | TestCode/TrainTest/Station.hpp | C++ | lgpl-3.0 | 3,065 |
package lab.s2jh.ctx;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import lab.s2jh.core.exception.ServiceException;
import lab.s2jh.core.service.PropertiesConfigService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.TemplateException;
@Service
public class FreemarkerService extends Configuration {
private final static Logger logger = LoggerFactory.getLogger(FreemarkerService.class);
private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
public FreemarkerService() {
this.setDefaultEncoding("UTF-8");
this.setTemplateLoader(stringTemplateLoader);
}
public String processTemplate(String templateName, long version, String templateContents,
Map<String, Object> dataMap) {
Assert.notNull(templateName);
Assert.notNull(version);
if (StringUtils.isBlank(templateContents)) {
return null;
}
Object templateSource = stringTemplateLoader.findTemplateSource(templateName);
if (templateSource == null) {
logger.debug("Init freemarker template: {}", templateName);
stringTemplateLoader.putTemplate(templateName, templateContents, version);
} else {
long ver = stringTemplateLoader.getLastModified(templateSource);
if (version > ver) {
logger.debug("Update freemarker template: {}", templateName);
stringTemplateLoader.putTemplate(templateName, templateContents, version);
}
}
return processTemplateByName(templateName, dataMap);
}
private String processTemplateByName(String templateName, Map<String, Object> dataMap) {
StringWriter strWriter = new StringWriter();
try {
this.getTemplate(templateName).process(dataMap, strWriter);
strWriter.flush();
} catch (TemplateException e) {
throw new ServiceException("error.freemarker.template.process", e);
} catch (IOException e) {
throw new ServiceException("error.freemarker.template.process", e);
}
return strWriter.toString();
}
public String processTemplateByContents(String templateContents, Map<String, Object> dataMap) {
String templateName = "_" + templateContents.hashCode();
return processTemplate(templateName, 0, templateContents, dataMap);
}
public String processTemplateByFileName(String templateFileName, Map<String, Object> dataMap) {
String templateDir = PropertiesConfigService.getWebRootRealPath();
templateDir += File.separator + "WEB-INF" + File.separator + "template" + File.separator + "freemarker";
File targetTemplateFile = new File(templateDir + File.separator + templateFileName + ".ftl");
//TODO: 可添加额外从classpath加载文件处理
logger.debug("Processing freemarker template file: {}", targetTemplateFile.getAbsolutePath());
long fileVersion = targetTemplateFile.lastModified();
Object templateSource = stringTemplateLoader.findTemplateSource(templateFileName);
long templateVersion = 0;
if (templateSource != null) {
templateVersion = stringTemplateLoader.getLastModified(templateSource);
}
if (fileVersion > templateVersion) {
try {
String contents = FileUtils.readFileToString(targetTemplateFile);
return processTemplate(templateFileName, fileVersion, contents, dataMap);
} catch (IOException e) {
throw new ServiceException("error.freemarker.template.process", e);
}
} else {
return processTemplateByName(templateFileName, dataMap);
}
}
}
| xautlx/s2jh | common-service/src/main/java/lab/s2jh/ctx/FreemarkerService.java | Java | lgpl-3.0 | 4,142 |
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.tenant;
import junit.framework.TestCase;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.test_category.OwnJVMTestsCategory;
import org.alfresco.util.ApplicationContextHelper;
import org.alfresco.util.GUID;
import org.junit.experimental.categories.Category;
import org.springframework.context.ApplicationContext;
/**
* @see MultiTNodeServiceInterceptor
*
* @since 3.0
* @author Derek Hulley
*/
@Category(OwnJVMTestsCategory.class)
public class MultiTNodeServiceInterceptorTest extends TestCase
{
public static ApplicationContext ctx = ApplicationContextHelper.getApplicationContext();
private String tenant1 = "tenant-" + GUID.generate();
private String tenant1Pwd = "pwd1";
private boolean enableTest = true;
private TransactionService transactionService;
private TenantAdminService tenantAdminService;
private TenantService tenantService;
private MultiTNodeServiceInterceptor interceptor;
@Override
public void setUp() throws Exception
{
transactionService = (TransactionService) ctx.getBean("TransactionService");
tenantAdminService = (TenantAdminService) ctx.getBean("tenantAdminService");
tenantService = (TenantService) ctx.getBean("tenantService");
interceptor = (MultiTNodeServiceInterceptor) ctx.getBean("multiTNodeServiceInterceptor");
// If MT is disabled, then disable all tests
if (!tenantAdminService.isEnabled())
{
enableTest = false;
return;
}
// Create a tenant
RetryingTransactionCallback<Object> createTenantCallback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
tenantAdminService.createTenant(tenant1, tenant1Pwd.toCharArray());
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(createTenantCallback, false, true);
}
@Override
public void tearDown() throws Exception
{
// If MT is disabled, then disable all tests
if (!tenantAdminService.isEnabled())
{
return;
}
// Delete a tenant
RetryingTransactionCallback<Object> createTenantCallback = new RetryingTransactionCallback<Object>()
{
public Object execute() throws Throwable
{
tenantAdminService.deleteTenant(tenant1);
return null;
}
};
transactionService.getRetryingTransactionHelper().doInTransaction(createTenantCallback, false, true);
}
/**
* Control case.
*/
public void testSetUp()
{
}
}
| Alfresco/community-edition | projects/repository/source/test-java/org/alfresco/repo/tenant/MultiTNodeServiceInterceptorTest.java | Java | lgpl-3.0 | 4,003 |
/**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic 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.
*
* FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.domain;
import static org.fenixedu.academic.predicate.AccessControl.check;
import java.math.BigDecimal;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import org.apache.commons.lang.StringUtils;
import org.fenixedu.academic.domain.degree.DegreeType;
import org.fenixedu.academic.domain.exceptions.DomainException;
import org.fenixedu.academic.domain.person.RoleType;
import org.fenixedu.academic.domain.student.Registration;
import org.fenixedu.academic.domain.util.email.ExecutionCourseSender;
import org.fenixedu.academic.domain.util.email.Message;
import org.fenixedu.academic.domain.util.email.Recipient;
import org.fenixedu.academic.predicate.AccessControl;
import org.fenixedu.academic.predicate.ResourceAllocationRolePredicates;
import org.fenixedu.academic.util.Bundle;
import org.fenixedu.academic.util.DiaSemana;
import org.fenixedu.academic.util.WeekDay;
import org.fenixedu.bennu.core.domain.Bennu;
import org.fenixedu.bennu.core.groups.UserGroup;
import org.fenixedu.bennu.core.i18n.BundleUtil;
import org.joda.time.Duration;
import pt.ist.fenixframework.Atomic;
import pt.ist.fenixframework.dml.runtime.RelationAdapter;
public class Shift extends Shift_Base {
public static final Comparator<Shift> SHIFT_COMPARATOR_BY_NAME = new Comparator<Shift>() {
@Override
public int compare(Shift o1, Shift o2) {
return Collator.getInstance().compare(o1.getNome(), o2.getNome());
}
};
public static final Comparator<Shift> SHIFT_COMPARATOR_BY_TYPE_AND_ORDERED_LESSONS = new Comparator<Shift>() {
@Override
public int compare(Shift o1, Shift o2) {
final int ce = o1.getExecutionCourse().getNome().compareTo(o2.getExecutionCourse().getNome());
if (ce != 0) {
return ce;
}
final int cs = o1.getShiftTypesIntegerComparator().compareTo(o2.getShiftTypesIntegerComparator());
if (cs != 0) {
return cs;
}
final int cl = o1.getLessonsStringComparator().compareTo(o2.getLessonsStringComparator());
return cl == 0 ? DomainObjectUtil.COMPARATOR_BY_ID.compare(o1, o2) : cl;
}
};
static {
Registration.getRelationShiftStudent().addListener(new ShiftStudentListener());
}
public Shift(final ExecutionCourse executionCourse, Collection<ShiftType> types, final Integer lotacao) {
// check(this, ResourceAllocationRolePredicates.checkPermissionsToManageShifts);
super();
setRootDomainObject(Bennu.getInstance());
shiftTypeManagement(types, executionCourse);
setLotacao(lotacao);
executionCourse.setShiftNames();
if (getCourseLoadsSet().isEmpty()) {
throw new DomainException("error.Shift.empty.courseLoads");
}
}
public void edit(List<ShiftType> newTypes, Integer newCapacity, ExecutionCourse newExecutionCourse, String newName,
String comment) {
check(this, ResourceAllocationRolePredicates.checkPermissionsToManageShifts);
ExecutionCourse beforeExecutionCourse = getExecutionCourse();
final Shift otherShiftWithSameNewName = newExecutionCourse.findShiftByName(newName);
if (otherShiftWithSameNewName != null && otherShiftWithSameNewName != this) {
throw new DomainException("error.Shift.with.this.name.already.exists");
}
if (newCapacity != null && getStudentsSet().size() > newCapacity.intValue()) {
throw new DomainException("errors.exception.invalid.finalAvailability");
}
setLotacao(newCapacity);
shiftTypeManagement(newTypes, newExecutionCourse);
beforeExecutionCourse.setShiftNames();
if (!beforeExecutionCourse.equals(newExecutionCourse)) {
newExecutionCourse.setShiftNames();
}
if (getCourseLoadsSet().isEmpty()) {
throw new DomainException("error.Shift.empty.courseLoads");
}
setComment(comment);
}
@Override
public Set<StudentGroup> getAssociatedStudentGroupsSet() {
Set<StudentGroup> result = new HashSet<StudentGroup>();
for (StudentGroup sg : super.getAssociatedStudentGroupsSet()) {
if (sg.getValid()) {
result.add(sg);
}
}
return Collections.unmodifiableSet(result);
}
public void delete() {
check(this, ResourceAllocationRolePredicates.checkPermissionsToManageShifts);
DomainException.throwWhenDeleteBlocked(getDeletionBlockers());
final ExecutionCourse executionCourse = getExecutionCourse();
for (; !getAssociatedLessonsSet().isEmpty(); getAssociatedLessonsSet().iterator().next().delete()) {
;
}
for (; !getAssociatedShiftProfessorshipSet().isEmpty(); getAssociatedShiftProfessorshipSet().iterator().next().delete()) {
;
}
for (; !getShiftDistributionEntriesSet().isEmpty(); getShiftDistributionEntriesSet().iterator().next().delete()) {
;
}
getAssociatedClassesSet().clear();
getCourseLoadsSet().clear();
if (getShiftGroupingProperties() != null) {
getShiftGroupingProperties().delete();
}
setRootDomainObject(null);
super.deleteDomainObject();
executionCourse.setShiftNames();
}
@jvstm.cps.ConsistencyPredicate
protected boolean checkRequiredParameters() {
return getLotacao() != null && !StringUtils.isEmpty(getNome());
}
@Deprecated
public ExecutionCourse getDisciplinaExecucao() {
return getExecutionCourse();
}
public ExecutionCourse getExecutionCourse() {
CourseLoad courseLoad = getCourseLoadsSet().iterator().next();
if (courseLoad != null) {
return courseLoad.getExecutionCourse();
} else {
return null;
}
}
public ExecutionSemester getExecutionPeriod() {
return getExecutionCourse().getExecutionPeriod();
}
private void shiftTypeManagement(Collection<ShiftType> types, ExecutionCourse executionCourse) {
if (executionCourse != null) {
getCourseLoadsSet().clear();
for (ShiftType shiftType : types) {
CourseLoad courseLoad = executionCourse.getCourseLoadByShiftType(shiftType);
if (courseLoad != null) {
addCourseLoads(courseLoad);
}
}
}
}
public List<ShiftType> getTypes() {
List<ShiftType> result = new ArrayList<ShiftType>();
for (CourseLoad courseLoad : getCourseLoadsSet()) {
result.add(courseLoad.getType());
}
return result;
}
public SortedSet<ShiftType> getSortedTypes() {
SortedSet<ShiftType> result = new TreeSet<ShiftType>();
for (CourseLoad courseLoad : getCourseLoadsSet()) {
result.add(courseLoad.getType());
}
return result;
}
public boolean containsType(ShiftType shiftType) {
if (shiftType != null) {
for (CourseLoad courseLoad : getCourseLoadsSet()) {
if (courseLoad.getType().equals(shiftType)) {
return true;
}
}
}
return false;
}
@Override
protected void checkForDeletionBlockers(Collection<String> blockers) {
super.checkForDeletionBlockers(blockers);
if (!getAssociatedStudentGroupsSet().isEmpty()) {
blockers.add(BundleUtil.getString(Bundle.RESOURCE_ALLOCATION, "error.deleteShift.with.studentGroups", getNome()));
}
if (!getStudentsSet().isEmpty()) {
blockers.add(BundleUtil.getString(Bundle.RESOURCE_ALLOCATION, "error.deleteShift.with.students", getNome()));
}
if (!getAssociatedSummariesSet().isEmpty()) {
blockers.add(BundleUtil.getString(Bundle.RESOURCE_ALLOCATION, "error.deleteShift.with.summaries", getNome()));
}
}
public BigDecimal getTotalHours() {
Collection<Lesson> lessons = getAssociatedLessonsSet();
BigDecimal lessonTotalHours = BigDecimal.ZERO;
for (Lesson lesson : lessons) {
lessonTotalHours = lessonTotalHours.add(lesson.getTotalHours());
}
return lessonTotalHours;
}
public Duration getTotalDuration() {
Duration duration = Duration.ZERO;
Collection<Lesson> lessons = getAssociatedLessonsSet();
for (Lesson lesson : lessons) {
duration = duration.plus(lesson.getTotalDuration());
}
return duration;
}
public BigDecimal getMaxLessonDuration() {
BigDecimal maxHours = BigDecimal.ZERO;
for (Lesson lesson : getAssociatedLessonsSet()) {
BigDecimal lessonHours = lesson.getUnitHours();
if (maxHours.compareTo(lessonHours) == -1) {
maxHours = lessonHours;
}
}
return maxHours;
}
public BigDecimal getUnitHours() {
BigDecimal hours = BigDecimal.ZERO;
Collection<Lesson> lessons = getAssociatedLessonsSet();
for (Lesson lesson : lessons) {
hours = hours.add(lesson.getUnitHours());
}
return hours;
}
public double getHoursOnSaturdaysOrNightHours(int nightHour) {
double hours = 0;
Collection<Lesson> lessons = this.getAssociatedLessonsSet();
for (Lesson lesson : lessons) {
if (lesson.getDiaSemana().equals(new DiaSemana(DiaSemana.SABADO))) {
hours += lesson.getUnitHours().doubleValue();
} else {
hours += lesson.hoursAfter(nightHour);
}
}
return hours;
}
public int getNumberOfLessonInstances() {
Collection<Lesson> lessons = getAssociatedLessonsSet();
int totalLessonsDates = 0;
for (Lesson lesson : lessons) {
totalLessonsDates += lesson.getFinalNumberOfLessonInstances();
}
return totalLessonsDates;
}
public BigDecimal getCourseLoadWeeklyAverage() {
BigDecimal weeklyHours = BigDecimal.ZERO;
for (CourseLoad courseLoad : getCourseLoadsSet()) {
weeklyHours = weeklyHours.add(courseLoad.getWeeklyHours());
}
return weeklyHours;
}
public BigDecimal getCourseLoadTotalHours() {
BigDecimal weeklyHours = BigDecimal.ZERO;
for (CourseLoad courseLoad : getCourseLoadsSet()) {
weeklyHours = weeklyHours.add(courseLoad.getTotalQuantity());
}
return weeklyHours;
}
public void associateSchoolClass(SchoolClass schoolClass) {
if (schoolClass == null) {
throw new NullPointerException();
}
if (!this.getAssociatedClassesSet().contains(schoolClass)) {
this.getAssociatedClassesSet().add(schoolClass);
}
if (!schoolClass.getAssociatedShiftsSet().contains(this)) {
schoolClass.getAssociatedShiftsSet().add(this);
}
}
public SortedSet<Lesson> getLessonsOrderedByWeekDayAndStartTime() {
final SortedSet<Lesson> lessons = new TreeSet<Lesson>(Lesson.LESSON_COMPARATOR_BY_WEEKDAY_AND_STARTTIME);
lessons.addAll(getAssociatedLessonsSet());
return lessons;
}
public String getLessonsStringComparator() {
final StringBuilder stringBuilder = new StringBuilder();
for (final Lesson lesson : getLessonsOrderedByWeekDayAndStartTime()) {
stringBuilder.append(lesson.getDiaSemana().getDiaSemana().toString());
stringBuilder.append(lesson.getBeginHourMinuteSecond().toString());
}
return stringBuilder.toString();
}
public Integer getShiftTypesIntegerComparator() {
final StringBuilder stringBuilder = new StringBuilder();
for (ShiftType shiftType : getSortedTypes()) {
stringBuilder.append(shiftType.ordinal() + 1);
}
return Integer.valueOf(stringBuilder.toString());
}
public boolean reserveForStudent(final Registration registration) {
final boolean result = getLotacao().intValue() > getStudentsSet().size();
if (result || isResourceAllocationManager()) {
GroupsAndShiftsManagementLog.createLog(getExecutionCourse(), Bundle.MESSAGING,
"log.executionCourse.groupAndShifts.shifts.attends.added", registration.getNumber().toString(), getNome(),
getExecutionCourse().getNome(), getExecutionCourse().getDegreePresentationString());
addStudents(registration);
}
return result;
}
private boolean isResourceAllocationManager() {
final Person person = AccessControl.getPerson();
return person != null && RoleType.RESOURCE_ALLOCATION_MANAGER.isMember(person.getUser());
}
public SortedSet<ShiftEnrolment> getShiftEnrolmentsOrderedByDate() {
final SortedSet<ShiftEnrolment> shiftEnrolments = new TreeSet<ShiftEnrolment>(ShiftEnrolment.COMPARATOR_BY_DATE);
shiftEnrolments.addAll(getShiftEnrolmentsSet());
return shiftEnrolments;
}
public String getClassesPrettyPrint() {
StringBuilder builder = new StringBuilder();
int index = 0;
for (SchoolClass schoolClass : getAssociatedClassesSet()) {
builder.append(schoolClass.getNome());
index++;
if (index < getAssociatedClassesSet().size()) {
builder.append(", ");
}
}
return builder.toString();
}
public String getShiftTypesPrettyPrint() {
StringBuilder builder = new StringBuilder();
int index = 0;
SortedSet<ShiftType> sortedTypes = getSortedTypes();
for (ShiftType shiftType : sortedTypes) {
builder.append(BundleUtil.getString(Bundle.ENUMERATION, shiftType.getName()));
index++;
if (index < sortedTypes.size()) {
builder.append(", ");
}
}
return builder.toString();
}
public String getShiftTypesCapitalizedPrettyPrint() {
StringBuilder builder = new StringBuilder();
int index = 0;
SortedSet<ShiftType> sortedTypes = getSortedTypes();
for (ShiftType shiftType : sortedTypes) {
builder.append(shiftType.getFullNameTipoAula());
index++;
if (index < sortedTypes.size()) {
builder.append(", ");
}
}
return builder.toString();
}
public String getShiftTypesCodePrettyPrint() {
StringBuilder builder = new StringBuilder();
int index = 0;
SortedSet<ShiftType> sortedTypes = getSortedTypes();
for (ShiftType shiftType : sortedTypes) {
builder.append(shiftType.getSiglaTipoAula());
index++;
if (index < sortedTypes.size()) {
builder.append(", ");
}
}
return builder.toString();
}
public List<Summary> getExtraSummaries() {
List<Summary> result = new ArrayList<Summary>();
Set<Summary> summaries = getAssociatedSummariesSet();
for (Summary summary : summaries) {
if (summary.isExtraSummary()) {
result.add(summary);
}
}
return result;
}
private static class ShiftStudentListener extends RelationAdapter<Registration, Shift> {
@Override
public void afterAdd(Registration registration, Shift shift) {
if (!shift.hasShiftEnrolment(registration)) {
new ShiftEnrolment(shift, registration);
}
}
@Override
public void afterRemove(Registration registration, Shift shift) {
shift.unEnrolStudent(registration);
}
}
private boolean hasShiftEnrolment(final Registration registration) {
for (final ShiftEnrolment shiftEnrolment : getShiftEnrolmentsSet()) {
if (shiftEnrolment.hasRegistration(registration)) {
return true;
}
}
return false;
}
public void unEnrolStudent(final Registration registration) {
final ShiftEnrolment shiftEnrolment = findShiftEnrolment(registration);
if (shiftEnrolment != null) {
shiftEnrolment.delete();
}
}
private ShiftEnrolment findShiftEnrolment(final Registration registration) {
for (final ShiftEnrolment shiftEnrolment : getShiftEnrolmentsSet()) {
if (shiftEnrolment.getRegistration() == registration) {
return shiftEnrolment;
}
}
return null;
}
public int getCapacityBasedOnSmallestRoom() {
int capacity =
getAssociatedLessonsSet().stream().filter(Lesson::hasSala)
.mapToInt(lesson -> lesson.getSala().getAllocatableCapacity()).min().orElse(0);
return capacity + (capacity / 10);
}
public boolean hasShiftType(final ShiftType shiftType) {
for (CourseLoad courseLoad : getCourseLoadsSet()) {
if (courseLoad.getType() == shiftType) {
return true;
}
}
return false;
}
public boolean hasSchoolClassForDegreeType(DegreeType degreeType) {
for (SchoolClass schoolClass : getAssociatedClassesSet()) {
if (schoolClass.getExecutionDegree().getDegreeType() == degreeType) {
return true;
}
}
return false;
}
@Atomic
public void removeAttendFromShift(Registration registration, ExecutionCourse executionCourse) {
GroupsAndShiftsManagementLog.createLog(getExecutionCourse(), Bundle.MESSAGING,
"log.executionCourse.groupAndShifts.shifts.attends.removed", registration.getNumber().toString(), getNome(),
getExecutionCourse().getNome(), getExecutionCourse().getDegreePresentationString());
registration.removeShifts(this);
ExecutionCourseSender sender = ExecutionCourseSender.newInstance(executionCourse);
Collection<Recipient> recipients =
Collections.singletonList(new Recipient(UserGroup.of(registration.getPerson().getUser())));
final String subject = BundleUtil.getString(Bundle.APPLICATION, "label.shift.remove.subject");
final String body = BundleUtil.getString(Bundle.APPLICATION, "label.shift.remove.body", getNome());
new Message(sender, sender.getConcreteReplyTos(), recipients, subject, body, "");
}
public boolean hasAnyStudentsInAssociatedStudentGroups() {
for (final StudentGroup studentGroup : getAssociatedStudentGroupsSet()) {
if (studentGroup.getAttendsSet().size() > 0) {
return true;
}
}
return false;
}
public String getPresentationName() {
StringBuilder stringBuilder = new StringBuilder(this.getNome());
if (!this.getAssociatedLessonsSet().isEmpty()) {
stringBuilder.append(" ( ");
for (Iterator<Lesson> iterator = this.getAssociatedLessonsSet().iterator(); iterator.hasNext();) {
Lesson lesson = iterator.next();
stringBuilder.append(WeekDay.getWeekDay(lesson.getDiaSemana()).getLabelShort());
stringBuilder.append(" ");
stringBuilder.append(lesson.getBeginHourMinuteSecond().toString("HH:mm"));
stringBuilder.append(" - ");
stringBuilder.append(lesson.getEndHourMinuteSecond().toString("HH:mm"));
if (lesson.hasSala()) {
stringBuilder.append(" - ");
stringBuilder.append(lesson.getSala().getName());
}
if (iterator.hasNext()) {
stringBuilder.append(" ; ");
}
}
stringBuilder.append(" ) ");
}
return stringBuilder.toString();
}
public String getLessonPresentationString() {
StringBuilder stringBuilder = new StringBuilder(this.getNome());
if (!this.getAssociatedLessonsSet().isEmpty()) {
for (Iterator<Lesson> iterator = this.getAssociatedLessonsSet().iterator(); iterator.hasNext();) {
Lesson lesson = iterator.next();
stringBuilder.append(" ");
stringBuilder.append(WeekDay.getWeekDay(lesson.getDiaSemana()).getLabelShort());
stringBuilder.append(" ");
stringBuilder.append(lesson.getBeginHourMinuteSecond().toString("HH:mm"));
stringBuilder.append(" - ");
stringBuilder.append(lesson.getEndHourMinuteSecond().toString("HH:mm"));
if (lesson.hasSala()) {
stringBuilder.append(" - ");
stringBuilder.append(lesson.getSala().getName());
}
if (iterator.hasNext()) {
stringBuilder.append(" ; ");
}
}
}
return stringBuilder.toString();
}
public List<StudentGroup> getAssociatedStudentGroups(Grouping grouping) {
List<StudentGroup> result = new ArrayList<StudentGroup>();
for (StudentGroup studentGroup : getAssociatedStudentGroupsSet()) {
if (studentGroup.getGrouping() == grouping) {
result.add(studentGroup);
}
}
return result;
}
public boolean isTotalShiftLoadExceeded() {
final BigDecimal totalHours = getTotalHours();
for (final CourseLoad courseLoad : getCourseLoadsSet()) {
if (totalHours.compareTo(courseLoad.getTotalQuantity()) == 1) {
return true;
}
}
return false;
}
}
| ricardorcr/fenixedu-academic | src/main/java/org/fenixedu/academic/domain/Shift.java | Java | lgpl-3.0 | 22,904 |
package org.molgenis.data.annotation.resources.impl;
import static org.mockito.Mockito.when;
import java.io.File;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.molgenis.data.Query;
import org.molgenis.data.annotation.resources.ResourceConfig;
import org.molgenis.data.support.QueryImpl;
import org.molgenis.util.ResourceUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ResourceImplTest
{
@Mock
ResourceConfig config;
@Mock
TabixRepositoryFactory factory;
private ResourceImpl resource;
@BeforeMethod
public void beforeMethod()
{
MockitoAnnotations.initMocks(this);
resource = new ResourceImpl("cadd_test", config, new TabixVcfRepositoryFactory("cadd"));
}
@Test
public void ifSettingIsNotDefinedResourceIsUnavailable()
{
Assert.assertFalse(resource.isAvailable());
}
/**
* FIXME: reuse in config test
*
* @Test public void ifSettingBecomesDefinedAndFileExistsResourceBecomesAvailable() {
* Assert.assertFalse(resource.isAvailable()); when(molgenisSettings.getProperty("cadd_key",
* null)).thenReturn("src/test/resources/cadd_test.vcf.gz"); Assert.assertTrue(resource.isAvailable());
* when(molgenisSettings.getProperty("cadd_key", null)).thenReturn("nonsense");
* Assert.assertFalse(resource.isAvailable()); when(molgenisSettings.getProperty("cadd_key",
* null)).thenReturn("src/test/resources/cadd_test.vcf.gz"); Assert.assertTrue(resource.isAvailable()); }
* @Test public void ifDefaultDoesNotExistResourceIsUnavailable() { resource = new ResourceImpl("cadd_test", config,
* new TabixVcfRepositoryFactory("cadd")); Assert.assertFalse(resource.isAvailable()); }
**/
@Test
public void testFindAllReturnsResult()
{
File file = ResourceUtils.getFile(getClass(), "/gonl/gonl.chr1.snps_indels.r5.vcf.gz");
when(config.getFile()).thenReturn(file);
Query query = QueryImpl.EQ("#CHROM", "1").and().eq("POS", 126108);
System.out.println(resource.findAll(query));
}
@Test
public void testFindAllReturnsResultFile2()
{
File file = ResourceUtils.getFile(getClass(),
"/ALL.chr1.phase3_shapeit2_mvncall_integrated_v5.20130502.genotypes.vcf.gz");
when(config.getFile()).thenReturn(file);
Query query = QueryImpl.EQ("#CHROM", "1").and().eq("POS", 10352);
System.out.println(resource.findAll(query));
}
}
| marieke-bijlsma/molgenis | molgenis-data-annotators/src/test/java/org/molgenis/data/annotation/resources/impl/ResourceImplTest.java | Java | lgpl-3.0 | 2,417 |
/*
* Copyright 2014 Jacopo Aliprandi, Dario Archetti
*
* This file is part of SPF.
*
* SPF 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.
*
* SPF 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 SPF. If not, see <http://www.gnu.org/licenses/>.
*
*/
package it.polimi.spf.framework.services;
import java.util.Collection;
import android.content.Context;
import android.util.Log;
import it.polimi.spf.shared.model.InvocationRequest;
import it.polimi.spf.shared.model.InvocationResponse;
import it.polimi.spf.shared.model.SPFActivity;
import it.polimi.spf.shared.model.SPFServiceDescriptor;
/**
* Refactored version of {@link ServiceDispatcher}
*
* @author darioarchetti
*
*/
public class SPFServiceRegistry {
private static final String TAG = "ServiceRegistry";
private ActivityConsumerRouteTable mActivityTable;
private ServiceRegistryTable mServiceTable;
private AppCommunicationAgent mCommunicationAgent;
public SPFServiceRegistry(Context context) {
mServiceTable = new ServiceRegistryTable(context);
mActivityTable = new ActivityConsumerRouteTable(context);
mCommunicationAgent = new AppCommunicationAgent(context);
}
/**
* Registers a service. The owner application must be already registered.
*
* @param descriptor
* @return true if the service was registered
*/
public boolean registerService(SPFServiceDescriptor descriptor) {
return mServiceTable.registerService(descriptor) && mActivityTable.registerService(descriptor);
}
/**
* Unregisters a service.
*
* @param descriptor
* - the descriptor of the service to unregister
* @return true if the service was removed
*/
public boolean unregisterService(SPFServiceDescriptor descriptor) {
return mServiceTable.unregisterService(descriptor) && mActivityTable.unregisterService(descriptor);
}
/**
* Unregisters all the service of an application
*
* @param appIdentifier
* - the identifier of the app whose service to remove
* @return true if all the services where removed.
*/
public boolean unregisterAllServicesOfApp(String appIdentifier) {
return mServiceTable.unregisterAllServicesOfApp(appIdentifier) && mActivityTable.unregisterAllServicesOfApp(appIdentifier);
}
/**
* Retrieves all the services of an app.
*
* @param appIdentifier
* - the id of the app whose service to retrieve
* @return the list of its services
*/
public SPFServiceDescriptor[] getServicesOfApp(String appIdentifier) {
return mServiceTable.getServicesOfApp(appIdentifier);
}
/**
* Dispatches an invocation request to the right application. If the
* application is not found, an error response is returned.
*
* @param request
* @return
*/
public InvocationResponse dispatchInvocation(InvocationRequest request) {
String appName = request.getAppName();
String serviceName = request.getServiceName();
String componentName = mServiceTable.getComponentForService(appName, serviceName);
if (componentName == null) {
return InvocationResponse.error("Application " + appName + " doesn't have a service named " + serviceName);
}
AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName);
if (proxy == null) {
return InvocationResponse.error("Cannot bind to service");
}
try {
return proxy.executeService(request);
} catch (Throwable t) {
Log.e("ServiceRegistry", "Error dispatching invocation: ", t);
return InvocationResponse.error("Internal error: " + t.getMessage());
}
}
/**
* Dispatches an activity to the right application according to {@link
* ActivityConsumerRouteTable#}
*
* @param activity
* @return
*/
public InvocationResponse sendActivity(SPFActivity activity) {
ServiceIdentifier id = mActivityTable.getServiceFor(activity);
String componentName = mServiceTable.getComponentForService(id);
if (componentName == null) {
String msg = "No service to handle " + activity;
Log.d(TAG, msg);
return InvocationResponse.error(msg);
}
AppServiceProxy proxy = mCommunicationAgent.getProxy(componentName);
if (proxy == null) {
String msg = "Can't bind to service " + componentName;
Log.d(TAG, msg);
return InvocationResponse.error(msg);
}
try {
InvocationResponse r = proxy.sendActivity(activity);
Log.v(TAG, "Activity dispatched: " + r);
return r;
} catch (Throwable t) {
Log.e(TAG, "Error dispatching invocation: ", t);
return InvocationResponse.error("Internal error: " + t.getMessage());
}
}
@Deprecated
public Collection<ActivityVerb> getVerbSupportList() {
return mActivityTable.getVerbSupport();
}
public Collection<ActivityVerb> getSupportedVerbs() {
return mActivityTable.getVerbSupport();
}
public void setDefaultConsumerForVerb(String verb, ServiceIdentifier identifier) {
mActivityTable.setDefaultServiceForVerb(verb, identifier);
}
}
| deib-polimi/SPF2 | sPFFramework/src/main/java/it/polimi/spf/framework/services/SPFServiceRegistry.java | Java | lgpl-3.0 | 5,348 |
# :include: ../rdoc/log4jxmlformatter
#
# == Other Info
#
# Version:: $Id$
require "log4r/formatter/formatter"
require "rubygems"
require "builder"
module Log4r
class Log4jXmlFormatter < BasicFormatter
def format(logevent)
logger = logevent.fullname.gsub('::', '.')
timestamp = (Time.now.to_f * 1000).to_i
level = LNAMES[logevent.level]
message = format_object(logevent.data)
exception = message if logevent.data.kind_of? Exception
file, line, method = parse_caller(logevent.tracer[0]) if logevent.tracer
builder = Builder::XmlMarkup.new
xml = builder.log4j :event, :logger => logger,
:timestamp => timestamp,
:level => level,
:thread => '' do |e|
e.log4j :NDC, NDC.get
e.log4j :message, message
e.log4j :throwable, exception if exception
e.log4j :locationInfo, :class => '',
:method => method,
:file => file,
:line => line
e.log4j :properties do |p|
MDC.get_context.each do |key, value|
p.log4j :data, :name => key, :value => value
end
end
end
xml
end
#######
private
#######
def parse_caller(line)
if /^(.+?):(\d+)(?::in `(.*)')?/ =~ line
file = Regexp.last_match[1]
line = Regexp.last_match[2].to_i
method = Regexp.last_match[3]
[file, line, method]
else
[]
end
end
end
end
| BayRu/log4r | src/log4r/formatter/log4jxmlformatter.rb | Ruby | lgpl-3.0 | 1,699 |
package se.sics.gvod.net;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author <a href="mailto:bruno@factor45.org">Bruno de Carvalho</a>
* @author Steffen Grohsschmiedt
*/
public class MessageCounter extends ChannelDuplexHandler {
// internal vars ----------------------------------------------------------
private final String id;
private final AtomicLong writtenMessages;
private final AtomicLong readMessages;
// constructors -----------------------------------------------------------
public MessageCounter(String id) {
this.id = id;
this.writtenMessages = new AtomicLong();
this.readMessages = new AtomicLong();
}
// SimpleChannelHandler ---------------------------------------------------
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
this.readMessages.incrementAndGet();
super.channelRead(ctx, msg);
}
@Override
public void write(ChannelHandlerContext ctx, Object msgs, ChannelPromise promise) throws Exception {
promise.addListener(new GenericFutureListener<Future<? super Void>>() {
@Override
public void operationComplete(Future<? super Void> future) throws Exception {
MessageCounter.this.readMessages.getAndIncrement();
}
});
super.write(ctx, msgs, promise);
}
// @Override
// public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
// System.out.println(this.id + ctx.channel() + " -> sent: " + this.getWrittenMessages()
// + ", recv: " + this.getReadMessages());
// super.channelUnregistered(ctx);
// }
// getters & setters ------------------------------------------------------
public long getWrittenMessages() {
return writtenMessages.get();
}
public long getReadMessages() {
return readMessages.get();
}
}
| jimdowling/nat-traverser | network/netty/src/main/java/se/sics/gvod/net/MessageCounter.java | Java | lgpl-3.0 | 2,282 |
package org.jetbrains.yaml.completion;
import com.intellij.codeInsight.completion.InsertHandler;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorModificationUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLElementGenerator;
import org.jetbrains.yaml.YAMLTokenTypes;
import org.jetbrains.yaml.psi.YAMLDocument;
import org.jetbrains.yaml.psi.YAMLKeyValue;
import org.jetbrains.yaml.psi.YAMLValue;
public abstract class YamlKeyCompletionInsertHandler<T extends LookupElement> implements InsertHandler<T> {
@NotNull
protected abstract YAMLKeyValue createNewEntry(@NotNull YAMLDocument document, T item);
@Override
public void handleInsert(InsertionContext context, T item) {
final PsiElement currentElement = context.getFile().findElementAt(context.getStartOffset());
assert currentElement != null : "no element at " + context.getStartOffset();
final YAMLDocument holdingDocument = PsiTreeUtil.getParentOfType(currentElement, YAMLDocument.class);
assert holdingDocument != null;
final YAMLValue oldValue = deleteLookupTextAndRetrieveOldValue(context, currentElement);
final YAMLKeyValue created = createNewEntry(holdingDocument, item);
context.getEditor().getCaretModel().moveToOffset(created.getTextRange().getEndOffset());
if (oldValue != null) {
WriteCommandAction.runWriteCommandAction(context.getProject(), new Runnable() {
@Override
public void run() {
created.setValue(oldValue);
}
});
}
PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(context.getDocument());
if (!isCharAtCaret(context.getEditor(), ' ')) {
EditorModificationUtil.insertStringAtCaret(context.getEditor(), " ");
}
else {
context.getEditor().getCaretModel().moveCaretRelatively(1, 0, false, false, true);
}
}
@Nullable
protected YAMLValue deleteLookupTextAndRetrieveOldValue(InsertionContext context, @NotNull PsiElement elementAtCaret) {
final YAMLValue oldValue;
if (elementAtCaret.getNode().getElementType() != YAMLTokenTypes.SCALAR_KEY) {
deleteLookupPlain(context);
return null;
}
final YAMLKeyValue keyValue = PsiTreeUtil.getParentOfType(elementAtCaret, YAMLKeyValue.class);
assert keyValue != null;
context.commitDocument();
if (keyValue.getValue() != null) {
// Save old value somewhere
final YAMLKeyValue dummyKV = YAMLElementGenerator.getInstance(context.getProject()).createYamlKeyValue("foo", "b");
dummyKV.setValue(keyValue.getValue());
oldValue = dummyKV.getValue();
}
else {
oldValue = null;
}
context.setTailOffset(keyValue.getTextRange().getEndOffset());
WriteCommandAction.runWriteCommandAction(context.getProject(), new Runnable() {
@Override
public void run() {
keyValue.getParentMapping().deleteKeyValue(keyValue);
}
});
return oldValue;
}
private static void deleteLookupPlain(InsertionContext context) {
final Document document = context.getDocument();
final CharSequence sequence = document.getCharsSequence();
int offset = context.getStartOffset() - 1;
while (offset >= 0) {
final char c = sequence.charAt(offset);
if (c != ' ' && c != '\t') {
if (c == '\n') {
offset--;
}
else {
offset = context.getStartOffset() - 1;
}
break;
}
offset--;
}
document.deleteString(offset + 1, context.getTailOffset());
context.commitDocument();
}
public static boolean isCharAtCaret(Editor editor, char ch) {
final int startOffset = editor.getCaretModel().getOffset();
final Document document = editor.getDocument();
return document.getTextLength() > startOffset && document.getCharsSequence().charAt(startOffset) == ch;
}
}
| Soya93/Extract-Refactoring | plugins/yaml/src/org/jetbrains/yaml/completion/YamlKeyCompletionInsertHandler.java | Java | apache-2.0 | 4,294 |
jQuery(function($){
var callback = function(){
var shutterLinks = {}, shutterSets = {}; shutterReloaded.Init();
};
$(this).bind('refreshed', callback);
$(document).on('lazy_resources_loaded', function(){
var flag = 'shutterReloaded';
if (typeof($(window).data(flag)) == 'undefined')
$(window).data(flag, true);
else return;
callback();
});
}); | Lucas1313/miesner | www/wp-content/plugins/nextgen-gallery/products/photocrati_nextgen/modules/lightbox/static/shutter_reloaded/nextgen_shutter_reloaded.js | JavaScript | apache-2.0 | 397 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.bigtop.bigpetstore.datagenerator.generators.store;
import java.util.List;
import org.apache.bigtop.bigpetstore.datagenerator.datamodels.inputs.ZipcodeRecord;
import org.apache.bigtop.bigpetstore.datagenerator.framework.pdfs.ProbabilityDensityFunction;
public class StoreLocationIncomePDF implements ProbabilityDensityFunction<ZipcodeRecord>
{
double incomeNormalizationFactor;
double minIncome;
double k;
public StoreLocationIncomePDF(List<ZipcodeRecord> zipcodeTable, double incomeScalingFactor)
{
double maxIncome = 0.0;
minIncome = Double.MAX_VALUE;
for(ZipcodeRecord record : zipcodeTable)
{
maxIncome = Math.max(maxIncome, record.getMedianHouseholdIncome());
minIncome = Math.min(minIncome, record.getMedianHouseholdIncome());
}
k = Math.log(incomeScalingFactor) / (maxIncome - minIncome);
incomeNormalizationFactor = 0.0d;
for(ZipcodeRecord record : zipcodeTable)
{
double weight = incomeWeight(record);
incomeNormalizationFactor += weight;
}
}
private double incomeWeight(ZipcodeRecord record)
{
return Math.exp(k * (record.getMedianHouseholdIncome() - minIncome));
}
@Override
public double probability(ZipcodeRecord datum)
{
double weight = incomeWeight(datum);
return weight / this.incomeNormalizationFactor;
}
}
| jagatsingh/bigtop | bigtop-bigpetstore/bigpetstore-data-generator/src/main/java/org/apache/bigtop/bigpetstore/datagenerator/generators/store/StoreLocationIncomePDF.java | Java | apache-2.0 | 2,116 |
/*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.buffer;
import java.nio.ByteOrder;
import static org.junit.Assert.*;
/**
* Tests little-endian heap channel buffers
*/
public class PooledLittleEndianHeapByteBufTest extends AbstractPooledByteBufTest {
@Override
protected ByteBuf alloc(int length, int maxCapacity) {
ByteBuf buffer = PooledByteBufAllocator.DEFAULT.heapBuffer(length, maxCapacity).order(ByteOrder.LITTLE_ENDIAN);
assertSame(ByteOrder.LITTLE_ENDIAN, buffer.order());
return buffer;
}
}
| zer0se7en/netty | buffer/src/test/java/io/netty/buffer/PooledLittleEndianHeapByteBufTest.java | Java | apache-2.0 | 1,146 |
package com.google.api.ads.dfp.jaxws.v201405;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for LineItemCreativeAssociationOperationError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="LineItemCreativeAssociationOperationError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="NOT_ALLOWED"/>
* <enumeration value="NOT_APPLICABLE"/>
* <enumeration value="CANNOT_ACTIVATE_INVALID_CREATIVE"/>
* <enumeration value="UNKNOWN"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "LineItemCreativeAssociationOperationError.Reason")
@XmlEnum
public enum LineItemCreativeAssociationOperationErrorReason {
/**
*
* The operation is not allowed due to permissions
*
*
*/
NOT_ALLOWED,
/**
*
* The operation is not applicable to the current state
*
*
*/
NOT_APPLICABLE,
/**
*
* Cannot activate an invalid creative
*
*
*/
CANNOT_ACTIVATE_INVALID_CREATIVE,
/**
*
* The value returned if the actual value is not exposed by the requested API version.
*
*
*/
UNKNOWN;
public String value() {
return name();
}
public static LineItemCreativeAssociationOperationErrorReason fromValue(String v) {
return valueOf(v);
}
}
| stoksey69/googleads-java-lib | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201405/LineItemCreativeAssociationOperationErrorReason.java | Java | apache-2.0 | 1,675 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jdbi.v3.core.qualifier;
import java.util.Objects;
public class QualifiedConstructorParamThing {
private final int id;
private final String name;
public QualifiedConstructorParamThing(int id, @Reversed String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QualifiedConstructorParamThing that = (QualifiedConstructorParamThing) o;
return id == that.id
&& Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "QualifiedConstructorParamThing{"
+ "id=" + id
+ ", name='" + name + '\''
+ '}';
}
}
| john9x/jdbi | core/src/test/java/org/jdbi/v3/core/qualifier/QualifiedConstructorParamThing.java | Java | apache-2.0 | 1,607 |
package user_test
import (
"code.cloudfoundry.org/cli/cf/api/apifakes"
"code.cloudfoundry.org/cli/cf/commandregistry"
"code.cloudfoundry.org/cli/cf/configuration/coreconfig"
"code.cloudfoundry.org/cli/cf/models"
"code.cloudfoundry.org/cli/cf/requirements"
"code.cloudfoundry.org/cli/cf/requirements/requirementsfakes"
"code.cloudfoundry.org/cli/cf/trace/tracefakes"
"code.cloudfoundry.org/cli/plugin/models"
testcmd "code.cloudfoundry.org/cli/testhelpers/commands"
testconfig "code.cloudfoundry.org/cli/testhelpers/configuration"
testterm "code.cloudfoundry.org/cli/testhelpers/terminal"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"os"
. "code.cloudfoundry.org/cli/testhelpers/matchers"
)
var _ = Describe("org-users command", func() {
var (
ui *testterm.FakeUI
requirementsFactory *requirementsfakes.FakeFactory
configRepo coreconfig.Repository
userRepo *apifakes.FakeUserRepository
deps commandregistry.Dependency
)
updateCommandDependency := func(pluginCall bool) {
deps.UI = ui
deps.Config = configRepo
deps.RepoLocator = deps.RepoLocator.SetUserRepository(userRepo)
commandregistry.Commands.SetCommand(commandregistry.Commands.FindCommand("org-users").SetDependency(deps, pluginCall))
}
BeforeEach(func() {
ui = &testterm.FakeUI{}
userRepo = new(apifakes.FakeUserRepository)
configRepo = testconfig.NewRepositoryWithDefaults()
requirementsFactory = new(requirementsfakes.FakeFactory)
deps = commandregistry.NewDependency(os.Stdout, new(tracefakes.FakePrinter), "")
})
runCommand := func(args ...string) bool {
return testcmd.RunCLICommand("org-users", args, requirementsFactory, updateCommandDependency, false, ui)
}
Describe("requirements", func() {
It("fails with usage when invoked without an org name", func() {
requirementsFactory.NewLoginRequirementReturns(requirements.Passing{})
runCommand()
Expect(ui.Outputs()).To(ContainSubstrings(
[]string{"Incorrect Usage", "Requires an argument"},
))
})
It("fails when not logged in", func() {
requirementsFactory.NewLoginRequirementReturns(requirements.Failing{Message: "not logged in"})
Expect(runCommand("say-hello-to-my-little-org")).To(BeFalse())
})
})
Context("when logged in and given an org with no users in a particular role", func() {
var (
user1, user2 models.UserFields
)
BeforeEach(func() {
org := models.Organization{}
org.Name = "the-org"
org.GUID = "the-org-guid"
user1 = models.UserFields{}
user1.Username = "user1"
user2 = models.UserFields{}
user2.Username = "user2"
requirementsFactory.NewLoginRequirementReturns(requirements.Passing{})
organizationReq := new(requirementsfakes.FakeOrganizationRequirement)
organizationReq.GetOrganizationReturns(org)
requirementsFactory.NewOrganizationRequirementReturns(organizationReq)
})
Context("shows friendly messaage when no users in ORG_MANAGER role", func() {
It("shows the special users in the given org", func() {
userRepo.ListUsersInOrgForRoleStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgManager: {},
models.RoleBillingManager: {user1},
models.RoleOrgAuditor: {user2},
}[roleName]
return userFields, nil
}
runCommand("the-org")
Expect(userRepo.ListUsersInOrgForRoleCallCount()).To(Equal(3))
for i, expectedRole := range []models.Role{models.RoleOrgManager, models.RoleBillingManager, models.RoleOrgAuditor} {
orgGUID, actualRole := userRepo.ListUsersInOrgForRoleArgsForCall(i)
Expect(orgGUID).To(Equal("the-org-guid"))
Expect(actualRole).To(Equal(expectedRole))
}
Expect(ui.Outputs()).To(BeInDisplayOrder(
[]string{"Getting users in org", "the-org", "my-user"},
[]string{"ORG MANAGER"},
[]string{" No ORG MANAGER found"},
[]string{"BILLING MANAGER"},
[]string{" user1"},
[]string{"ORG AUDITOR"},
[]string{" user2"},
))
})
})
Context("shows friendly messaage when no users in BILLING_MANAGER role", func() {
It("shows the special users in the given org", func() {
userRepo.ListUsersInOrgForRoleStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgManager: {user1},
models.RoleBillingManager: {},
models.RoleOrgAuditor: {user2},
}[roleName]
return userFields, nil
}
runCommand("the-org")
Expect(userRepo.ListUsersInOrgForRoleCallCount()).To(Equal(3))
for i, expectedRole := range []models.Role{models.RoleOrgManager, models.RoleBillingManager, models.RoleOrgAuditor} {
orgGUID, actualRole := userRepo.ListUsersInOrgForRoleArgsForCall(i)
Expect(orgGUID).To(Equal("the-org-guid"))
Expect(actualRole).To(Equal(expectedRole))
}
Expect(ui.Outputs()).To(BeInDisplayOrder(
[]string{"Getting users in org", "the-org", "my-user"},
[]string{"ORG MANAGER"},
[]string{" user1"},
[]string{"BILLING MANAGER"},
[]string{" No BILLING MANAGER found"},
[]string{"ORG AUDITOR"},
[]string{" user2"},
))
})
})
Context("shows friendly messaage when no users in ORG_AUDITOR role", func() {
It("shows the special users in the given org", func() {
userRepo.ListUsersInOrgForRoleStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgManager: {user1},
models.RoleBillingManager: {user2},
models.RoleOrgAuditor: {},
}[roleName]
return userFields, nil
}
runCommand("the-org")
Expect(userRepo.ListUsersInOrgForRoleCallCount()).To(Equal(3))
for i, expectedRole := range []models.Role{models.RoleOrgManager, models.RoleBillingManager, models.RoleOrgAuditor} {
orgGUID, actualRole := userRepo.ListUsersInOrgForRoleArgsForCall(i)
Expect(orgGUID).To(Equal("the-org-guid"))
Expect(actualRole).To(Equal(expectedRole))
}
Expect(ui.Outputs()).To(BeInDisplayOrder(
[]string{"Getting users in org", "the-org", "my-user"},
[]string{"ORG MANAGER"},
[]string{" user1"},
[]string{"BILLING MANAGER"},
[]string{" user2"},
[]string{"ORG AUDITOR"},
[]string{" No ORG AUDITOR found"},
))
})
})
})
Context("when logged in and given an org with users", func() {
BeforeEach(func() {
org := models.Organization{}
org.Name = "the-org"
org.GUID = "the-org-guid"
user := models.UserFields{Username: "user1"}
user2 := models.UserFields{Username: "user2"}
user3 := models.UserFields{Username: "user3"}
user4 := models.UserFields{Username: "user4"}
userRepo.ListUsersInOrgForRoleStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgManager: {user, user2},
models.RoleBillingManager: {user4},
models.RoleOrgAuditor: {user3},
}[roleName]
return userFields, nil
}
requirementsFactory.NewLoginRequirementReturns(requirements.Passing{})
organizationReq := new(requirementsfakes.FakeOrganizationRequirement)
organizationReq.GetOrganizationReturns(org)
requirementsFactory.NewOrganizationRequirementReturns(organizationReq)
})
It("shows the special users in the given org", func() {
runCommand("the-org")
orgGUID, _ := userRepo.ListUsersInOrgForRoleArgsForCall(0)
Expect(orgGUID).To(Equal("the-org-guid"))
Expect(ui.Outputs()).To(ContainSubstrings(
[]string{"Getting users in org", "the-org", "my-user"},
[]string{"ORG MANAGER"},
[]string{"user1"},
[]string{"user2"},
[]string{"BILLING MANAGER"},
[]string{"user4"},
[]string{"ORG AUDITOR"},
[]string{"user3"},
))
})
Context("when the -a flag is provided", func() {
BeforeEach(func() {
user := models.UserFields{Username: "user1"}
user2 := models.UserFields{Username: "user2"}
userRepo.ListUsersInOrgForRoleStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgUser: {user, user2},
}[roleName]
return userFields, nil
}
})
It("lists all org users, regardless of role", func() {
runCommand("-a", "the-org")
orgGUID, _ := userRepo.ListUsersInOrgForRoleArgsForCall(0)
Expect(orgGUID).To(Equal("the-org-guid"))
Expect(ui.Outputs()).To(ContainSubstrings(
[]string{"Getting users in org", "the-org", "my-user"},
[]string{"USERS"},
[]string{"user1"},
[]string{"user2"},
))
})
})
Context("when cc api verson is >= 2.21.0", func() {
It("calls ListUsersInOrgForRoleWithNoUAA()", func() {
configRepo.SetAPIVersion("2.22.0")
runCommand("the-org")
Expect(userRepo.ListUsersInOrgForRoleWithNoUAACallCount()).To(BeNumerically(">=", 1))
Expect(userRepo.ListUsersInOrgForRoleCallCount()).To(Equal(0))
})
})
Context("when cc api verson is < 2.21.0", func() {
It("calls ListUsersInOrgForRole()", func() {
configRepo.SetAPIVersion("2.20.0")
runCommand("the-org")
Expect(userRepo.ListUsersInOrgForRoleWithNoUAACallCount()).To(Equal(0))
Expect(userRepo.ListUsersInOrgForRoleCallCount()).To(BeNumerically(">=", 1))
})
})
})
Describe("when invoked by a plugin", func() {
var (
pluginUserModel []plugin_models.GetOrgUsers_Model
)
BeforeEach(func() {
configRepo.SetAPIVersion("2.22.0")
})
Context("single roles", func() {
BeforeEach(func() {
org := models.Organization{}
org.Name = "the-org"
org.GUID = "the-org-guid"
// org managers
user := models.UserFields{}
user.Username = "user1"
user.GUID = "1111"
user2 := models.UserFields{}
user2.Username = "user2"
user2.GUID = "2222"
// billing manager
user3 := models.UserFields{}
user3.Username = "user3"
user3.GUID = "3333"
// auditors
user4 := models.UserFields{}
user4.Username = "user4"
user4.GUID = "4444"
userRepo.ListUsersInOrgForRoleWithNoUAAStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgManager: {user, user2},
models.RoleBillingManager: {user4},
models.RoleOrgAuditor: {user3},
models.RoleOrgUser: {user3},
}[roleName]
return userFields, nil
}
requirementsFactory.NewLoginRequirementReturns(requirements.Passing{})
organizationReq := new(requirementsfakes.FakeOrganizationRequirement)
organizationReq.GetOrganizationReturns(org)
requirementsFactory.NewOrganizationRequirementReturns(organizationReq)
pluginUserModel = []plugin_models.GetOrgUsers_Model{}
deps.PluginModels.OrgUsers = &pluginUserModel
})
It("populates the plugin model with users with single roles", func() {
testcmd.RunCLICommand("org-users", []string{"the-org"}, requirementsFactory, updateCommandDependency, true, ui)
Expect(pluginUserModel).To(HaveLen(4))
for _, u := range pluginUserModel {
switch u.Username {
case "user1":
Expect(u.Guid).To(Equal("1111"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgManager"}))
case "user2":
Expect(u.Guid).To(Equal("2222"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgManager"}))
case "user3":
Expect(u.Guid).To(Equal("3333"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgAuditor"}))
case "user4":
Expect(u.Guid).To(Equal("4444"))
Expect(u.Roles).To(ConsistOf([]string{"RoleBillingManager"}))
default:
Fail("unexpected user: " + u.Username)
}
}
})
It("populates the plugin model with users with single roles -a flag", func() {
testcmd.RunCLICommand("org-users", []string{"-a", "the-org"}, requirementsFactory, updateCommandDependency, true, ui)
Expect(pluginUserModel).To(HaveLen(1))
Expect(pluginUserModel[0].Username).To(Equal("user3"))
Expect(pluginUserModel[0].Guid).To(Equal("3333"))
Expect(pluginUserModel[0].Roles[0]).To(Equal("RoleOrgUser"))
})
})
Context("multiple roles", func() {
BeforeEach(func() {
org := models.Organization{}
org.Name = "the-org"
org.GUID = "the-org-guid"
// org managers
user := models.UserFields{}
user.Username = "user1"
user.GUID = "1111"
user.IsAdmin = true
user2 := models.UserFields{}
user2.Username = "user2"
user2.GUID = "2222"
// billing manager
user3 := models.UserFields{}
user3.Username = "user3"
user3.GUID = "3333"
// auditors
user4 := models.UserFields{}
user4.Username = "user4"
user4.GUID = "4444"
userRepo.ListUsersInOrgForRoleWithNoUAAStub = func(_ string, roleName models.Role) ([]models.UserFields, error) {
userFields := map[models.Role][]models.UserFields{
models.RoleOrgManager: {user, user2, user3, user4},
models.RoleBillingManager: {user2, user4},
models.RoleOrgAuditor: {user, user3},
models.RoleOrgUser: {user, user2, user3, user4},
}[roleName]
return userFields, nil
}
requirementsFactory.NewLoginRequirementReturns(requirements.Passing{})
organizationReq := new(requirementsfakes.FakeOrganizationRequirement)
organizationReq.GetOrganizationReturns(org)
requirementsFactory.NewOrganizationRequirementReturns(organizationReq)
pluginUserModel = []plugin_models.GetOrgUsers_Model{}
deps.PluginModels.OrgUsers = &pluginUserModel
})
It("populates the plugin model with users with multiple roles", func() {
testcmd.RunCLICommand("org-users", []string{"the-org"}, requirementsFactory, updateCommandDependency, true, ui)
Expect(pluginUserModel).To(HaveLen(4))
for _, u := range pluginUserModel {
switch u.Username {
case "user1":
Expect(u.Guid).To(Equal("1111"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgManager", "RoleOrgAuditor"}))
Expect(u.IsAdmin).To(BeTrue())
case "user2":
Expect(u.Guid).To(Equal("2222"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgManager", "RoleBillingManager"}))
case "user3":
Expect(u.Guid).To(Equal("3333"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgAuditor", "RoleOrgManager"}))
case "user4":
Expect(u.Guid).To(Equal("4444"))
Expect(u.Roles).To(ConsistOf([]string{"RoleBillingManager", "RoleOrgManager"}))
default:
Fail("unexpected user: " + u.Username)
}
}
})
It("populates the plugin model with users with multiple roles -a flag", func() {
testcmd.RunCLICommand("org-users", []string{"-a", "the-org"}, requirementsFactory, updateCommandDependency, true, ui)
Expect(pluginUserModel).To(HaveLen(4))
for _, u := range pluginUserModel {
switch u.Username {
case "user1":
Expect(u.Guid).To(Equal("1111"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgUser"}))
case "user2":
Expect(u.Guid).To(Equal("2222"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgUser"}))
case "user3":
Expect(u.Guid).To(Equal("3333"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgUser"}))
case "user4":
Expect(u.Guid).To(Equal("4444"))
Expect(u.Roles).To(ConsistOf([]string{"RoleOrgUser"}))
default:
Fail("unexpected user: " + u.Username)
}
}
})
})
})
})
| cloudfoundry/v3-cli-plugin | vendor/code.cloudfoundry.org/cli/cf/commands/user/org_users_test.go | GO | apache-2.0 | 15,566 |
package org.jbpm.services.task.impl.model.xml;
import static org.jbpm.services.task.impl.model.xml.AbstractJaxbTaskObject.unsupported;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import org.kie.internal.task.api.model.AccessType;
import org.kie.internal.task.api.model.FaultData;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
@XmlRootElement(name="fault-data")
@XmlAccessorType(XmlAccessType.FIELD)
@JsonAutoDetect(getterVisibility=JsonAutoDetect.Visibility.NONE, setterVisibility=JsonAutoDetect.Visibility.NONE, fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class JaxbFaultData implements FaultData {
@XmlElement
private AccessType accessType;
@XmlElement
@XmlSchemaType(name="string")
private String type;
@XmlElement
@XmlSchemaType(name="base64Binary")
private byte[] content = null;
private Object contentObject;
@XmlElement(name="fault-name")
@XmlSchemaType(name="string")
private String faultName;
public JaxbFaultData() {
// JAXB constructor
}
public JaxbFaultData(FaultData faultData) {
this.accessType = faultData.getAccessType();
this.content = faultData.getContent();
this.faultName = faultData.getFaultName();
this.type = faultData.getType();
}
@Override
public AccessType getAccessType() {
return accessType;
}
@Override
public void setAccessType( AccessType accessType ) {
this.accessType = accessType;
}
@Override
public String getType() {
return type;
}
@Override
public void setType( String type ) {
this.type = type;
}
@Override
public byte[] getContent() {
return content;
}
@Override
public void setContent( byte[] content ) {
this.content = content;
}
@Override
public String getFaultName() {
return faultName;
}
@Override
public void setFaultName( String faultName ) {
this.faultName = faultName;
}
@Override
public Object getContentObject() {
return contentObject;
}
@Override
public void setContentObject(Object object) {
this.contentObject = object;
}
@Override
public void writeExternal( ObjectOutput out ) throws IOException {
unsupported(FaultData.class);
}
@Override
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
unsupported(FaultData.class);
}
}
| jakubschwan/jbpm | jbpm-human-task/jbpm-human-task-core/src/main/java/org/jbpm/services/task/impl/model/xml/JaxbFaultData.java | Java | apache-2.0 | 2,814 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.