repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
thiagosgarcia/Whisperer-DailyMeeting-Slackbot | Whisperer/App_Start/FilterConfig.cs | 264 | using System.Web;
using System.Web.Mvc;
namespace Whisperer
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| agpl-3.0 |
fabricematrat/charmstore | config/config.go | 7476 | // Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// The config package defines configuration parameters for
// the charm store.
package config // import "gopkg.in/juju/charmstore.v5/config"
import (
"crypto"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
"gopkg.in/errgo.v1"
"gopkg.in/goose.v2/identity"
"gopkg.in/macaroon-bakery.v2-unstable/bakery"
"gopkg.in/yaml.v2"
)
type Config struct {
// TODO(rog) rename this to MongoAddr - it's not a URL.
MongoURL string `yaml:"mongo-url,omitempty"`
AuditLogFile string `yaml:"audit-log-file,omitempty"`
AuditLogMaxSize int `yaml:"audit-log-max-size,omitempty"`
AuditLogMaxAge int `yaml:"audit-log-max-age,omitempty"`
APIAddr string `yaml:"api-addr,omitempty"`
AuthUsername string `yaml:"auth-username,omitempty"`
AuthPassword string `yaml:"auth-password,omitempty"`
ESAddr string `yaml:"elasticsearch-addr,omitempty"` // elasticsearch is optional
IdentityPublicKey *bakery.PublicKey `yaml:"identity-public-key,omitempty"`
IdentityLocation string `yaml:"identity-location"`
TermsPublicKey *bakery.PublicKey `yaml:"terms-public-key,omitempty"`
TermsLocation string `yaml:"terms-location,omitempty"`
AgentUsername string `yaml:"agent-username,omitempty"`
AgentKey *bakery.KeyPair `yaml:"agent-key,omitempty"`
MaxMgoSessions int `yaml:"max-mgo-sessions,omitempty"`
RequestTimeout DurationString `yaml:"request-timeout,omitempty"`
StatsCacheMaxAge DurationString `yaml:"stats-cache-max-age,omitempty"`
SearchCacheMaxAge DurationString `yaml:"search-cache-max-age,omitempty"`
Database string `yaml:"database,omitempty"`
AccessLog string `yaml:"access-log"`
MinUploadPartSize int64 `yaml:"min-upload-part-size"`
MaxUploadPartSize int64 `yaml:"max-upload-part-size"`
MaxUploadParts int `yaml:"max-upload-parts"`
BlobStore BlobStoreType `yaml:"blobstore"`
SwiftAuthURL string `yaml:"swift-auth-url"`
SwiftEndpointURL string `yaml:"swift-endpoint-url"`
SwiftUsername string `yaml:"swift-username"`
SwiftSecret string `yaml:"swift-secret"`
SwiftBucket string `yaml:"swift-bucket"`
SwiftRegion string `yaml:"swift-region"`
SwiftTenant string `yaml:"swift-tenant"`
SwiftAuthMode *SwiftAuthMode `yaml:"swift-authmode"`
LoggingConfig string `yaml:"logging-config"`
DockerRegistryAddress string `yaml:"docker-registry-address"`
DockerRegistryAuthCertificates X509Certificates `yaml:"docker-registry-auth-certs"`
DockerRegistryAuthKey X509PrivateKey `yaml:"docker-registry-auth-key"`
DockerRegistryTokenDuration DurationString `yaml:"docker-registry-token-duration"`
DisableSlowMetadata bool `yaml:"disable-slow-metadata"`
TempDir string `yaml:"tempdir"`
}
type BlobStoreType string
const (
MongoDBBlobStore BlobStoreType = "mongodb"
SwiftBlobStore BlobStoreType = "swift"
)
// SwiftAuthMode implements unmarshaling for
// an identity.AuthMode.
type SwiftAuthMode struct {
Mode identity.AuthMode
}
func (m *SwiftAuthMode) UnmarshalText(data []byte) error {
switch string(data) {
case "legacy":
m.Mode = identity.AuthLegacy
case "keypair":
m.Mode = identity.AuthKeyPair
case "userpassv3":
m.Mode = identity.AuthUserPassV3
case "userpass":
m.Mode = identity.AuthUserPass
default:
return errgo.Newf("unknown swift auth mode %q", data)
}
return nil
}
func (c *Config) validate() error {
var missing []string
needString := func(name, val string) {
if val == "" {
missing = append(missing, name)
}
}
needString("mongo-url", c.MongoURL)
needString("api-addr", c.APIAddr)
needString("auth-username", c.AuthUsername)
if strings.Contains(c.AuthUsername, ":") {
return fmt.Errorf("invalid user name %q (contains ':')", c.AuthUsername)
}
needString("auth-password", c.AuthPassword)
if c.BlobStore == "" {
c.BlobStore = MongoDBBlobStore
}
switch c.BlobStore {
case SwiftBlobStore:
needString("swift-auth-url", c.SwiftAuthURL)
needString("swift-username", c.SwiftUsername)
needString("swift-secret", c.SwiftSecret)
needString("swift-bucket", c.SwiftBucket)
needString("swift-region", c.SwiftRegion)
needString("swift-tenant", c.SwiftTenant)
if c.SwiftAuthMode == nil {
missing = append(missing, "swift-auth-mode")
}
case MongoDBBlobStore:
default:
return errgo.Newf("invalid blob store type %q", c.BlobStore)
}
if len(missing) != 0 {
return errgo.Newf("missing fields %s in config file", strings.Join(missing, ", "))
}
return nil
}
// Read reads a charm store configuration file from the
// given path.
func Read(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, errgo.Notef(err, "cannot open config file")
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, errgo.Notef(err, "cannot read %q", path)
}
var conf Config
err = yaml.Unmarshal(data, &conf)
if err != nil {
return nil, errgo.Notef(err, "cannot parse %q", path)
}
if err := conf.validate(); err != nil {
return nil, errgo.Mask(err)
}
return &conf, nil
}
// DurationString holds a duration that marshals and
// unmarshals as a friendly string.
type DurationString struct {
time.Duration
}
func (dp *DurationString) UnmarshalText(data []byte) error {
d, err := time.ParseDuration(string(data))
if err != nil {
return errgo.Mask(err)
}
dp.Duration = d
return nil
}
type X509Certificates struct {
Certificates []*x509.Certificate
}
func (c *X509Certificates) UnmarshalText(data []byte) error {
if len(data) == 0 {
c.Certificates = nil
return nil
}
for {
var b *pem.Block
b, data = pem.Decode(data)
if b == nil {
break
}
cert, err := x509.ParseCertificate(b.Bytes)
if err != nil {
return errgo.Mask(err)
}
c.Certificates = append(c.Certificates, cert)
}
if len(c.Certificates) == 0 {
return errgo.Newf("no certificates found")
}
return nil
}
type X509PrivateKey struct {
Key crypto.Signer
}
func (k *X509PrivateKey) UnmarshalText(data []byte) error {
if len(data) == 0 {
return nil
}
b, _ := pem.Decode(data)
if b == nil {
return errgo.Newf("no private key found")
}
var err error
switch b.Type {
case "EC PRIVATE KEY":
k.Key, err = x509.ParseECPrivateKey(b.Bytes)
case "RSA PRIVATE KEY":
k.Key, err = x509.ParsePKCS1PrivateKey(b.Bytes)
case "PRIVATE KEY":
var key interface{}
key, err = x509.ParsePKCS8PrivateKey(b.Bytes)
if err == nil {
k.Key = key.(crypto.Signer)
}
default:
err = errgo.Newf("unsupported key type %q", b.Type)
}
return errgo.Mask(err)
}
| agpl-3.0 |
Zepheus/javanx | src/net/zepheus/nxjava/NXFile.java | 8841 | /**
* nxjava: a library for loading the NX file format
* Copyright (C) 2012 Cedric Van Goethem
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.zepheus.nxjava;
import java.util.EnumSet;
import java.util.concurrent.locks.ReentrantLock;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
public class NXFile {
public static final String PKG_FORMAT = "PKG3";
private static final String ENCODING = "UTF-8";
private static final boolean OPEN_BY_DEFAULT = true;
private static final EnumSet<NXReadMode> DEFAULT_PARSE_MODE = EnumSet.of(NXReadMode.EAGER_PARSE_STRINGS);
// Read properties
private boolean low_memory;
private boolean lazy_strings;
// File access stuff
private final RandomAccessFile file;
private ByteBuffer byteBuffer;
private SeekableLittleEndianAccessor slea;
private SeekableLittleEndianAccessor node_reader;
private boolean parsed;
private boolean closed;
private final ReentrantLock lock = new ReentrantLock();
// Format specific properties
private EnumSet<NXReadMode> parseProperties;
private NXHeader header;
private String[] strings;
private byte[][] stringsb;
private long[] string_offsets;
private long[] bmp_offsets;
private long[] mp3_offsets;
// Data containers
private BufferedImage[] bmp_loaded;
private byte[][] mp3_loaded;
private NXNode root;
public NXFile(String path) throws FileNotFoundException, IOException {
this(new RandomAccessFile(path, "r"));
}
public NXFile(String path, EnumSet<NXReadMode> properties) throws FileNotFoundException, IOException {
this(new RandomAccessFile(path, "r"), OPEN_BY_DEFAULT, properties);
}
public NXFile(RandomAccessFile file) throws IOException {
this(file, OPEN_BY_DEFAULT, DEFAULT_PARSE_MODE);
}
public NXFile(RandomAccessFile file, boolean open, EnumSet<NXReadMode> properties) throws IOException {
this.file = file;
this.parseProperties = properties;
low_memory = parseProperties.contains(NXReadMode.LOW_MEMORY);
lazy_strings = parseProperties.contains(NXReadMode.EAGER_PARSE_STRINGS) || low_memory;
if (open) {
this.open();
this.parse();
}
}
public void open() throws IOException {
FileChannel fileChannel = file.getChannel();
byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
slea = new SeekableLittleEndianAccessor(byteBuffer);
}
public void parse() {
if(parsed)
return;
lock();
try {
header = new NXHeader(slea);
parseStrings();
parsed = true;
} finally { unlock(); }
}
private void parseStrings()
{
long offset = header.getStringOffset();
int stringCount = header.getStringCount();
strings = new String[stringCount];
slea.seek(offset);
if(!lazy_strings) {
stringsb = new byte[stringCount][];
for(int i = 0; i < strings.length; i++) {
//strings[i] = slea.getUTFString();
stringsb[i] = slea.getUTFStringB();
}
} else {
string_offsets = new long[stringCount];
for(int i = 0; i < stringCount; i++) {
int size = slea.getUShort();
string_offsets[i] = offset;
slea.skip(size);
offset += (size + 2);
}
}
}
public String getString(int id) {
try {
if(strings[id] == null) {
if(lazy_strings) {
lock();
try { //TODO: check all deadlocks that could happen during getstring
int cpos = slea.position();
slea.seek(string_offsets[id]);
strings[id] = slea.getUTFString();
slea.seek(cpos);
} finally { unlock(); }
} else {
strings[id] = new String(stringsb[id], ENCODING);
stringsb[id] = null; //force GC
}
}
return strings[id];
} catch (UnsupportedEncodingException e) {
return null;
}
}
public NXNode getRoot() {
if(root == null) {
lock();
try {
if(!low_memory) {
slea.seek(header.getNodeOffset());
ByteBuffer node_buff = ByteBuffer.wrap(slea.getBytes(header.getNodeCount() * NXNode.SIZE));
node_reader = new SeekableLittleEndianAccessor(node_buff);
}
root = NXNodeParser.parse(getNodeStream(0), null, this);
} finally { unlock(); }
}
return root;
}
public NXNode resolvePath(String... path) {
NXNode currentNode = getRoot();
int offset = 0;
while(offset < path.length) {
currentNode = currentNode.getChild(path[offset++]);
if(currentNode == null)
throw new NXException("Invalid path");
}
return currentNode;
}
public byte[] getMP3(int id) {
byte[] value;
if(!low_memory && mp3_loaded != null && (value = mp3_loaded[id]) != null) {
return value;
} else {
long offset = getMP3Offset(id);
if(offset < 0)
throw new NXException("The NX file does not include this MP3.");
lock();
try {
SeekableLittleEndianAccessor slea = getStreamAtOffset(offset);
int size = (int)slea.getUInt(); //Warning: this could go out of bounds (but unlikely)
value = slea.getBytes(size);
} finally { unlock(); }
if(!low_memory) {
mp3_loaded[id] = value;
}
return value;
}
}
public BufferedImage getBitmap(int id) {
BufferedImage value;
if(!low_memory && bmp_loaded != null && (value = bmp_loaded[id]) != null) {
return value;
} else {
long offset = getBitmapOffset(id);
if(offset == -1)
throw new NXException("NX file does not this canvas.");
lock();
try {
SeekableLittleEndianAccessor slea = getStreamAtOffset(offset);
int width = slea.getUShort();
int height = slea.getUShort();
long length = slea.getUInt();
ByteBuffer output = ByteBuffer.allocateDirect(width * height * 4);
NXCompression.decompress(slea.getBuffer(), offset + 4, length + 4, output, 0);
output.rewind();
output.order(ByteOrder.LITTLE_ENDIAN);
//TODO: optimize this without bitshifts.
value = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
int b = output.get() & 0xFF;
int g = output.get() & 0xFF;
int r = output.get() & 0xFF;
int a = output.get() & 0xFF;
value.setRGB(w, h, (a << 24) | (r << 16) | (g << 8) | b);
}
}
} finally { unlock(); }
if(!low_memory) bmp_loaded[id] = value;
return value;
}
}
public long getBitmapOffset(int id) {
int count = header.getBmpCount();
if(count == 0 || id > count)
return -1;
if(bmp_offsets == null) {
bmp_offsets = new long[count];
lock();
try {
populateOffsetTable(bmp_offsets, header.getBmpOffset());
} finally { unlock(); }
if(!low_memory) {
bmp_loaded = new BufferedImage[count];
}
}
return bmp_offsets[id];
}
public long getMP3Offset(int id) {
int count = header.getMp3Count();
if(count == 0 || id > count)
return -1;
if(mp3_offsets == null) {
mp3_offsets = new long[count];
lock();
try {
populateOffsetTable(mp3_offsets, header.getMp3Offset());
} finally { unlock(); }
if(!low_memory) {
mp3_loaded = new byte[count][];
}
}
return mp3_offsets[id];
}
private void populateOffsetTable(long[] to, long start) {
slea.seek(start);
for(int i = 0; i < to.length; i++) {
to[i] = slea.getLong();
}
}
public SeekableLittleEndianAccessor getNodeStream(int id) {
if(closed)
throw new NXException("File already closed.");
SeekableLittleEndianAccessor stream = low_memory ? slea : node_reader;
stream.seek((low_memory ? header.getNodeOffset() : 0) + id * NXNode.SIZE);
return stream;
}
public SeekableLittleEndianAccessor getStreamAtOffset(long offset) {
if(closed)
throw new NXException("File already closed.");
slea.seek(offset);
return slea;
}
public void lock()
{
lock.lock();
}
public void unlock()
{
lock.unlock();
}
public void close()
{
if(closed)
return;
lock();
try {
file.close();
slea = null;
node_reader = null;
byteBuffer = null;
closed = true;
} catch (IOException e) {}
finally { unlock(); }
}
public NXHeader getHeader() {
return header;
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/bind/BindAction.java | 1479 | package com.x.organization.assemble.authentication.jaxrs.bind;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.x.base.core.project.annotation.JaxrsDescribe;
import com.x.base.core.project.annotation.JaxrsMethodDescribe;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.HttpMediaType;
import com.x.base.core.project.jaxrs.ResponseFactory;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.organization.assemble.authentication.wrapout.WrapOutBind;
@Path("bind")
@JaxrsDescribe("绑定")
public class BindAction extends StandardJaxrsAction {
@JaxrsMethodDescribe(value = "列示所有Bind对象.", action = ActionList.class)
@GET
@Path("list")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listNext(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request) {
ActionResult<List<WrapOutBind>> result = new ActionResult<>();
try {
result = new ActionList().execute();
} catch (Throwable th) {
th.printStackTrace();
result.error(th);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
} | agpl-3.0 |
ebeshero/Pittsburgh_Frankenstein | collateXPrep/python/Part4-allWitnessIM_collation_to_xml.py | 11125 | from collatex import *
from xml.dom import pulldom
import re
import glob
from datetime import datetime, date
# import pytz
# from tzlocal import get_localzone
# today = date.today()
# utc_dt = datetime(today, tzinfo=pytz.utc)
# dateTime = utc_dt.astimezone(get_localzone())
# strDateTime = str(dateTime)
now = datetime.utcnow()
nowStr = str(now)
print('test: ', dir(Collation))
regexWhitespace = re.compile(r'\s+')
regexNonWhitespace = re.compile(r'\S+')
regexEmptyTag = re.compile(r'/>$')
regexBlankLine = re.compile(r'\n{2,}')
regexLeadingBlankLine = re.compile(r'^\n')
regexPageBreak = re.compile(r'<pb.+?/>')
RE_MARKUP = re.compile(r'<.+?>')
RE_PARA = re.compile(r'<p\s[^<]+?/>')
RE_INCLUDE = re.compile(r'<include[^<]*/>')
RE_MILESTONE = re.compile(r'<milestone[^<]*/>')
RE_HEAD = re.compile(r'<head[^<]*/>')
RE_AB = re.compile(r'<ab[^<]*/>')
# 2018-10-1 ebb: ampersands are apparently not treated in python regex as entities any more than angle brackets.
# RE_AMP_NSB = re.compile(r'\S&\s')
# RE_AMP_NSE = re.compile(r'\s&\S')
# RE_AMP_SQUISH = re.compile(r'\S&\S')
# RE_AMP = re.compile(r'\s&\s')
RE_AMP = re.compile(r'&')
# RE_MULTICAPS = re.compile(r'(?<=\W|\s|\>)[A-Z][A-Z]+[A-Z]*\s')
# RE_INNERCAPS = re.compile(r'(?<=hi\d"/>)[A-Z]+[A-Z]+[A-Z]+[A-Z]*')
# TITLE_MultiCaps = match(RE_MULTICAPS).lower()
RE_DELSTART = re.compile(r'<del[^<]*>')
RE_ADDSTART = re.compile(r'<add[^<]*>')
RE_MDEL = re.compile(r'<mdel[^<]*>.+?</mdel>')
RE_SHI = re.compile(r'<shi[^<]*>.+?</shi>')
RE_METAMARK = re.compile(r'<metamark[^<]*>.+?</metamark>')
RE_HI = re.compile(r'<hi\s[^<]*/>')
RE_PB = re.compile(r'<pb[^<]*/>')
RE_LB = re.compile(r'<lb[^<]*/>')
RE_LG = re.compile(r'<lg[^<]*/>')
RE_L = re.compile(r'<l\s[^<]*/>')
RE_CIT = re.compile(r'<cit\s[^<]*/>')
RE_QUOTE = re.compile(r'<quote\s[^<]*/>')
RE_OPENQT = re.compile(r'“')
RE_CLOSEQT = re.compile(r'”')
RE_GAP = re.compile(r'<gap\s[^<]*/>')
# <milestone unit="tei:p"/>
RE_sgaP = re.compile(r'<milestone\sunit="tei:p"[^<]*/>')
# RE_hyphen = re.compile(r'-')
# ebb: RE_MDEL = those pesky deletions of two letters or less that we want to normalize out of the collation, but preserve in the output.
# Element types: xml, div, head, p, hi, pb, note, lg, l; comment()
# Tags to ignore, with content to keep: xml, comment, anchor
# Structural elements: div, p, lg, l
# Inline elements (empty) retained in normalization: pb, milestone, xi:include
# Inline and block elements (with content) retained in normalization: note, hi, head, ab
# GIs fall into one three classes
# 2017-05-21 ebb: Due to trouble with pulldom parsing XML comments, I have converted these to comment elements,
# 2017-05-21 ebb: to be ignored during collation.
# 2017-05-30 ebb: Determined that comment elements cannot really be ignored when they have text nodes (the text is
# 2017-05-30 ebb: collated but the tags are not). Decision to make the comments into self-closing elements with text
# 2017-05-30 ebb: contents as attribute values, and content such as tags simplified to be legal attribute values.
# 2017-05-22 ebb: I've set anchor elements with @xml:ids to be the indicators of collation "chunks" to process together
ignore = ['sourceDoc', 'xml', 'comment', 'w', 'mod', 'anchor', 'include', 'delSpan', 'addSpan', 'add', 'handShift', 'damage', 'restore', 'zone', 'surface', 'graphic', 'unclear', 'retrace']
blockEmpty = ['pb', 'p', 'div', 'milestone', 'lg', 'l', 'note', 'cit', 'quote', 'bibl', 'ab', 'head']
inlineEmpty = ['lb', 'gap', 'del', 'hi']
# 2018-05-12 (mysteriously removed but reinstated 2018-09-27) ebb: I'm setting a white space on either side of the inlineEmpty elements in line 103
# 2018-07-20: ebb: CHECK: are there white spaces on either side of empty elements in the output?
inlineContent = ['metamark', 'mdel', 'shi']
#2018-07-17 ebb: I moved the following list up into inlineEmpty, since they are all now empty elements: blockElement = ['lg', 'l', 'note', 'cit', 'quote', 'bibl']
# ebb: Tried removing 'comment', from blockElement list above, because we don't want these to be collated.
# 10-23-2017 ebb rv:
def normalizeSpace(inText):
"""Replaces all whitespace spans with single space characters"""
#2018-09-28 ebb: Is this doing what we think?
if regexNonWhitespace.search(inText):
return regexWhitespace.sub('\n', inText)
else:
return ''
def extract(input_xml):
"""Process entire input XML document, firing on events"""
# Start pulling; it continues automatically
doc = pulldom.parse(input_xml)
output = ''
for event, node in doc:
# elements to ignore: xml
if event == pulldom.START_ELEMENT and node.localName in ignore:
continue
# copy comments intact
elif event == pulldom.COMMENT:
doc.expandNode(node)
output += node.toxml()
# ebb: Next (below): empty block elements: pb, milestone, lb, lg, l, p, ab, head, hi,
# We COULD set white spaces around these like this ' ' + node.toxml() + ' '
# but what seems to happen is that the white spaces get added to tokens; they aren't used to
# isolate the markup into separate tokens, which is really what we'd want.
# So, I'm removing the white spaces here.
# NOTE: Removing the white space seems to improve/expand app alignment
elif event == pulldom.START_ELEMENT and node.localName in blockEmpty:
output += node.toxml()
# ebb: empty inline elements that do not take surrounding white spaces:
elif event == pulldom.START_ELEMENT and node.localName in inlineEmpty:
output += node.toxml()
# non-empty inline elements: mdel, shi, metamark
elif event == pulldom.START_ELEMENT and node.localName in inlineContent:
output += regexEmptyTag.sub('>', node.toxml())
elif event == pulldom.END_ELEMENT and node.localName in inlineContent:
output += '</' + node.localName + '>'
# elif event == pulldom.START_ELEMENT and node.localName in blockElement:
# output += '\n<' + node.localName + '>\n'
#elif event == pulldom.END_ELEMENT and node.localName in blockElement:
# output += '\n</' + node.localName + '>'
elif event == pulldom.CHARACTERS:
output += normalizeSpace(node.data)
else:
continue
return output
def normalize(inputText):
# 2018-09-23 ebb THIS WORKS, SOMETIMES, BUT NOT EVERWHERE: RE_MULTICAPS.sub(format(re.findall(RE_MULTICAPS, inputText, flags=0)).title(), \
# RE_INNERCAPS.sub(format(re.findall(RE_INNERCAPS, inputText, flags=0)).lower(), \
return RE_MILESTONE.sub('', \
RE_INCLUDE.sub('', \
RE_AB.sub('', \
RE_HEAD.sub('', \
RE_AMP.sub('and', \
RE_MDEL.sub('', \
RE_SHI.sub('', \
RE_HI.sub('', \
RE_LB.sub('', \
RE_PB.sub('', \
RE_PARA.sub('<p/>', \
RE_sgaP.sub('<p/>', \
RE_LG.sub('<lg/>', \
RE_L.sub('<l/>', \
RE_CIT.sub('', \
RE_QUOTE.sub('', \
RE_OPENQT.sub('"', \
RE_CLOSEQT.sub('"', \
RE_GAP.sub('', \
RE_DELSTART.sub('<del>', \
RE_ADDSTART.sub('<add>', \
RE_METAMARK.sub('', inputText)))))))))))))))))))))).lower()
# to lowercase the normalized tokens, add .lower() to the end.
# return regexPageBreak('',inputText)
# ebb: The normalize function makes it possible to return normalized tokens that screen out some markup, but not all.
def processToken(inputText):
return {"t": inputText + ' ', "n": normalize(inputText)}
def processWitness(inputWitness, id):
return {'id': id, 'tokens': [processToken(token) for token in inputWitness]}
for name in glob.glob('../collChunks-Part4/1818_fullFlat_*'):
try:
matchString = name.split("fullFlat_", 1)[1]
# ebb: above gets C30.xml for example
matchStr = matchString.split(".", 1)[0]
# ebb: above strips off the file extension
with open(name, 'rb') as f1818file, \
open('../collChunks-Part4/1823_fullFlat_' + matchString, 'rb') as f1823file, \
open('../collChunks-Part4/Thomas_fullFlat_' + matchString, 'rb') as fThomasfile, \
open('../collChunks-Part4/1831_fullFlat_' + matchString, 'rb') as f1831file, \
open('../collChunks-Part4/msColl_' + matchString, 'rb') as fMSfile, \
open('../Full_Part4_xmlOutput/collation_' + matchStr + '.xml', 'w') as outputFile:
# open('collationChunks/msColl_c56_' + matchString, 'rb') as fMSc56file, \
# open('collationChunks/msColl_c58_' + matchString, 'rb') as fMSc58file, \
# open('collationChunks/msColl_c57Frag_' + matchString, 'rb') as fMSc57Fragfile, \
# open('collationChunks/msColl_c58Frag_' + matchString, 'rb') as fMSc58Fragfile, \
# fMSc56_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(fMSc56file))).split('\n')
# fMSc58_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(fMSc58file))).split('\n')
# fMSc57Frag_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(fMSc57Fragfile))).split('\n')
# fMSc58Frag_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(fMSc58Fragfile))).split('\n')
f1818_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(f1818file))).split('\n')
fThomas_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(fThomasfile))).split('\n')
f1823_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(f1823file))).split('\n')
f1831_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(f1831file))).split('\n')
fMS_tokens = regexLeadingBlankLine.sub('', regexBlankLine.sub('\n', extract(fMSfile))).split('\n')
f1818_tokenlist = processWitness(f1818_tokens, 'f1818')
fThomas_tokenlist = processWitness(fThomas_tokens, 'fThomas')
f1823_tokenlist = processWitness(f1823_tokens, 'f1823')
f1831_tokenlist = processWitness(f1831_tokens, 'f1831')
fMS_tokenlist = processWitness(fMS_tokens, 'fMS')
# fMSc56_tokenlist = processWitness(fMSc56_tokens, 'fMSc56')
# fMSc58_tokenlist = processWitness(fMSc58_tokens, 'fMSc58')
# fMSc57Frag_tokenlist = processWitness(fMSc57Frag_tokens, 'fMSc57Frag')
# fMSc58Frag_tokenlist = processWitness(fMSc58Frag_tokens, 'fMSc58Frag')
collation_input = {"witnesses": [f1818_tokenlist, f1823_tokenlist, fThomas_tokenlist, fMS_tokenlist, f1831_tokenlist]}
# table = collate(collation_input, output='tei', segmentation=True)
# table = collate(collation_input, segmentation=True, layout='vertical')
table = collate(collation_input, output='xml', segmentation=True)
print(table + '<!-- ' + nowStr + ' -->', file=outputFile)
# print(table, file=outputFile)
except IOError:
pass
| agpl-3.0 |
Tesora/tesora-dve-pub | tesora-dve-core/src/test/java/com/tesora/dve/sql/IgnoreForeignKeyTest.java | 8393 | package com.tesora.dve.sql;
/*
* #%L
* Tesora Inc.
* Database Virtualization Engine
* %%
* Copyright (C) 2011 - 2014 Tesora Inc.
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.lang.SystemUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.tesora.dve.common.catalog.FKMode;
import com.tesora.dve.common.catalog.TemplateMode;
import com.tesora.dve.server.bootstrap.BootstrapHost;
import com.tesora.dve.sql.util.DBHelperConnectionResource;
import com.tesora.dve.sql.util.PEDDL;
import com.tesora.dve.sql.util.PortalDBHelperConnectionResource;
import com.tesora.dve.sql.util.ProjectDDL;
import com.tesora.dve.sql.util.StorageGroupDDL;
import com.tesora.dve.standalone.PETest;
public class IgnoreForeignKeyTest extends SchemaTest {
private static StorageGroupDDL sg = new StorageGroupDDL("check",2,"checkg");
private static final ProjectDDL checkDDL =
new PEDDL("adb",sg,
"database").withFKMode(FKMode.IGNORE);
@BeforeClass
public static void setup() throws Exception {
PETest.projectSetup(checkDDL);
PETest.bootHost = BootstrapHost.startServices(PETest.class);
}
private PortalDBHelperConnectionResource conn;
private DBHelperConnectionResource dbh;
@Before
public void before() throws Throwable {
conn = new PortalDBHelperConnectionResource();
dbh = new DBHelperConnectionResource();
}
@After
public void after() throws Throwable {
if(conn != null) {
conn.disconnect();
}
if(dbh != null) {
dbh.disconnect();
}
conn = null;
dbh = null;
}
// make sure the declaration works and we can get the info out
@Test
public void testDBDeclaration() throws Throwable {
try {
checkDDL.create(conn);
conn.assertResults("select * from information_schema.schemata where schema_name = '" + checkDDL.getDatabaseName() + "'",
br(nr, "def", "adb", "checkg", null, TemplateMode.OPTIONAL.toString(), "off", "ignore", "utf8", "utf8_general_ci"));
} finally {
checkDDL.destroy(conn);
}
}
private static final String peinfoSql =
"select table_name, column_name, referenced_table_name, referenced_column_name from information_schema.key_column_usage where referenced_column_name is not null and table_schema = '" + checkDDL.getDatabaseName() + "'";
private static final String nativeInfoSql =
"select table_name, column_name, referenced_table_name, referenced_column_name from information_schema.key_column_usage where referenced_column_name is not null and table_schema = '" + sg.getPhysicalSiteNames(checkDDL.getDatabaseName()).get(0) + "'";
// first make sure that when things are colocated we don't screw it up
@Test
public void testColocatedDeclaration() throws Throwable {
try {
checkDDL.create(conn);
conn.execute("create range openrange (int) persistent group checkg");
conn.execute("create table P (`id` int, `fid` int, `sid` int, primary key (`id`)) range distribute on (id) using openrange");
conn.execute("create table C (`id` int, `fid` int, primary key (`id`), foreign key (`fid`) references P (`id`)) range distribute on (fid) using openrange");
assertFalse("should not have warnings",conn.hasWarnings());
Object[] results = br(nr,"C","fid","P","id");
Object[] windowsNativeResults = br(nr,"c","fid","p","id");
conn.assertResults(peinfoSql,results);
dbh.assertResults(nativeInfoSql, (SystemUtils.IS_OS_WINDOWS ? windowsNativeResults : results));
} finally {
checkDDL.destroy(conn);
}
}
// noncolocated - we should still report the fk in our info schema but the backing tables shouldn't have it
@Test
public void testNoncolocatedDeclaration() throws Throwable {
try {
checkDDL.create(conn);
conn.execute("create range openrange (int) persistent group checkg");
conn.execute("create table P (`id` int, `fid` int, `sid` int, primary key (`id`)) range distribute on (id) using openrange");
conn.execute("create table C (`id` int, `fid` int, primary key (`id`), foreign key (`fid`) references P (`id`)) broadcast distribute");
assertTrue("should have warnings",conn.hasWarnings());
conn.assertResults("show warnings",
br(nr,"Warning",getIgnore(),
"Invalid foreign key C.C_ibfk_1: table C is not colocated with P - not persisted"));
conn.assertResults(peinfoSql,
br(nr,"C","fid","P","id"));
// make sure the fk doesn't make it onto a psite
dbh.assertResults(nativeInfoSql, br());
} finally {
checkDDL.destroy(conn);
}
}
// make sure the forward handling code still works - if it's colocated we should allow it and
// the fk should make it to the database
@Test
public void testForwardColocated() throws Throwable {
try {
checkDDL.create(conn);
conn.execute("set foreign_key_checks=0");
conn.execute("create range openrange (int) persistent group checkg");
conn.execute("create table C (`id` int, `fid` int, primary key (`id`), foreign key (`fid`) references P (`id`)) range distribute on (fid) using openrange");
conn.execute("create table P (`id` int, `fid` int, `sid` int, primary key (`id`)) range distribute on (id) using openrange");
assertFalse("should not have warnings",conn.hasWarnings());
Object[] results = br(nr,"C","fid","P","id");
Object[] windowsNativeResults = br(nr,"c","fid","p","id");
conn.assertResults(peinfoSql,results);
dbh.assertResults(nativeInfoSql, (SystemUtils.IS_OS_WINDOWS ? windowsNativeResults : results));
} finally {
checkDDL.destroy(conn);
}
}
// if it's not colocated we should just silently drop it regardless of the value of foreign key checks
@Test
public void testForwardNonColocated() throws Throwable {
// This test won't work on Mysql 5.1 due to a known mysql issue
// with some FK operations
if (SchemaTest.getDBVersion() != DBVersion.MYSQL_51) {
try {
checkDDL.create(conn);
conn.execute("set foreign_key_checks=0");
conn.execute("create range openrange (int) persistent group checkg");
conn.execute("create table C (`id` int, `fid` int, primary key (`id`), foreign key (`fid`) references P (`id`)) broadcast distribute");
conn.execute("create table P (`id` int, `fid` int, `sid` int, primary key (`id`)) range distribute on (id) using openrange");
assertTrue("should have warnings",conn.hasWarnings());
conn.assertResults("show warnings",
br(nr,"Warning",getIgnore(),
"Invalid foreign key C.C_ibfk_1: table C is not colocated with P - not persisted"));
conn.assertResults(peinfoSql,
br(nr,"C","fid","P","id"));
// make sure the fk doesn't make it onto a psite
dbh.assertResults(nativeInfoSql, br());
} finally {
checkDDL.destroy(conn);
}
}
}
// if we didn't persist it, we should just noop a drop
@Test
public void testNonPersistedDrop() throws Throwable {
try {
checkDDL.create(conn);
conn.execute("create range openrange (int) persistent group checkg");
conn.execute("create table P (`id` int, `fid` int, `sid` int, primary key (`id`)) range distribute on (id) using openrange");
conn.execute("create table C (`id` int, `fid` int, primary key (`id`), foreign key (`fid`) references P (`id`)) broadcast distribute");
assertTrue("should have warnings",conn.hasWarnings());
conn.assertResults("show warnings",
br(nr,"Warning",getIgnore(),
"Invalid foreign key C.C_ibfk_1: table C is not colocated with P - not persisted"));
conn.assertResults(peinfoSql,
br(nr,"C","fid","P","id"));
// make sure the fk doesn't make it onto a psite
dbh.assertResults(nativeInfoSql, br());
conn.execute("alter table C drop key C_ibfk_1");
conn.assertResults(peinfoSql, br());
} finally {
checkDDL.destroy(conn);
}
}
}
| agpl-3.0 |
davecheney/juju | provider/openstack/config_test.go | 13516 | // Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package openstack
import (
"os"
jc "github.com/juju/testing/checkers"
gc "gopkg.in/check.v1"
"github.com/juju/juju/cloud"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
envtesting "github.com/juju/juju/environs/testing"
"github.com/juju/juju/testing"
)
type ConfigSuite struct {
testing.BaseSuite
savedVars map[string]string
}
// Ensure any environment variables a user may have set locally are reset.
var envVars = map[string]string{
"AWS_SECRET_ACCESS_KEY": "",
"EC2_SECRET_KEYS": "",
"NOVA_API_KEY": "",
"NOVA_PASSWORD": "",
"NOVA_PROJECT_ID": "",
"NOVA_REGION": "",
"NOVA_USERNAME": "",
"OS_ACCESS_KEY": "",
"OS_AUTH_URL": "",
"OS_PASSWORD": "",
"OS_REGION_NAME": "",
"OS_SECRET_KEY": "",
"OS_TENANT_NAME": "",
"OS_USERNAME": "",
}
var _ = gc.Suite(&ConfigSuite{})
// configTest specifies a config parsing test, checking that env when
// parsed as the openstack section of a config file matches
// baseConfigResult when mutated by the mutate function, or that the
// parse matches the given error.
type configTest struct {
summary string
config testing.Attrs
change map[string]interface{}
expect map[string]interface{}
envVars map[string]string
region string
useFloatingIP bool
useDefaultSecurityGroup bool
network string
username string
password string
tenantName string
authMode AuthMode
authURL string
accessKey string
secretKey string
firewallMode string
err string
sslHostnameVerification bool
sslHostnameSet bool
blockStorageSource string
}
var requiredConfig = testing.Attrs{
"region": "configtest",
"auth-url": "http://auth",
"username": "user",
"password": "pass",
"tenant-name": "tenant",
}
func restoreEnvVars(envVars map[string]string) {
for k, v := range envVars {
os.Setenv(k, v)
}
}
func (t configTest) check(c *gc.C) {
attrs := testing.FakeConfig().Merge(testing.Attrs{
"type": "openstack",
}).Merge(t.config)
cfg, err := config.New(config.NoDefaults, attrs)
c.Assert(err, jc.ErrorIsNil)
// Set environment variables if any.
savedVars := make(map[string]string)
if t.envVars != nil {
for k, v := range t.envVars {
savedVars[k] = os.Getenv(k)
os.Setenv(k, v)
}
}
defer restoreEnvVars(savedVars)
e, err := environs.New(cfg)
if t.change != nil {
c.Assert(err, jc.ErrorIsNil)
// Testing a change in configuration.
var old, changed, valid *config.Config
osenv := e.(*Environ)
old = osenv.ecfg().Config
changed, err = old.Apply(t.change)
c.Assert(err, jc.ErrorIsNil)
// Keep err for validation below.
valid, err = providerInstance.Validate(changed, old)
if err == nil {
err = osenv.SetConfig(valid)
}
}
if t.err != "" {
c.Check(err, gc.ErrorMatches, t.err)
return
}
c.Assert(err, jc.ErrorIsNil)
ecfg := e.(*Environ).ecfg()
c.Assert(ecfg.Name(), gc.Equals, "testenv")
if t.region != "" {
c.Assert(ecfg.region(), gc.Equals, t.region)
}
if t.authMode != "" {
c.Assert(ecfg.authMode(), gc.Equals, t.authMode)
}
if t.accessKey != "" {
c.Assert(ecfg.accessKey(), gc.Equals, t.accessKey)
}
if t.secretKey != "" {
c.Assert(ecfg.secretKey(), gc.Equals, t.secretKey)
}
if t.username != "" {
c.Assert(ecfg.username(), gc.Equals, t.username)
c.Assert(ecfg.password(), gc.Equals, t.password)
c.Assert(ecfg.tenantName(), gc.Equals, t.tenantName)
c.Assert(ecfg.authURL(), gc.Equals, t.authURL)
expected := map[string]string{
"username": t.username,
"password": t.password,
"tenant-name": t.tenantName,
}
c.Assert(err, jc.ErrorIsNil)
actual, err := e.Provider().SecretAttrs(ecfg.Config)
c.Assert(err, jc.ErrorIsNil)
c.Assert(expected, gc.DeepEquals, actual)
}
if t.firewallMode != "" {
c.Assert(ecfg.FirewallMode(), gc.Equals, t.firewallMode)
}
c.Assert(ecfg.useFloatingIP(), gc.Equals, t.useFloatingIP)
c.Assert(ecfg.useDefaultSecurityGroup(), gc.Equals, t.useDefaultSecurityGroup)
c.Assert(ecfg.network(), gc.Equals, t.network)
// Default should be true
expectedHostnameVerification := true
if t.sslHostnameSet {
expectedHostnameVerification = t.sslHostnameVerification
}
c.Assert(ecfg.SSLHostnameVerification(), gc.Equals, expectedHostnameVerification)
for name, expect := range t.expect {
actual, found := ecfg.UnknownAttrs()[name]
c.Check(found, jc.IsTrue)
c.Check(actual, gc.Equals, expect)
}
expectedStorage := "cinder"
if t.blockStorageSource != "" {
expectedStorage = t.blockStorageSource
}
storage, ok := ecfg.StorageDefaultBlockSource()
c.Assert(ok, jc.IsTrue)
c.Assert(storage, gc.Equals, expectedStorage)
}
func (s *ConfigSuite) SetUpTest(c *gc.C) {
s.BaseSuite.SetUpTest(c)
s.savedVars = make(map[string]string)
for v, val := range envVars {
s.savedVars[v] = os.Getenv(v)
os.Setenv(v, val)
}
s.PatchValue(&authenticateClient, func(*Environ) error { return nil })
}
func (s *ConfigSuite) TearDownTest(c *gc.C) {
for k, v := range s.savedVars {
os.Setenv(k, v)
}
s.BaseSuite.TearDownTest(c)
}
var configTests = []configTest{
{
summary: "setting region",
config: requiredConfig.Merge(testing.Attrs{
"region": "testreg",
}),
region: "testreg",
}, {
summary: "setting region (2)",
config: requiredConfig.Merge(testing.Attrs{
"region": "configtest",
}),
region: "configtest",
}, {
summary: "changing region",
config: requiredConfig,
change: testing.Attrs{
"region": "otherregion",
},
err: `cannot change region from "configtest" to "otherregion"`,
}, {
summary: "invalid region",
config: requiredConfig.Merge(testing.Attrs{
"region": 666,
}),
err: `.*expected string, got int\(666\)`,
}, {
summary: "missing region in model",
config: requiredConfig.Delete("region"),
err: "missing region not valid",
}, {
summary: "invalid username",
config: requiredConfig.Merge(testing.Attrs{
"username": 666,
}),
err: `.*expected string, got int\(666\)`,
}, {
summary: "missing username in model",
config: requiredConfig.Delete("username"),
err: "missing username not valid",
}, {
summary: "invalid password",
config: requiredConfig.Merge(testing.Attrs{
"password": 666,
}),
err: `.*expected string, got int\(666\)`,
}, {
summary: "missing password in model",
config: requiredConfig.Delete("password"),
err: "missing password not valid",
}, {
summary: "invalid tenant-name",
config: requiredConfig.Merge(testing.Attrs{
"tenant-name": 666,
}),
err: `.*expected string, got int\(666\)`,
}, {
summary: "missing tenant in model",
config: requiredConfig.Delete("tenant-name"),
err: "missing tenant-name not valid",
}, {
summary: "invalid auth-url type",
config: requiredConfig.Merge(testing.Attrs{
"auth-url": 666,
}),
err: `.*expected string, got int\(666\)`,
}, {
summary: "missing auth-url in model",
config: requiredConfig.Delete("auth-url"),
err: "missing auth-url not valid",
}, {
summary: "invalid authorization mode",
config: requiredConfig.Merge(testing.Attrs{
"auth-mode": "invalid-mode",
}),
err: `auth-mode: expected one of \[keypair legacy userpass\], got "invalid-mode"`,
}, {
summary: "keypair authorization mode",
config: requiredConfig.Merge(testing.Attrs{
"auth-mode": "keypair",
"access-key": "MyAccessKey",
"secret-key": "MySecretKey",
}),
authMode: "keypair",
accessKey: "MyAccessKey",
secretKey: "MySecretKey",
}, {
summary: "keypair authorization mode without access key",
config: requiredConfig.Merge(testing.Attrs{
"auth-mode": "keypair",
"secret-key": "MySecretKey",
}),
err: "missing access-key not valid",
}, {
summary: "keypair authorization mode without secret key",
config: requiredConfig.Merge(testing.Attrs{
"auth-mode": "keypair",
"access-key": "MyAccessKey",
}),
err: "missing secret-key not valid",
}, {
summary: "invalid auth-url format",
config: requiredConfig.Merge(testing.Attrs{
"auth-url": "invalid",
}),
err: `invalid auth-url value "invalid"`,
}, {
summary: "valid auth args",
config: requiredConfig.Merge(testing.Attrs{
"username": "jujuer",
"password": "open sesame",
"tenant-name": "juju tenant",
"auth-mode": "legacy",
"auth-url": "http://some/url",
}),
username: "jujuer",
password: "open sesame",
tenantName: "juju tenant",
authURL: "http://some/url",
authMode: AuthLegacy,
}, {
summary: "default use floating ip",
config: requiredConfig,
// Do not use floating IP's by default.
useFloatingIP: false,
}, {
summary: "use floating ip",
config: requiredConfig.Merge(testing.Attrs{
"use-floating-ip": true,
}),
useFloatingIP: true,
}, {
summary: "default use default security group",
config: requiredConfig,
// Do not use default security group by default.
useDefaultSecurityGroup: false,
}, {
summary: "use default security group",
config: requiredConfig.Merge(testing.Attrs{
"use-default-secgroup": true,
}),
useDefaultSecurityGroup: true,
}, {
summary: "admin-secret given",
config: requiredConfig.Merge(testing.Attrs{
"admin-secret": "Futumpsh",
}),
}, {
summary: "default firewall-mode",
config: requiredConfig,
firewallMode: config.FwInstance,
}, {
summary: "instance firewall-mode",
config: requiredConfig.Merge(testing.Attrs{
"firewall-mode": "instance",
}),
firewallMode: config.FwInstance,
}, {
summary: "global firewall-mode",
config: requiredConfig.Merge(testing.Attrs{
"firewall-mode": "global",
}),
firewallMode: config.FwGlobal,
}, {
summary: "none firewall-mode",
config: requiredConfig.Merge(testing.Attrs{
"firewall-mode": "none",
}),
firewallMode: config.FwNone,
}, {
config: requiredConfig.Merge(testing.Attrs{
"future": "hammerstein",
}),
expect: testing.Attrs{
"future": "hammerstein",
},
}, {
config: requiredConfig,
change: testing.Attrs{
"future": "hammerstein",
},
expect: testing.Attrs{
"future": "hammerstein",
},
}, {
config: requiredConfig,
change: testing.Attrs{
"ssl-hostname-verification": false,
},
sslHostnameVerification: false,
sslHostnameSet: true,
}, {
config: requiredConfig,
change: testing.Attrs{
"ssl-hostname-verification": true,
},
sslHostnameVerification: true,
sslHostnameSet: true,
}, {
summary: "default network",
config: requiredConfig,
network: "",
}, {
summary: "network",
config: requiredConfig.Merge(testing.Attrs{
"network": "a-network-label",
}),
network: "a-network-label",
}, {
summary: "no default block storage specified",
config: requiredConfig,
blockStorageSource: "cinder",
}, {
summary: "block storage specified",
config: requiredConfig.Merge(testing.Attrs{
"storage-default-block-source": "my-cinder",
}),
blockStorageSource: "my-cinder",
},
}
func (s *ConfigSuite) TestConfig(c *gc.C) {
for i, t := range configTests {
c.Logf("test %d: %s (%v)", i, t.summary, t.config)
t.check(c)
}
}
func (s *ConfigSuite) TestDeprecatedAttributesRemoved(c *gc.C) {
attrs := testing.FakeConfig().Merge(testing.Attrs{
"type": "openstack",
"default-image-id": "id-1234",
"default-instance-type": "big",
"username": "u",
"password": "p",
"tenant-name": "t",
"region": "r",
"auth-url": "http://auth",
})
cfg, err := config.New(config.NoDefaults, attrs)
c.Assert(err, jc.ErrorIsNil)
// Keep err for validation below.
valid, err := providerInstance.Validate(cfg, nil)
c.Assert(err, jc.ErrorIsNil)
// Check deprecated attributes removed.
allAttrs := valid.AllAttrs()
for _, attr := range []string{"default-image-id", "default-instance-type"} {
_, ok := allAttrs[attr]
c.Assert(ok, jc.IsFalse)
}
}
func (s *ConfigSuite) TestPrepareSetsDefaultBlockSource(c *gc.C) {
attrs := testing.FakeConfig().Merge(testing.Attrs{
"type": "openstack",
})
cfg, err := config.New(config.NoDefaults, attrs)
c.Assert(err, jc.ErrorIsNil)
env, err := providerInstance.PrepareForBootstrap(envtesting.BootstrapContext(c), s.prepareForBootstrapParams(cfg))
c.Assert(err, jc.ErrorIsNil)
source, ok := env.(*Environ).ecfg().StorageDefaultBlockSource()
c.Assert(ok, jc.IsTrue)
c.Assert(source, gc.Equals, "cinder")
}
func (s *ConfigSuite) prepareForBootstrapParams(cfg *config.Config) environs.PrepareForBootstrapParams {
return environs.PrepareForBootstrapParams{
Config: cfg,
Credentials: cloud.NewCredential(cloud.UserPassAuthType, map[string]string{
"username": "user",
"password": "secret",
"tenant-name": "sometenant",
}),
CloudRegion: "region",
CloudEndpoint: "http://auth",
}
}
func (*ConfigSuite) TestSchema(c *gc.C) {
fields := providerInstance.Schema()
// Check that all the fields defined in environs/config
// are in the returned schema.
globalFields, err := config.Schema(nil)
c.Assert(err, gc.IsNil)
for name, field := range globalFields {
c.Check(fields[name], jc.DeepEquals, field)
}
}
| agpl-3.0 |
KWZwickau/KREDA-Sphere | Library/MOC-V/Component/Database/Vendor/Doctrine2ORM/2.5-Master/lib/Doctrine/ORM/LazyCriteriaCollection.php | 3561 | <?php
/*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the MIT license. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ORM;
use Doctrine\Common\Collections\AbstractLazyCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Selectable;
use Doctrine\ORM\Persisters\Entity\BasicEntityPersister;
use Doctrine\ORM\Persisters\Entity\EntityPersister;
/**
* A lazy collection that allow a fast count when using criteria object
* Once count gets executed once without collection being initialized, result
* is cached and returned on subsequent calls until collection gets loaded,
* then returning the number of loaded results.
*
* @since 2.5
* @author Guilherme Blanco <guilhermeblanco@hotmail.com>
* @author Michaël Gallego <mic.gallego@gmail.com>
*/
class LazyCriteriaCollection extends AbstractLazyCollection implements Selectable
{
/**
* @var BasicEntityPersister
*/
protected $entityPersister;
/**
* @var Criteria
*/
protected $criteria;
/**
* @var integer|null
*/
private $count;
/**
* @param EntityPersister $entityPersister
* @param Criteria $criteria
*/
public function __construct( EntityPersister $entityPersister, Criteria $criteria )
{
$this->entityPersister = $entityPersister;
$this->criteria = $criteria;
}
/**
* Do an efficient count on the collection
*
* @return integer
*/
public function count()
{
if ($this->isInitialized()) {
return $this->collection->count();
}
// Return cached result in case count query was already executed
if ($this->count !== null) {
return $this->count;
}
return $this->count = $this->entityPersister->count( $this->criteria );
}
/**
* Do an optimized search of an element
*
* @param object $element
*
* @return bool
*/
public function contains( $element )
{
if ($this->isInitialized()) {
return $this->collection->contains( $element );
}
return $this->entityPersister->exists( $element, $this->criteria );
}
/**
* {@inheritDoc}
*/
public function matching( Criteria $criteria )
{
$this->initialize();
return $this->collection->matching( $criteria );
}
/**
* {@inheritDoc}
*/
protected function doInitialize()
{
$elements = $this->entityPersister->loadCriteria( $this->criteria );
$this->collection = new ArrayCollection( $elements );
}
}
| agpl-3.0 |
dondonz/rorganize.it | spec/features/sign_in_spec.rb | 2450 | require 'spec_helper'
describe 'Signing in', :type => :feature do
subject { page }
before { visit new_person_session_path }
let(:person) { create(:person) }
context 'with the correct information' do
before do
sign_in person
end
it 'goes to the main page' do
expect(current_path).to eq(root_path)
end
it 'displays the correct alert message' do
expect(page).to have_content 'Signed in successfully'
end
end
context 'with the incorrect information' do
before do
fill_in 'Email', with: person.email
fill_in 'Password', with: 'wrongpassword'
click_button 'Sign in'
end
it 'does not sign in the person' do
expect(current_path).to eq(new_person_session_path)
end
it 'displays the correct alert message' do
expect(page).to have_content 'Invalid email or password'
end
end
context 'with github' do
before(:each) do
# https://github.com/intridea/omniauth/wiki/Integration-Testing#omniauthconfigadd_mock
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:github,
provider: "github",
uid: "1234567",
info: {
nickname: "Willow",
email: "willow.rosenberg@example.com",
name: "Willow Rosenberg",
image: ""
}
)
end
before do
visit root_path
click_link "Sign in with GitHub"
end
it 'successfully signs in the user via github' do
expect(page).to have_content("Successfully authenticated from GitHub account")
end
end
context 'merging an account with github' do
let!(:person) { create(:person, email: 'cordelia.chase@example.com', first_name: 'Cordelia', provider: nil) }
before(:each) do
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:github,
provider: "github",
uid: "7654321",
info: {
nickname: "Cordelia",
email: "cordelia.chase@example.com",
name: "Cordelia Chase",
image: ""
}
)
end
it 'successfully merges the users account with github' do
sign_in person
visit person_path(person)
find("#github-button").click
expect(page).to have_content("Successfully authenticated from GitHub account")
expect(page).to_not have_content("Link account with GitHub")
expect(page).to have_content("Account linked with GitHub")
end
end
end
| agpl-3.0 |
shihjay2/nosh-core | app/models/Vaccine_temp.php | 148 | <?php
class Vaccine_temp extends Eloquent
{
public $timestamps = false;
protected $table = 'vaccine_temp';
protected $primaryKey = 'temp_id';
}
| agpl-3.0 |
google-code-export/fullmetalgalaxy | src/com/fullmetalgalaxy/model/persist/gamelog/EbEvtRepair.java | 5063 | /* *********************************************************************
*
* This file is part of Full Metal Galaxy.
* http://www.fullmetalgalaxy.com
*
* Full Metal Galaxy 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.
*
* Full Metal Galaxy 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 Full Metal Galaxy.
* If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2010 to 2015 Vincent Legendre
*
* *********************************************************************/
package com.fullmetalgalaxy.model.persist.gamelog;
import com.fullmetalgalaxy.model.EnuColor;
import com.fullmetalgalaxy.model.Location;
import com.fullmetalgalaxy.model.RpcFmpException;
import com.fullmetalgalaxy.model.TokenType;
import com.fullmetalgalaxy.model.persist.AnBoardPosition;
import com.fullmetalgalaxy.model.persist.EbToken;
import com.fullmetalgalaxy.model.persist.Game;
/**
* @author Vincent Legendre
*
*/
public class EbEvtRepair extends AnEventPlay
{
static final long serialVersionUID = 1;
/**
*
*/
public EbEvtRepair()
{
super();
init();
}
@Override
public void reinit()
{
super.reinit();
this.init();
}
private void init()
{
setCost( 2 );
}
@Override
public GameLogType getType()
{
return GameLogType.EvtRepair;
}
@Override
public AnBoardPosition getSelectedPosition(Game p_game)
{
return getPosition();
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.persist.AnAction#check()
*/
@Override
public void check(Game p_game) throws RpcFmpException
{
super.check(p_game);
EbToken freighter = p_game.getToken( getPosition(), TokenType.Freighter );
EbToken turret = p_game.getToken( getPosition(), TokenType.Turret );
if( (freighter == null) || (turret != null) )
{
// no i18n as HMI won't allow this action
throw new RpcFmpException( "you can repair only destroyed turret" );
}
// check he don't repair center freighter
if( freighter.getPosition().equals( getPosition() ) )
{
// no i18n as HMI won't allow this action
throw new RpcFmpException( "you can repair only destroyed turret" );
}
if( freighter.getBulletCount() <= 0 )
{
// no i18n as HMI won't allow this action
throw new RpcFmpException( "you can't repair any more turrets" );
}
EnuColor fireCoverColor = p_game.getOpponentFireCover( getMyTeam( p_game ).getColors(p_game.getPreview()),
getPosition() );
if( fireCoverColor.getValue() != EnuColor.None )
{
throw new RpcFmpException( errMsg().cantRepairTurretFireCover() );
}
// check that no other turret construction occur on this hex since last
// control
int iback = 0;
AnEvent event = p_game.getLastLog( iback );
int maxIBack = p_game.getLogs().size() - 10;
while( event != null && iback < maxIBack )
{
if( event instanceof EbEvtControlFreighter
&& ((EbEvtControlFreighter)event).getTokenFreighter( p_game ).getId() == freighter
.getId() )
{
break;
}
if( event instanceof EbEvtRepair && ((EbEvtRepair)event).getPosition().equals( getPosition() ) )
{
throw new RpcFmpException( errMsg().cantRepairTurretTwice() );
}
iback++;
event = p_game.getLastLog( iback );
}
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.persist.AnAction#exec()
*/
@Override
public void exec(Game p_game) throws RpcFmpException
{
super.exec(p_game);
EbToken freighter = p_game.getToken( getPosition(), TokenType.Freighter );
EbToken turret = new EbToken();
turret.setType( TokenType.Turret );
turret.setColor( freighter.getColor() );
p_game.addToken( turret );
p_game.moveToken( turret, getPosition() );
turret.getPosition().setSector( p_game.getCoordinateSystem().getSector( freighter.getPosition(), getPosition() ) );
turret.incVersion();
freighter.setBulletCount( freighter.getBulletCount() - 1 );
execFireDisabling( p_game, getPosition() );
}
/* (non-Javadoc)
* @see com.fullmetalgalaxy.model.persist.AnAction#unexec()
*/
@Override
public void unexec(Game p_game) throws RpcFmpException
{
super.unexec(p_game);
EbToken freighter = p_game.getToken( getPosition(), TokenType.Freighter );
EbToken turret = p_game.getToken( getPosition(), TokenType.Turret );
turret.setLocation( Location.Graveyard );
turret.decVersion();
freighter.setBulletCount( freighter.getBulletCount() + 1 );
unexecFireDisabling( p_game );
}
}
| agpl-3.0 |
hiveship/enssat-serveur-voeux | application/views/errors/cli/error_php.php | 645 | <?php
defined( 'BASEPATH' ) or exit( 'No direct script access allowed' );
?>
A PHP Error was encountered
Severity: <?php echo $severity;?>
Message: <?php echo $message;?>
Filename: <?php echo $filepath;?>
Line Number: <?php echo $line;?>
<?php if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE === TRUE): ?>
Backtrace:
<?php foreach (debug_backtrace() as $error): ?>
<?php if (isset($error['file']) && strpos($error['file'], realpath(BASEPATH)) !== 0): ?>
File: <?php echo $error['file'];?>
Line: <?php echo $error['line'];?>
Function: <?php echo $error['function'];?>
<?php endif ?>
<?php endforeach ?>
<?php endif ?> | agpl-3.0 |
martinp23/elabchem | make_csv.php | 4090 | <?php
/********************************************************************************
* *
* Copyright 2012 Nicolas CARPi (nicolas.carpi@gmail.com) *
* http://www.elabftw.net/ *
* *
********************************************************************************/
/********************************************************************************
* This file is part of eLabFTW. *
* *
* eLabFTW 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. *
* *
* eLabFTW 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 eLabFTW. If not, see <http://www.gnu.org/licenses/>. *
* *
********************************************************************************/
/* make_csv.php -- export database in spreadsheet file */
require_once('inc/common.php');
require_once('inc/head.php');
$page_title='Make CSV';
require_once('inc/menu.php');
require_once('inc/info_box.php');
// this is the lines in the csv file
$list = array();
// Switch exp/items
if ($_GET['type'] === 'exp') {
$list[] = array('id', 'date', 'title', 'status', 'elabid');
$table = 'experiments';
} elseif ($_GET['type'] === 'items') {
$list[] = array('id', 'date', 'type', 'title', 'rating');
$table = 'items';
} else {
die('bad type');
}
// Check id is valid and assign it to $id
if(isset($_GET['id']) && !empty($_GET['id'])) {
$id_arr = explode(" ", $_GET['id']);
foreach($id_arr as $id) {
// MAIN LOOP
////////////////
// SQL
//$sql = "SELECT * FROM :table WHERE id = :id";
$sql = "SELECT * FROM $table WHERE id = $id";
$req = $bdd->prepare($sql);
$req->execute();
/*
$req->execute(array(
'table' => $table,
'id' => $id
));
*/
$csv_data = $req->fetch();
if ($table === 'experiments') {
$list[] = array($csv_data['id'], $csv_data['date'], $csv_data['title'], $csv_data['status'], $csv_data['elabid']);
} else { // items
$list[] = array($csv_data['id'], $csv_data['date'], $csv_data['type'], $csv_data['title'], $csv_data['rating']);
}
}
} else {
die('No id to export :/');
}
// make CSV file
$filename = hash("sha512", uniqid(rand(), true));
$filepath = 'uploads/'.$filename;
$fp = fopen($filepath, 'w+');
// utf8 headers
fwrite($fp,"\xEF\xBB\xBF");
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
// PAGE BEGIN
echo "<div class='item'>";
// Get zip size
$filesize = filesize($filepath);
echo "<p>Download CSV file <span class='filesize'>(".format_bytes($filesize).")</span> :<br />
<img src='themes/".$_SESSION['prefs']['theme']."/img/download.png' alt='' />
<a href='download.php?f=".$filepath."&name=elabftw-export.csv' target='_blank'>elabftw-export.csv</a></p>";
echo "</div>";
require_once('inc/footer.php');
| agpl-3.0 |
CiviCooP/no.maf.corrections | api/v3/SmsFinal/Load.php | 1875 | <?php
/**
* SmsFinal.Cancel API
* Find contacts for pswincom file
*
* @param array $params
* @return array API result descriptor
* @see civicrm_api3_create_success
* @see civicrm_api3_create_error
* @throws API_Exception
*/
function civicrm_api3_sms_final_load($params) {
set_time_limit(0);
$returnValues = array();
$dao = CRM_Core_DAO::executeQuery("SELECT * FROM sms_donations_30_nov");
while ($dao->fetch()) {
$phoneCount = CRM_Core_DAO::singleValueQuery("SELECT COUNT(*) FROM civicrm_phone WHERE phone = %1", array(
1 => array($dao->phone, 'String')));
switch ($phoneCount) {
case 0:
$sql = 'UPDATE sms_donations_30_nov SET more_phones = %1 WHERE message_id = %2';
$sqlParams = array(
1 => array(0, 'Integer'),
2 => array($dao->message_id, 'String'));
break;
case 1:
$contact = CRM_Core_DAO::executeQuery("SELECT p.contact_id, c.is_deleted
FROM civicrm_phone p JOIN civicrm_contact c ON p.contact_id = c.id
WHERE p.phone = %1", array(
1 => array($dao->phone, 'String')));
$contact->fetch();
$sql = 'UPDATE sms_donations_30_nov SET more_phones = %1, contact_id = %2, soft_deleted = %3 WHERE message_id = %4';
$sqlParams = array(
1 => array(0, 'Integer'),
2 => array($contact->contact_id, 'Integer'),
3 => array($contact->is_deleted, 'Integer'),
4 => array($dao->message_id, 'String'));
break;
default:
$sql = 'UPDATE sms_donations_30_nov SET more_phones = %1 WHERE message_id = %2';
$sqlParams = array(
1 => array(1, 'Integer'),
2 => array($dao->message_id, 'String'));
break;
}
CRM_Core_DAO::executeQuery($sql, $sqlParams);
}
return civicrm_api3_create_success($returnValues, $params, 'SmsFinal', 'Load');
}
| agpl-3.0 |
ihanli/puzzlesBackEnd | app/models/battle.rb | 1714 | class Battle < ActiveRecord::Base
acts_as_state_machine :initial => :pending
state :pending
state :opened#, :enter => :copy_decks
state :drawing
state :placing
state :attacking
state :finished, :enter => :clean_up
private
# TODO: test me
def clean_up
destroy
end
# TODO: test me
def copy_decks
fighters.each do |fighter|
puts fighter.inspect
puts fighter.deck.inspect
fighter.deck.cards.each do |card|
card_copy = CardInGame.create(card)
# card_copy.target_id = card_copy.id if card.talent.include?("self") or card.talent.include?("own")
card_copy.card_in_game = card_copy if card.talent.include?("self") or card.talent.include?("own")
end
end
end
public
event :start do
transitions :from => :pending, :to => :opened
end
event :draw do
transitions :from => :opened, :to => :drawing
transitions :from => :attacking, :to => :drawing
transitions :from => :placing, :to => :drawing
end
event :place do
transitions :from => :opened, :to => :placing
transitions :from => :drawing, :to => :placing
end
event :attack do
transitions :from => :drawing, :to => :attacking
transitions :from => :placing, :to => :attacking
end
event :finish do
transitions :from => :opened, :to => :finished
transitions :from => :drawing, :to => :finished
transitions :from => :placing, :to => :finished
transitions :from => :attacking, :to => :finished
end
has_many :fighters, :dependent => :delete_all
has_many :users, :through => :fighters
def self.get_battles_by_user(fb_id)
self.find(:all, :include => :users, :conditions => ['users.fb_id = ?', fb_id])
end
end
| agpl-3.0 |
livingcomputermuseum/ContrAlto | Contralto/UI/AlternateBootWindow.cs | 5844 | /*
This file is part of ContrAlto.
ContrAlto 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.
ContrAlto 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 ContrAlto. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Windows.Forms;
namespace Contralto
{
public partial class AlternateBootOptions : Form
{
public AlternateBootOptions()
{
InitializeComponent();
LoadBootEntries();
if (Configuration.AlternateBootType == AlternateBootType.Disk)
{
DiskBootRadioButton.Checked = true;
}
else
{
EthernetBootRadioButton.Checked = true;
}
SetBootAddress(Configuration.BootAddress);
SelectBootFile(Configuration.BootFile);
}
private void LoadBootEntries()
{
foreach(BootFileEntry e in _bootEntries)
{
BootFileComboBox.Items.Add(e);
}
}
private void SelectBootFile(ushort fileNumber)
{
// Find the matching entry, if any.
bool found = false;
for (int i = 0; i < BootFileComboBox.Items.Count; i++)
{
if (((BootFileEntry)BootFileComboBox.Items[i]).FileNumber == fileNumber)
{
BootFileComboBox.Select(i, 1);
BootFileComboBox.Text = BootFileComboBox.Items[i].ToString();
found = true;
break;
}
}
if (!found)
{
// No matching entry, just fill in the text box with the number.
BootFileComboBox.Text = Conversion.ToOctal(fileNumber);
}
}
private void SetBootAddress(ushort address)
{
DiskBootAddressTextBox.Text = Conversion.ToOctal(address);
}
private void BootFileComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
_selectedBootFile = ((BootFileEntry)BootFileComboBox.SelectedItem).FileNumber;
}
private void OKButton_Click(object sender, EventArgs e)
{
try
{
_selectedBootAddress = Convert.ToUInt16(DiskBootAddressTextBox.Text, 8);
}
catch
{
MessageBox.Show("The disk boot address must be an octal value between 0 and 177777.");
return;
}
if (BootFileComboBox.SelectedItem == null)
{
try
{
_selectedBootFile = Convert.ToUInt16(BootFileComboBox.Text, 8);
}
catch
{
MessageBox.Show("Please select a valid boot entry or type in a valid boot number.", "Invalid selection");
return;
}
}
else
{
_selectedBootFile = ((BootFileEntry)BootFileComboBox.SelectedItem).FileNumber;
}
Configuration.BootAddress = _selectedBootAddress;
Configuration.BootFile = _selectedBootFile;
if (DiskBootRadioButton.Checked)
{
Configuration.AlternateBootType = AlternateBootType.Disk;
}
else
{
Configuration.AlternateBootType = AlternateBootType.Ethernet;
}
this.Close();
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Close();
}
private BootFileEntry[] _bootEntries = new BootFileEntry[]
{
new BootFileEntry(0, "DMT"),
new BootFileEntry(1, "NewOS"),
new BootFileEntry(2, "FTP"),
new BootFileEntry(3, "Scavenger"),
new BootFileEntry(4, "CopyDisk"),
new BootFileEntry(5, "CRTTest"),
new BootFileEntry(6, "MADTest"),
new BootFileEntry(7, "Chat"),
new BootFileEntry(8, "NetExec"),
new BootFileEntry(9, "PupTest"),
new BootFileEntry(10, "EtherWatch"),
new BootFileEntry(11, "KeyTest"),
new BootFileEntry(13, "DiEx"),
new BootFileEntry(15, "EDP"),
new BootFileEntry(16, "BFSTest"),
new BootFileEntry(17, "GateControl"),
new BootFileEntry(18, "EtherLoad"),
};
private ushort _selectedBootFile;
private ushort _selectedBootAddress;
}
public struct BootFileEntry
{
public BootFileEntry(ushort number, string desc)
{
FileNumber = number;
Description = desc;
}
public override string ToString()
{
return String.Format("{0} - {1}", Conversion.ToOctal(FileNumber), Description);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public ushort FileNumber;
public string Description;
}
}
| agpl-3.0 |
subugoe/gdz-backend | app/workers/process_mets_file_set.rb | 423 | require 'helper/process_mets_file_set_helper'
class ProcessMetsFileSet
include Sidekiq::Worker
sidekiq_options queue: :metsfileset, backtrace: true, retry: false
def initialize
@logger = Logger.new(STDOUT)
@logger.level = Logger::DEBUG
end
def perform(ppn, work_id)
ProcessMetsFileSetHelper.new(ppn, work_id).createMetsFileSets
@logger.info("METS file set created for #{ppn}")
end
end | agpl-3.0 |
hacklabr/viradacultural-social-api | viradacultural_social_api/serializer.py | 851 | from rest_framework import serializers
from .models import FbUser, Event
class EventsListingField(serializers.RelatedField):
def to_representation(self, value):
return value.event_id
class FbUserSerializer(serializers.ModelSerializer):
position_timestamp = serializers.DateTimeField(format='%Y-%m-%d %H:%M', required=False)
events = EventsListingField(many=True, read_only=True)
lat = serializers.SerializerMethodField()
long = serializers.SerializerMethodField()
class Meta:
model = FbUser
@staticmethod
def get_lat(obj):
if obj.position:
return str(obj.position.y)
@staticmethod
def get_long(obj):
if obj.position:
return str(obj.position.x)
class EventSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Event
| agpl-3.0 |
GemBoutique/GBReact | app/controllers/api/customer_requests_controller.rb | 1104 | class Api::CustomerRequestsController < ApplicationController
def index
@messages = CustomerRequest.all
render "/api/customer_requests/index"
end
def create
@request = CustomerRequest.new
@request.attributes = customer_request_params.reject {|k, v| !@request.attributes.keys.member?(k.to_s)}
if verify_recaptcha(response: customer_request_params["recaptcha_response"]) && @request.save
ContactMailer.send_copy(@request).deliver_now
render "/api/customer_requests/show"
else
@errors = @request.errors.full_messages
render "/api/shared/error", status: 422
end
end
def update
@request = CustomerRequest.find(params[:id])
@request.update_attributes(customer_request_params)
render "/api/customer_requests/show"
end
def show
@request = CustomerRequest.find(params[:id])
if @request
render "/api/customer_requests/show"
else
render json: nil, status: 404
end
end
private
def customer_request_params
params.require(:request).permit(:subject, :body, :f_name, :l_name, :request_type, :email, :phone, :status, :notes, :recaptcha_response)
end
end
| agpl-3.0 |
Som-Energia/plantmeter | som_plantmeter/__init__.py | 23 | import som_plantmeter
| agpl-3.0 |
ChristophWurst/weinstein_server | app/Validation/Validator.php | 3499 | <?php
/**
* @author Christoph Wurst <christoph@winzerhof-wurst.at>
*
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License,version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
namespace App\Validation;
use App\Exceptions\ValidationException;
use App\Exceptions\ValidationModelMissingException;
use Illuminate\Database\Eloquent\Model;
use InvalidArgumentException;
class Validator
{
/**
* Models class name.
*
* @var string
* @psalm-var class-string
*/
protected $modelClass = null;
/**
* Input form data.
*
* @var array
*/
protected $data = [];
/**
* Model needed for creating some update rules.
*
* @var Model
*/
protected $model = null;
/**
* Get attribute names as array.
*
* @return array
*/
protected function getAttributeNames()
{
return [];
}
/**
* Get validation error messages.
*
* @return array
*/
protected function getErrorMessages()
{
return [];
}
/**
* Get rules for creating a new model.
*
* @param array $data
* @return array
*/
protected function getCreateRules(array $data)
{
return [];
}
/**
* Get rules for updating an existing model.
*
* @param array $data
* @param Model $model
* @return array
*/
protected function getUpdateRules(array $data, Model $model = null)
{
return [];
}
/**
* Prepare input data for validation.
*
* @param array $data
* @return array
*/
protected function prepareData(array $data)
{
return $data;
}
/**
* Constructor.
*
* @param array $data
* @param Model $model
*/
public function __construct(array $data, Model $model = null)
{
$this->data = $data;
if ($model && ! $model instanceof $this->modelClass) {
throw new InvalidArgumentException;
}
$this->model = $model;
}
/**
* Validate creation of a new model.
*
* @throws ValidationException
*/
public function validateCreate()
{
$validator = \Validator::make($this->data, $this->getCreateRules($this->data), $this->getErrorMessages(), $this->getAttributeNames());
if ($validator->fails()) {
throw new ValidationException($validator->messages());
}
}
/**
* Validate update of an existing model.
*
* @throws ValidationException
*/
public function validateUpdate()
{
if (! $this->model) {
throw new ValidationModelMissingException;
}
$validator = \Validator::make($this->data, $this->getUpdateRules($this->data, $this->model), $this->getErrorMessages(), $this->getAttributeNames());
if ($validator->fails()) {
throw new ValidationException($validator->messages());
}
}
}
| agpl-3.0 |
Tanaguru/Tanaguru | rules/accessiweb2.2/src/main/java/org/tanaguru/rules/accessiweb22/Aw22Rule12101.java | 1509 | /*
* Tanaguru - Automated webpage assessment
* Copyright (C) 2008-2015 Tanaguru.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: tanaguru AT tanaguru DOT org
*/
package org.tanaguru.rules.accessiweb22;
import org.tanaguru.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 12.10.1 of the referential Accessiweb 2.2.
* <br>
* For more details about the implementation, refer to <a href="http://www.tanaguru.org/en/content/aw22-rule-12-10-1">the rule 12.10.1 design page.</a>
* @see <a href="http://www.accessiweb.org/index.php/accessiweb-22-english-version.html#test-12-10-1"> 12.10.1 rule specification</a>
*
* @author jkowalczyk
*/
public class Aw22Rule12101 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Aw22Rule12101 () {
super();
}
} | agpl-3.0 |
ubtue/ub_tools | cpp/marc_tools/marc_head.cc | 1991 | /** \brief Utility for extracting the first N records from a collection of MARC records.
* have some metadata for these items.
* \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
*
* \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdexcept>
#include <cstdio>
#include <cstdlib>
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
void ProcessRecords(const unsigned N, MARC::Reader * const marc_reader, MARC::Writer * const marc_writer) {
unsigned record_count(0);
while (const MARC::Record record = marc_reader->read()) {
if (record_count == N)
break;
++record_count;
marc_writer->write(record);
}
LOG_INFO("Copied " + std::to_string(record_count) + " record(s).");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc != 4)
::Usage("count marc_input marc_output");
unsigned count;
if (not StringUtil::ToUnsigned(argv[1], &count) or count == 0)
LOG_ERROR("count must be a postive integer!");
const auto marc_reader(MARC::Reader::Factory(argv[2]));
const auto marc_writer(MARC::Writer::Factory(argv[3]));
ProcessRecords(count, marc_reader.get(), marc_writer.get());
return EXIT_SUCCESS;
}
| agpl-3.0 |
sgmap/tps | app/models/champs/engagement_champ.rb | 492 | # == Schema Information
#
# Table name: champs
#
# id :integer not null, primary key
# private :boolean default(FALSE), not null
# row :integer
# type :string
# value :string
# created_at :datetime
# updated_at :datetime
# dossier_id :integer
# etablissement_id :integer
# parent_id :bigint
# type_de_champ_id :integer
#
class Champs::EngagementChamp < Champs::CheckboxChamp
end
| agpl-3.0 |
HongPong/intersango | orderbook.php | 2185 | <?php
require 'util.php';
function display_double_entry($curr_a, $curr_b, $base_curr)
{
echo "<div class='content_box'>\n";
echo "<h3>People offering $curr_a for $curr_b</h3>\n";
$exchange_fields = calc_exchange_rate($curr_a, $curr_b, $base_curr);
if (!$exchange_fields) {
echo "<p>Nobody is selling $curr_a for $curr_b.</p>";
echo "</div>";
return;
}
list($total_amount, $total_want_amount, $rate) = $exchange_fields;
echo "<p>Best exchange rate is ";
if ($base_curr == BASE_CURRENCY::A)
echo "1 $curr_a is worth <b>$rate $curr_b</b>";
else
echo "1 $curr_b is worth <b>$rate $curr_a</b>";
echo ".</p>";
echo "<p>$total_amount $curr_a being sold for $total_want_amount $curr_b.</p>";
?><table class='display_data'>
<tr>
<th>Cost / BTC</th>
<th>Giving</th>
<th>Wanted</th>
</tr><?php
$query = "
SELECT
*,
IF(
type='BTC',
initial_want_amount/initial_amount,
initial_amount/initial_want_amount
) AS rate
FROM orderbook
WHERE type='$curr_a' AND want_type='$curr_b' AND status='OPEN'
ORDER BY
IF(type='BTC', rate, -rate) ASC
";
$result = do_query($query);
while ($row = mysql_fetch_array($result)) {
$amount = internal_to_numstr($row['amount']);
$want_amount = internal_to_numstr($row['want_amount']);
# MySQL kindly computes this for us.
# we trim the excessive 0
$rate = clean_sql_numstr($row['rate']);
echo " <tr>\n";
echo " <td>$rate</td>\n";
echo " <td>$amount $curr_a</td>\n";
echo " <td>$want_amount $curr_b</td>\n";
echo " </tr>\n";
}
echo " <tr>\n";
echo " <td>Total:</td>\n";
echo " <td>$total_amount $curr_a</td>\n";
echo " <td>$total_want_amount $curr_b</td>\n";
echo " </tr>\n";
echo "</table></div>";
}
display_double_entry('BTC', 'GBP', BASE_CURRENCY::A);
display_double_entry('GBP', 'BTC', BASE_CURRENCY::B);
?>
| agpl-3.0 |
dlkw/ceylon-graphql | source/de/dlkw/graphql/antlr4java/generated/GraphQLBaseListener.java | 13612 | // Generated from de.dlkw.graphql.antlr4java.generated/GraphQL.g4 by ANTLR 4.6
package de.dlkw.graphql.antlr4java.generated;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ErrorNode;
import org.antlr.v4.runtime.tree.TerminalNode;
/**
* This class provides an empty implementation of {@link GraphQLListener},
* which can be extended to create a listener which only needs to handle a subset
* of the available methods.
*/
public class GraphQLBaseListener implements GraphQLListener {
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDocument(GraphQLParser.DocumentContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDocument(GraphQLParser.DocumentContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDefinition(GraphQLParser.DefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDefinition(GraphQLParser.DefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperationDefinition(GraphQLParser.OperationDefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperationDefinition(GraphQLParser.OperationDefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSelectionSet(GraphQLParser.SelectionSetContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSelectionSet(GraphQLParser.SelectionSetContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterOperationType(GraphQLParser.OperationTypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitOperationType(GraphQLParser.OperationTypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterSelection(GraphQLParser.SelectionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitSelection(GraphQLParser.SelectionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterField(GraphQLParser.FieldContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitField(GraphQLParser.FieldContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFieldName(GraphQLParser.FieldNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFieldName(GraphQLParser.FieldNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterAlias(GraphQLParser.AliasContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitAlias(GraphQLParser.AliasContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterArguments(GraphQLParser.ArgumentsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitArguments(GraphQLParser.ArgumentsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterArgument(GraphQLParser.ArgumentContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitArgument(GraphQLParser.ArgumentContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFragmentSpread(GraphQLParser.FragmentSpreadContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFragmentSpread(GraphQLParser.FragmentSpreadContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterInlineFragment(GraphQLParser.InlineFragmentContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitInlineFragment(GraphQLParser.InlineFragmentContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFragmentDefinition(GraphQLParser.FragmentDefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFragmentDefinition(GraphQLParser.FragmentDefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterFragmentName(GraphQLParser.FragmentNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitFragmentName(GraphQLParser.FragmentNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDirectives(GraphQLParser.DirectivesContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDirectives(GraphQLParser.DirectivesContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDirective(GraphQLParser.DirectiveContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDirective(GraphQLParser.DirectiveContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTypeCondition(GraphQLParser.TypeConditionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTypeCondition(GraphQLParser.TypeConditionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVariableDefinitions(GraphQLParser.VariableDefinitionsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVariableDefinitions(GraphQLParser.VariableDefinitionsContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVariableDefinition(GraphQLParser.VariableDefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVariableDefinition(GraphQLParser.VariableDefinitionContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterVariable(GraphQLParser.VariableContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitVariable(GraphQLParser.VariableContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterDefaultValue(GraphQLParser.DefaultValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitDefaultValue(GraphQLParser.DefaultValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterValueOrVariable(GraphQLParser.ValueOrVariableContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitValueOrVariable(GraphQLParser.ValueOrVariableContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNullValue(GraphQLParser.NullValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNullValue(GraphQLParser.NullValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterBooleanValue(GraphQLParser.BooleanValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitBooleanValue(GraphQLParser.BooleanValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterStringValue(GraphQLParser.StringValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitStringValue(GraphQLParser.StringValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNumberValue(GraphQLParser.NumberValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNumberValue(GraphQLParser.NumberValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEnumValue(GraphQLParser.EnumValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEnumValue(GraphQLParser.EnumValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterArrayValue(GraphQLParser.ArrayValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitArrayValue(GraphQLParser.ArrayValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterObjectValue(GraphQLParser.ObjectValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitObjectValue(GraphQLParser.ObjectValueContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterType(GraphQLParser.TypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitType(GraphQLParser.TypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterTypeName(GraphQLParser.TypeNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitTypeName(GraphQLParser.TypeNameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterListType(GraphQLParser.ListTypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitListType(GraphQLParser.ListTypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterNonNullType(GraphQLParser.NonNullTypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitNonNullType(GraphQLParser.NonNullTypeContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterArray(GraphQLParser.ArrayContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitArray(GraphQLParser.ArrayContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterObject(GraphQLParser.ObjectContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitObject(GraphQLParser.ObjectContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterName(GraphQLParser.NameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitName(GraphQLParser.NameContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEnumConstant(GraphQLParser.EnumConstantContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEnumConstant(GraphQLParser.EnumConstantContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void enterEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void exitEveryRule(ParserRuleContext ctx) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitTerminal(TerminalNode node) { }
/**
* {@inheritDoc}
*
* <p>The default implementation does nothing.</p>
*/
@Override public void visitErrorNode(ErrorNode node) { }
} | agpl-3.0 |
mathijshenquet/dnsleergemeenschap | cache/frontend/prod/config/config_factories.yml.php | 5472 | <?php
// auto-generated by sfFactoryConfigHandler
// date: 2010/04/09 11:48:25
$class = sfConfig::get('sf_factory_logger', 'sfNoLogger');
$this->factories['logger'] = new $class($this->dispatcher, array_merge(array('auto_shutdown' => false), sfConfig::get('sf_factory_logger_parameters', array (
'level' => 'err',
'loggers' => NULL,
))));
if (sfConfig::get('sf_i18n'))
{
$class = sfConfig::get('sf_factory_i18n', 'sfI18N');
$cache = new sfFileCache(array (
'automatic_cleaning_factor' => 0,
'cache_dir' => 'E:\\Webserver\\leergemeenschap\\cache\\frontend\\prod\\i18n',
'lifetime' => 31556926,
'prefix' => 'E:\\Webserver\\leergemeenschap\\apps\\frontend/i18n',
));
$this->factories['i18n'] = new $class($this->configuration, $cache, array (
'source' => 'XLIFF',
'debug' => false,
'untranslated_prefix' => '[T]',
'untranslated_suffix' => '[/T]',
));
sfWidgetFormSchemaFormatter::setTranslationCallable(array($this->factories['i18n'], '__'));
}
$class = sfConfig::get('sf_factory_controller', 'sfFrontWebController');
$this->factories['controller'] = new $class($this);
$class = sfConfig::get('sf_factory_request', 'sfWebRequest');
$this->factories['request'] = new $class($this->dispatcher, array(), array(), sfConfig::get('sf_factory_request_parameters', array (
'logging' => '',
'path_info_array' => 'SERVER',
'path_info_key' => 'PATH_INFO',
'relative_url_root' => NULL,
'formats' =>
array (
'txt' => 'text/plain',
'js' =>
array (
0 => 'application/javascript',
1 => 'application/x-javascript',
2 => 'text/javascript',
),
'css' => 'text/css',
'json' =>
array (
0 => 'application/json',
1 => 'application/x-json',
),
'xml' =>
array (
0 => 'text/xml',
1 => 'application/xml',
2 => 'application/x-xml',
),
'rdf' => 'application/rdf+xml',
'atom' => 'application/atom+xml',
),
'no_script_name' => true,
)), sfConfig::get('sf_factory_request_attributes', array()));
$class = sfConfig::get('sf_factory_response', 'sfWebResponse');
$this->factories['response'] = new $class($this->dispatcher, sfConfig::get('sf_factory_response_parameters', array_merge(array('http_protocol' => isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : null), array (
'logging' => '',
'charset' => 'utf-8',
'send_http_headers' => true,
))));
if ($this->factories['request'] instanceof sfWebRequest
&& $this->factories['response'] instanceof sfWebResponse
&& 'HEAD' == $this->factories['request']->getMethod())
{
$this->factories['response']->setHeaderOnly(true);
}
$class = sfConfig::get('sf_factory_routing', 'swPatternRouting');
$cache = null;
$this->factories['routing'] = new $class($this->dispatcher, $cache, array_merge(array('auto_shutdown' => false, 'context' => $this->factories['request']->getRequestContext()), sfConfig::get('sf_factory_routing_parameters', array (
'load_configuration' => true,
'suffix' => '',
'default_module' => 'default',
'default_action' => 'index',
'debug' => '',
'logging' => '',
'generate_shortest_url' => true,
'extra_parameters_as_query_string' => true,
'cache' => NULL,
))));
if ($parameters = $this->factories['routing']->parse($this->factories['request']->getPathInfo()))
{
$this->factories['request']->addRequestParameters($parameters);
}
$class = sfConfig::get('sf_factory_storage', 'sfSessionStorage');
$this->factories['storage'] = new $class(array_merge(array(
'auto_shutdown' => false, 'session_id' => $this->getRequest()->getParameter('leerlingensite'),
), sfConfig::get('sf_factory_storage_parameters', array (
'session_name' => 'leerlingensite',
'session_cookie_domain' => 'dnsleerroutes.net',
))));
$class = sfConfig::get('sf_factory_user', 'myUser');
$this->factories['user'] = new $class($this->dispatcher, $this->factories['storage'], array_merge(array('auto_shutdown' => false, 'culture' => $this->factories['request']->getParameter('sf_culture')), sfConfig::get('sf_factory_user_parameters', array (
'timeout' => 1800,
'logging' => '',
'use_flash' => true,
'default_culture' => 'nl',
))));
if (sfConfig::get('sf_cache'))
{
$class = sfConfig::get('sf_factory_view_cache', 'sfFileCache');
$cache = new $class(sfConfig::get('sf_factory_view_cache_parameters', array (
'automatic_cleaning_factor' => 0,
'cache_dir' => 'E:\\Webserver\\leergemeenschap\\cache\\frontend\\prod\\template',
'lifetime' => 86400,
'prefix' => 'E:\\Webserver\\leergemeenschap\\apps\\frontend/template',
)));
$this->factories['viewCacheManager'] = new sfViewCacheManager($this, $cache, array (
'cache_key_use_vary_headers' => true,
'cache_key_use_host_name' => true,
));
}
else
{
$this->factories['viewCacheManager'] = null;
}
require_once sfConfig::get('sf_symfony_lib_dir').'/vendor/swiftmailer/classes/Swift.php';
Swift::registerAutoload();
sfMailer::initialize();
$this->setMailerConfiguration(array_merge(array('class' => sfConfig::get('sf_factory_mailer', 'sfMailer')), sfConfig::get('sf_factory_mailer_parameters', array (
'logging' => '',
'charset' => 'utf-8',
'delivery_strategy' => 'realtime',
'transport' =>
array (
'class' => 'Swift_SmtpTransport',
'param' =>
array (
'host' => 'localhost',
'port' => 25,
'encryption' => NULL,
'username' => NULL,
'password' => NULL,
),
),
))));
| agpl-3.0 |
aakhmerov/battlehack_2015 | backend/melder_dal/src/main/java/com/battlehack/melder/api/domain/entities/MelderUser.java | 331 | package com.battlehack.melder.api.domain.entities;
import org.springframework.data.jpa.domain.AbstractPersistable;
import javax.persistence.Entity;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Created by aakhmerov on 21.06.15.
*/
@Entity
@XmlRootElement
public class MelderUser extends AbstractPersistable<Long> {
}
| agpl-3.0 |
malikov/platform-android | ushahidi/src/main/java/com/ushahidi/android/data/repository/datasource/post/PostApiDataSource.java | 6079 | /*
* Copyright (c) 2015 Ushahidi Inc
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program in the file LICENSE-AGPL. If not, see
* https://www.gnu.org/licenses/agpl-3.0.html
*/
package com.ushahidi.android.data.repository.datasource.post;
import com.google.gson.JsonElement;
import com.ushahidi.android.data.api.PostApi;
import com.ushahidi.android.data.api.model.FormAttributes;
import com.ushahidi.android.data.api.model.Forms;
import com.ushahidi.android.data.api.model.Posts;
import com.ushahidi.android.data.api.model.Tags;
import com.ushahidi.android.data.database.PostDatabaseHelper;
import com.ushahidi.android.data.entity.FormAttributeEntity;
import com.ushahidi.android.data.entity.FormEntity;
import com.ushahidi.android.data.entity.GeoJsonEntity;
import com.ushahidi.android.data.entity.PostEntity;
import com.ushahidi.android.data.entity.TagEntity;
import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
import rx.Observable;
/**
* Data source for manipulating {@link com.ushahidi.android.data.entity.PostEntity} data to and
* from the API.
*
* @author Ushahidi Team <team@ushahidi.com>
*/
public class PostApiDataSource implements PostDataSource {
private PostApi mPostApi;
private PostDatabaseHelper mPostDatabaseHelper;
/**
* Default constructor
*
* @param postApi The post api
* @param postDatabaseHelper The post database helper
*/
public PostApiDataSource(@NonNull PostApi postApi,
@NonNull PostDatabaseHelper postDatabaseHelper) {
mPostApi = postApi;
mPostDatabaseHelper = postDatabaseHelper;
}
@Override
public Observable<Long> putPostEntities(List<PostEntity> postEntity) {
// Do nothing. Not posting via the API ATM
return null;
}
@Override
public Observable<Long> putPostEntity(PostEntity postEntity) {
// TODO: Implement post entity upload via the API
return null;
}
@Override
public Observable<List<PostEntity>> getPostEntityList(Long deploymentId) {
return Observable.zip(mPostApi.getTags(), mPostApi.getPostList(), mPostApi.getGeoJson(),
mPostApi.getForms(),
(tags, posts, geoJsons, forms) -> mPostDatabaseHelper.putFetchedPosts(deploymentId,
setTag(tags, deploymentId),
setPost(posts, deploymentId),
setGeoJson(geoJsons, deploymentId),
setForms(forms, deploymentId)));
}
@Override
public Observable<PostEntity> getPostEntityById(Long deploymentId, Long postEntityId) {
// Do nothing. Not getting post by Id via the API ATM
throw new UnsupportedOperationException();
}
@Override
public Observable<Boolean> deletePostEntity(PostEntity postEntity) {
// Do nothing. Not deleting via the API ATM
throw new UnsupportedOperationException();
}
@Override
public Observable<List<PostEntity>> search(Long deploymentId, String query) {
// Do nothing. Not searching via the API ATM
throw new UnsupportedOperationException();
}
/**
* Set the deployment ID for the TagModel since it's not set by the
* API
*
* @param posts The TagModel to set the deployment Id on
* @param deploymentId The ID of the deployment to set
* @return observable
*/
private List<PostEntity> setPost(Posts posts, Long deploymentId) {
List<PostEntity> postEntityList = new ArrayList<>(posts.getPosts().size());
for (PostEntity postEntity : posts.getPosts()) {
postEntity.setDeploymentId(deploymentId);
postEntityList.add(postEntity);
}
return postEntityList;
}
/**
* Set the deployment ID for the TagModel since it's not set by the
* API
*
* @param tags The TagModel to set the deployment Id on
* @param deploymentId The ID of the deployment to set
* @return observable
*/
private List<TagEntity> setTag(Tags tags,
Long deploymentId) {
List<TagEntity> tagEntityList = new ArrayList<>(tags.getTags().size());
for (TagEntity tagEntity : tags.getTags()) {
tagEntity.setDeploymentId(deploymentId);
tagEntityList.add(tagEntity);
}
return tagEntityList;
}
private GeoJsonEntity setGeoJson(JsonElement jsonElement, Long deploymentId) {
GeoJsonEntity geoJsonEntity = new GeoJsonEntity();
geoJsonEntity.setGeoJson(jsonElement.toString());
geoJsonEntity.setDeploymentId(deploymentId);
return geoJsonEntity;
}
private List<FormEntity> setForms(Forms forms, Long deploymentId) {
List<FormEntity> formEntityList = new ArrayList<>();
for (FormEntity formEntity : forms.getForms()) {
formEntity.setDeploymentId(deploymentId);
formEntityList.add(formEntity);
}
return formEntityList;
}
private List<FormAttributeEntity> setFormAttributes(FormAttributes formAttributes,
Long deploymentId) {
List<FormAttributeEntity> formAttributeEntities = new ArrayList<>();
for (FormAttributeEntity formAttributeEntity : formAttributes.getFormAttributes()) {
formAttributeEntity.setDeploymentId(deploymentId);
formAttributeEntities.add(formAttributeEntity);
}
return formAttributeEntities;
}
}
| agpl-3.0 |
schiessle/locationtracker | appinfo/routes.php | 1051 | <?php
/**
* @copyright Copyright (c) 2016 Bjoern Schiessle <bjoern@schiessle.org>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
$application = new \OCP\AppFramework\App('locationtracker');
$application->registerRoutes(
$this,
[
'routes' => [
[
'name' => 'LocationTracker#store',
'url' => '/api/v1/location',
'verb' => 'POST',
],
],
]
);
| agpl-3.0 |
vhost-api/vhost-api | init.rb | 2929 | # frozen_string_literal: true
require 'yaml'
lp = File.expand_path(__dir__)
@environment = ENV['RACK_ENV'] || 'development'
# rubocop:disable Security/YAMLLoad
@dbconfig = YAML.load(File.read("#{lp}/config/database.yml"))[@environment]
# rubocop:enable Security/YAMLLoad
require 'bundler/setup'
require 'fileutils'
require 'tempfile'
require 'data_mapper'
require 'dm-migrations'
require 'dm-constraints'
require 'dm-timestamps'
require 'dm-serializer'
require 'securerandom'
case @dbconfig[:db_adapter].upcase
when 'POSTGRES'
require 'dm-postgres-adapter'
@dbconfig[:db_port] = 5432 if @dbconfig[:db_port].nil?
when 'MYSQL'
require 'dm-mysql-adapter'
@dbconfig[:db_port] = 3306 if @dbconfig[:db_port].nil?
end
require 'bcrypt'
require 'sshkey'
# monkey patch to fix deprecation warning
# rubocop:disable Style/Documentation, Style/RaiseArgs, Metrics/LineLength
# rubocop:disable Style/CaseEquality
module DataObjects
module Pooling
class Pool
attr_reader :available
attr_reader :used
def initialize(max_size, resource, args)
raise ArgumentError.new("+max_size+ should be an Integer but was #{max_size.inspect}") unless Integer === max_size
raise ArgumentError.new("+resource+ should be a Class but was #{resource.inspect}") unless Class === resource
@max_size = max_size
@resource = resource
@args = args
@available = []
@used = {}
DataObjects::Pooling.append_pool(self)
end
end
end
end
# rubocop:enable Style/Documentation, Style/RaiseArgs, Metrics/LineLength
# rubocop:enable Style/CaseEquality
# load models and stuff
require_relative 'app/models/group'
require_relative 'app/models/user'
require_relative 'app/models/package'
require_relative 'app/models/apikey'
require_relative 'app/models/domain'
require_relative 'app/models/dkim'
require_relative 'app/models/dkimsigning'
require_relative 'app/models/mailforwarding'
require_relative 'app/models/mailaccount'
require_relative 'app/models/mailsource'
require_relative 'app/models/mailalias'
require_relative 'app/models/ipv4address'
require_relative 'app/models/ipv6address'
require_relative 'app/models/phpruntime'
require_relative 'app/models/vhost'
require_relative 'app/models/shell'
require_relative 'app/models/sftpuser'
require_relative 'app/models/shelluser'
require_relative 'app/models/sshpubkey'
require_relative 'app/models/databaseuser'
require_relative 'app/models/database'
require_relative 'app/helpers/classes/authentication_error'
require_relative 'app/helpers/classes/apiresponse'
require_relative 'app/helpers/classes/apiresponse_error'
require_relative 'app/helpers/classes/apiresponse_success'
Dir.glob("#{lp}/app/policies/*.rb").each { |file| require file }
require "#{lp}/app/helpers/generic_helper.rb"
# finalize db layout when all models have been loaded
DataMapper.finalize
# create logdir
FileUtils.mkdir_p('log')
| agpl-3.0 |
Bram28/LEGUP | code/edu/rpi/phil/legup/puzzles/lightup/CaseSatisfyNumber.java | 17798 | package edu.rpi.phil.legup.puzzles.lightup;
import java.awt.Point;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.swing.ImageIcon;
import edu.rpi.phil.legup.Contradiction;
import edu.rpi.phil.legup.BoardState;
import edu.rpi.phil.legup.CaseRule;
import edu.rpi.phil.legup.CellPredicate;
import edu.rpi.phil.legup.Legup;
import edu.rpi.phil.legup.Permutations;
import edu.rpi.phil.legup.PuzzleModule;
import edu.rpi.phil.legup.newgui.CaseRuleSelectionHelper;
import edu.rpi.phil.legup.newgui.LEGUP_Gui;
import edu.rpi.phil.legup.puzzles.treetent.CaseLinkTree;
public class CaseSatisfyNumber extends CaseRule
{
static final long serialVersionUID = 5238481899970588295L;
public String getImageName()
{
return "images/lightup/cases/SatisfyNumber.png";
}
// CaseRuleSelectionHelper Methods to highlight cells with a number in them
public CaseRuleSelectionHelper getSelectionHelper()
{
return new CaseRuleSelectionHelper(CellPredicate.typeWhitelist(getTileTypes()));
}
private Set<Integer> tileTypes = null;
public Set<Integer> getTileTypes()
{
if(tileTypes == null)
{
tileTypes = new LinkedHashSet<Integer>();
tileTypes.add(LightUp.CELL_BLOCK0);
tileTypes.add(LightUp.CELL_BLOCK1);
tileTypes.add(LightUp.CELL_BLOCK2);
tileTypes.add(LightUp.CELL_BLOCK3);
tileTypes.add(LightUp.CELL_BLOCK4);
}
return tileTypes;
}
// AutoGenerateCases Method will generate every possible case that does not directly lead to a contradiction
public BoardState autoGenerateCases(BoardState cur, Point pointSelected)
{
PuzzleModule pm = Legup.getInstance().getPuzzleModule();
int num_blanks = CaseLinkTree.calcAdjacentTiles(cur,pointSelected,LightUp.CELL_UNKNOWN);
int num_lights = CaseLinkTree.calcAdjacentTiles(cur,pointSelected,LightUp.CELL_LIGHT);
int num_lights_needed = CaseSatisfyNumber.getBlockValue(cur.getCellContents(pointSelected.x,pointSelected.y))-num_lights;
int num_empties = num_blanks - num_lights_needed;
int[] whatgoesintheblanks = new int[num_blanks];
for(int c1=0;c1<num_blanks;c1++)
{
whatgoesintheblanks[c1] = 0;
}
// Used to remove any cases which have a bulb in light
Contradiction contra = new ContradictionBulbsInPath();
while(Permutations.nextPermutation(whatgoesintheblanks,num_empties))
{
BoardState tmp = cur.copy();
int counter = 0;
Map<Point, Integer> pointsChanged = new HashMap<Point, Integer>();
for(int c3=0;c3<4;c3++)
{
int x = pointSelected.x + ((c3<2) ? ((c3%2 == 0)?-1:1) : 0);
int y = pointSelected.y + ((c3<2) ? 0 : ((c3%2 == 0)?-1:1));
if(x < 0 || x >= cur.getWidth() || y < 0 || y >= cur.getHeight())continue;
if(cur.getCellContents(x,y) != LightUp.CELL_UNKNOWN)continue;
int contents = pm.getStateNumber(pm.getStateName(whatgoesintheblanks[counter]));
tmp.setCellContents(x, y, contents);
pointsChanged.put(new Point(x, y), contents);
++counter;
}
if (contra.checkContradictionRaw(tmp) == null) continue; // Do not add case if light is in already lit area
tmp = cur.addTransitionFrom();
tmp.setCaseSplitJustification(this);
for (Map.Entry<Point, Integer> m : pointsChanged.entrySet()) {
tmp.setCellContents(m.getKey().x, m.getKey().y, m.getValue());
}
tmp.endTransition();
}
return Legup.getCurrentState();
}
public CaseSatisfyNumber()
{
setName("Satisfy Number");
description = "The different ways a blocks number can be satisfied.";
}
public String checkCaseRuleRaw(BoardState state)
{
/* Uncomment to make a case rule application with a single case an error */
// BoardState parent = state.getSingleParentState();
// if (parent != null && parent.getChildren().size() < 2){
// return "This case rule can only be applied on a split transition";
// }
return null;
}
//returns the tiles that are adjacent to all changed tiles between parent and state
//if types is null, all tiles are returned, if not, only tiles whitelisted in types are counted
static Vector<Point> findCommonTile(BoardState parent,BoardState state,Set<Integer> types)
{
ArrayList<Point> dif = BoardState.getDifferenceLocations(parent,state);
Vector<Point> ret = new Vector<Point>();
Vector<Integer> adjacents = new Vector<Integer>();
if(dif.size() >= 1)
{
for(int x=0;x<parent.getHeight();x++)
{
for(int y=0;y<parent.getWidth();y++)
{
boolean is_common_point = false;
int num_adjacents = 0;
int tmp_x;// = x;
int tmp_y;// = y;
Point tmp_p = null;
for(int dir=0;dir<4;dir++)
{
tmp_x = (dir<2)? ((dir%2==0)?(x-1):(x+1)) :x; //these two lines enumerate all orthagonal
tmp_y = (dir<2)?y: ((dir%2==0)?(y-1):(y+1)) ; //directions 1 unit from (x,y)
if(tmp_x < 0 || tmp_x >= parent.getWidth())continue;
if(tmp_y < 0 || tmp_y >= parent.getHeight())continue;
if(parent.getCellContents(tmp_x,tmp_y) != PuzzleModule.CELL_UNKNOWN)continue;
tmp_p = new Point(tmp_x,tmp_y);
//System.out.println("At ("+tmp_x+","+tmp_y+") from ("+x+","+y+"), dir == "+dir);
if(dif.contains(tmp_p))
{
is_common_point = true;
num_adjacents++;
}
}
if(is_common_point)
{
tmp_p = new Point(x,y);
if(!ret.contains(tmp_p))
{
if(types == null || types.contains(parent.getCellContents(x,y)))
{
ret.add(tmp_p);
adjacents.add(num_adjacents);
//System.out.println(tmp_p+" has "+num_adjacents+" adjacents.");
}
}
}
}
}
}
int max_adjs = 0;
//assumes ret and adjacent are the same size
//removes any element with less adjacent difs than the maximum
for(int c1=0;c1<ret.size();c1++)
{
if(adjacents.get(c1) > max_adjs)max_adjs = adjacents.get(c1);
}
for(int c1=0;c1<ret.size();c1++)
{
if(adjacents.get(c1) < max_adjs)
{
ret.remove(c1);
adjacents.remove(c1);
c1--;
}
}
return ret;
}
static Point findCommonBlock(BoardState parent,BoardState state)
{
ArrayList<Point> dif = BoardState.getDifferenceLocations(parent,state);
if(dif.size() == 2)return findBlock(dif.get(0),dif.get(1),state);
else if(dif.size() == 3)return findBlock(dif.get(0),dif.get(1),dif.get(2));
else if(dif.size() == 4)return findBlock(dif.get(0),dif.get(1),dif.get(2),dif.get(3));
else return null;
}
static Point findBlock(Point cell1, Point cell2, BoardState state)
{
if(cell1.x == cell2.x)
{
if(cell1.y + 2 == cell2.y)
{
return new Point(cell1.x, cell1.y+1);
}
else if(cell1.y - 2 == cell2.y)
{
return new Point(cell1.x, cell1.y-1);
}
else
return null;
}
else if(cell1.y == cell2.y)
{
if(cell1.x + 2 == cell2.x)
{
return new Point(cell1.x + 1, cell1.y);
}
else if(cell1.x - 2 == cell2.x)
{
return new Point(cell1.x - 1, cell1.y);
}
else
return null;
}
else if(cell1.x + 1 == cell2.x)
{
if(cell1.y + 1 == cell2.y)
{
return lookUpBlock(cell1,cell2, new Point(cell1.x + 1, cell1.y), new Point(cell1.x, cell1.y+1), state);
}
else if(cell1.y - 1 == cell2.y)
{
return lookUpBlock(cell1,cell2, new Point(cell1.x + 1, cell1.y), new Point(cell1.x, cell1.y-1), state);
}
else
return null;
}
else if(cell1.x - 1 == cell2.x)
{
if(cell1.y + 1 == cell2.y)
{
return lookUpBlock(cell1,cell2, new Point(cell1.x - 1, cell1.y), new Point(cell1.x, cell1.y+1), state);
}
else if(cell1.y - 1 == cell2.y)
{
return lookUpBlock(cell1,cell2, new Point(cell1.x - 1, cell1.y), new Point(cell1.x, cell1.y-1), state);
}
else
return null;
}
else
return null;
}
static Point findBlock(Point cell1, Point cell2, Point cell3)
{
if(cell1.x == cell2.x)
{
if(cell1.y + 2 == cell2.y)
{
if(cell1.y + 1 == cell3.y)
{
if(cell1.x - 1 == cell3.x || cell1.x + 1 == cell3.x)
return new Point(cell1.x, cell1.y + 1);
else
return null;
}
else return null;
}
else if(cell1.y - 2 == cell2.y)
{
if(cell1.y - 1 == cell3.y)
{
if(cell1.x - 1 == cell3.x || cell1.x + 1 == cell3.x)
return new Point(cell1.x, cell1.y - 1);
else
return null;
}
else return null;
}
else
return null;
}
else if(cell1.x == cell3.x)
{
if(cell1.y + 2 == cell3.y)
{
if(cell1.y + 1 == cell2.y)
{
if(cell1.x - 1 == cell2.x || cell1.x + 1 == cell2.x)
return new Point(cell1.x, cell1.y + 1);
else
return null;
}
else return null;
}
else if(cell1.y - 2 == cell3.y)
{
if(cell1.y - 1 == cell2.y)
{
if(cell1.x - 1 == cell2.x || cell1.x + 1 == cell2.x)
return new Point(cell1.x, cell1.y - 1);
else
return null;
}
else return null;
}
else
return null;
}
else if(cell3.x == cell2.x)
{
if(cell3.y + 2 == cell2.y)
{
if(cell3.y + 1 == cell1.y)
{
if(cell3.x - 1 == cell1.x || cell3.x + 1 == cell1.x)
return new Point(cell3.x, cell3.y + 1);
else
return null;
}
else return null;
}
else if(cell3.y - 2 == cell2.y)
{
if(cell3.y - 1 == cell1.y)
{
if(cell3.x - 1 == cell1.x || cell3.x + 1 == cell1.x)
return new Point(cell3.x, cell3.y - 1);
else
return null;
}
else return null;
}
else
return null;
}
else if(cell1.y == cell2.y)
{
if(cell1.x + 2 == cell2.x)
{
if(cell1.x + 1 == cell3.x)
{
if(cell1.y - 1 == cell3.y || cell1.y + 1 == cell3.y)
return new Point(cell1.x + 1, cell1.y );
else
return null;
}
else return null;
}
else if(cell1.x - 2 == cell2.x)
{
if(cell1.x - 1 == cell3.x)
{
if(cell1.y - 1 == cell3.y || cell1.y + 1 == cell3.y)
return new Point(cell1.x - 1, cell1.y);
else
return null;
}
else return null;
}
else
return null;
}
else if(cell1.y == cell3.y)
{
if(cell1.x + 2 == cell3.x)
{
if(cell1.x + 1 == cell2.x)
{
if(cell1.y - 1 == cell2.y || cell1.y + 1 == cell2.y)
return new Point(cell1.x + 1, cell1.y );
else
return null;
}
else return null;
}
else if(cell1.x - 2 == cell3.x)
{
if(cell1.x - 1 == cell2.x)
{
if(cell1.y - 1 == cell2.y || cell1.y + 1 == cell2.y)
return new Point(cell1.x - 1, cell1.y);
else
return null;
}
else return null;
}
else
return null;
}
else if(cell3.y == cell2.y)
{
if(cell3.x + 2 == cell2.x)
{
if(cell3.x + 1 == cell1.x)
{
if(cell3.y - 1 == cell1.y || cell3.y + 1 == cell1.y)
return new Point(cell3.x + 1, cell3.y );
else
return null;
}
else return null;
}
else if(cell3.x - 2 == cell2.x)
{
if(cell3.x - 1 == cell1.x)
{
if(cell3.y - 1 == cell1.y || cell3.y + 1 == cell1.y)
return new Point(cell3.x - 1, cell3.y);
else
return null;
}
else return null;
}
else
return null;
}
else
return null;
}
static Point findBlock(Point cell1, Point cell2, Point cell3, Point cell4)
{
int minx = Math.min(Math.min(cell1.x, cell2.x),Math.min(cell3.x, cell4.x));
int maxx = Math.max(Math.max(cell1.x, cell2.x),Math.max(cell3.x, cell4.x));
int miny = Math.min(Math.min(cell1.y, cell2.y),Math.min(cell3.x, cell4.y));
int maxy = Math.max(Math.max(cell1.y, cell2.y),Math.max(cell3.x, cell4.y));
int countminx = 0;
int countmaxx = 0;
int countminy = 0;
int countmaxy = 0;
if(minx + 2 == maxx)
{
if(miny + 2 == maxy)
{
if(cell1.x == minx)
++countminx;
if(cell1.x == maxx)
++countmaxx;
if(cell1.y == miny)
++countminx;
if(cell1.y == maxy)
++countmaxx;
if(cell2.x == minx)
++countminx;
if(cell2.x == maxx)
++countmaxx;
if(cell2.y == miny)
++countminx;
if(cell2.y == maxy)
++countmaxx;
if(cell3.x == minx)
++countminx;
if(cell3.x == maxx)
++countmaxx;
if(cell3.y == miny)
++countminx;
if(cell3.y == maxy)
++countmaxx;
if(cell4.x == minx)
++countminx;
if(cell4.x == maxx)
++countmaxx;
if(cell4.y == miny)
++countminx;
if(cell4.y == maxy)
++countmaxx;
if(countminx == 1 && countmaxx == 1 && countminy == 1 && countmaxy == 1)
{
return new Point(minx + 1, miny + 1);
}
else
return null;
}
else
return null;
}
else
return null;
}
static Point lookUpBlock( Point cell1, Point cell2, Point test1, Point test2, BoardState state)
{
if(state.getCellContents(test1.x,test1.y) > 10 && state.getCellContents(test1.x,test1.y) < 14)
{
int cellValue = state.getCellContents(test1.x, test1.y);
cellValue -= 10;
int blanks = 0;
int bulbs = 0;
if(test1.x + 1 < state.getWidth())
{
if(state.getCellContents(test1.x + 1, test1.y) > 1)
++blanks;
else if(state.getCellContents(test1.x + 1, test1.y) == 1)
++bulbs;
}
else
++blanks;
if(test1.x - 1 > 0)
{
if(state.getCellContents(test1.x - 1, test1.y) > 1)
++blanks;
else if(state.getCellContents(test1.x - 1, test1.y) == 1)
++bulbs;
}
else
++blanks;
if(test1.y + 1 < state.getHeight())
{
if(state.getCellContents(test1.x, test1.y + 1) > 1)
++blanks;
else if(state.getCellContents(test1.x, test1.y + 1) == 1)
++bulbs;
}
else
++blanks;
if(test1.y - 1 > 0)
{
if(state.getCellContents(test1.x, test1.y - 1) > 1)
++blanks;
else if(state.getCellContents(test1.x, test1.y - 1) == 1)
++bulbs;
}
else
++blanks;
if(cellValue - bulbs == 1)
{
if(bulbs + blanks == 2)
{
return test1;
}
}
}
if(state.getCellContents(test2.x,test2.y) > 10 && state.getCellContents(test2.x,test2.y) < 14)
{
int cellValue = state.getCellContents(test2.x, test2.y);
cellValue -= 10;
int blanks = 0;
int bulbs = 0;
if(test2.x + 1 < state.getWidth())
{
if(state.getCellContents(test2.x + 1, test2.y) > 1)
++blanks;
else if(state.getCellContents(test2.x + 1, test2.y) == 1)
++bulbs;
}
else
++blanks;
if(test2.x - 1 > 0)
{
if(state.getCellContents(test2.x - 1, test2.y) > 1)
++blanks;
else if(state.getCellContents(test2.x - 1, test2.y) == 1)
++bulbs;
}
else
++blanks;
if(test2.y + 1 < state.getHeight())
{
if(state.getCellContents(test2.x, test2.y + 1) > 1)
++blanks;
else if(state.getCellContents(test2.x, test2.y + 1) == 1)
++bulbs;
}
else
++blanks;
if(test2.y - 1 > 0)
{
if(state.getCellContents(test2.x, test2.y - 1) > 1)
++blanks;
else if(state.getCellContents(test2.x, test2.y - 1) == 1)
++bulbs;
}
else
++blanks;
if(cellValue - bulbs == 1)
{
if(bulbs + blanks == 2)
{
return test2;
}
}
}
return null;
}
int checkBlock(Point block, BoardState state)
{
if(state.getCellContents(block.x,block.y) > 10 && state.getCellContents(block.x,block.y) < 14)
{
int cellValue = state.getCellContents(block.x, block.y);
cellValue -= 10;
int blanks = 0;
int bulbs = 0;
if(block.x + 1 < state.getWidth())
{
if(state.getCellContents(block.x + 1, block.y) > 1)
++blanks;
else if(state.getCellContents(block.x + 1, block.y) == 1)
++bulbs;
}
else
++blanks;
if(block.x - 1 > 0)
{
if(state.getCellContents(block.x - 1, block.y) > 1)
++blanks;
else if(state.getCellContents(block.x - 1, block.y) == 1)
++bulbs;
}
else
++blanks;
if(block.y + 1 < state.getHeight())
{
if(state.getCellContents(block.x, block.y + 1) > 1)
++blanks;
else if(state.getCellContents(block.x, block.y + 1) == 1)
++bulbs;
}
else
++blanks;
if(block.y - 1 > 0)
{
if(state.getCellContents(block.x, block.y - 1) > 1)
++blanks;
else if(state.getCellContents(block.x, block.y - 1) == 1)
++bulbs;
}
else
++blanks;
if(cellValue - bulbs == 1 || cellValue - bulbs == 2)
{
if(bulbs + blanks == 1)
{
return cellValue - bulbs;
}
}
}
return -1;
}
public static int getBlockValue(int cell)
{
if(cell == LightUp.CELL_BLOCK0)return 0;
else if(cell == LightUp.CELL_BLOCK1)return 1;
else if(cell == LightUp.CELL_BLOCK2)return 2;
else if(cell == LightUp.CELL_BLOCK3)return 3;
else if(cell == LightUp.CELL_BLOCK4)return 4;
else return -1;
}
public boolean startDefaultApplicationRaw(BoardState state)
{
return true;
}
public boolean aultApplicationRaw(BoardState state, PuzzleModule pm ,Point location)
{
Vector<Point> cells = new Vector<Point>();
cells.add( new Point(0,0));
cells.add(new Point(0,1));
Vector<Integer> states = new Vector<Integer>();
states.add( null );
states.add( 2 );
Vector<Integer> statecounts = new Vector<Integer>();
statecounts.add( 1 );
statecounts.add( 9 );
Permutations.permutationRow( state, 1, states, statecounts );
return true;
}
}
| agpl-3.0 |
Turan-no/Turan | apps/turan/migrations/0026_auto__chg_field_component_removed.py | 27387 | # 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):
# Changing field 'Component.removed'
db.alter_column('turan_component', 'removed', self.gf('django.db.models.fields.DateTimeField')(null=True))
def backwards(self, orm):
# Changing field 'Component.removed'
db.alter_column('turan_component', 'removed', self.gf('django.db.models.fields.DateTimeField')())
models = {
'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.now'}),
'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.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'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'})
},
'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'})
},
'turan.bestpowereffort': {
'Meta': {'ordering': "('duration',)", 'object_name': 'BestPowerEffort'},
'ascent': ('django.db.models.fields.IntegerField', [], {}),
'descent': ('django.db.models.fields.IntegerField', [], {}),
'duration': ('django.db.models.fields.IntegerField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'length': ('django.db.models.fields.FloatField', [], {}),
'pos': ('django.db.models.fields.FloatField', [], {}),
'power': ('django.db.models.fields.IntegerField', [], {})
},
'turan.bestspeedeffort': {
'Meta': {'ordering': "('duration',)", 'object_name': 'BestSpeedEffort'},
'ascent': ('django.db.models.fields.IntegerField', [], {}),
'descent': ('django.db.models.fields.IntegerField', [], {}),
'duration': ('django.db.models.fields.IntegerField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'length': ('django.db.models.fields.FloatField', [], {}),
'pos': ('django.db.models.fields.FloatField', [], {}),
'speed': ('django.db.models.fields.FloatField', [], {})
},
'turan.component': {
'Meta': {'object_name': 'Component'},
'added': ('django.db.models.fields.DateTimeField', [], {}),
'brand': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'componenttype': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.ComponentType']"}),
'equipment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Equipment']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'removed': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'weight': ('django.db.models.fields.FloatField', [], {'default': '0', 'blank': 'True'})
},
'turan.componenttype': {
'Meta': {'object_name': 'ComponentType'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '140'})
},
'turan.equipment': {
'Meta': {'object_name': 'Equipment'},
'brand': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'equipmenttype': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.EquipmentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '140'}),
'notes': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'weight': ('django.db.models.fields.FloatField', [], {'blank': 'True'})
},
'turan.equipmenttype': {
'Meta': {'object_name': 'EquipmentType'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '140'})
},
'turan.exercise': {
'Meta': {'ordering': "('-date', '-time')", 'object_name': 'Exercise'},
'avg_cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_hr': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_pedaling_cad': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_pedaling_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_speed': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'comment': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']", 'null': 'True'}),
'date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'duration': ('django.db.models.fields.DecimalField', [], {'default': '0', 'blank': 'True'}),
'exercise_permission': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}),
'exercise_type': ('django.db.models.fields.related.ForeignKey', [], {'default': '13', 'to': "orm['turan.ExerciseType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'kcal': ('django.db.models.fields.IntegerField', [], {'default': '0', 'blank': 'True'}),
'live_state': ('django.db.models.fields.CharField', [], {'default': "'F'", 'max_length': '1', 'null': 'True', 'blank': 'True'}),
'max_cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_hr': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_speed': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'max_temperature': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'min_temperature': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'normalized_hr': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'normalized_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'route': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Route']", 'null': 'True', 'blank': 'True'}),
'sensor_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}),
'tags': ('tagging.fields.TagField', [], {}),
'temperature': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'time': ('django.db.models.fields.TimeField', [], {'null': 'True', 'blank': 'True'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'turan.exercisedetail': {
'Meta': {'ordering': "('time',)", 'object_name': 'ExerciseDetail'},
'altitude': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'distance': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'hr': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lat': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'lon': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'speed': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'temp': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'time': ('django.db.models.fields.DateTimeField', [], {})
},
'turan.exercisepermission': {
'Meta': {'object_name': 'ExercisePermission'},
'cadence': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}),
'exercise': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['turan.Exercise']", 'unique': 'True', 'primary_key': 'True'}),
'hr': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}),
'power': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}),
'speed': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'})
},
'turan.exercisetype': {
'Meta': {'ordering': "('name',)", 'object_name': 'ExerciseType'},
'altitude': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '40'}),
'slopes': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'turan.hrzonesummary': {
'Meta': {'ordering': "('zone',)", 'object_name': 'HRZoneSummary'},
'duration': ('django.db.models.fields.IntegerField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'zone': ('django.db.models.fields.IntegerField', [], {})
},
'turan.interval': {
'Meta': {'ordering': "('start_time',)", 'object_name': 'Interval'},
'ascent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_hr': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
'avg_pedaling_cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'avg_speed': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'avg_temp': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'descent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'distance': ('django.db.models.fields.FloatField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
'duration': ('django.db.models.fields.IntegerField', [], {}),
'end_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'end_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'kcal': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_hr': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_speed': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'min_cadence': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_hr': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_power': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_speed': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'start': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'start_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'start_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'start_time': ('django.db.models.fields.DateTimeField', [], {})
},
'turan.location': {
'Meta': {'object_name': 'Location'},
'country': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'county': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'lat': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'lon': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'town': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
'url': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128', 'blank': 'True'})
},
'turan.mergesensorfile': {
'Meta': {'object_name': 'MergeSensorFile'},
'altitude': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'cadence': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'hr': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'merge_strategy': ('django.db.models.fields.CharField', [], {'default': "'M'", 'max_length': '1'}),
'position': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'power': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'sensor_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'speed': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'turan.route': {
'Meta': {'ordering': "('-created', 'name')", 'object_name': 'Route'},
'ascent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'descent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
'distance': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'end_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'blank': 'True'}),
'end_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'blank': 'True'}),
'gpx_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_altitude': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_altitude': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '160', 'blank': 'True'}),
'route_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'single_serving': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'start_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'blank': 'True'}),
'start_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'blank': 'True'}),
'tags': ('tagging.fields.TagField', [], {})
},
'turan.segment': {
'Meta': {'object_name': 'Segment'},
'ascent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'category': ('django.db.models.fields.IntegerField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'descent': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {}),
'distance': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'end_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'end_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'gpx_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}),
'grade': ('django.db.models.fields.FloatField', [], {'default': '0', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_altitude': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_altitude': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '160'}),
'segment_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'}),
'start_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'start_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'tags': ('tagging.fields.TagField', [], {})
},
'turan.segmentdetail': {
'Meta': {'ordering': "('duration',)", 'object_name': 'SegmentDetail'},
'act_power': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'ascent': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'avg_hr': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'duration': ('django.db.models.fields.IntegerField', [], {}),
'end_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'end_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'est_power': ('django.db.models.fields.FloatField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'grade': ('django.db.models.fields.FloatField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'length': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'power_per_kg': ('django.db.models.fields.FloatField', [], {}),
'segment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Segment']", 'null': 'True', 'blank': 'True'}),
'speed': ('django.db.models.fields.FloatField', [], {}),
'start': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'start_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'start_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'vam': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'turan.slope': {
'Meta': {'ordering': "('-exercise__date',)", 'object_name': 'Slope'},
'act_power': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'ascent': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'avg_hr': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'category': ('django.db.models.fields.IntegerField', [], {}),
'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'duration': ('django.db.models.fields.IntegerField', [], {}),
'end_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'end_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'est_power': ('django.db.models.fields.FloatField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'grade': ('django.db.models.fields.FloatField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'length': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'power_per_kg': ('django.db.models.fields.FloatField', [], {}),
'segment': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Segment']", 'null': 'True', 'blank': 'True'}),
'speed': ('django.db.models.fields.FloatField', [], {}),
'start': ('django.db.models.fields.FloatField', [], {'default': '0'}),
'start_lat': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'start_lon': ('django.db.models.fields.FloatField', [], {'default': '0.0', 'null': 'True', 'blank': 'True'}),
'vam': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'turan.wzonesummary': {
'Meta': {'ordering': "('zone',)", 'object_name': 'WZoneSummary'},
'duration': ('django.db.models.fields.IntegerField', [], {}),
'exercise': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['turan.Exercise']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'zone': ('django.db.models.fields.IntegerField', [], {})
}
}
complete_apps = ['turan']
| agpl-3.0 |
SPnl/nl.sp.reports | CRM/Reports/Form/Report/Kerncijfers.php | 8785 | <?php
class CRM_Reports_Form_Report_Kerncijfers extends CRM_Report_Form {
protected $_summary = NULL;
protected $_noFields = TRUE;
private $_membershipTypes;
private $_membershipStatuses;
private $_rowHeaders;
public function __construct() {
$this->_columns = [];
$this->_groupFilter = FALSE;
$this->_tagFilter = FALSE;
parent::__construct();
}
public function preProcess() {
$this->assign('reportTitle', ts('Kerncijfers SP'));
parent::preProcess();
}
public function postProcess() {
// Lange of korte weergave based on context
$context = $_GET['context'];
switch ($context) {
case 'dashlet':
$weekCount = 2;
$yearCount = 1;
break;
default:
$weekCount = 13;
$yearCount = 1; // 2014 geeft veel verwarring ivm migratie/correcties
break;
}
$this->beginPostProcess();
$this->_membershipTypes = CRM_Member_PseudoConstant::membershipType();
$this->_membershipStatuses = CRM_Member_PseudoConstant::membershipStatus();
$this->_columnHeaders = [
'name' => ['title' => 'Omschrijving', 'type' => 0],
];
$this->_rowHeaders = [
'sp_begin' => ['section' => 'SP', 'name' => 'Beginstand'],
'sp_new' => ['section' => 'SP', 'name' => 'Ingeschreven'],
'sp_expired' => ['section' => 'SP', 'name' => 'Uitgeschreven'],
'sp_deceased' => ['section' => 'SP', 'name' => 'Overleden'],
'sp_end' => ['section' => 'SP', 'name' => 'Eindstand'],
'rood_begin' => ['section' => 'ROOD', 'name' => 'Beginstand'],
'rood_new' => ['section' => 'ROOD', 'name' => 'Ingeschreven'],
'rood_expired' => ['section' => 'ROOD', 'name' => 'Uitgeschreven'],
'rood_end' => ['section' => 'ROOD', 'name' => 'Eindstand'],
'other_tribune' => ['section' => 'Overig', 'name' => 'Abonnees Tribune'],
'other_tribproef' => ['section' => 'Overig', 'name' => 'Proefabonnees Tribune'],
'other_spanning' => ['section' => 'Overig', 'name' => 'Abonnees Spanning'],
'other_donateurs' => ['section' => 'Overig', 'name' => 'Donateurs'],
'other_total' => ['section' => 'Overig', 'name' => 'Totaal'],
];
$rows = [];
$data = [];
// Cijfers per week
for ($week = $weekCount - 1; $week >= 0; $week--) {
$wk = new \DateTime('monday this week');
if ($week > 0) {
$wk->sub(new \DateInterval('P' . $week . 'W'));
}
$wf = (int) $wk->format('W');
$this->_columnHeaders['wk' . $wf] = ['title' => 'Wk ' . $wf, 'type' => 1];
$wkEnd = clone $wk;
$wkEnd->add(new \DateInterval('P1W'));
$data['wk' . $wf] = [
'sp_begin' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], NULL, $wk, 'join'),
'sp_new' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], $wk, $wkEnd, 'join'),
'sp_expired' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], $wk, $wkEnd, 'end_not_deceased'),
'sp_deceased' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], $wk, $wkEnd, 'deceased'),
'sp_end' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], NULL, $wkEnd, 'join'),
'rood_begin' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], NULL, $wk, 'join'),
'rood_new' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], $wk, $wkEnd, 'join'),
'rood_expired' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], $wk, $wkEnd, 'end'),
'rood_end' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], NULL, $wkEnd, 'join'),
'other_tribune' => $this->_getCount(['Abonnee Blad-Tribune Betaald', 'Abonnee Audio-Tribune Betaald'], NULL, $wkEnd, 'join'),
'other_tribproef' => $this->_getCount(['Abonnee Blad-Tribune Proef'], NULL, $wkEnd, 'join'),
'other_spanning' => $this->_getCount(['Abonnee SPanning Betaald'], NULL, $wkEnd, 'join'),
'other_donateurs' => $this->_getCount(['SP Donateur'], NULL, $wkEnd, 'join'),
'other_total' => $this->_getCount(['Abonnee Blad-Tribune Betaald', 'Abonnee Blad-Tribune Proef', 'Abonnee Audio-Tribune Betaald', 'Abonnee SPanning Betaald', 'SP Donateur'], NULL, $wkEnd, 'join'),
];
}
// Cijfers per jaar
for ($year = 0; $year < $yearCount; $year++) {
$yr = new \DateTime('01/01');
$yrEnd = clone $yr;
if ($year > 0) {
$interval = new \DateInterval('P' . $year . 'Y');
$yr->sub($interval);
$yrEnd->sub($interval)->add(new \DateInterval('P1Y'));
$yf = (int) $yr->format('Y');
$key = (int) $yr->format('Y');
$title = '(' . $yf . ')';
}
else {
$yf = (int) $yr->format('Y');
$yrEnd->add(new \DateInterval('P364D')); // 364 dagen ivm einddata 31-12
$key = 'ycur';
$title = $yf;
}
$this->_columnHeaders[$key] = ['title' => $title, 'type' => 1];
$data[$key] = [
'sp_begin' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], NULL, $yr, 'join'),
'sp_new' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], $yr, $yrEnd, 'join'),
'sp_expired' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], $yr, $yrEnd, 'end_not_deceased'),
'sp_deceased' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], $yr, $yrEnd, 'deceased'),
'sp_end' => $this->_getCount(['Lid SP', 'Lid SP en ROOD'], NULL, $yrEnd, 'join'),
'rood_begin' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], NULL, $yr, 'join'),
'rood_new' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], $yr, $yrEnd, 'join'),
'rood_expired' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], $yr, $yrEnd, 'end'),
'rood_end' => $this->_getCount(['Lid SP en ROOD', 'Lid ROOD'], NULL, $yrEnd, 'join'),
'other_tribune' => $this->_getCount(['Abonnee Blad-Tribune Betaald', 'Abonnee Audio-Tribune Betaald'], NULL, $yrEnd, 'join'),
'other_tribproef' => $this->_getCount(['Abonnee Blad-Tribune Proef'], NULL, $yrEnd, 'join'),
'other_spanning' => $this->_getCount(['Abonnee SPanning Betaald'], NULL, $yrEnd, 'join'),
'other_donateurs' => $this->_getCount(['SP Donateur'], NULL, $yrEnd, 'join'),
'other_total' => $this->_getCount(['Abonnee Blad-Tribune Betaald', 'Abonnee Blad-Tribune Proef', 'Abonnee Audio-Tribune Betaald', 'Abonnee SPanning Betaald', 'SP Donateur'], NULL, $yrEnd, 'join'),
];
}
// Data uitschrijven in rijen...:
foreach ($this->_rowHeaders as $rkey => $row) {
foreach ($this->_columnHeaders as $ckey => $cheader) {
if ($ckey == 'name') {
continue;
}
$row[$ckey] = $data[$ckey][$rkey];
}
$rows[] = $row;
}
// Section headers and totals
$this->assign('sections', [
'section' => [
'title' => 'Kerncijfers',
'name' => 'section',
'type' => 1,
],
]);
$this->assign('sectionTotals', [
'SP' => $data['ycur']['sp_end'],
'ROOD' => $data['ycur']['rood_end'],
'Overig' => $data['ycur']['other_total'],
]);
// Finalize
$this->formatDisplay($rows);
$this->doTemplateAssignment($rows);
$this->endPostProcess($rows);
}
// Feitelijke counts uitvoeren
private function _getCount($membershipTypes, $from = NULL, $to, $type = 'join') {
foreach ($membershipTypes as &$t) {
$t = array_search($t, $this->_membershipTypes);
}
$membershipTypeString = implode(',', $membershipTypes);
$statuses = ['New', 'Current', 'Grace', 'Expired', 'Cancelled']; // ie excluding Pending
if($type == 'deceased') {
$statuses = ['Deceased'];
} elseif($type != 'end_not_deceased') {
$statuses[] = 'Deceased';
}
foreach ($statuses as &$s) {
$s = array_search($s, $this->_membershipStatuses);
}
$membershipStatusString = implode(',', $statuses);
$query = "SELECT COUNT(*) FROM civicrm_membership
WHERE membership_type_id IN ({$membershipTypeString})
AND status_id IN ({$membershipStatusString})
";
if ($type == 'join') {
if ($from) {
$query .= "AND join_date >= '" . $from->format('Y-m-d') . "' ";
}
$query .= "AND join_date < '" . $to->format('Y-m-d') . "'
AND (end_date IS NULL OR end_date >= '" . $to->format('Y-m-d') . "')
";
}
else {
if ($from) {
$query .= "AND end_date >= '" . $from->format('Y-m-d') . "' ";
}
$query .= "AND end_date < '" . $to->format('Y-m-d') . "'
";
}
return CRM_Core_DAO::singleValueQuery($query);
}
}
| agpl-3.0 |
BirkbeckCTP/janeway | src/press/migrations/0023_auto_20200718_1117.py | 468 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-18 11:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('press', '0022_press_disable_journals'),
]
operations = [
migrations.AlterField(
model_name='press',
name='theme',
field=models.CharField(default='OLH', max_length=255),
),
]
| agpl-3.0 |
ludaac/noosfero-mx | plugins/bsc/test/functional/bsc_plugin_admin_controller_test.rb | 3163 | require File.dirname(__FILE__) + '/../../../../test/test_helper'
require File.dirname(__FILE__) + '/../../controllers/bsc_plugin_admin_controller'
require File.dirname(__FILE__) + '/../../../../app/models/uploaded_file'
# Re-raise errors caught by the controller.
class BscPluginAdminController; def rescue_action(e) raise e end; end
class BscPluginAdminControllerTest < ActionController::TestCase
VALID_CNPJ = '94.132.024/0001-48'
def setup
@controller = BscPluginAdminController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
user_login = create_admin_user(Environment.default)
login_as(user_login)
@admin = User[user_login].person
e = Environment.default
e.enabled_plugins = ['BscPlugin']
e.save!
end
attr_accessor :admin
should 'create a new bsc' do
assert_difference BscPlugin::Bsc, :count, 1 do
post :new, :profile_data => {:business_name => 'Sample Bsc', :identifier => 'sample-bsc', :company_name => 'Sample Bsc Ltda.', :cnpj => VALID_CNPJ}
end
assert_redirected_to :controller => 'profile_editor', :profile => 'sample-bsc'
end
should 'not create an invalid bsc' do
assert_difference BscPlugin::Bsc, :count, 0 do
post :new, :profile_data => {:business_name => 'Sample Bsc', :identifier => 'sample-bsc', :company_name => 'Sample Bsc Ltda.', :cnpj => '29837492304'}
end
assert_response 200
end
should 'set the current user as the bsc admin' do
name = 'Sample Bsc'
post :new, :profile_data => {:business_name => name, :identifier => 'sample-bsc', :company_name => 'Sample Bsc Ltda.', :cnpj => VALID_CNPJ}
bsc = BscPlugin::Bsc.find_by_name(name)
assert_includes bsc.admins, admin
end
should 'list correct enterprises on search' do
# Should list if: not validated AND (name matches OR identifier matches) AND not bsc
e1 = Enterprise.create!(:name => 'Sample Enterprise 1', :identifier => 'bli', :validated => false)
e2 = Enterprise.create!(:name => 'Bla', :identifier => 'sample-enterprise-6', :validated => false)
e3 = Enterprise.create!(:name => 'Blo', :identifier => 'blo', :validated => false)
e4 = BscPlugin::Bsc.create!(:business_name => "Sample Bsc", :identifier => 'sample-bsc', :company_name => 'Sample Bsc Ltda.', :cnpj => VALID_CNPJ, :validated => false)
e5 = Enterprise.create!(:name => 'Sample Enterprise 5', :identifier => 'sample-enterprise-5')
e5.validated = true
e5.save!
get :search_enterprise, :q => 'sampl'
assert_match /#{e1.name}/, @response.body
assert_match /#{e2.name}/, @response.body
assert_no_match /#{e3.name}/, @response.body
assert_no_match /#{e4.name}/, @response.body
assert_no_match /#{e5.name}/, @response.body
end
should 'save validations' do
e1 = fast_create(Enterprise, :validated => false)
e2 = fast_create(Enterprise, :validated => false)
e3 = fast_create(Enterprise, :validated => false)
post :save_validations, :q => "#{e1.id},#{e2.id}"
e1.reload
e2.reload
e3.reload
assert e1.validated
assert e2.validated
assert !e3.validated
end
end
| agpl-3.0 |
fqqb/yamcs | yamcs-web/src/main/webapp/src/app/shared/dialogs/SelectParameterDialog.ts | 2129 | import { ChangeDetectionStrategy, Component, Inject, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { Observable } from 'rxjs';
import { debounceTime, map, switchMap } from 'rxjs/operators';
import { Parameter } from '../../client';
import { YamcsService } from '../../core/services/YamcsService';
export interface SelectParameterOptions {
label?: string;
okLabel?: string;
exclude?: string[];
limit?: number;
}
/**
* Reusabe dialog for selecting a single parameter via its qualified name.
* Allows also manual parameter entry for parameters that do not (yet) exist on the server.
*/
@Component({
selector: 'app-select-parameter-dialog',
templateUrl: './SelectParameterDialog.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SelectParameterDialog implements OnInit {
parameter = new FormControl(null, [Validators.required]);
filteredOptions: Observable<Parameter[]>;
label: string;
okLabel: string;
limit: number;
constructor(
private dialogRef: MatDialogRef<SelectParameterDialog>,
private yamcs: YamcsService,
@Inject(MAT_DIALOG_DATA) readonly data: SelectParameterOptions,
) {
this.label = data.label || 'Search parameter';
this.okLabel = data.okLabel || 'SELECT';
this.limit = data.limit || 10;
}
ngOnInit() {
const excludedParameters = this.data.exclude || [];
this.filteredOptions = this.parameter.valueChanges.pipe(
debounceTime(300),
switchMap(val => this.yamcs.yamcsClient.getParameters(this.yamcs.instance!, {
q: val,
limit: this.limit,
})),
map(page => page.parameters || []),
map(candidates => {
return candidates.filter(candidate => {
for (const excludedParameter of excludedParameters) {
if (excludedParameter === candidate.qualifiedName) {
return false;
}
}
return true;
});
}),
);
}
select() {
this.dialogRef.close(this.parameter.value);
}
}
| agpl-3.0 |
yajinni/WoWAnalyzer | analysis/priestdiscipline/src/normalizers/AtonementSuccessiveDamage.test.js | 2839 | import { AtonementOnPlayer1, AtonementOnPlayer2, DamagingEvent1, DamagingEvent2, thisPlayer } from '@wowanalyzer/priest-discipline/src/test-fixtures/TestingEvents';
import AtonementSuccessiveDamage from './AtonementSuccessiveDamage';
describe('DisciplinePriest.Reordering', () => {
let atonementSuccessiveDamageNormalizer;
beforeEach(() => {
atonementSuccessiveDamageNormalizer = new AtonementSuccessiveDamage({
reorder: () => true,
toPlayer: () => true,
byPlayer: () => true,
toPlayerPet: () => false,
byPlayerPet: () => false,
playerId: thisPlayer,
});
});
it('If 2 damaging events happen simultaneously, the atonement ahead is split in two', () => {
const AtonementOf2DamingEventsGroupedTogether = [
AtonementOnPlayer2,
DamagingEvent1,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2,
AtonementOnPlayer1,
AtonementOnPlayer2,
];
const result = atonementSuccessiveDamageNormalizer.normalize(AtonementOf2DamingEventsGroupedTogether);
expect(result).toEqual([
AtonementOnPlayer2,
DamagingEvent1,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2]);
});
it('If the atonement of 2 events is correct, it stays untouched', () => {
const AtonementOf2DamingEventsGroupedTogether = [
AtonementOnPlayer2,
DamagingEvent1,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2,
];
const result = atonementSuccessiveDamageNormalizer.normalize(AtonementOf2DamingEventsGroupedTogether);
expect(result).toEqual([
AtonementOnPlayer2,
DamagingEvent1,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2]);
});
it('If the 2 damaging blocks scenario happens twice, both are corrected', () => {
const AtonementOf2DamingEventsGroupedTogether = [
AtonementOnPlayer2,
DamagingEvent1,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent1,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2,
AtonementOnPlayer1,
AtonementOnPlayer2,
];
const result = atonementSuccessiveDamageNormalizer.normalize(AtonementOf2DamingEventsGroupedTogether);
expect(result).toEqual([
AtonementOnPlayer2,
DamagingEvent1,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent1,
AtonementOnPlayer1,
AtonementOnPlayer2,
DamagingEvent2,
AtonementOnPlayer1,
AtonementOnPlayer2,
]);
});
});
| agpl-3.0 |
brosnanyuen/Project-S | Babylon.js-master/Babylon/babylon.mixins.ts | 2633 | // Mixins
interface Window {
mozIndexedDB(func: any): any;
webkitIndexedDB(func: any): any;
IDBTransaction(func: any): any;
webkitIDBTransaction(func: any): any;
msIDBTransaction(func: any): any;
IDBKeyRange(func: any): any;
webkitIDBKeyRange(func: any): any;
msIDBKeyRange(func: any): any;
URL: HTMLURL;
webkitURL: HTMLURL;
webkitRequestAnimationFrame(func: any): any;
mozRequestAnimationFrame(func: any): any;
oRequestAnimationFrame(func: any): any;
WebGLRenderingContext: WebGLRenderingContext;
MSGesture: MSGesture;
CANNON: any;
SIMD: any;
AudioContext: AudioContext;
webkitAudioContext: AudioContext;
}
interface HTMLURL {
createObjectURL(param1: any, param2?: any);
}
interface Document {
exitFullscreen(): void;
webkitCancelFullScreen(): void;
mozCancelFullScreen(): void;
msCancelFullScreen(): void;
webkitIsFullScreen: boolean;
mozFullScreen: boolean;
msIsFullScreen: boolean;
fullscreen: boolean;
mozPointerLockElement: HTMLElement;
msPointerLockElement: HTMLElement;
webkitPointerLockElement: HTMLElement;
pointerLockElement: HTMLElement;
}
interface HTMLCanvasElement {
requestPointerLock(): void;
msRequestPointerLock(): void;
mozRequestPointerLock(): void;
webkitRequestPointerLock(): void;
}
interface CanvasRenderingContext2D {
imageSmoothingEnabled: boolean;
mozImageSmoothingEnabled: boolean;
oImageSmoothingEnabled: boolean;
webkitImageSmoothingEnabled: boolean;
}
interface WebGLTexture {
isReady: boolean;
isCube:boolean;
url: string;
noMipmap: boolean;
samplingMode: number;
references: number;
generateMipMaps: boolean;
_size: number;
_baseWidth: number;
_baseHeight: number;
_width: number;
_height: number;
_workingCanvas: HTMLCanvasElement;
_workingContext: CanvasRenderingContext2D;
_framebuffer: WebGLFramebuffer;
_depthBuffer: WebGLRenderbuffer;
_cachedCoordinatesMode: number;
_cachedWrapU: number;
_cachedWrapV: number;
}
interface WebGLBuffer {
references: number;
capacity: number;
is32Bits: boolean;
}
interface MouseEvent {
movementX: number;
movementY: number;
mozMovementX: number;
mozMovementY: number;
webkitMovementX: number;
webkitMovementY: number;
msMovementX: number;
msMovementY: number;
}
interface MSStyleCSSProperties {
webkitTransform: string;
webkitTransition: string;
}
interface Navigator {
getVRDevices: () => any;
mozGetVRDevices: (any) => any;
isCocoonJS: boolean;
} | agpl-3.0 |
gSafe/mark | mark-pdf/src/main/java/fr/novapost/mark/pdf/PDFBuilder.java | 5306 | package fr.novapost.mark.pdf;
/*
* #%L
* mark-pdf
* %%
* Copyright (C) 2013 - 2015 gSafe
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
import com.google.common.base.Strings;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import java.io.*;
public class PDFBuilder {
private static final int[] BARCODE_DIMENSIONS = { 10, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120, 132, 144 };
public static InputStream stampText(InputStream pdfInput, String text, String info) throws Exception {
if (Strings.isNullOrEmpty(text) && Strings.isNullOrEmpty(info)) {
return pdfInput;
}
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
PdfGState gs = new PdfGState();
ExtendedColor textColor = new GrayColor(0.6f);
ExtendedColor infoColor = new GrayColor(0.4f);
gs.setFillOpacity(0.40f);
PdfReader reader = null;
PdfStamper stamper = null;
File tmpFile = File.createTempFile("nova", "stamp-label");
OutputStream output = null;
try {
output = new FileOutputStream(tmpFile);
reader = new PdfReader(pdfInput);
stamper = new PdfStamper(reader, output);
PdfContentByte over;
PdfContentByte infoOver;
for (int index = 1; index < reader.getNumberOfPages() + 1; ++index) {
Rectangle size = reader.getPageSize(index);
if (text != null) {
over = stamper.getOverContent(index);
over.setGState(gs);
over.beginText();
over.setFontAndSize(bf, size.getHeight() / 9);
over.setColorFill(textColor);
over.showTextAligned(PdfContentByte.ALIGN_LEFT, text, size.getWidth() / 6, size.getHeight() / 6, 40);
over.endText();
}
if (info != null) {
infoOver = stamper.getOverContent(index);
infoOver.setGState(gs);
infoOver.beginText();
infoOver.setFontAndSize(bf, 10);
infoOver.setColorFill(infoColor);
infoOver.showTextAligned(PdfContentByte.ALIGN_LEFT, info, 20, 10, 0);
infoOver.endText();
}
}
pdfInput.close();
return new FileInputStream(tmpFile);
} finally {
if (stamper != null) {
stamper.close();
}
if (reader != null) {
reader.close();
}
if (output != null) {
output.close();
}
}
}
public static InputStream stampDatamatrix(InputStream pdfInput, String barcodeData, int x, int y) throws Exception {
if (Strings.isNullOrEmpty(barcodeData)) {
return pdfInput;
}
PdfReader reader = null;
PdfStamper stamper = null;
try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
reader = new PdfReader(pdfInput);
stamper = new PdfStamper(reader, output);
for (int index = 1; index < reader.getNumberOfPages() + 1; ++index) {
Image img = generateAutoSizedDatamatrix(barcodeData);
img.setAbsolutePosition(x, y);
stamper.getOverContent(index).addImage(img);
}
stamper.close();
return new ByteArrayInputStream(output.toByteArray());
} finally {
if (reader != null) {
reader.close();
}
if (pdfInput != null) {
pdfInput.close();
}
}
}
private static Image generateAutoSizedDatamatrix(String textToEncode) throws Exception {
BarcodeDatamatrix barcode = new BarcodeDatamatrix();
barcode.setOptions(BarcodeDatamatrix.DM_AUTO);
int returnResult = BarcodeDatamatrix.DM_NO_ERROR;
// try to generate the barcode, resizing as needed.
for (int generateCount = 0; generateCount < BARCODE_DIMENSIONS.length; generateCount++) {
barcode.setWidth(BARCODE_DIMENSIONS[generateCount]);
barcode.setHeight(BARCODE_DIMENSIONS[generateCount]);
returnResult = barcode.generate(textToEncode);
if (returnResult == BarcodeDatamatrix.DM_NO_ERROR) {
return barcode.createImage();
}
}
throw new Exception("Error generating barcode. Error " + returnResult);
}
}
| agpl-3.0 |
splicemachine/spliceengine | splice_machine/src/main/java/com/splicemachine/derby/stream/function/CogroupFullOuterJoinRestrictionFlatMapFunction.java | 5216 | /*
* Copyright (c) 2012 - 2020 Splice Machine, Inc.
*
* This file is part of Splice Machine.
* Splice Machine 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, or (at your option) any later version.
* Splice Machine 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 Splice Machine.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.splicemachine.derby.stream.function;
import com.splicemachine.db.iapi.services.io.ArrayUtil;
import com.splicemachine.db.iapi.sql.execute.ExecRow;
import com.splicemachine.derby.iapi.sql.execute.SpliceOperation;
import com.splicemachine.derby.impl.sql.execute.operations.JoinUtils;
import com.splicemachine.derby.stream.iapi.OperationContext;
import scala.Tuple2;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.BitSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Created by yxia on 12/1/19.
*/
public class CogroupFullOuterJoinRestrictionFlatMapFunction<Op extends SpliceOperation>
extends SpliceJoinFlatMapFunction<Op, Tuple2<ExecRow,Tuple2<Iterable<ExecRow>,Iterable<ExecRow>>>,ExecRow> {
private int[] hashKeys;
public CogroupFullOuterJoinRestrictionFlatMapFunction() {
super();
}
public CogroupFullOuterJoinRestrictionFlatMapFunction(OperationContext<Op> operationContext, int[] hashKeys) {
super(operationContext);
assert hashKeys!=null && hashKeys.length >0 : "Bad Hash Keys Passed into Null Filter Function";
this.hashKeys = hashKeys;
}
@Override
public Iterator<ExecRow> call(Tuple2<ExecRow,Tuple2<Iterable<ExecRow>, Iterable<ExecRow>>> tuple) throws Exception {
ExecRow mergedRow;
checkInit();
List<ExecRow> returnRows = new LinkedList<>();
BitSet matchingRights = new BitSet();
for(ExecRow leftRow : tuple._2._1){
Iterator<ExecRow> it = tuple._2._2.iterator();
boolean leftHasMatch = false;
// check if hashkey is null or not to prevent null=null to be qualified as true
if (!hashKeyIsNull(leftRow)) {
int rightIndex = 0;
while (it.hasNext()) {
ExecRow rightRow = it.next();
mergedRow = JoinUtils.getMergedRow(leftRow,
rightRow, op.wasRightOuterJoin,
executionFactory.getValueRow(numberOfColumns));
mergedRow.setKey(leftRow.getKey());
op.setCurrentRow(mergedRow);
if (op.getRestriction().apply(mergedRow)) { // Has Row, abandon
if (!leftHasMatch)
leftHasMatch = true;
returnRows.add(mergedRow);
matchingRights.set(rightIndex);
}
operationContext.recordFilter();
rightIndex++;
}
}
if (!leftHasMatch) {
mergedRow = JoinUtils.getMergedRow(leftRow,
op.getRightEmptyRow(), op.wasRightOuterJoin,
executionFactory.getValueRow(numberOfColumns));
mergedRow.setKey(leftRow.getKey());
returnRows.add(mergedRow);
}
}
// add the non-matching right rows
Iterator<ExecRow> it = tuple._2._2.iterator();
int rightIndex = 0;
while (it.hasNext()) {
ExecRow rightRow = it.next();
if (!matchingRights.get(rightIndex)) {
mergedRow = JoinUtils.getMergedRow(op.getLeftEmptyRow(),
rightRow, op.wasRightOuterJoin,
executionFactory.getValueRow(numberOfColumns));
// TODO: DB-7810? what is the key?
mergedRow.setKey(rightRow.getKey());
returnRows.add(mergedRow);
}
rightIndex++;
}
return returnRows.iterator();
}
private boolean hashKeyIsNull(ExecRow row) {
try {
for (int i = 0; i < hashKeys.length; i++) {
if (row.getColumn(hashKeys[i] + 1).isNull()) {
operationContext.recordFilter();
return true;
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return false;
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal(out);
ArrayUtil.writeIntArray(out,hashKeys);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
hashKeys = ArrayUtil.readIntArray(in);
}
}
| agpl-3.0 |
sinnwerkstatt/landmatrix | apps/grid/forms/deal_spatial_form.py | 8927 | from django.contrib.gis import forms
from django.forms.models import BaseFormSet, formset_factory
from django.utils.translation import ugettext_lazy as _
from apps.grid.fields import AreaField, CountryField, TitleField
from apps.grid.gis import parse_shapefile
from apps.grid.widgets import AreaWidget, CommentInput
from apps.ol3_widgets.widgets import LocationWidget, MapWidget
from .base_form import BaseForm
class DealSpatialForm(BaseForm):
exclude_in_export = ["contract_area", "intended_area", "production_area"]
ACCURACY_CHOICES = (
("", _("---------")),
("Country", _("Country")),
("Administrative region", _("Administrative region")),
("Approximate location", _("Approximate location")),
("Exact location", _("Exact location")),
("Coordinates", _("Coordinates")),
)
AREA_FIELDS = ("contract_area", "intended_area", "production_area")
form_title = _("Location")
tg_location = TitleField(required=False, label="", initial=_("Location"))
level_of_accuracy = forms.ChoiceField(
required=False, label=_("Spatial accuracy level"), choices=ACCURACY_CHOICES
)
location = forms.CharField(
required=False, label=_("Location"), widget=LocationWidget
)
point_lat = forms.CharField(
required=False, label=_("Latitude"), widget=forms.TextInput, initial=""
)
point_lon = forms.CharField(
required=False, label=_("Longitude"), widget=forms.TextInput, initial=""
)
facility_name = forms.CharField(
required=False, label=_("Facility name"), widget=forms.TextInput, initial=""
)
target_country = CountryField(required=False, label=_("Target country"))
# target_region = forms.ModelChoiceField(
# required=False, label=_("Target Region"), widget=forms.HiddenInput,
# queryset=Region.objects.all().order_by("name"))
location_description = forms.CharField(
required=False,
label=_("Location description"),
widget=forms.TextInput,
initial="",
)
contract_area = AreaField(required=False, label=_("Contract area"))
intended_area = AreaField(required=False, label=_("Intended area"))
production_area = AreaField(required=False, label=_("Area in operation"))
tg_location_comment = forms.CharField(
required=False, label=_("Comment on location"), widget=CommentInput
)
class Meta:
name = "location"
def __init__(self, *args, **kwargs):
"""
Pass the values we need through to map widgets
"""
super().__init__(*args, **kwargs)
lat_lon_attrs = self.get_default_lat_lon_attrs()
# Bind area maps to the main location map
area_attrs = {"bound_map_field_id": "{}-map".format(self["location"].html_name)}
area_attrs.update(lat_lon_attrs)
location_attrs = self.get_location_map_widget_attrs()
location_attrs.update(lat_lon_attrs)
if area_attrs:
for polygon_field in self.AREA_FIELDS:
widget = AreaWidget(map_attrs=area_attrs)
self.fields[polygon_field].widget = widget
# Public field gets a mapwidget, so check for that
if isinstance(self.fields["location"].widget, MapWidget):
self.fields["location"].widget = MapWidget(attrs=location_attrs)
else:
self.fields["location"].widget = LocationWidget(map_attrs=location_attrs)
def get_location_map_widget_attrs(self):
attrs = {"show_layer_switcher": True}
bound_fields = (
("location", "bound_location_field_id"),
("target_country", "bound_target_country_field_id"),
("level_of_accuracy", "bound_level_of_accuracy_field_id"),
("point_lat", "bound_lat_field_id"),
("point_lon", "bound_lon_field_id"),
)
for field, attr in bound_fields:
try:
attrs[attr] = self[field].auto_id
except KeyError: # pragma: no cover
pass
return attrs
def get_default_lat_lon_attrs(self):
attrs = {}
try:
lat = float(self["point_lat"].value() or 0)
except ValueError: # pragma: no cover
lat = None
try:
lon = float(self["point_lon"].value() or 0)
except ValueError: # pragma: no cover
lon = None
if lat and lon:
attrs.update(
{
"initial_center_lon": lon,
"initial_center_lat": lat,
"initial_point": [lon, lat],
}
)
return attrs
def _clean_area_field(self, field_name):
value = self.cleaned_data[field_name]
try:
# Check if we got a file here, as
value.name
value.size
except AttributeError:
value_is_file = False
else:
value_is_file = True
if value_is_file:
# Files are the second widget, so append _1
field_name = "{}_1".format(self[field_name].html_name)
shapefile_data = (
hasattr(self.files, "getlist")
and self.files.getlist(field_name)
or self.files[field_name]
)
try:
value = parse_shapefile(shapefile_data)
except ValueError as err: # pragma: no cover
error_msg = _("Error parsing shapefile: %s") % err
raise forms.ValidationError(error_msg)
return value
def clean_contract_area(self):
return self._clean_area_field("contract_area")
def clean_intended_area(self):
return self._clean_area_field("intended_area")
def clean_production_area(self):
return self._clean_area_field("production_area")
def get_attributes(self, request=None):
attributes = super().get_attributes()
# For polygon fields, pass the value directly
for field_name in self.AREA_FIELDS:
polygon_value = self.cleaned_data.get(field_name)
attributes[field_name] = {"polygon": polygon_value}
return attributes
@classmethod
def get_data(cls, activity, group=None, prefix=""):
data = super().get_data(activity, group=group, prefix=prefix)
for area_field_name in cls.AREA_FIELDS:
area_attribute = activity.attributes.filter(
fk_group__name=group, name=area_field_name
).first()
if area_attribute:
data[area_field_name] = area_attribute.polygon
return data
def get_fields_display(self, user=None):
fields = super().get_fields_display(user=user)
# Hide coordinates depending on level of accuracy
accuracy = self.initial.get("level_of_accuracy", "")
if accuracy in ("Country", "Administrative region", "Approximate location"):
for field in fields:
if field["name"] in ("point_lat", "point_lon"):
field["hidden"] = True
return fields
class PublicDealSpatialForm(DealSpatialForm):
AREA_WIDGET_ATTRS = {
"map_width": 600,
"map_height": 400,
"default_zoom": 8,
"default_lat": 0,
"default_lon": 0,
"geom_type": "MULTIPOLYGON",
"disable_drawing": True,
}
location = forms.CharField(required=True, label=_("Location"), widget=MapWidget)
def get_location_map_widget_attrs(self):
location_attrs = super().get_location_map_widget_attrs()
location_attrs["disable_drawing"] = True
return location_attrs
class DealSpatialBaseFormSet(BaseFormSet):
form_title = _("Location")
@classmethod
def get_data(cls, activity, group=None, prefix=""):
groups = (
activity.attributes.filter(fk_group__name__startswith=cls.Meta.name)
.values_list("fk_group__name", flat=True)
.order_by("fk_group__name")
.distinct()
)
data = []
for i, group in enumerate(groups):
form_data = DealSpatialForm.get_data(
activity, group=group
) # , prefix='%s-%i' % (cls.Meta.name, i))
if form_data:
data.append(form_data)
return data
def get_attributes(self, request=None):
return [form.get_attributes(request=request) for form in self.forms]
@property
def meta(self):
# Required for template access to Meta class
return hasattr(self, "Meta") and self.Meta or None
class Meta:
name = "location"
DealSpatialFormSet = formset_factory(
DealSpatialForm,
min_num=1,
validate_min=True,
extra=0,
formset=DealSpatialBaseFormSet,
)
PublicViewDealSpatialFormSet = formset_factory(
PublicDealSpatialForm, formset=DealSpatialBaseFormSet, extra=0
)
| agpl-3.0 |
rwl/openpowersystem | dynamics/dynamics/power_system_stabilizers/pss_sb4.py | 1445 | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard Lincoln
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation; version 2 dated June, 1991.
#
# This software is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANDABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#------------------------------------------------------------------------------
# <<< imports
# @generated
from dynamics.dynamics.power_system_stabilizers.power_system_stabilizer import PowerSystemStabilizer
from google.appengine.ext import db
# >>> imports
class PssSB4(PowerSystemStabilizer):
""" Power sensitive stabilizer model
"""
# <<< pss_sb4.attributes
# @generated
# >>> pss_sb4.attributes
# <<< pss_sb4.references
# @generated
# >>> pss_sb4.references
# <<< pss_sb4.operations
# @generated
# >>> pss_sb4.operations
# EOF -------------------------------------------------------------------------
| agpl-3.0 |
adfinis-sygroup/timed-frontend | tests/integration/components/progress-tooltip/component-test.js | 4885 | import EmberObject from "@ember/object";
import { render } from "@ember/test-helpers";
import { setupRenderingTest } from "ember-qunit";
import wait from "ember-test-helpers/wait";
import hbs from "htmlbars-inline-precompile";
import moment from "moment";
import { module, skip, test } from "qunit";
import { startMirage } from "timed/initializers/ember-cli-mirage";
module("Integration | Component | progress tooltip", function(hooks) {
setupRenderingTest(hooks);
hooks.beforeEach(function() {
this.server = startMirage();
this.server.create("task");
});
hooks.afterEach(function() {
this.server.shutdown();
});
test("renders", async function(assert) {
this.set(
"model",
EmberObject.create({
id: 1,
estimatedTime: moment.duration({ h: 50 }),
constructor: EmberObject.create({
modelName: "project"
})
})
);
await render(hbs`
<span id='target'></span>
{{progress-tooltip target='#target' model=model visible=true}}
`);
return wait().then(() => {
assert.dom(".progress-tooltip").exists();
assert
.dom(".progress-tooltip .time-info .time-info-durations p:nth-child(1)")
.hasText(/^Spent \(Total\): \d+h \d+m$/);
assert
.dom(".progress-tooltip .time-info .time-info-durations p:nth-child(2)")
.hasText(/^Spent \(Billable\): \d+h \d+m$/);
assert
.dom(".progress-tooltip .time-info .time-info-durations p:nth-child(3)")
.hasText("Budget: 50h 0m");
});
});
test("renders with tasks", async function(assert) {
this.set(
"model",
EmberObject.create({
id: 1,
estimatedTime: moment.duration({ h: 100, m: 30 }),
constructor: EmberObject.create({
modelName: "task"
})
})
);
await render(hbs`
<span id='target'></span>
{{progress-tooltip target='#target' model=model visible=true}}
`);
return wait().then(() => {
assert.dom(".progress-tooltip").exists();
assert
.dom(".progress-tooltip .time-info .time-info-durations p:nth-child(1)")
.hasText(/^Spent \(Total\): \d+h \d+m$/);
assert
.dom(".progress-tooltip .time-info .time-info-durations p:nth-child(2)")
.hasText(/^Spent \(Billable\): \d+h \d+m$/);
assert
.dom(".progress-tooltip .time-info .time-info-durations p:nth-child(3)")
.hasText("Budget: 100h 30m");
});
});
test("toggles correctly", async function(assert) {
this.set(
"model",
EmberObject.create({
id: 1,
estimatedTime: moment.duration({ h: 100, m: 30 }),
constructor: EmberObject.create({
modelName: "task"
})
})
);
this.set("visible", false);
await render(hbs`
<span id='target'></span>
{{progress-tooltip target='#target' model=model visible=visible}}
`);
assert.dom(".progress-tooltip").doesNotExist();
this.set("visible", true);
return wait().then(() => {
assert.dom(".progress-tooltip").exists();
});
});
// TODO enable this
skip("uses danger color when the factor is more than 1", async function(assert) {
this.set(
"model",
EmberObject.create({
id: 1,
estimatedTime: moment.duration({ h: 100 }),
constructor: EmberObject.create({
modelName: "project"
})
})
);
this.server.get("/projects/:id", function({ projects }, request) {
return {
...this.serialize(projects.find(request.params.id)),
meta: {
"spent-time": "4 05:00:00" // 101 hours
}
};
});
await render(hbs`
<span id='target'></span>
{{progress-tooltip target='#target' model=model visible=true}}
`);
return wait().then(() => {
assert.dom(".progress-tooltip .badge--danger").exists();
assert.dom(".progress-tooltip .progress-bar.danger").exists();
});
});
// TODO enable this
skip("uses warning color when the factor is 0.9 or more", async function(assert) {
this.set(
"model",
EmberObject.create({
id: 1,
estimatedTime: moment.duration({ h: 100 }),
constructor: EmberObject.create({
modelName: "project"
})
})
);
this.server.get("/projects/:id", function({ projects }, request) {
return {
...this.serialize(projects.find(request.params.id)),
meta: {
"spent-time": "3 18:00:00" // 90 hours
}
};
});
await render(hbs`
<span id='target'></span>
{{progress-tooltip target='#target' model=model visible=true}}
`);
return wait().then(() => {
assert.dom(".progress-tooltip .badge--warning").exists();
assert.dom(".progress-tooltip .progress-bar.warning").exists();
});
});
});
| agpl-3.0 |
PedroFelipe/cm42-central | app/operations/project_operations.rb | 534 | module ProjectOperations
class Create < BaseOperations::Create
end
class Update < BaseOperations::Update
end
class Destroy < BaseOperations::Destroy
protected
def operate!
# because of dependent => destroy it can take a very long time to delete a project
# FIXME instead of deleting we should add something like Papertrail to
# implement an 'Archive'-like feature instead
if Rails.env.production?
model.delay.destroy
else
model.destroy!
end
end
end
end
| agpl-3.0 |
yonkon/nedvig | custom/modules/Tasks/metadata/subpanels/default.php | 3604 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$subpanel_layout = array(
//Removed button because this layout def is a component of
//the activities sub-panel.
'top_buttons' => array(
array (
'widget_class'=>'SubPanelTopCreateButton',
),
array (
'widget_class'=>'SubPanelTopSelectButton', 'popup_module' => 'Tasks'
),
),
'list_fields' => array(
'object_image'=>array(
'vname' => 'LBL_OBJECT_IMAGE',
'widget_class' => 'SubPanelIcon',
'width' => '2%',
),
'name'=>array(
'vname' => 'LBL_LIST_SUBJECT',
'widget_class' => 'SubPanelDetailViewLink',
'width' => '30%',
),
'status'=>array(
'widget_class' => 'SubPanelActivitiesStatusField',
'vname' => 'LBL_LIST_STATUS',
'width' => '15%',
),
'parent_name'=>array(
'vname' => 'LBL_LIST_RELATED_TO',
'width' => '22%',
'target_record_key' => 'parent_id',
'target_module_key'=>'parent_type',
'widget_class' => 'SubPanelDetailViewLink',
'sortable'=>false,
),
'date_modified'=>array(
'vname' => 'LBL_LIST_DATE_MODIFIED',
'width' => '10%',
),
'edit_button'=>array(
'vname' => 'LBL_EDIT_BUTTON',
'widget_class' => 'SubPanelEditButton',
'width' => '2%',
),
'remove_button'=>array(
'vname' => 'LBL_REMOVE',
'widget_class' => 'SubPanelRemoveButton',
'width' => '2%',
),
'parent_id'=>array(
'usage'=>'query_only',
),
'parent_type'=>array(
'usage'=>'query_only',
),
'filename'=>array(
'usage'=>'query_only',
'force_exists'=>true
),
),
);
?>
| agpl-3.0 |
TEA-ebook/teabook-reader-ffox-app | app/js/reader/gestures.js | 4784 | /*global define, ReadiumSDK, window*/
/*jslint nomen: true*/
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
define('gestures', ['jquery', 'hammer'], function ($, Hammer) {
"use strict";
var gesturesHandler, onSwipe, onPinch, onPinchMove, onTap, computeFontSize, isGestureHandled, setupHammer;
gesturesHandler = function (reader, viewport) {
onSwipe = function (event) {
if (event.direction === Hammer.DIRECTION_LEFT) {
reader.trigger(ReadiumSDK.Events.GESTURE_SWIPE_LEFT);
reader.openPageRight();
} else if (event.direction === Hammer.DIRECTION_RIGHT) {
reader.trigger(ReadiumSDK.Events.GESTURE_SWIPE_RIGHT);
reader.openPageLeft();
}
};
onTap = function (event) {
if (event.target.hasAttribute('href') || (event.target.parentNode.hasAttribute && event.target.parentNode.hasAttribute('href'))) {
$(event.target).click();
} else {
reader.trigger(ReadiumSDK.Events.GESTURE_TAP, event.center);
}
};
onPinchMove = function (event) {
reader.trigger(ReadiumSDK.Events.GESTURE_PINCH_MOVE, {
"fontSize": computeFontSize(event.scale),
"center": event.center,
"timestamp": Date.now().toString()
});
};
onPinch = function (event) {
if (event.eventType === Hammer.INPUT_END) {
reader.trigger(ReadiumSDK.Events.GESTURE_PINCH);
setTimeout(function () {
reader.updateSettings({
fontSize: computeFontSize(event.scale)
});
}, 50);
} else if (event.eventType === Hammer.INPUT_MOVE) {
onPinchMove(event);
}
};
computeFontSize = function (eventScale) {
var scale, fontSize;
scale = isNaN(parseInt(eventScale, 10)) ? 1 : eventScale;
fontSize = reader.viewerSettings().fontSize;
if (scale < 1) {
fontSize -= Math.round(30 / scale);
} else {
fontSize += Math.round(20 * scale);
}
if (fontSize < 50) {
fontSize = 50;
} else if (fontSize > 250) {
fontSize = 250;
}
return fontSize;
};
isGestureHandled = function () {
var viewType = reader.getCurrentViewType();
return viewType === ReadiumSDK.Views.ReaderView.VIEW_TYPE_FIXED || viewType === ReadiumSDK.Views.ReaderView.VIEW_TYPE_COLUMNIZED;
};
setupHammer = function (element) {
var hammertime = new Hammer(element, { prevent_mouseevents: true });
hammertime.get('swipe').set({ threshold: 1, velocity: 0.1 });
hammertime.get('pinch').set({ enable: true });
// set up the hammer gesture events swiping handlers
hammertime.on("swipeleft", onSwipe);
hammertime.on("swiperight", onSwipe);
hammertime.on("tap", onTap);
hammertime.on("pinchin", onPinch);
hammertime.on("pinchout", onPinch);
return hammertime;
};
this.initialize = function () {
reader.on(ReadiumSDK.Events.CONTENT_DOCUMENT_LOADED, function (iframe) {
// set hammer's document root
setupHammer(iframe[0].contentDocument.documentElement);
});
// remove stupid ipad safari elastic scrolling (improves UX for gestures)
$(viewport).on(
'touchmove',
function (e) {
if (isGestureHandled()) {
e.preventDefault();
}
}
);
// handlers on viewport
setupHammer($(viewport)[0]);
};
};
return gesturesHandler;
});
/*jslint nomen: false*/ | agpl-3.0 |
boob-sbcm/3838438 | src/main/java/com/rapidminer/tools/att/AttributeDataSource.java | 12469 | /**
* Copyright (C) 2001-2017 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.tools.att;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Level;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Attributes;
import com.rapidminer.example.table.AttributeFactory;
import com.rapidminer.example.table.NominalMapping;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.LoggingHandler;
import com.rapidminer.tools.Ontology;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.XMLException;
/**
* Reference to source of an attribute, i.e. file, column number (token number). Statics methods of
* this class can be used to parse an attribute description file.
*
* @author Ingo Mierswa, Simon Fischer
*/
public class AttributeDataSource {
private File file;
private int column;
private Attribute attribute;
private String attributeType;
public AttributeDataSource(Attribute attribute, File file, int column, String attributeType) {
this.attribute = attribute;
this.file = file;
this.column = column;
this.attributeType = attributeType;
}
public void setAttribute(Attribute attribute) {
this.attribute = attribute;
}
public Attribute getAttribute() {
return attribute;
}
public int getColumn() {
return column;
}
public File getFile() {
return file;
}
public void setType(String type) {
this.attributeType = type;
}
public String getType() {
return attributeType;
}
public void setSource(File file, int column) {
this.file = file;
this.column = column;
}
public Element writeXML(Document document, File defaultSource) throws IOException {
Element attributeElement = document.createElement(attributeType);
attributeElement.setAttribute("name", attribute.getName());
if (!getFile().equals(defaultSource)) {
attributeElement.setAttribute("sourcefile", getFile().getAbsolutePath());
}
attributeElement.setAttribute("sourcecol", (getColumn() + 1) + "");
attributeElement.setAttribute("valuetype", Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(attribute.getValueType()));
if (!Ontology.ATTRIBUTE_BLOCK_TYPE.isA(attribute.getBlockType(), Ontology.SINGLE_VALUE)) {
attributeElement.setAttribute("blocktype", Ontology.ATTRIBUTE_BLOCK_TYPE.mapIndex(attribute.getBlockType()));
}
if ((Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), Ontology.NOMINAL))
&& (!attributeType.equals(Attributes.KNOWN_ATTRIBUTE_TYPES[Attributes.TYPE_ID]))) {
Iterator<String> i = attribute.getMapping().getValues().iterator();
while (i.hasNext()) {
Element valueElement = document.createElement("value");
valueElement.setTextContent(i.next());
attributeElement.appendChild(valueElement);
}
}
return attributeElement;
}
/** Returns a list of {@link AttributeDataSource}s read from the file. */
public static AttributeDataSources createAttributeDataSources(File attributeDescriptionFile, boolean sourceColRequired,
LoggingHandler logging) throws XMLException, ParserConfigurationException, SAXException, IOException {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(attributeDescriptionFile);
Element attributeSet = document.getDocumentElement();
if (!attributeSet.getTagName().equals("attributeset")) {
throw new XMLException("Outer tag of attribute description file must be <attributeset>");
}
File defaultSource = null;
if (attributeSet.getAttribute("default_source") != null) {
defaultSource = Tools.getFile(attributeDescriptionFile.getParentFile(),
attributeSet.getAttribute("default_source"));
}
Charset encoding = null;
if (attributeSet.getAttribute("encoding") != null) {
try {
encoding = Charset.forName(attributeSet.getAttribute("encoding"));
} catch (IllegalCharsetNameException e) {
} catch (IllegalArgumentException e) {
}
}
// attributes
List<AttributeDataSource> attributeDataSources = new LinkedList<AttributeDataSource>();
NodeList attributes = attributeSet.getChildNodes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
if (node instanceof Element) {
Element attributeTag = (Element) node;
String type = attributeTag.getTagName();
String name = attributeTag.getAttribute("name");
String file = null;
Attr fileAttr = attributeTag.getAttributeNode("sourcefile");
if (fileAttr != null) {
file = fileAttr.getValue();
}
int firstSourceCol = -1;
Attr sourcecolAttr = attributeTag.getAttributeNode("sourcecol");
if (sourcecolAttr != null) {
if (sourcecolAttr.getValue().equals("none")) {
firstSourceCol = -1;
} else {
try {
firstSourceCol = Integer.parseInt(sourcecolAttr.getValue()) - 1;
} catch (NumberFormatException e) {
throw new XMLException("Attribute sourcecol must be 'none' or an integer (was: '"
+ sourcecolAttr.getValue() + "')!");
}
}
}
int lastSourceCol = -1;
Attr sourceEndAttr = attributeTag.getAttributeNode("sourcecol_end");
if (sourceEndAttr != null) {
try {
lastSourceCol = Integer.parseInt(sourceEndAttr.getValue()) - 1;
} catch (NumberFormatException e) {
throw new XMLException("Attribute sourcecol_end must be 'none' or an integer (was: '"
+ sourceEndAttr.getValue() + "')!");
}
}
int valueType = Ontology.VALUE_TYPE;
Attr valueTypeAttr = attributeTag.getAttributeNode("valuetype");
if (valueTypeAttr != null) {
try {
valueType = Integer.parseInt(valueTypeAttr.getValue());
} catch (NumberFormatException e) {
valueType = Ontology.ATTRIBUTE_VALUE_TYPE.mapName(valueTypeAttr.getValue());
if (valueType < 0) {
throw new XMLException("valuetype must be an index number or a legal value type name (was: '"
+ valueTypeAttr.getValue() + "')");
}
}
}
int blockType = Ontology.SINGLE_VALUE;
Attr blockTypeAttr = attributeTag.getAttributeNode("blocktype");
if (blockTypeAttr != null) {
try {
blockType = Integer.parseInt(blockTypeAttr.getValue());
} catch (NumberFormatException e) {
blockType = Ontology.ATTRIBUTE_BLOCK_TYPE.mapName(blockTypeAttr.getValue());
if (blockType < 0) {
throw new XMLException("blocktype must be an index number or a legal block type name (was: '"
+ blockTypeAttr.getValue() + "')");
}
}
}
List<String> classList = null;
if (Ontology.ATTRIBUTE_VALUE_TYPE.isA(valueType, Ontology.NOMINAL)) {
// nominal? check possible values...
classList = new LinkedList<String>();
// try inner tags <value>...</value>
NodeList values = attributeTag.getElementsByTagName("value");
for (int v = 0; v < values.getLength(); v++) {
Node value = values.item(v);
String valueText = value.getTextContent();
classList.add(valueText);
}
// if list is still empty try depreciated 'classes' attribute
Attr classesAttr = attributeTag.getAttributeNode("classes");
if (classesAttr != null) {
if (classList.size() == 0) {
StringTokenizer tokenizer = new StringTokenizer(classesAttr.getValue());
while (tokenizer.hasMoreTokens()) {
classList.add(tokenizer.nextToken());
}
} else {
logging.logWarning("XML attribute 'classes' ignored since possible values are already defined by inner <value>...</value> tags.");
}
}
if (classList.size() == 0) { // still empty class list? --> Warning
if (type.equals(Attributes.ID_NAME)) {
logging.logNote("The ID attribute '"
+ name
+ "' is defined with a nominal value type but the possible values are not defined! "
+ "Although this often does not lead to problems (unlike for labels or regular nominal attributes) you might want "
+ "to specify the possible values by inner tags <value>first</value><value>second</value>....");
} else if (type.equals(Attributes.LABEL_NAME)) {
logging.logError("The label attribute (class) '"
+ name
+ "' is defined with a nominal value type but the possible values are not defined! "
+ "Please specify the possible values by inner tags <value>first</value><value>second</value>.... "
+ "Otherwise it might happen that the same nominal values of two example sets are handled in different ways which might cause flipped predictions.");
} else {
logging.logWarning("At least one of the attributes is defined with a nominal value type but the possible values are not defined! "
+ "Please specify the possible values by inner tags <value>first</value><value>second</value>.... "
+ "Otherwise it might happen that the same nominal values of two example sets are handled in different ways which might cause less accurate models.");
}
}
}
if (lastSourceCol == -1) {
lastSourceCol = firstSourceCol;
}
if (sourceColRequired) {
if (firstSourceCol < 0) {
throw new XMLException("sourcecol not defined for " + type + " '" + name + "'!");
}
if (lastSourceCol < firstSourceCol) {
throw new XMLException("sourcecol < sourcecol_end must hold.");
}
}
for (int col = firstSourceCol; col <= lastSourceCol; col++) {
int thisBlockType = blockType;
String theName = name;
if (lastSourceCol > firstSourceCol) {
theName = name + "_" + (col + 1);
if (col == firstSourceCol && blockType == Ontology.VALUE_SERIES) {
thisBlockType = Ontology.VALUE_SERIES_START;
}
if (col == lastSourceCol && blockType == Ontology.VALUE_SERIES) {
thisBlockType = Ontology.VALUE_SERIES_END;
}
}
Attribute attribute = AttributeFactory.createAttribute(theName, valueType, thisBlockType);
if (attribute.isNominal() && classList != null) {
NominalMapping mapping = attribute.getMapping();
classList.forEach(mapping::mapString);
}
if (!attribute.isNominal() && classList != null && classList.size() != 0) {
// LogService.getGlobal().log("Ignoring classes for non-nominal attribute "
// + theName + ".", LogService.WARNING);
LogService.getRoot().log(Level.WARNING,
"com.rapidminer.tools.att.AttributeDataSource.ignoring_classes_for_non_nominal_attribute",
theName);
}
attributeDataSources.add(new AttributeDataSource(attribute, (file != null) ? Tools.getFile(
attributeDescriptionFile.getParentFile(), file) : defaultSource, col, type));
}
}
}
return new AttributeDataSources(attributeDataSources, defaultSource, encoding);
}
@Override
public String toString() {
return attribute.getName() + " (type: " + attributeType + ", value type: "
+ Ontology.VALUE_TYPE_NAMES[attribute.getValueType()] + ") from " + file.getName() + " (" + column + ")";
}
}
| agpl-3.0 |
sgRomaric/scheduling | rest/rest-smartproxy/src/test/java/functionaltests/RestSmartProxyTest.java | 17541 | /*
* ProActive Parallel Suite(TM):
* The Open Source library for parallel and distributed
* Workflows & Scheduling, Orchestration, Cloud Automation
* and Big Data Analysis on Enterprise Grids & Clouds.
*
* Copyright (c) 2007 - 2017 ActiveEon
* Contact: contact@activeeon.com
*
* This library 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: version 3 of
* the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*/
package functionaltests;
import static com.google.common.truth.Truth.assertThat;
import static functionaltests.RestFuncTHelper.getRestServerUrl;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import org.apache.commons.lang3.mutable.MutableBoolean;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.ow2.proactive.authentication.ConnectionInfo;
import org.ow2.proactive.scheduler.common.NotificationData;
import org.ow2.proactive.scheduler.common.SchedulerEvent;
import org.ow2.proactive.scheduler.common.exception.NotConnectedException;
import org.ow2.proactive.scheduler.common.exception.PermissionException;
import org.ow2.proactive.scheduler.common.exception.UnknownJobException;
import org.ow2.proactive.scheduler.common.exception.UserException;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.JobStatus;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.job.UserIdentification;
import org.ow2.proactive.scheduler.common.job.factories.Job2XMLTransformer;
import org.ow2.proactive.scheduler.common.task.ForkEnvironment;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.OnTaskError;
import org.ow2.proactive.scheduler.common.task.ScriptTask;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.dataspaces.InputAccessMode;
import org.ow2.proactive.scheduler.common.task.dataspaces.OutputAccessMode;
import org.ow2.proactive.scheduler.smartproxy.common.SchedulerEventListenerExtended;
import org.ow2.proactive.scripting.InvalidScriptException;
import org.ow2.proactive.scripting.SimpleScript;
import org.ow2.proactive.scripting.TaskScript;
import org.ow2.proactive_grid_cloud_portal.smartproxy.RestSmartProxyImpl;
import com.google.common.base.Throwables;
public final class RestSmartProxyTest extends AbstractRestFuncTestCase {
private static final long ONE_SECOND = TimeUnit.SECONDS.toMillis(1);
private static final long TEN_MINUTES = 600000; // in milliseconds
protected static int NB_TASKS = 4;
protected File inputLocalFolder;
protected File outputLocalFolder;
protected String userspace;
protected String pushUrl;
protected String pullUrl;
protected static final String TASK_NAME = "TestJavaTask";
// we add special characters to ensure they are supported
public final static String INPUT_FILE_BASE_NAME = "input é";
public final static String INPUT_FILE_EXT = ".txt";
public final static String OUTPUT_FILE_BASE_NAME = "output é";
public final static String OUTPUT_FILE_EXT = ".out";
protected RestSmartProxyImpl restSmartProxy;
@Rule
public TemporaryFolder tempDir = new TemporaryFolder();
@BeforeClass
public static void beforeClass() throws Exception {
init();
}
@Before
public void setup() throws Exception {
initializeRestSmartProxyInstance();
}
@After
public void teardown() throws Exception {
if (restSmartProxy != null) {
restSmartProxy.terminate();
}
}
private void initializeRestSmartProxyInstance() throws Exception {
restSmartProxy = new RestSmartProxyImpl();
restSmartProxy.cleanDatabase();
restSmartProxy.setSessionName(uniqueSessionId());
restSmartProxy.init(new ConnectionInfo(getRestServerUrl(), getLogin(), getPassword(), null, true));
userspace = restSmartProxy.getUserSpaceURIs().get(0);
pushUrl = userspace;
pullUrl = userspace;
// we add special characters and space to the folders to make sure
// transfer occurs normally
inputLocalFolder = tempDir.newFolder("input é");
outputLocalFolder = tempDir.newFolder("output é");
}
@Test(timeout = TEN_MINUTES)
public void testNoAutomaticTransfer() throws Exception {
testJobSubmission(false, false);
}
@Test(timeout = TEN_MINUTES)
public void testAutomaticTransfer() throws Exception {
testJobSubmission(false, true);
}
@Test(timeout = TEN_MINUTES)
public void testInErrorEventsReception() throws Exception {
TaskFlowJob job = createInErrorJob();
final Semaphore semaphore = new Semaphore(0);
printJobXmlRepresentation(job);
final MutableBoolean taskHasBeenInError = new MutableBoolean(false);
final MutableBoolean restartedFromErrorEventReceived = new MutableBoolean(false);
SchedulerEventListenerExtended listener = new SchedulerEventListenerExtended() {
@Override
public void schedulerStateUpdatedEvent(SchedulerEvent eventType) {
System.out.println("RestSmartProxyTest.schedulerStateUpdatedEvent " + eventType);
}
@Override
public void jobSubmittedEvent(JobState job) {
System.out.println("RestSmartProxyTest.jobSubmittedEvent");
}
@Override
public void jobStateUpdatedEvent(NotificationData<JobInfo> notification) {
JobStatus status = notification.getData().getStatus();
System.out.println("RestSmartProxyTest.jobStateUpdatedEvent, eventType=" + notification.getEventType() +
", jobStatus=" + status);
if (notification.getEventType() == SchedulerEvent.JOB_RESTARTED_FROM_ERROR) {
restartedFromErrorEventReceived.setTrue();
}
if (status == JobStatus.IN_ERROR) {
semaphore.release();
}
}
@Override
public void taskStateUpdatedEvent(NotificationData<TaskInfo> notification) {
TaskStatus status = notification.getData().getStatus();
System.out.println("RestSmartProxyTest.taskStateUpdatedEvent, taskStatus=" + status);
if (status == TaskStatus.WAITING_ON_ERROR || status == TaskStatus.IN_ERROR) { // IN_ERROR previously
taskHasBeenInError.setTrue();
}
}
@Override
public void usersUpdatedEvent(NotificationData<UserIdentification> notification) {
System.out.println("RestSmartProxyTest.usersUpdatedEvent " + notification.getData());
}
@Override
public void pullDataFinished(String jobId, String taskName, String localFolderPath) {
System.out.println("RestSmartProxyTest.pullDataFinished");
}
@Override
public void pullDataFailed(String jobId, String taskName, String remoteFolder_URL, Throwable t) {
System.out.println("RestSmartProxyTest.pullDataFailed");
}
@Override
public void jobUpdatedFullDataEvent(JobState job) {
System.out.println("RestSmartProxyTest.jobUpdatedFullDataEvent");
}
};
restSmartProxy.addEventListener(listener);
JobId jobId = restSmartProxy.submit(job,
inputLocalFolder.getAbsolutePath(),
pushUrl,
outputLocalFolder.getAbsolutePath(),
pullUrl,
false,
false);
// the next line blocks until jobStateUpdatedEvent is called on the
// listener
// with job status set to IN_ERROR
semaphore.acquire();
String jobIdAsString = jobId.value();
System.out.println("Restarting all In-Error tasks");
restSmartProxy.restartAllInErrorTasks(jobIdAsString);
assertThat(restartedFromErrorEventReceived.booleanValue()).isTrue();
assertThat(taskHasBeenInError.booleanValue()).isTrue();
}
private JobState waitForJobFinishState(String jobIdAsString)
throws InterruptedException, NotConnectedException, UnknownJobException, PermissionException {
JobState jobState = restSmartProxy.getJobState(jobIdAsString);
Thread.sleep(ONE_SECOND);
while (jobState.getStatus().isJobAlive()) {
jobState = restSmartProxy.getJobState(jobIdAsString);
Thread.sleep(ONE_SECOND);
}
return jobState;
}
private void printJobXmlRepresentation(TaskFlowJob job)
throws TransformerException, ParserConfigurationException, IOException {
// debugging the job produced
String jobXml = new Job2XMLTransformer().jobToxmlString(job);
System.out.println(jobXml);
}
private TaskFlowJob createInErrorJob() throws InvalidScriptException, UserException {
TaskFlowJob job = new TaskFlowJob();
job.setName("JobWithInErrorTask");
ScriptTask scriptTask = new ScriptTask();
scriptTask.setName("task");
scriptTask.setScript(new TaskScript(new SimpleScript("syntax error", "python")));
scriptTask.setOnTaskError(OnTaskError.PAUSE_TASK);
scriptTask.setMaxNumberOfExecution(2);
job.addTask(scriptTask);
job.setInputSpace(userspace);
job.setOutputSpace(userspace);
return job;
}
@Test
public void testTerminate() throws Exception {
restSmartProxy.terminate();
Assert.assertFalse(restSmartProxy.isConnected());
try {
restSmartProxy.getStatus();
fail("Using the restsmartproxy after termination should throw an exception");
} catch (Throwable t) {
} finally {
restSmartProxy = null;
}
}
@Test
public void testReconnection() throws Exception {
restSmartProxy.reconnect();
Assert.assertTrue(restSmartProxy.isConnected());
// try a random method and verify that no exception is thrown
restSmartProxy.getStatus();
restSmartProxy.disconnect();
Assert.assertFalse(restSmartProxy.isConnected());
}
private void testJobSubmission(boolean isolateTaskOutput, boolean automaticTransfer) throws Exception {
TaskFlowJob job = createTestJob(isolateTaskOutput);
printJobXmlRepresentation(job);
DataTransferNotifier notifier = new DataTransferNotifier();
if (automaticTransfer) {
restSmartProxy.addEventListener(notifier);
}
JobId id = restSmartProxy.submit(job,
inputLocalFolder.getAbsolutePath(),
pushUrl,
outputLocalFolder.getAbsolutePath(),
pullUrl,
isolateTaskOutput,
automaticTransfer);
JobState jobState = waitForJobFinishState(id.toString());
assertEquals(JobStatus.FINISHED, jobState.getStatus());
if (!automaticTransfer) {
for (int i = 0; i < NB_TASKS; i++) {
restSmartProxy.pullData(id.toString(), TASK_NAME + i, outputLocalFolder.getAbsolutePath());
}
} else {
List<String> taskNames = taskNameList();
while (!taskNames.isEmpty()) {
String finishedTask = notifier.finishedTask();
if (taskNames.contains(finishedTask)) {
taskNames.remove(finishedTask);
}
}
}
// check the presence of output files
for (int i = 0; i < NB_TASKS; i++) {
String outputFileName = OUTPUT_FILE_BASE_NAME + "_" + i + OUTPUT_FILE_EXT;
File outputFile = new File(outputLocalFolder, outputFileName);
Assert.assertTrue(String.format("%s does not exist.", outputFile.getAbsolutePath()), outputFile.exists());
}
}
private TaskFlowJob createTestJob(boolean isolateOutputs) throws Exception {
TaskFlowJob job = new TaskFlowJob();
// add a special character to the job name to ensure the job is parsed
// correctly by the server
job.setName(this.getClass().getSimpleName() + " é");
for (int i = 0; i < NB_TASKS; i++) {
JavaTask testTask = new JavaTask();
testTask.setName(TASK_NAME + i);
testTask.setExecutableClassName(SimpleJavaExecutable.class.getName());
testTask.setForkEnvironment(new ForkEnvironment());
File inputFile = new File(inputLocalFolder, INPUT_FILE_BASE_NAME + "_" + i + INPUT_FILE_EXT);
String outputFileName = OUTPUT_FILE_BASE_NAME + "_" + i + OUTPUT_FILE_EXT;
// delete files after the test is finished
File outputFile = new File(outputLocalFolder, outputFileName);
outputFile.deleteOnExit();
inputFile.deleteOnExit();
FileWriter fileWriter = new FileWriter(inputFile);
for (int j = 0; j <= Math.round(Math.random() * 100) + 1; j++) {
fileWriter.write("Some random input");
}
fileWriter.close();
// Add dummy input files, make sure no error happen
testTask.addInputFiles("DUMMY", InputAccessMode.TransferFromInputSpace);
testTask.addInputFiles(inputFile.getName(), InputAccessMode.TransferFromInputSpace);
if (isolateOutputs) {
testTask.addOutputFiles("*.out", OutputAccessMode.TransferToOutputSpace);
} else {
testTask.addOutputFiles(outputFileName, OutputAccessMode.TransferToOutputSpace);
}
job.addTask(testTask);
}
job.setInputSpace(userspace);
job.setOutputSpace(userspace);
return job;
}
private String uniqueSessionId() {
return String.format("TEST_SID_%s", Long.toHexString(System.currentTimeMillis()));
}
private List<String> taskNameList() {
List<String> taskNames = new ArrayList<>(NB_TASKS);
for (int i = 0; i < NB_TASKS; i++) {
taskNames.add(TASK_NAME + i);
}
return taskNames;
}
private static final class DataTransferNotifier implements SchedulerEventListenerExtended {
private final BlockingQueue<String> finishedTask = new ArrayBlockingQueue<>(NB_TASKS);
@Override
public void pullDataFailed(String jobId, String taskName, String localFolderPath, Throwable error) {
try {
finishedTask.put(taskName);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
@Override
public void pullDataFinished(String jobId, String taskName, String localFolderPath) {
try {
finishedTask.put(taskName);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
public String finishedTask() {
try {
return finishedTask.take();
} catch (InterruptedException e) {
throw Throwables.propagate(e);
}
}
@Override
public void jobStateUpdatedEvent(NotificationData<JobInfo> arg0) {
}
@Override
public void jobSubmittedEvent(JobState arg0) {
}
@Override
public void schedulerStateUpdatedEvent(SchedulerEvent arg0) {
}
@Override
public void taskStateUpdatedEvent(NotificationData<TaskInfo> arg0) {
}
@Override
public void usersUpdatedEvent(NotificationData<UserIdentification> arg0) {
}
@Override
public void jobUpdatedFullDataEvent(JobState job) {
}
}
}
| agpl-3.0 |
weiss19ja/amos-ss16-proj2 | backend/src/main/java/de/developgroup/mrf/server/handler/SingleDriverHandler.java | 1283 | /**
* This file is part of Mobile Robot Framework.
* Mobile Robot Framework is free software under the terms of GNU AFFERO GENERAL PUBLIC LICENSE.
*/
package de.developgroup.mrf.server.handler;
public interface SingleDriverHandler {
/**
* Acquires exclusive driver mode. There can only be one driver at a time so
* this method must check for existing drivers and notify all clients about
* the new (or old) driver.
*
* @param clientId
* that acquires the driver mode
* @return void
*/
void acquireDriver(int clientId);
/**
* release exclusive driver mode. All clients get notified about released
* driver mode. Another client might now control the rover (must call
* aquireDriver()).
*
* @param clientId
* that releases the driver mode
* @return void
*/
void releaseDriver(int clientId);
/**
* Gets called everytime a connection closes and verifies that driver is
* still available in websocket connection pool. When driver closes
* connection (i.e. close browser) the driver must be released.
*
* @return void
*/
void verifyDriverAvailability();
/**
* Get client id of the current driver
*
* @return current driver clientId
*/
int getCurrentDriverId();
void sendClientNotification();
}
| agpl-3.0 |
muhammadnadeem/diagnostic-feedback | diagnostic_feedback/helpers/__init__.py | 230 | from buzzfeed_choice import BuzzfeedChoice
from category import Category
from choice import Choice
from diagnostic_choice import DiagnosticChoice
from question import Question
from range import Range
from helper import MainHelper
| agpl-3.0 |
MuwuM/wiki | client/js/helpers/lodash.js | 1482 | 'use strict'
// ====================================
// Load minimal lodash
// ====================================
import cloneDeep from 'lodash/cloneDeep'
import concat from 'lodash/concat'
import debounce from 'lodash/debounce'
import deburr from 'lodash/deburr'
import delay from 'lodash/delay'
import filter from 'lodash/filter'
import find from 'lodash/find'
import findKey from 'lodash/findKey'
import forEach from 'lodash/forEach'
import includes from 'lodash/includes'
import isBoolean from 'lodash/isBoolean'
import isEmpty from 'lodash/isEmpty'
import isNil from 'lodash/isNil'
import join from 'lodash/join'
import kebabCase from 'lodash/kebabCase'
import last from 'lodash/last'
import map from 'lodash/map'
import nth from 'lodash/nth'
import pullAt from 'lodash/pullAt'
import reject from 'lodash/reject'
import slice from 'lodash/slice'
import split from 'lodash/split'
import startCase from 'lodash/startCase'
import startsWith from 'lodash/startsWith'
import toString from 'lodash/toString'
import toUpper from 'lodash/toUpper'
import trim from 'lodash/trim'
// ====================================
// Build lodash object
// ====================================
module.exports = {
deburr,
concat,
cloneDeep,
debounce,
delay,
filter,
find,
findKey,
forEach,
includes,
isBoolean,
isEmpty,
isNil,
join,
kebabCase,
last,
map,
nth,
pullAt,
reject,
slice,
split,
startCase,
startsWith,
toString,
toUpper,
trim
}
| agpl-3.0 |
N7-Consulting/Incipio | src/Service/Publish/SiajeEtudeImporter.php | 13281 | <?php
namespace App\Service\Publish;
use App\Entity\Personne\Employe;
use App\Entity\Personne\Membre;
use App\Entity\Personne\Personne;
use App\Entity\Personne\Prospect;
use App\Entity\Project\Ap;
use App\Entity\Project\Cc;
use App\Entity\Project\Etude;
use App\Entity\Project\GroupePhases;
use App\Entity\Project\Phase;
use App\Entity\Project\ProcesVerbal;
use Doctrine\ORM\EntityManager;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* Class SiajeImporter.
*/
class SiajeEtudeImporter extends CsvImporter implements FileImporterInterface
{
const EXPECTED_FORMAT = ['No Etude', 'Exercice comptable', 'Intitule', 'Statut', 'Domaine de compétence', 'Montant HT', 'Frais de dossier HT', 'Frais variables', 'Acompte', 'JEHs', 'Durée en semaine', 'Suiveur principal', 'Suiveur qualité', 'Contact', 'Email', 'Entreprise', 'Adresse', 'Code Postal', 'Ville', 'Provenance', 'Progression', 'Date d\'ajout', 'Date d\'édition', 'Date d\'envoi du devis', 'Date signature CC', 'Date signature PV', 'Date de cloturation', 'Date de mise en standby', 'Date de signature projetée', 'Date d\'avortement'];
//link between siaje string for state and our stateID integer. Slugified
const SIAJE_AVAILABLE_STATE = ['Contact initial' => 1, 'Devis envoye' => 1, 'En realisation' => 2, 'En attente de cloture' => 2, 'Stand-By' => 3, 'Cloturee' => 4, 'Avortee' => 5];
private $em;
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* @return array an array 2 fields :
* - file format, the expected file format
* - columns_format, expected columns in file
*/
public function expectedFormat()
{
return ['file_format' => 'csv', 'columns_format' => self::EXPECTED_FORMAT];
}
/**
* @param UploadedFile $file resources file contzaining data to import
*
* @return mixed Process Import.
* Process Import
*/
public function run(UploadedFile $file)
{
if ('txt' == $file->guessExtension()) {
//csv is seen as text/plain
$i = 1;
$inserted_projects = 0;
$inserted_prospects = 0;
if (false !== ($handle = fopen($file->getPathname(), 'r'))) {
$array_manager = []; //an array containing references to managers.
$array_prospect = []; //an array containing references to projects.
//iterate csv, row by row
while (false !== ($data = fgetcsv($handle, 0, ','))) {
if ($i > 1 && '' != $this->readArray($data, 'Intitule')) { //first row is column headers
$etude = $this->em->getRepository(Etude::class)->findOneByNom($this->readArray($data, 'Intitule'));
if (null === $etude) {
//create project if it doesn't exists in DB
$e = new Etude();
++$inserted_projects;
$e->setMandat($this->readArray($data, 'Exercice comptable'));
// $e->setNum($this->readArray($data, 'No Etude')); //untrusted, can be duplicated in siaje.
$e->setNom($this->readArray($data, 'Intitule'));
$e->setDescription($this->readArray($data, 'Domaine de compétence'));
$e->setDateCreation($this->dateManager($this->readArray($data, 'Date d\'ajout')));
if (array_key_exists($this->normalize($this->readArray($data, 'Statut')), self::SIAJE_AVAILABLE_STATE)) {
$e->setStateID(self::SIAJE_AVAILABLE_STATE[$this->normalize($this->readArray($data, 'Statut'))]);
} else {
$e->setStateID(self::SIAJE_AVAILABLE_STATE['Contact initial']);
}
$e->setAcompte(true);
if (null !== $this->readArray($data, 'Acompte')) {
$rate = explode(',', $this->readArray($data, 'Acompte')); //acompte is a percentage such as "30,00%".
$e->setPourcentageAcompte($rate['0'] / 100);
}
$e->setFraisDossier($this->readArray($data, 'Frais de dossier HT'));
$e->setPresentationProjet('Etude importée depuis Siaje');
$e->setDescriptionPrestation($this->readArray($data, 'Domaine de compétence'));
$e->setPourcentageAcompte($this->readArray($data, 'Acompte'));
$this->em->persist($e);
/* Prospect management */
// Check if a prospect with same already exists in database
if ('' !== $this->readArray($data, 'Entreprise', true)) {
$prospect = $this->em->getRepository(Prospect::class)->findOneByNom($this->readArray($data, 'Entreprise', true));
if (null === $prospect) {
//check if prospect already exist in local objects
if (array_key_exists($this->readArray($data, 'Entreprise', true), $array_prospect)) {
$prospect = $array_prospect[$this->readArray($data, 'Entreprise', true)];
}
}
} else {
$prospect = null;
}
if (null !== $prospect) {
$e->setProspect($prospect);
} else {
$p = new Prospect();
++$inserted_prospects;
if ('' !== $this->readArray($data, 'Entreprise', true)) {
$p->setNom($this->readArray($data, 'Entreprise', true));
} else {
$p->setNom('Prospect sans nom ' . rand());
}
$p->setAdresse($this->readArray($data, 'Adresse'));
$p->setCodePostal($this->readArray($data, 'Code Postal'));
$p->setVille($this->readArray($data, 'Ville'));
$contact = explode(' ', $this->normalize($this->readArray($data, 'Contact', true)));
$pe = new Personne();
$pe->setPrenom($contact[0]); //whitespace explode : not perfect but better than nothing
unset($contact[0]);
if ('' == implode(' ', $contact)) {
$pe->setNom('inconnu');
} else {
$pe->setNom(implode(' ', $contact));
}
$pe->setEmailEstValide(true);
$pe->setEstAbonneNewsletter(false);
$pe->setEmail($this->readArray($data, 'Email'));
$pe->setAdresse($this->readArray($data, 'Adresse'));
$pe->setCodePostal($this->readArray($data, 'Code Postal'));
$pe->setVille($this->readArray($data, 'Ville'));
$emp = new Employe();
$emp->setProspect($p);
$p->addEmploye($emp);
$emp->setPersonne($pe);
$this->em->persist($emp->getPersonne());
$this->em->persist($emp);
$this->em->persist($p);
$e->setProspect($p);
$array_prospect[$this->readArray($data, 'Entreprise', true)] = $p;
}
//create phases
$g = new GroupePhases(); //default group
$g->setTitre('Imported from Siaje');
$g->setNumero(1);
$g->setDescription('Automatic description');
$g->setEtude($e);
$this->em->persist($g);
$ph = new Phase();
$ph->setEtude($e);
$ph->setGroupe($g);
$ph->setPosition(0);
$ph->setNbrJEH($this->readArray($data, 'JEHs'));
if ($this->readArray($data, 'JEHs') > 0) {
$ph->setPrixJEH(round($this->floatManager($this->readArray($data, 'Montant HT')) / $this->floatManager($this->readArray($data, 'JEHs'))));
}
$ph->setTitre('Default phase');
$ph->setDelai($this->readArray($data, 'Durée en semaine') * 7);
$ph->setDateDebut($this->dateManager($this->readArray($data, 'Date signature CC')));
$this->em->persist($ph);
//manage project manager
$contact = explode(' ', $this->normalize($this->readArray($data, 'Suiveur principal', true)));
$firstname = $contact[0];
unset($contact[0]);
$surname = implode(' ', $contact);
$pm = $this->em->getRepository(Personne::class)->findOneBy(['nom' => $surname, 'prenom' => $firstname]);
if (null !== $pm) {
$e->setSuiveur($pm);
} else {
//create a new member and a new person
if (array_key_exists($this->readArray($data, 'Suiveur principal', true), $array_manager) && '' != $this->readArray($data, 'Suiveur principal', true)) {
//has already been created before
$e->setSuiveur($array_manager[$this->readArray($data, 'Suiveur principal', true)]);
} else {
$pm = new Personne();
$pm->setPrenom($firstname);
if ('' == $surname) {
$pm->setNom('inconnu');
} else {
$pm->setNom($surname);
}
$pm->setEmailEstValide(false);
$pm->setEstAbonneNewsletter(false);
$this->em->persist($pm);
$m = new Membre();
$m->setPersonne($pm);
$this->em->persist($m);
$e->setSuiveur($pm);
$array_manager[$this->readArray($data, 'Suiveur principal', true)] = $pm;
}
}
//manage AP & CC
if (null !== $this->dateManager($this->readArray($data, 'Date signature CC'))) {
$ap = new Ap();
$ap->setEtude($e);
$this->em->persist($ap);
$cc = new Cc();
$cc->setEtude($e);
$cc->setDateSignature($this->dateManager($this->readArray($data, 'Date signature CC')));
if (isset($pe)) {
//if firm has been created in this loop iteration
$cc->setSignataire2($pe);
}
$this->em->persist($cc);
}
//manage PVR
if (null !== $this->dateManager($this->readArray($data, 'Date signature PV'))) {
$pv = new ProcesVerbal();
$pv->setEtude($e);
$pv->setDateSignature($this->dateManager($this->readArray($data, 'Date signature PV')));
$this->em->persist($pv);
}
}
}
++$i;
}
fclose($handle);
$this->em->flush();
}
return ['inserted_projects' => $inserted_projects, 'inserted_prospects' => $inserted_prospects];
}
return ['inserted_projects' => 0, 'inserted_prospects' => 0];
}
}
| agpl-3.0 |
o2oa/o2oa | o2server/x_processplatform_assemble_bam/src/main/java/com/x/processplatform/assemble/bam/jaxrs/state/TimerOrganization.java | 9789 | package com.x.processplatform.assemble.bam.jaxrs.state;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import com.x.processplatform.assemble.bam.Business;
import com.x.processplatform.assemble.bam.ThisApplication;
import com.x.processplatform.assemble.bam.stub.PersonStub;
import com.x.processplatform.assemble.bam.stub.UnitStub;
import com.x.processplatform.core.entity.content.Task;
import com.x.processplatform.core.entity.content.TaskCompleted;
import com.x.processplatform.core.entity.content.TaskCompleted_;
import com.x.processplatform.core.entity.content.Task_;
public class TimerOrganization extends ActionBase {
public void execute(Business business) throws Exception {
ActionOrganization.Wo wo = new ActionOrganization.Wo();
Date start = this.getStart();
Date current = new Date();
wo.setUnit(this.unit(business, start, current));
wo.setPerson(this.person(business, start, current));
ThisApplication.state.setOrganization(wo);
}
private List<ActionOrganization.WoUnit> unit(Business business, Date start, Date current) throws Exception {
List<ActionOrganization.WoUnit> list = new ArrayList<>();
for (UnitStub stub : ThisApplication.state.getUnitStubs()) {
List<String> us = new ArrayList<>();
us.add(stub.getValue());
us.addAll(business.organization().unit().listWithUnitSubNested(stub.getValue()));
Long count = this.countWithUnit(business, start, us);
Long expiredCount = this.countExpiredWithUnit(business, start, current, us);
Long duration = this.durationWithUnit(business, start, current, us);
Long completedCount = this.countCompletedWithUnit(business, start, us);
Long completedExpiredCount = this.countExpiredCompletedWithUnit(business, start, us);
ActionOrganization.WoUnit wo = new ActionOrganization.WoUnit();
wo.setName(stub.getName());
wo.setValue(stub.getValue());
wo.setCount(count);
wo.setExpiredCount(expiredCount);
wo.setDuration(duration);
wo.setCompletedCount(completedCount);
wo.setCompletedExpiredCount(completedExpiredCount);
list.add(wo);
}
return list;
}
private Long countWithUnit(Business business, Date start, List<String> units) throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Task> root = cq.from(Task.class);
Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
p = cb.and(p, root.get(Task_.unit).in(units));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private Long countExpiredWithUnit(Business business, Date start, Date current, List<String> units)
throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Task> root = cq.from(Task.class);
Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
p = cb.and(p, cb.lessThan(root.get(Task_.expireTime), current));
p = cb.and(p, root.get(Task_.unit).in(units));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private Long durationWithUnit(Business business, Date start, Date current, List<String> units) throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Date> cq = cb.createQuery(Date.class);
Root<Task> root = cq.from(Task.class);
Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
p = cb.and(p, root.get(Task_.unit).in(units));
cq.select(root.get(Task_.startTime)).where(p);
List<Date> os = em.createQuery(cq).getResultList();
long duration = 0;
for (Date o : os) {
duration += current.getTime() - o.getTime();
}
/** 转化为分钟 */
duration = duration / (1000L * 60L);
return duration;
}
private Long countCompletedWithUnit(Business business, Date start, List<String> units) throws Exception {
EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<TaskCompleted> root = cq.from(TaskCompleted.class);
Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start);
p = cb.and(p, root.get(TaskCompleted_.unit).in(units));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private Long countExpiredCompletedWithUnit(Business business, Date start, List<String> units) throws Exception {
EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<TaskCompleted> root = cq.from(TaskCompleted.class);
Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start);
p = cb.and(p, root.get(TaskCompleted_.unit).in(units));
p = cb.and(p, cb.equal(root.get(TaskCompleted_.expired), true));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private List<ActionOrganization.WoPerson> person(Business business, Date start, Date current) throws Exception {
List<ActionOrganization.WoPerson> list = new ArrayList<>();
for (PersonStub stub : ThisApplication.state.getPersonStubs()) {
Long count = this.countWithPerson(business, start, stub.getValue());
Long expiredCount = this.countExpiredWithPerson(business, start, current, stub.getValue());
Long duration = this.durationWithPerson(business, start, current, stub.getValue());
Long completedCount = this.countCompletedWithPerson(business, start, stub.getValue());
Long completedExpiredCount = this.countExpiredCompletedWithPerson(business, start, stub.getValue());
ActionOrganization.WoPerson wo = new ActionOrganization.WoPerson();
wo.setName(stub.getName());
wo.setValue(stub.getValue());
wo.setCount(count);
wo.setExpiredCount(expiredCount);
wo.setDuration(duration);
wo.setCompletedCount(completedCount);
wo.setCompletedExpiredCount(completedExpiredCount);
list.add(wo);
}
list = list.stream().sorted(
Comparator.comparing(ActionOrganization.WoPerson::getCount, Comparator.nullsLast(Long::compareTo)))
.collect(Collectors.toList());
return list;
}
private Long countWithPerson(Business business, Date start, String person) throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Task> root = cq.from(Task.class);
Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
p = cb.and(p, cb.equal(root.get(Task_.person), person));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private Long countExpiredWithPerson(Business business, Date start, Date current, String person) throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<Task> root = cq.from(Task.class);
Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
p = cb.and(p, cb.equal(root.get(Task_.person), person));
p = cb.and(p, cb.lessThan(root.get(Task_.expireTime), current));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private Long durationWithPerson(Business business, Date start, Date current, String person) throws Exception {
EntityManager em = business.entityManagerContainer().get(Task.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Date> cq = cb.createQuery(Date.class);
Root<Task> root = cq.from(Task.class);
Predicate p = cb.greaterThan(root.get(Task_.startTime), start);
p = cb.and(p, cb.equal(root.get(Task_.person), person));
cq.select(root.get(Task_.startTime)).where(p);
List<Date> os = em.createQuery(cq).getResultList();
long duration = 0;
for (Date o : os) {
duration += current.getTime() - o.getTime();
}
duration = duration / (1000L * 60L);
return duration;
}
private Long countCompletedWithPerson(Business business, Date start, String person) throws Exception {
EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<TaskCompleted> root = cq.from(TaskCompleted.class);
Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start);
p = cb.and(p, cb.equal(root.get(TaskCompleted_.person), person));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
private Long countExpiredCompletedWithPerson(Business business, Date start, String person) throws Exception {
EntityManager em = business.entityManagerContainer().get(TaskCompleted.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<TaskCompleted> root = cq.from(TaskCompleted.class);
Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start);
p = cb.and(p, cb.equal(root.get(TaskCompleted_.person), person));
p = cb.and(p, cb.equal(root.get(TaskCompleted_.expired), true));
cq.select(cb.count(root)).where(p);
return em.createQuery(cq).getSingleResult();
}
} | agpl-3.0 |
Asqatasun/Asqatasun | rules/rules-rgaa2.2/src/main/java/org/asqatasun/rules/rgaa22/Rgaa22Rule05081.java | 1471 | /*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa22;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 5.8 of the referential RGAA 2.2.
* <br/>
* For more details about the implementation, refer to <a href="http://www.old-dot-org.org/en/content/rgaa22-rule-5-8">the rule 5.8 design page.</a>
* @see <a href="http://rgaa.net/Presence-d-une-description-audio,53.html"> 5.8 rule specification </a>
*
* @author jkowalczyk
*/
public class Rgaa22Rule05081 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa22Rule05081 () {
super();
}
}
| agpl-3.0 |
mapcentia/geocloud2 | public/js/heron/ux/oleditor/ole/client/lib/Editor/Control/Gc2Load.js | 1186 | OpenLayers.Editor.Control.Gc2Load = OpenLayers.Class(OpenLayers.Control.Button, {
layer: null,
initialize: function (layer, options) {
this.layer = layer;
OpenLayers.Control.Button.prototype.initialize.apply(this, [options]);
this.trigger = this.load;
this.title = OpenLayers.i18n('Load drawings from disk');
},
load: function () {
var wkt = new OpenLayers.Format.WKT(),
vLayer = this.layer,
get = function () {
$.get(host + "/controllers/drawing",
function (data, status) {
vLayer.addFeatures(wkt.read(data.data));
MapCentia.gc2.map.zoomToExtent(vLayer.getDataExtent(),false);
},
"json"
);
};
if (vLayer.features.length > 0) {
if (confirm("Are you sure? Any unsaved drawings will be lost!")) {
vLayer.destroyFeatures();
get();
} else {
return false;
}
} else {
get();
}
},
CLASS_NAME: 'OpenLayers.Editor.Control.Gc2Load'
}); | agpl-3.0 |
bantolov/Rhetos | CommonConcepts/Plugins/Rhetos.Dom.DefaultConcepts/Persistence/EntityFrameworkGenerateMetadataFiles.cs | 6204 | /*
Copyright (C) 2014 Omega software d.o.o.
This file is part of Rhetos.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using Rhetos.Extensibility;
using Rhetos.Logging;
using Rhetos.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
namespace Rhetos.Dom.DefaultConcepts.Persistence
{
/// <summary>
/// The generated EntityFrameworkContext will work with or without these metadata files,
/// but context initialization is faster when loading metadata from the pregenerated files.
/// </summary>
[Export(typeof(IGenerator))]
public class EntityFrameworkGenerateMetadataFiles : IGenerator
{
private readonly ILogger _performanceLogger;
private readonly IDomainObjectModel _dom;
private readonly ConnectionString _connectionString;
private readonly GeneratedFilesCache _cache;
private readonly IConfiguration _configuration;
public EntityFrameworkGenerateMetadataFiles(
ILogProvider logProvider,
IDomainObjectModel dom,
ConnectionString connectionString,
GeneratedFilesCache cache,
IConfiguration configuration)
{
_performanceLogger = logProvider.GetLogger("Performance");
_dom = dom;
_connectionString = connectionString;
_cache = cache;
_configuration = configuration;
}
public IEnumerable<string> Dependencies
{
get { return null; }
}
public void Generate()
{
var sw = Stopwatch.StartNew();
byte[] sourceHash = GetOrmHash();
string sampleEdmFile = Path.Combine(Paths.GeneratedFolder, EntityFrameworkMetadata.SegmentsFromCode.First().FileName);
var edmExtensions = EntityFrameworkMetadata.SegmentsFromCode.Select(s => Path.GetExtension(s.FileName));
if (_cache.RestoreCachedFiles(sampleEdmFile, sourceHash, Paths.GeneratedFolder, edmExtensions) != null)
{
_performanceLogger.Write(sw, "EntityFrameworkMetadata: Restore cached EDM files.");
}
else
{
var connection = new SqlConnection(_connectionString);
var dbConfiguration = (DbConfiguration)_dom.GetType("Common.EntityFrameworkConfiguration")
.GetConstructor(new Type[] { })
.Invoke(new object[] { });
var dbContext = (DbContext)_dom.GetType("Common.EntityFrameworkContext")
.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(DbConnection), dbConfiguration.GetType(), typeof(IConfiguration) }, null)
.Invoke(new object[] { connection, dbConfiguration, _configuration });
string edmx;
using (var stringWriter = new StringWriter())
using (var xmlWriter = new XmlTextWriter(stringWriter))
{
xmlWriter.Formatting = System.Xml.Formatting.Indented;
EdmxWriter.WriteEdmx(dbContext, xmlWriter);
edmx = stringWriter.ToString();
}
_performanceLogger.Write(sw, "EntityFrameworkMetadata: Extract EDMX.");
foreach (var segment in EntityFrameworkMetadata.SegmentsFromCode)
{
string startTag = "\r\n <" + segment.TagName + ">\r\n";
string endTag = "\r\n </" + segment.TagName + ">\r\n";
int start = edmx.IndexOf(startTag, StringComparison.Ordinal);
int end = edmx.IndexOf(endTag, StringComparison.Ordinal);
int alternativeStart = edmx.IndexOf(startTag, start + 1, StringComparison.Ordinal);
int alternativeEnd = edmx.IndexOf(endTag, end + 1, StringComparison.Ordinal);
if (start == -1 || alternativeStart != -1 || end == -1 || alternativeEnd != -1)
throw new Exception("Unexpected EDMX format. " + segment.TagName + " tag locations: start=" + start + " alternativeStart=" + alternativeStart + " end=" + end + " alternativeEnd=" + alternativeEnd + ".");
string segmentXml = edmx.Substring(start + startTag.Length, end - start - startTag.Length);
File.WriteAllText(Path.Combine(Paths.GeneratedFolder, segment.FileName), segmentXml, Encoding.UTF8);
}
_performanceLogger.Write(sw, "EntityFrameworkMetadata: Save EDM files.");
}
_cache.SaveHash(sampleEdmFile, sourceHash);
}
private byte[] GetOrmHash()
{
var hashes = new[]
{
_cache.LoadHash(Paths.GetDomAssemblyFile(DomAssemblies.Model)),
_cache.LoadHash(Paths.GetDomAssemblyFile(DomAssemblies.Orm)),
// TODO: Add DatabaseGenerator hash for new created ConceptApplications.
_cache.GetHash(MsSqlUtility.GetProviderManifestToken())
};
return _cache.JoinHashes(hashes);
}
}
}
| agpl-3.0 |
grafana/grafana | public/app/plugins/datasource/prometheus/configuration/AzureAuthSettings.tsx | 1953 | import React, { FunctionComponent, useMemo } from 'react';
import { InlineFormLabel, Input } from '@grafana/ui';
import { config } from '@grafana/runtime';
import { KnownAzureClouds, AzureCredentials } from './AzureCredentials';
import { getCredentials, updateCredentials } from './AzureCredentialsConfig';
import { AzureCredentialsForm } from './AzureCredentialsForm';
import { HttpSettingsBaseProps } from '@grafana/ui/src/components/DataSourceSettings/types';
export const AzureAuthSettings: FunctionComponent<HttpSettingsBaseProps> = (props: HttpSettingsBaseProps) => {
const { dataSourceConfig, onChange } = props;
const credentials = useMemo(() => getCredentials(dataSourceConfig), [dataSourceConfig]);
const onCredentialsChange = (credentials: AzureCredentials): void => {
onChange(updateCredentials(dataSourceConfig, credentials));
};
return (
<>
<h6>Azure Authentication</h6>
<AzureCredentialsForm
managedIdentityEnabled={config.azure.managedIdentityEnabled}
credentials={credentials}
azureCloudOptions={KnownAzureClouds}
onCredentialsChange={onCredentialsChange}
/>
<h6>Azure Configuration</h6>
<div className="gf-form-group">
<div className="gf-form-inline">
<div className="gf-form">
<InlineFormLabel className="width-12">AAD resource ID</InlineFormLabel>
<div className="width-15">
<Input
className="width-30"
value={dataSourceConfig.jsonData.azureEndpointResourceId || ''}
onChange={(event) =>
onChange({
...dataSourceConfig,
jsonData: { ...dataSourceConfig.jsonData, azureEndpointResourceId: event.currentTarget.value },
})
}
/>
</div>
</div>
</div>
</div>
</>
);
};
export default AzureAuthSettings;
| agpl-3.0 |
floored1585/pixel | lib/instance.rb | 5178 | #
# Pixel is an open source network monitoring system
# Copyright (C) 2016 all Pixel contributors!
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# instance.rb
#
require 'logger'
require 'json'
require 'digest/md5'
require 'ipaddr'
$LOG ||= Logger.new(STDOUT)
class Instance
def self.fetch(hostname: nil)
resource = '/v2/instance'
params = "?hostname=#{hostname}" if hostname
params ||= ''
result = API.get(
src: 'instance',
dst: 'core',
resource: "#{resource}#{params}",
what: 'instances',
)
result.each do |object|
unless object.is_a?(Instance)
raise "Received bad object in Instance.fetch"
return []
end
end
return result
end
def self.get_master
instance = API.get(
src: 'instance',
dst: 'core',
resource: '/v2/instance/get_master',
what: 'master instance'
).first
return nil unless instance.class == Instance
return instance
end
def self.fetch_from_db(db:, hostname: nil, master: nil, poller: nil)
instances = []
instance = db[:instance]
instance = instance.where(:hostname => hostname) if hostname
instance = instance.where(:master => true) if master
instance = instance.where(:poller => true) if poller
instance.each do |row|
instances.push Instance.new(
hostname: row[:hostname],
ip: row[:ip],
last_updated: row[:last_updated],
core: row[:core],
master: row[:master],
poller: row[:poller],
config_hash: row[:config_hash]
)
end
return instances
end
def self.delete(db:, hostname:)
DB[:instance].where(:hostname => hostname).delete
end
def initialize(hostname: nil, ip: nil, last_updated: nil, core: nil,
master: nil, poller: nil, config_hash: nil)
@hostname = hostname
@ip = IPAddr.new(ip) if ip
@core = core
@master = master
@poller = poller
@config_hash = config_hash
@last_updated = last_updated
end
def hostname
@hostname.to_s
end
def ip
@ip || IPAddr.new
end
def core?
!!@core
end
def master?
!!@master
end
def set_master(value)
@master = value
end
def poller?
!!@poller
end
def config_hash
@config_hash.to_s
end
def update!(config:)
new_hostname = Socket.gethostname
new_ip = IPAddr.new(UDPSocket.open {|s| s.connect("8.8.8.8", 1); s.addr.last})
new_config_hash = config.hash
@hostname = new_hostname
@ip = new_ip
@core = true if @core.nil?
@master = false if @master.nil?
@poller = false if @poller.nil?
@config_hash = new_config_hash
@last_updated = Time.now.to_i
return self
end
def save(db)
begin
data = {}
data[:hostname] = @hostname
data[:ip] = @ip ? @ip.to_s : nil
data[:core] = @core
data[:master] = @master
data[:poller] = @poller
data[:config_hash] = @config_hash
data[:last_updated] = @last_updated
existing = db[:instance].where(:hostname => @hostname)
if existing.update(data) != 1
db[:instance].insert(data)
end
rescue Sequel::NotNullConstraintViolation, Sequel::ForeignKeyConstraintViolation => e
$LOG.error("INSTANCE: Save failed. #{e.to_s.gsub(/\n/,'. ')}")
return nil
end
return self
end
def send
start = Time.now.to_i
if API.post(
src: 'instance',
dst: 'core',
resource: '/v2/instance',
what: "instance #{@hostname}",
data: to_json
)
elapsed = Time.now.to_i - start
$LOG.info("INSTANCE: POST successful for #{@hostname} (#{elapsed} seconds)")
return true
else
$LOG.error("INSTANCE: POST failed for #{@hostname}; Aborting")
return false
end
end
def to_json(*a)
hash = {
"json_class" => self.class.name,
"data" => {}
}
hash['data']['hostname'] = @hostname
hash['data']['ip'] = @ip
hash['data']['core'] = @core
hash['data']['master'] = @master
hash['data']['poller'] = @poller
hash['data']['config_hash'] = @config_hash
hash['data']['last_updated'] = @last_updated
hash.to_json(*a)
end
def self.json_create(json)
data = json['data']
return Instance.new(
hostname: data['hostname'],
ip: data['ip'],
core: data['core'],
master: data['master'],
poller: data['poller'],
config_hash: data['config_hash'],
last_updated: data['last_updated']
)
end
private # All methods below are private!!
end
| agpl-3.0 |
nlv/suitecrm | modules/Employees/language/ru_ru.lang.php | 9828 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
// Replaced by RAPIRA -->
********************************************************************************/
/*********************************************************************************
*
* This file was generated by the RAPIRA Translation Suite ----------
*
***********************************************************************likhobory*/
/*********************************************************************************
* Description : Defines the Russian language pack for the base application.
* Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights Reserved.
* Contributor(s):
*********************************************************************************/
// Replaced by RAPIRA <--
$mod_strings = array (
'LBL_MODULE_NAME' => 'Сотрудники' ,
'LBL_MODULE_TITLE' => 'Сотрудники - ГЛАВНАЯ' ,
'LBL_SEARCH_FORM_TITLE' => 'Поиск сотрудника' ,
'LBL_LIST_FORM_TITLE' => 'Сотрудники' ,
'LBL_NEW_FORM_TITLE' => 'Новый сотрудник' ,
'LBL_EMPLOYEE' => 'Сотрудники:' ,
'LBL_LOGIN' => 'Вход' ,
'LBL_RESET_PREFERENCES' => 'Установить стандартные значения' ,
'LBL_TIME_FORMAT' => 'Формат времени:' ,
'LBL_DATE_FORMAT' => 'Формат даты:' ,
'LBL_TIMEZONE' => 'Текущее время:' ,
'LBL_CURRENCY' => 'Валюта:' ,
'LBL_LIST_NAME' => 'ФИО' ,
'LBL_LIST_LAST_NAME' => 'Фамилия' ,
'LBL_LIST_EMPLOYEE_NAME' => 'ФИО сотрудника' ,
'LBL_LIST_DEPARTMENT' => 'Отдел' ,
'LBL_LIST_REPORTS_TO_NAME' => 'Руководитель' ,
'LBL_LIST_EMAIL' => 'E-mail' ,
'LBL_LIST_PRIMARY_PHONE' => 'Основной тел.' ,
'LBL_LIST_USER_NAME' => 'Логин' ,
'LBL_LIST_ADMIN' => 'Администрирование' ,
'LBL_NEW_EMPLOYEE_BUTTON_TITLE' => 'Новый сотрудник' ,
'LBL_NEW_EMPLOYEE_BUTTON_LABEL' => 'Новый сотрудник' ,
'LBL_NEW_EMPLOYEE_BUTTON_KEY' => 'N' ,
'LBL_ERROR' => 'Ошибка:' ,
'LBL_PASSWORD' => 'Пароль:' ,
'LBL_EMPLOYEE_NAME' => 'ФИО сотрудника:' ,
'LBL_USER_NAME' => 'Логин:' ,
'LBL_USER_TYPE' => 'Тип пользователя',
'LBL_FIRST_NAME' => 'Имя:' ,
'LBL_LAST_NAME' => 'Фамилия:' ,
'LBL_EMPLOYEE_SETTINGS' => 'Настройки сотрудника' ,
'LBL_THEME' => 'Тема:' ,
'LBL_LANGUAGE' => 'Язык:' ,
'LBL_ADMIN' => 'Администратор:' ,
'LBL_EMPLOYEE_INFORMATION' => 'Информация о сотруднике' ,
'LBL_OFFICE_PHONE' => 'Тел. (раб.):' ,
'LBL_REPORTS_TO' => 'Руководитель (ID):',
'LBL_REPORTS_TO_NAME' => 'Руководитель:',
'LBL_OTHER_PHONE' => 'Другое:' ,
'LBL_OTHER_EMAIL' => 'Другой E-mail:' ,
'LBL_NOTES' => 'Заметки:' ,
'LBL_DEPARTMENT' => 'Отдел:' ,
'LBL_TITLE' => 'Должность:' ,
'LBL_ANY_ADDRESS' => 'Любой адрес:',
'LBL_ANY_PHONE' => 'Любой тел.:' ,
'LBL_ANY_EMAIL' => 'Любой E-mail:' ,
'LBL_ADDRESS' => 'Адрес:' ,
'LBL_CITY' => 'Город:' ,
'LBL_STATE' => 'Область:' ,
'LBL_POSTAL_CODE' => 'Индекс:' ,
'LBL_COUNTRY' => 'Страна:' ,
'LBL_NAME' => 'ФИО:' ,
'LBL_MOBILE_PHONE' => 'Тел. (моб.):' ,
'LBL_OTHER' => 'Другое:' ,
'LBL_FAX' => 'Факс:' ,
'LBL_EMAIL' => 'E-mail:' ,
'LBL_EMAIL_LINK_TYPE'=> 'Почтовый клиент',
'LBL_EMAIL_LINK_TYPE_HELP'=> '<b>Почтовый клиент SuiteCRM</b> - отправка электронных писем при помощи встроенного в SuiteCRM почтового клиента.<br><b>Внешний почтовый клиент</b> - любой другой почтовый клиент, например Microsoft Outlook.',
'LBL_HOME_PHONE' => 'Тел. (дом.):' ,
'LBL_WORK_PHONE' => 'Тел. (раб.):',
'LBL_ADDRESS_INFORMATION' => 'Адресная информация' ,
'LBL_EMPLOYEE_STATUS' => 'Статус сотрудника:' ,
'LBL_PRIMARY_ADDRESS' => 'Основной адрес:' ,
'LBL_SAVED_SEARCH' => 'Параметры макета',
'LBL_CREATE_USER_BUTTON_TITLE' => 'Создать пользователя' ,
'LBL_CREATE_USER_BUTTON_LABEL' => 'Создать пользователя' ,
'LBL_CREATE_USER_BUTTON_KEY' => 'N' ,
'LBL_FAVORITE_COLOR' => 'Любимый цвет:' ,
'LBL_MESSENGER_ID' => 'IM - имя / E-mail:' ,
'LBL_MESSENGER_TYPE' => 'IM-тип:' ,
'ERR_EMPLOYEE_NAME_EXISTS_1' => 'Имя сотрудника ' ,
'ERR_EMPLOYEE_NAME_EXISTS_2' => ' уже существует. Дублирование имён сотрудников не допускается. Измените имя сотрудника, чтобы оно стало уникальным.' ,
'ERR_LAST_ADMIN_1' => 'Имя сотрудника \"' ,
'ERR_LAST_ADMIN_2' => '\" последний сотрудник с правами администратора. По крайней мере один сотрудник должен быть администратором.' ,
'LNK_NEW_EMPLOYEE' => 'Создать сотрудника' ,
'LNK_EMPLOYEE_LIST' => 'Сотрудники' ,
'ERR_DELETE_RECORD' => 'Перед удалением вы должны указать запись.',
'LBL_LIST_EMPLOYEE_STATUS' => 'Статус сотрудника',
'LBL_SUGAR_LOGIN' => 'Пользователь системы',
'LBL_RECEIVE_NOTIFICATIONS' => 'Уведомлять при назначении',
'LBL_IS_ADMIN' => 'Администратор',
'LBL_GROUP' => 'Групповой пользователь',
'LBL_PORTAL_ONLY'=> 'Пользователь портала',
'LBL_PHOTO'=> 'Фото',
'LBL_DELETE_USER_CONFIRM' => 'Этот сотрудник также является пользователем системы. Удаление данного сотрудника приведёт к удалению соответствующей записи о пользователе системы; удалённый пользователь не будет иметь доступ к системе. Хотите продолжить удаление?',
'LBL_DELETE_EMPLOYEE_CONFIRM' => 'Вы действительно хотите удалить данного сотрудника?',
'LBL_ONLY_ACTIVE' => 'Активные сотрудники',
'LBL_SELECT' => 'Обзор' /*for 508 compliance fix*/,
'LBL_FF_CLEAR' => 'Очистить' /*for 508 compliance fix*/,
'LBL_AUTHENTICATE_ID' => 'ID аутентификации',
'LBL_EXT_AUTHENTICATE' => 'Внешняя аутентификация',
'LBL_GROUP_USER' => 'Групповой пользователь',
'LBL_LIST_ACCEPT_STATUS' => 'Статус',
'LBL_MODIFIED_BY' =>'Изменено',
'LBL_MODIFIED_BY_ID' =>'Изменено(ID)',
'LBL_CREATED_BY_NAME' => 'Создано', //bug48978
'LBL_PORTAL_ONLY_USER' => 'Portal API User', ///
'LBL_PSW_MODIFIED' => 'Последнее изменение пароля',
'LBL_SHOW_ON_EMPLOYEES' => 'Display Employee Record', ///
'LBL_USER_HASH' => 'Пароль',
'LBL_SYSTEM_GENERATED_PASSWORD' =>'Автоматически сгенерированный пароль',
'LBL_DESCRIPTION'=> 'Описание',
'LBL_FAX_PHONE'=> 'Факс',
'LBL_FAX'=> 'Факс',
'LBL_STATUS'=> 'Статус',
'LBL_ADDRESS_CITY'=> 'Адрес - город',
'LBL_ADDRESS_COUNTRY'=> 'Адрес - страна',
'LBL_ADDRESS_INFORMATION'=> 'Адресные данные',
'LBL_ADDRESS_POSTALCODE'=> 'Индекс',
'LBL_ADDRESS_STATE'=> 'Адрес - область',
'LBL_ADDRESS_STREET'=> 'Адрес - улица',
'LBL_ADDRESS'=> 'Адрес',
'LBL_DATE_MODIFIED' => 'Дата изменения',
'LBL_DATE_ENTERED' => 'Дата создания',
'LBL_DELETED' => 'Удалено',
);
?>
| agpl-3.0 |
opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/geometry/impl/BoundsImpl.java | 3673 | /**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.geometry.impl;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import org.bimserver.emf.IdEObjectImpl;
import org.bimserver.models.geometry.Bounds;
import org.bimserver.models.geometry.GeometryPackage;
import org.bimserver.models.geometry.Vector3f;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Bounds</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.bimserver.models.geometry.impl.BoundsImpl#getMin <em>Min</em>}</li>
* <li>{@link org.bimserver.models.geometry.impl.BoundsImpl#getMax <em>Max</em>}</li>
* </ul>
*
* @generated
*/
public class BoundsImpl extends IdEObjectImpl implements Bounds {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected BoundsImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GeometryPackage.Literals.BOUNDS;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected int eStaticFeatureCount() {
return 0;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Vector3f getMin() {
return (Vector3f) eGet(GeometryPackage.Literals.BOUNDS__MIN, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setMin(Vector3f newMin) {
eSet(GeometryPackage.Literals.BOUNDS__MIN, newMin);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Vector3f getMax() {
return (Vector3f) eGet(GeometryPackage.Literals.BOUNDS__MAX, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setMax(Vector3f newMax) {
eSet(GeometryPackage.Literals.BOUNDS__MAX, newMax);
}
} //BoundsImpl
| agpl-3.0 |
PaloAlto/jbilling | test/unit/com/sapienter/jbilling/server/process/task/SftpUploadTaskTest.java | 2381 | package com.sapienter.jbilling.server.process.task;
import com.sapienter.jbilling.common.Util;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskDTO;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskParameterDTO;
import com.sapienter.jbilling.server.pluggableTask.admin.PluggableTaskTypeDTO;
import junit.framework.TestCase;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author Brian Cowdery
* @since 08-06-2010
*/
public class SftpUploadTaskTest extends TestCase {
private static final String BASE_DIR = Util.getSysProp("base_dir");
// class under test
private SftpUploadTask task = new SftpUploadTask();
public SftpUploadTaskTest() {
}
public SftpUploadTaskTest(String name) {
super(name);
}
@Override
protected void setUp() throws Exception {
super.setUp();
// todo: fill in when running testSftpUpload()
List<PluggableTaskParameterDTO> parameters = new ArrayList<PluggableTaskParameterDTO>();
parameters.add(_mockParameter(SftpUploadTask.PARAM_SFTP_USERNAME, ""));
parameters.add(_mockParameter(SftpUploadTask.PARAM_SFTP_PASSWORD, ""));
parameters.add(_mockParameter(SftpUploadTask.PARAM_SFTP_HOST, ""));
parameters.add(_mockParameter(SftpUploadTask.PARAM_SFTP_REMOTE_PATH, ""));
PluggableTaskDTO dto = new PluggableTaskDTO();
dto.setEntityId(1);
dto.setParameters(parameters);
PluggableTaskTypeDTO type = new PluggableTaskTypeDTO();
type.setMinParameters(0);
dto.setType(type);
task.initializeParamters(dto);
}
private PluggableTaskParameterDTO _mockParameter(String name, String value) {
PluggableTaskParameterDTO parameter = new PluggableTaskParameterDTO();
parameter.setName(name);
parameter.setStrValue(value);
return parameter;
}
/**
* Placeholder test, uncomment testSftpUpload() to test upload against a real server.
*/
public void testNoop() {
assertTrue(true);
}
/*
public void testSftpUpload() throws Exception {
File path = new File(BASE_DIR);
List<File> files = task.collectFiles(path, ".*entity-1\\.jpg$", true);
assertEquals(1, files.size());
task.upload(files);
}
*/
} | agpl-3.0 |
sybreon/inorout | controllers/users_controller.php | 4722 | <?php
/**
INOROUT - Social Discussion Platform.
Copyright (C) 2010 Shawn Tan <shawn.tan@sybreon.com>
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public
License along with this program. If not, see
<http://www.gnu.org/licenses/>.
*/
//App::import('Core', 'HttpSocket');
//App::import('Sanitize');
App::import('Vendor','openid'); // Import LightOpenID library
class UsersController extends AppController {
var $name = 'Users';
var $components = array('RequestHandler');
var $helpers = array ('Form','Html','Ajax','Javascript','Time','Text','Paginator');
/**
Launch OpenID request.
*/
protected function requestID($url = null) {
// openid form login
$openid = new LightOpenID;
$openid->identity = $url;
$openid->required = array('contact/email','namePerson/friendly');
//$openid->optional = array('namePerson/friendly');
$this->redirect($openid->authUrl());
}
/**
Authenticate OpenID response.
*/
public function auth($param = null) {
if (!isset($this->params['url']['openid_mode'])) {
// do OpenID
switch ($this->data['User']['url']) {
case 'g': $this->requestID('http://www.google.com/accounts/o8/id'); break;
case 'y': $this->requestID('http://me.yahoo.com'); break;
case 'w': $this->requestID('http://wordpress.com'); break;
case 'm': $this->requestID('http://myopenid.com'); break;
}
} elseif ($this->params['url']['openid_mode'] == 'cancel') {
// openid cancel
$this->Session->setFlash('Authentication canceled!');
$this->redirect(array('controller' => 'users', 'action' => 'login', $param));
} else { //($this->params['url']['openid_mode'] == 'id_res') {
// openid callback
$openid = new LightOpenID;
if ($openid->validate()) {
// valid OpenID reply
$attr = $openid->getAttributes(); // extract attributes
$mail = (isset($attr['contact/email'])) ? md5(strtolower(trim($attr['contact/email']))) : '';
$nama = (isset($attr['namePerson/friendly'])) ? $attr['namePerson/friendly'] : preg_replace('/^([^@]+)(@.*)$/', '$1', $attr['contact/email']);
$oid = md5(trim($openid->identity)); // hash the id returned
// find the user based on claimed_id
if (($tmp = $this->User->findByOid($oid)) == false) {
// create user
$tmp['User']['oid'] = $oid;
$tmp['User']['mail'] = $mail;
$tmp['User']['nama'] = $nama;
$this->User->create();
$this->User->save($tmp);
$this->Session->setFlash('Welcome to In/Out user #'. $this->User->id .'!');
// TODO: redirect to n00b page.
} else {
// update user
$this->User->id = $tmp['User']['id'];
$this->User->saveField('mail',$mail);
$this->User->saveField('nama',$nama);
$this->Session->setFlash('Welcome back user #'. $this->User->id .'!');
}
// save to session
$this->Session->write('User.mail', $mail);
$this->Session->write('User.nama', $nama);
$this->Session->write('User.oid', $oid);
$this->Session->write('User.id', $this->User->id);
// redirect to source/default
$url = ($this->Session->check('Session.referer')) ? $this->Session->read('Session.referer') : array('controller' => 'posts', 'action' => 'index');
$this->redirect($url);
} else {
$this->Session->setFlash('Authentication failed!');
$this->redirect(array('controller' => 'users', 'action' => 'login', $param));
}
}
}
/*
Destroy session.
*/
public function logout() {
// destroy user session
$this->Session->delete('User');
//$this->redirect(array('controller' => 'users', 'action' => 'login'));
$this->redirect($this->referer());
}
/**
param is the return URL in Base64 encoding
*/
public function login($param = null) {
$this->pageTitle = 'OpenID Login';
$this->set('param',$param);
$this->Session->write('Session.referer', $this->referer());
}
public function view($id = null) {
$this->PageTitle = 'User #'. $id;
$this->set('user',$this->User->read(null,$id));
}
/**
List out users.
*/
public function index() {
$users = $this->User->find('all');
$this->set('users',$users);
}
}
?> | agpl-3.0 |
maxdelo77/replyit-master-3.2-final | src/java/com/sapienter/jbilling/common/SystemProperties.java | 5558 | /*
* JBILLING CONFIDENTIAL
* _____________________
*
* [2003] - [2012] Enterprise jBilling Software Ltd.
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Enterprise jBilling Software.
* The intellectual and technical concepts contained
* herein are proprietary to Enterprise jBilling Software
* and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden.
*/
package com.sapienter.jbilling.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* This is a Singleton call that provides the system properties from
* the jbilling.properties file
*/
public class SystemProperties {
private static final FormatLogger LOG = new FormatLogger(Logger.getLogger(SystemProperties.class));
private static final String JBILLING_HOME = "JBILLING_HOME";
private static final String PROPERTIES_FILE = "jbilling.properties";
private static final String RESOURCES_DIR = "resources";
private static final String BASE_DIR_PROPERTY = "base_dir";
private static SystemProperties INSTANCE;
private String resourcesDir = null;
private Properties prop = null;
/*
private singleton constructor
*/
private SystemProperties() throws IOException {
File properties = getPropertiesFile();
FileInputStream stream = new FileInputStream(properties);
prop = new Properties();
prop.load(stream);
stream.close();
LOG.debug("System properties loaded from: %s", properties.getPath());
System.out.println("System properties loaded from: " + properties.getPath());
resourcesDir = getJBillingResourcesDir();
LOG.debug("Resolved jbilling resources directory to: %s", resourcesDir);
System.out.println("Resolved jbilling resources directory to: " + resourcesDir);
}
/**
* Returns a singleton instance of SystemProperties
*
* @return instance
* @throws IOException if properties could not be loaded
*/
public static SystemProperties getSystemProperties() throws IOException{
if (INSTANCE == null)
INSTANCE = new SystemProperties();
return INSTANCE;
}
/**
* Returns the jBilling home path where resources and configuration files
* can be found.
*
* The environment variable JBILLING_HOME and system property JBILLING_HOME are examined
* for this value, with precedence given to system properties set via command line arguments.
*
* If no jBilling home path is set, properties will be loaded from the classpath.
*
* @return jbilling home path
*/
public static String getJBillingHome() {
String jbillingHome = System.getProperty(JBILLING_HOME);
if (jbillingHome == null) {
jbillingHome = System.getenv(JBILLING_HOME);
}
return jbillingHome;
}
/**
* Returns the path to the jBilling resources directory.
*
* The resources directory is always assumed to be located in JBILLING_HOME. If JBILLING_HOME is not
* set, this method will return a relative path as the default location for the resources directory.
*
* @return path to the resources directory
*/
public String getJBillingResourcesDir() {
// try JBILLING_HOME
String jbillingHome = getJBillingHome();
if (jbillingHome != null) {
return jbillingHome + File.separator + RESOURCES_DIR + File.separator;
}
try {
// try root dir
File resources = new File("." + File.separator + RESOURCES_DIR);
if (resources.exists()) {
return resources.getCanonicalPath() + File.separator;
}
// try one level down (tomcat root)
resources = new File(".." + File.separator + RESOURCES_DIR);
if (resources.exists()) {
return resources.getCanonicalPath() + File.separator;
}
} catch (IOException e) {
LOG.warn("IOException when attempting to resolve canonical path to jbilling resources/", e);
}
return "";
}
/**
* Returns the path to the jbilling.properties file.
*
* @return properties file
*/
public static File getPropertiesFile() {
String jbillingHome = getJBillingHome();
if (jbillingHome != null) {
// properties file from filesystem
return new File(jbillingHome + File.separator + PROPERTIES_FILE);
} else {
// properties file from classpath
URL url = SystemProperties.class.getResource("/" + PROPERTIES_FILE);
return new File(url.getFile());
}
}
public String get(String key) throws Exception {
// "base_dir" should always resolve to the JBILLING_HOME resources dir
// this value is no longer part of jbilling.properties
if (BASE_DIR_PROPERTY.equals(key)) {
return resourcesDir;
}
// get value from jbilling.properties
String value = prop.getProperty(key);
if (value == null)
throw new Exception("Missing system property: " + key);
return value;
}
public String get(String key, String defaultValue) {
return prop.getProperty(key, defaultValue);
}
}
| agpl-3.0 |
xurizaemon/civix | src/CRM/ClientBundle/ClientFactory.php | 3566 | <?php
namespace CRM\ClientBundle;
/**
* An adaptor which allows us to use CiviCRM's 'class.api.php' as
* a Symfony service.
*/
class ClientFactory {
/**
* Instantiate a configured API connection
*
* @return \civicrm_api3
*/
public function get() {
$origDir = $this->getPwd();
list ($cmsRoot, $civicrmConfigPhp) = $this->findCivicrmConfigPhp($origDir);
if (!is_dir($cmsRoot)) {
throw new \Exception('Failed to locate CMS. Please call civix from somewhere under the CMS root.');
}
if (!file_exists($civicrmConfigPhp)) {
throw new \Exception('Failed to locate civicrm.config.php. Please call civix from somewhere under the CMS root.');
}
$this->bootstrap($cmsRoot, $civicrmConfigPhp);
require_once __DIR__ . '/class.api.php';
$config = array();
$result = new \civicrm_api3($config);
chdir($origDir);
return $result;
}
/**
* @param string $startDir the directory in which to start the start
* @return null|array (0 => $cmsRoot, 1 => $civicrmConfigPhpPath)
*/
private function findCivicrmConfigPhp($startDir) {
$parts = explode('/', str_replace('\\', '/', $startDir));
while (!empty($parts)) {
$basePath = implode('/', $parts);
$relPaths = array(
'wp-content/plugins/civicrm/civicrm/civicrm.config.php',
'administrator/components/com_civicrm/civicrm/civicrm.config.php',
'sites/default/modules/civicrm/civicrm.config.php', // check 'default' first
'sites/default/modules/*/civicrm/civicrm.config.php', // check 'default' first
'sites/*/modules/civicrm/civicrm.config.php',
'sites/*/modules/*/civicrm/civicrm.config.php',
'profiles/*/modules/civicrm/civicrm.config.php',
'profiles/*/modules/*/civicrm/civicrm.config.php',
);
foreach ($relPaths as $relPath) {
$matches = glob("$basePath/$relPath");
if (!empty($matches)) {
return array($basePath, $matches[0]);
}
}
array_pop($parts);
}
return NULL;
}
private function bootstrap($cmsRoot, $civicrm_config_path) {
define('CIVICRM_CMSDIR', $cmsRoot);
require_once $civicrm_config_path;
// so the configuration works with php-cli
$_SERVER['PHP_SELF'] = "/index.php";
$_SERVER['HTTP_HOST'] = 'localhost'; // $this->_site;
$_SERVER['REMOTE_ADDR'] = "127.0.0.1";
$_SERVER['SERVER_SOFTWARE'] = NULL;
$_SERVER['REQUEST_METHOD'] = 'GET';
// SCRIPT_FILENAME needed by CRM_Utils_System::cmsRootPath
$_SERVER['SCRIPT_FILENAME'] = __FILE__;
// CRM-8917 - check if script name starts with /, if not - prepend it.
if (ord($_SERVER['SCRIPT_NAME']) != 47) {
$_SERVER['SCRIPT_NAME'] = '/' . $_SERVER['SCRIPT_NAME'];
}
$config = \CRM_Core_Config::singleton();
// HTTP_HOST will be 'localhost' unless overwritten with the -s argument.
// Now we have a Config object, we can set it from the Base URL.
if ($_SERVER['HTTP_HOST'] == 'localhost') {
$_SERVER['HTTP_HOST'] = preg_replace(
'!^https?://([^/]+)/.*$!i',
'$1',
$config->userFrameworkBaseURL);
}
global $civicrm_root;
if (!\CRM_Utils_System::loadBootstrap(array(), FALSE, FALSE, $civicrm_root)) {
throw new \Exception("Failed to bootstrap CMS");
// return FALSE;
}
return TRUE;
}
private function getPwd() {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
return getcwd();
}
else {
exec('pwd', $output);
return trim(implode("\n", $output));
}
}
}
| agpl-3.0 |
Extentsoftware/Quest | src/Quest.Common/Messages/Job/GetJobsRequest.cs | 180 | using System;
namespace Quest.Common.Messages.Job
{
[Serializable]
public class GetJobsRequest: Request
{
public int Skip;
public int Take;
}
}
| agpl-3.0 |
hiddentao/browsermail | src/js/alerts.js | 382 | /**
* User alerts
* @param msg
*/
_alert = function(type, msg) {
var classes = 'alert-box round ';
switch (type) {
case 'error':
classes += 'alert';
}
var a = $('<div class="' + classes + '">' + msg + '</div>');
$('#alerts').append(a);
setTimeout(function() {
a.fadeOut(500);
}, 2000);
};
exports.err = function(msg) {
_alert('error', msg);
};
| agpl-3.0 |
jcstrang-edu/CodePlay | src/database/Operator.java | 7434 | import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import java.util.*;
public enum Operator{;
public static final String DATABASE_TAG=".SeCo.dat";
private static final JFileChooser fileChooser=setChooser();
private static JFileChooser setChooser(){
JFileChooser hold= new JFileChooser(".");
hold.removeChoosableFileFilter(hold.getAcceptAllFileFilter());
hold.setFileFilter(new ExtensionFileFilter("SephirCorp Databases", new String[] { "Seco.dat" }));
return hold; }
private static final JFileChooser fileDirector=setDirector();
private static JFileChooser setDirector(){
JFileChooser hold= new JFileChooser(".");
hold.removeChoosableFileFilter(hold.getAcceptAllFileFilter());
hold.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
return hold; }
public static String writeToFile(DataBase database){
String title=database.getTitle();
int status=fileDirector.showOpenDialog(null);
String path;
if(status==JFileChooser.APPROVE_OPTION){
path=fileDirector.getSelectedFile().getAbsolutePath();
try{
String newp=path+=File.separator+title+DATABASE_TAG;
File file=new File(newp);
File bku=new File(newp+".bku");
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
out.writeObject(database);
ObjectOutputStream outbku = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(bku)));
outbku.writeObject(database);
bku.setWritable(false);
/*try{
Process p = Runtime.getRuntime().exec("attrib +H " + newp+".bku");
p.waitFor(); }*/
//catch(InterruptedException IE){ IE.printStackTrace(); }
out.flush();
out.close();
outbku.flush();
outbku.close(); }
catch(IOException IOE){ IOE.printStackTrace(); }}
else{
return writeToFile(database); }
return (path+title+DATABASE_TAG); }
public static DataBase getDataBase(){
int status=fileChooser.showOpenDialog(null);
String path;
DataBase get=null;
if(status==JFileChooser.APPROVE_OPTION){
path=fileChooser.getSelectedFile().getAbsolutePath();
try{
FileInputStream fis=null;
BufferedInputStream bis=null;
ObjectInputStream in=null;
try{
fis=new FileInputStream(path);
bis=new BufferedInputStream(fis);
in=new ObjectInputStream(bis);
try{
get=((DataBase)in.readObject()); }
finally{
fis.close();
bis.close();
in.close(); }}
catch(IOException IOE){
try{
fis.close();
bis.close();
in.close(); }
catch(IOException IOE2){}
catch(NullPointerException NPE){}
return get;}}
catch(ClassNotFoundException CNFE){}
return get; }
else{
return get;
}}
public static String[] deleteAllCorruptRemnants(){
ArrayList<String> files=new ArrayList<String>();
for(String path:locateCorruptDataBases()){
File file=new File(path);
if(file.delete()){
files.add(path); }}
return files.toArray(new String[0]); }
public static String[] locateCorruptDataBases(){
ArrayList<String> corruptDataBases=new ArrayList<String>();
String[] paths=locateAll(DATABASE_TAG);
for(String path:paths){
if(isCorrupt(path)){
corruptDataBases.add(path); }}
return corruptDataBases.toArray(new String[0]); }
public static boolean isCorrupt(String path){
FileInputStream fis=null;
BufferedInputStream bis=null;
ObjectInputStream in=null;
try{
fis=new FileInputStream(path);
bis=new BufferedInputStream(fis);
in=new ObjectInputStream(bis);
try{
DataBase test=((DataBase)in.readObject()); }
finally{
fis.close();
bis.close();
in.close(); }}
catch(IOException IOE){
try{
fis.close();
bis.close();
in.close(); }
catch(IOException IOE2){}
catch(NullPointerException NPE){}
return true; }
catch(ClassNotFoundException CNFE){}
return false; }
public static ArrayList<DataBase> getAllAvaliableDataBases(){
ArrayList<DataBase> avaliableDatabases=new ArrayList<DataBase>();
String[] paths=locateAll(DATABASE_TAG);
for(String path:paths){
ObjectInputStream in=null;
try{
in= new ObjectInputStream(new BufferedInputStream(new FileInputStream(path)));
avaliableDatabases.add((DataBase)in.readObject()); }
catch(IOException IOE){}
catch(ClassNotFoundException CNFE){}
finally{
if(in!=null){
try{
in.close(); }
catch(IOException logOrIgnore){}}}}
return avaliableDatabases; }
public static String[] locateAll(String extension){
ArrayList<String> list=new ArrayList<String>();
FileSystemView fsv = FileSystemView.getFileSystemView();
for(File path:File.listRoots()){
list.addAll(getFiles(path.getAbsolutePath(), extension)); }
return list.toArray(new String[0]); }
private static ArrayList<String> getFiles(String path, String extension){
File directory=new File(path);
String[] children=directory.list();
ArrayList<String> list=new ArrayList<String>();
if(children!=null){
for(int i=0;i<children.length;i++){
String filename=children[i];
File file=new File(path+File.separator+filename);
if(!file.isDirectory()){
if(file.getName().endsWith(extension)){
list.add(file.getAbsolutePath()); }}
else{
list.addAll(getFiles(path + File.separator + filename, extension)); }}}
return list; }
public static String manualSelect(){
int status=fileChooser.showOpenDialog(null);
if(status==JFileChooser.APPROVE_OPTION){
return fileChooser.getSelectedFile().getAbsolutePath(); }
return null; }
private static class ExtensionFileFilter extends FileFilter{
String description;
String extensions[];
public ExtensionFileFilter(String description, String extension){
this(description, new String[]{extension}); }
public ExtensionFileFilter(String description, String[] extensions){
if(description==null){
this.description=extensions[0]; }
else{
this.description=description; }
this.extensions=extensions;
toLower(this.extensions); }
private void toLower(String[] array) {
for(int i=0;i<array.length;i++){
array[i] = array[i].toLowerCase(); }}
public String getDescription(){
return description; }
public boolean accept(File file){
if(file.isDirectory()){
return true; }
else{
String path=file.getAbsolutePath().toLowerCase();
for(int i=0;i<extensions.length;i++){
String extension=extensions[i];
if((path.endsWith(extension)&&(path.charAt(path.length()-extension.length()-1))=='.')){
return true; }}}
return false; }}} | agpl-3.0 |
romain-li/edx-platform | cms/djangoapps/contentstore/tests/test_tasks.py | 4041 | """
Unit tests for course import and export Celery tasks
"""
from __future__ import absolute_import, division, print_function
import copy
import json
import mock
from uuid import uuid4
from django.conf import settings
from django.contrib.auth.models import User
from django.test.utils import override_settings
from user_tasks.models import UserTaskArtifact, UserTaskStatus
from contentstore.tasks import export_olx
from contentstore.tests.test_libraries import LibraryTestCase
from contentstore.tests.utils import CourseTestCase
TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE)
TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex
def side_effect_exception(*args, **kwargs): # pylint: disable=unused-argument
"""
Side effect for mocking which raises an exception
"""
raise Exception('Boom!')
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
class ExportCourseTestCase(CourseTestCase):
"""
Tests of the export_olx task applied to courses
"""
def test_success(self):
"""
Verify that a routine course export task succeeds
"""
key = str(self.course.location.course_key)
result = export_olx.delay(self.user.id, key, u'en')
status = UserTaskStatus.objects.get(task_id=result.id)
self.assertEqual(status.state, UserTaskStatus.SUCCEEDED)
artifacts = UserTaskArtifact.objects.filter(status=status)
self.assertEqual(len(artifacts), 1)
output = artifacts[0]
self.assertEqual(output.name, 'Output')
@mock.patch('contentstore.tasks.export_course_to_xml', side_effect=side_effect_exception)
def test_exception(self, mock_export): # pylint: disable=unused-argument
"""
The export task should fail gracefully if an exception is thrown
"""
key = str(self.course.location.course_key)
result = export_olx.delay(self.user.id, key, u'en')
self._assert_failed(result, json.dumps({u'raw_error_msg': u'Boom!'}))
def test_invalid_user_id(self):
"""
Verify that attempts to export a course as an invalid user fail
"""
user_id = User.objects.order_by(u'-id').first().pk + 100
key = str(self.course.location.course_key)
result = export_olx.delay(user_id, key, u'en')
self._assert_failed(result, u'Unknown User ID: {}'.format(user_id))
def test_non_course_author(self):
"""
Verify that users who aren't authors of the course are unable to export it
"""
_, nonstaff_user = self.create_non_staff_authed_user_client()
key = str(self.course.location.course_key)
result = export_olx.delay(nonstaff_user.id, key, u'en')
self._assert_failed(result, u'Permission denied')
def _assert_failed(self, task_result, error_message):
"""
Verify that a task failed with the specified error message
"""
status = UserTaskStatus.objects.get(task_id=task_result.id)
self.assertEqual(status.state, UserTaskStatus.FAILED)
artifacts = UserTaskArtifact.objects.filter(status=status)
self.assertEqual(len(artifacts), 1)
error = artifacts[0]
self.assertEqual(error.name, u'Error')
self.assertEqual(error.text, error_message)
@override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE)
class ExportLibraryTestCase(LibraryTestCase):
"""
Tests of the export_olx task applied to libraries
"""
def test_success(self):
"""
Verify that a routine library export task succeeds
"""
key = str(self.lib_key)
result = export_olx.delay(self.user.id, key, u'en') # pylint: disable=no-member
status = UserTaskStatus.objects.get(task_id=result.id)
self.assertEqual(status.state, UserTaskStatus.SUCCEEDED)
artifacts = UserTaskArtifact.objects.filter(status=status)
self.assertEqual(len(artifacts), 1)
output = artifacts[0]
self.assertEqual(output.name, 'Output')
| agpl-3.0 |
dukedorje/dreamcatcher | app/assets/javascripts/dreamcatcher-jmvc/scripts/docs.js | 155 | //js cookbook/scripts/doc.js
load('steal/rhino/steal.js');
steal.plugins("documentjs").then(function(){
DocumentJS('dreamcatcher/dreamcatcher.html');
}); | agpl-3.0 |
zamentur/owncloud-file-licence | tests/js/unit/controllers/maincontrollerSpec.js | 1163 |
/**
* ownCloud - Files Licencewizard app
*
* @author Valentin GRIMAUD
*
* @copyright 2013 Valentin GRIMAUD <valentin@grimaud.me>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
describe('MainController', function() {
var controller;
// use the FilesLicencewizard container
beforeEach(module('Files_Licencewizard'));
beforeEach(inject(function ($controller, $rootScope) {
controller = $controller('MainController', {
$scope: $rootScope.$new()
});
}));
it('should work', function () {
expect(2+2).toBe(4);
});
});
| agpl-3.0 |
vvfosprojects/sovvf | src/frontend/prototipi/cruscottoIntegratoSB/src/app/layout/bs-component/bs-component.module.ts | 1346 | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BsComponentRoutingModule } from './bs-component-routing.module';
import { BsComponentComponent } from './bs-component.component';
import {
AlertComponent,
ButtonsComponent,
ModalComponent,
CollapseComponent,
DatePickerComponent,
DropdownComponent,
PaginationComponent,
PopOverComponent,
ProgressbarComponent,
TabsComponent,
TooltipComponent,
TimepickerComponent
} from './components';
import { PageHeaderModule } from '../../shared';
@NgModule({
imports: [
CommonModule,
BsComponentRoutingModule,
FormsModule,
ReactiveFormsModule,
NgbModule.forRoot(),
PageHeaderModule
],
declarations: [
BsComponentComponent,
BsComponentComponent,
ButtonsComponent,
AlertComponent,
ModalComponent,
CollapseComponent,
DatePickerComponent,
DropdownComponent,
PaginationComponent,
PopOverComponent,
ProgressbarComponent,
TabsComponent,
TooltipComponent,
TimepickerComponent
]
})
export class BsComponentModule {}
| agpl-3.0 |
diederikd/DeBrug | languages/ObjectiefRecht/source_gen/ObjectiefRecht/editor/RechtsSubject_EditorBuilder_a.java | 29540 | package ObjectiefRecht.editor;
/*Generated by MPS */
import jetbrains.mps.editor.runtime.descriptor.AbstractEditorBuilder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.mps.openapi.model.SNode;
import jetbrains.mps.openapi.editor.EditorContext;
import jetbrains.mps.openapi.editor.cells.EditorCell;
import jetbrains.mps.nodeEditor.cells.EditorCell_Collection;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Horizontal;
import jetbrains.mps.openapi.editor.style.Style;
import jetbrains.mps.editor.runtime.style.StyleImpl;
import jetbrains.mps.editor.runtime.style.StyleAttributes;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations;
import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Indent;
import org.jetbrains.mps.openapi.language.SProperty;
import jetbrains.mps.openapi.editor.menus.transformation.SPropertyInfo;
import jetbrains.mps.nodeEditor.cells.EditorCell_Property;
import jetbrains.mps.nodeEditor.cells.SPropertyAccessor;
import jetbrains.mps.openapi.editor.cells.CellActionType;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSPropertyOrNode;
import jetbrains.mps.nodeEditor.cellActions.CellAction_DeleteNode;
import ObjectiefRecht.editor.GN_StyleSheet.SubjectStyleClass;
import jetbrains.mps.nodeEditor.cellMenu.SPropertySubstituteInfo;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.AttributeOperations;
import jetbrains.mps.lang.smodel.generator.smodelAdapter.IAttributeDescriptor;
import jetbrains.mps.internal.collections.runtime.Sequence;
import jetbrains.mps.internal.collections.runtime.IWhereFilter;
import java.util.Objects;
import jetbrains.mps.lang.core.behavior.PropertyAttribute__BehaviorDescriptor;
import jetbrains.mps.nodeEditor.EditorManager;
import jetbrains.mps.openapi.editor.update.AttributeKind;
import jetbrains.mps.nodeEditor.cells.EditorCell_Constant;
import jetbrains.mps.nodeEditor.cellProviders.CellProviderWithRole;
import de.slisson.mps.editor.multiline.cellProviders.MultilineCellProvider;
import jetbrains.mps.nodeEditor.cellProviders.AbstractCellListHandler;
import jetbrains.mps.nodeEditor.cellLayout.CellLayout_Vertical;
import jetbrains.mps.lang.editor.cellProviders.RefNodeListHandler;
import jetbrains.mps.smodel.action.NodeFactoryManager;
import jetbrains.mps.openapi.editor.menus.transformation.SNodeLocation;
import jetbrains.mps.openapi.editor.cells.DefaultSubstituteInfo;
import jetbrains.mps.nodeEditor.cellMenu.SChildSubstituteInfo;
import jetbrains.mps.internal.collections.runtime.ListSequence;
import jetbrains.mps.lang.editor.cellProviders.RefNodeListHandlerElementKeyMap;
import jetbrains.mps.lang.editor.cellProviders.SingleRoleCellProvider;
import org.jetbrains.mps.openapi.language.SContainmentLink;
import jetbrains.mps.editor.runtime.impl.cellActions.CellAction_DeleteSmart;
/*package*/ class RechtsSubject_EditorBuilder_a extends AbstractEditorBuilder {
@NotNull
private SNode myNode;
public RechtsSubject_EditorBuilder_a(@NotNull EditorContext context, @NotNull SNode node) {
super(context);
myNode = node;
}
@NotNull
@Override
public SNode getNode() {
return myNode;
}
/*package*/ EditorCell createCell() {
return createCollection_feb60b_a();
}
private EditorCell createCollection_feb60b_a() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Horizontal());
editorCell.setCellId("Collection_feb60b_a");
editorCell.setBig(true);
editorCell.setCellContext(getCellFactory().getCellContext());
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
if (nodeCondition_feb60b_a0a()) {
editorCell.addEditorCell(createCollection_feb60b_a0());
}
return editorCell;
}
private boolean nodeCondition_feb60b_a0a() {
SNode context;
int jaar;
int datumvan;
int datumtot;
boolean ta;
boolean result = false;
context = (SNode) SNodeOperations.getParent(myNode);
jaar = SPropertyOperations.getInteger(SLinkOperations.getTarget(context, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d02L, 0x4916e0625ce2cc63L, "zichtdatum")), MetaAdapterFactory.getProperty(0x61be2dc6a1404defL, 0xa5927499aa2bac19L, 0x630944a3c415c8c3L, 0x630944a3c415c8c9L, "jaar"));
datumvan = SPropertyOperations.getInteger(SLinkOperations.getTarget(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x4916e0625ce15ba0L, 0x4916e0625ce244baL, "brongeldigVan")), MetaAdapterFactory.getProperty(0x61be2dc6a1404defL, 0xa5927499aa2bac19L, 0x630944a3c415c8c3L, 0x630944a3c415c8c9L, "jaar"));
datumtot = SPropertyOperations.getInteger(SLinkOperations.getTarget(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x4916e0625ce15ba0L, 0x4916e0625ce244bcL, "brongeldigTot")), MetaAdapterFactory.getProperty(0x61be2dc6a1404defL, 0xa5927499aa2bac19L, 0x630944a3c415c8c3L, 0x630944a3c415c8c9L, "jaar"));
ta = SPropertyOperations.getBoolean(context, MetaAdapterFactory.getProperty(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d02L, 0x4916e0625ce39c8bL, "toonalles"));
if (datumtot == 0) {
result = (jaar >= datumvan) || ta;
}
if (datumtot > 0) {
result = ((jaar >= datumvan) && (jaar <= datumtot)) || ta;
}
return result;
}
private EditorCell createCollection_feb60b_a0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_feb60b_a0");
editorCell.addEditorCell(createProperty_feb60b_a0a());
editorCell.addEditorCell(createConstant_feb60b_b0a());
editorCell.addEditorCell(createMultiline_feb60b_c0a_0());
editorCell.addEditorCell(createConstant_feb60b_d0a());
editorCell.addEditorCell(createCollection_feb60b_e0a());
editorCell.addEditorCell(createConstant_feb60b_f0a());
editorCell.addEditorCell(createCollection_feb60b_g0a());
editorCell.addEditorCell(createCollection_feb60b_h0a());
editorCell.addEditorCell(createConstant_feb60b_i0a());
editorCell.addEditorCell(createConstant_feb60b_j0a());
editorCell.addEditorCell(createConstant_feb60b_k0a());
editorCell.addEditorCell(createRefNode_feb60b_l0a());
editorCell.addEditorCell(createConstant_feb60b_m0a());
editorCell.addEditorCell(createConstant_feb60b_n0a());
return editorCell;
}
private EditorCell createProperty_feb60b_a0a() {
getCellFactory().pushCellContext();
try {
final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, false, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.BACKWARD));
editorCell.setCellId("property_name");
Style style = new StyleImpl();
new SubjectStyleClass(getEditorContext(), getNode()).apply(style, editorCell);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"));
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
private EditorCell createConstant_feb60b_b0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_b0a");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createMultiline_feb60b_c0a(EditorContext editorContext, SNode node) {
CellProviderWithRole provider = new MultilineCellProvider(node, editorContext);
provider.setRole("definitie");
provider.setNoTargetText("<no definitie>");
EditorCell editorCell;
editorCell = provider.createEditorCell(editorContext);
editorCell.setCellId("property_definitie");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(provider.createDefaultSubstituteInfo());
SNode attributeConcept = provider.getRoleAttribute();
if (attributeConcept != null) {
return getUpdateSession().updateAttributeCell(provider.getRoleAttributeKind(), editorCell, attributeConcept);
} else
return editorCell;
}
private EditorCell createMultiline_feb60b_c0a_0() {
return createMultiline_feb60b_c0a(getEditorContext(), myNode);
}
private EditorCell createConstant_feb60b_d0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_d0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createCollection_feb60b_e0a() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_feb60b_e0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.addEditorCell(createRefNodeList_feb60b_a4a0());
return editorCell;
}
private EditorCell createRefNodeList_feb60b_a4a0() {
AbstractCellListHandler handler = new RechtsSubject_EditorBuilder_a.kenmerkListHandler_feb60b_a4a0(myNode, "kenmerk", getEditorContext());
EditorCell_Collection editorCell = handler.createCells(new CellLayout_Vertical(), false);
editorCell.setCellId("refNodeList_kenmerk");
editorCell.setRole(handler.getElementRole());
return editorCell;
}
private static class kenmerkListHandler_feb60b_a4a0 extends RefNodeListHandler {
@NotNull
private SNode myNode;
public kenmerkListHandler_feb60b_a4a0(SNode ownerNode, String childRole, EditorContext context) {
super(ownerNode, childRole, context, false);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
public SNode createNodeToInsert(EditorContext editorContext) {
return NodeFactoryManager.createNode(MetaAdapterFactory.getConcept(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x4916e0625cef8883L, "ObjectiefRecht.structure.Kenmerk"), null, getNode(), getNode().getModel());
}
public EditorCell createNodeCell(SNode elementNode) {
EditorCell elementCell = getUpdateSession().updateChildNodeCell(elementNode);
installElementCellActions(elementNode, elementCell);
return elementCell;
}
public EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(kenmerkListHandler_feb60b_a4a0.this.getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x5781f93f2e4f40faL, "kenmerk")));
try {
EditorCell emptyCell = null;
emptyCell = super.createEmptyCell();
installElementCellActions(null, emptyCell);
setCellContext(emptyCell);
return emptyCell;
} finally {
getCellFactory().popCellContext();
}
}
public void installElementCellActions(SNode elementNode, EditorCell elementCell) {
if (elementCell.getUserObject(AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET) == null) {
elementCell.putUserObject(AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET, AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET);
if (elementNode != null) {
elementCell.setAction(CellActionType.DELETE, new CellAction_DeleteNode(elementNode, CellAction_DeleteNode.DeleteDirection.FORWARD));
elementCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteNode(elementNode, CellAction_DeleteNode.DeleteDirection.BACKWARD));
}
if (elementCell.getSubstituteInfo() == null || elementCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
elementCell.setSubstituteInfo(new SChildSubstituteInfo(elementCell, getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x5781f93f2e4f40faL, "kenmerk"), elementNode));
}
}
}
}
private EditorCell createConstant_feb60b_f0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_f0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createCollection_feb60b_g0a() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_feb60b_g0a");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
editorCell.addEditorCell(createProperty_feb60b_a6a0());
return editorCell;
}
private EditorCell createProperty_feb60b_a6a0() {
getCellFactory().pushCellContext();
try {
final SProperty property = MetaAdapterFactory.getProperty(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x110396eaaa4L, 0x110396ec041L, "name");
getCellFactory().setPropertyInfo(new SPropertyInfo(myNode, property));
EditorCell_Property editorCell = EditorCell_Property.create(getEditorContext(), new SPropertyAccessor(myNode, property, false, false), myNode);
editorCell.setDefaultText("<no name>");
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSPropertyOrNode(myNode, property, CellAction_DeleteNode.DeleteDirection.BACKWARD));
editorCell.setCellId("property_name_1");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.setSubstituteInfo(new SPropertySubstituteInfo(editorCell, property));
setCellContext(editorCell);
Iterable<SNode> propertyAttributes = SNodeOperations.ofConcept(AttributeOperations.getAttributeList(myNode, new IAttributeDescriptor.AllAttributes()), MetaAdapterFactory.getConcept(0xceab519525ea4f22L, 0x9b92103b95ca8c0cL, 0x2eb1ad060897da56L, "jetbrains.mps.lang.core.structure.PropertyAttribute"));
Iterable<SNode> currentPropertyAttributes = Sequence.fromIterable(propertyAttributes).where(new IWhereFilter<SNode>() {
public boolean accept(SNode it) {
return Objects.equals(PropertyAttribute__BehaviorDescriptor.getProperty_id1avfQ4BBzOo.invoke(it), property);
}
});
if (Sequence.fromIterable(currentPropertyAttributes).isNotEmpty()) {
EditorManager manager = EditorManager.getInstanceFromContext(getEditorContext());
return manager.createNodeRoleAttributeCell(Sequence.fromIterable(currentPropertyAttributes).first(), AttributeKind.PROPERTY, editorCell);
} else
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
private EditorCell createCollection_feb60b_h0a() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_feb60b_h0a");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
if (nodeCondition_feb60b_a0h0a()) {
editorCell.addEditorCell(createCollection_feb60b_a7a0());
}
if (nodeCondition_feb60b_a1h0a()) {
editorCell.addEditorCell(createCollection_feb60b_b7a0());
}
editorCell.addEditorCell(createRefNodeList_feb60b_c7a0());
return editorCell;
}
private boolean nodeCondition_feb60b_a0h0a() {
int index = 0;
for (SNode kenmerk : ListSequence.fromList(SLinkOperations.getChildren(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x67229afa69bc26cfL, "uniekIdentificerendeKenmerken")))) {
index++;
}
return index > 1;
}
private boolean nodeCondition_feb60b_a1h0a() {
int index = 0;
for (SNode kenmerk : ListSequence.fromList(SLinkOperations.getChildren(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x67229afa69bc26cfL, "uniekIdentificerendeKenmerken")))) {
index++;
}
return (index <= 1);
}
private EditorCell createCollection_feb60b_a7a0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_feb60b_a7a0");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
style.set(StyleAttributes.INDENT_LAYOUT_INDENT, true);
editorCell.getStyle().putAll(style);
editorCell.addEditorCell(createConstant_feb60b_a0h0a());
return editorCell;
}
private EditorCell createConstant_feb60b_a0h0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "heeft de volgende identificerende kenmerken ");
editorCell.setCellId("Constant_feb60b_a0h0a");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createCollection_feb60b_b7a0() {
EditorCell_Collection editorCell = new EditorCell_Collection(getEditorContext(), myNode, new CellLayout_Indent());
editorCell.setCellId("Collection_feb60b_b7a0");
Style style = new StyleImpl();
style.set(StyleAttributes.SELECTABLE, false);
editorCell.getStyle().putAll(style);
editorCell.addEditorCell(createConstant_feb60b_a1h0a());
return editorCell;
}
private EditorCell createConstant_feb60b_a1h0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, " heeft het volgende identificerende kenmerk ");
editorCell.setCellId("Constant_feb60b_a1h0a");
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNodeList_feb60b_c7a0() {
AbstractCellListHandler handler = new RechtsSubject_EditorBuilder_a.uniekIdentificerendeKenmerkenListHandler_feb60b_c7a0(myNode, "uniekIdentificerendeKenmerken", getEditorContext());
EditorCell_Collection editorCell = handler.createCells(new CellLayout_Indent(), false);
editorCell.setCellId("refNodeList_uniekIdentificerendeKenmerken");
editorCell.setRole(handler.getElementRole());
return editorCell;
}
private static class uniekIdentificerendeKenmerkenListHandler_feb60b_c7a0 extends RefNodeListHandler {
@NotNull
private SNode myNode;
public uniekIdentificerendeKenmerkenListHandler_feb60b_c7a0(SNode ownerNode, String childRole, EditorContext context) {
super(ownerNode, childRole, context, false);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
public SNode createNodeToInsert(EditorContext editorContext) {
return NodeFactoryManager.createNode(MetaAdapterFactory.getConcept(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x6e43a734f8661e5dL, "ObjectiefRecht.structure.AbstractReferentieNaarKenmerk"), null, getNode(), getNode().getModel());
}
public EditorCell createNodeCell(SNode elementNode) {
EditorCell elementCell = getUpdateSession().updateChildNodeCell(elementNode);
installElementCellActions(elementNode, elementCell);
return elementCell;
}
public EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(uniekIdentificerendeKenmerkenListHandler_feb60b_c7a0.this.getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x67229afa69bc26cfL, "uniekIdentificerendeKenmerken")));
try {
EditorCell emptyCell = null;
emptyCell = super.createEmptyCell();
installElementCellActions(null, emptyCell);
setCellContext(emptyCell);
return emptyCell;
} finally {
getCellFactory().popCellContext();
}
}
public void installElementCellActions(SNode elementNode, EditorCell elementCell) {
if (elementCell.getUserObject(AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET) == null) {
elementCell.putUserObject(AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET, AbstractCellListHandler.ELEMENT_CELL_ACTIONS_SET);
if (elementNode != null) {
elementCell.setAction(CellActionType.DELETE, new CellAction_DeleteNode(elementNode, CellAction_DeleteNode.DeleteDirection.FORWARD));
elementCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteNode(elementNode, CellAction_DeleteNode.DeleteDirection.BACKWARD));
elementCell.addKeyMap(new RefNodeListHandlerElementKeyMap(this, ","));
}
if (elementCell.getSubstituteInfo() == null || elementCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
elementCell.setSubstituteInfo(new SChildSubstituteInfo(elementCell, getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x67229afa69bc26cfL, "uniekIdentificerendeKenmerken"), elementNode));
}
}
}
@Override
public EditorCell createSeparatorCell(SNode prevNode, SNode nextNode) {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), getNode(), ",");
editorCell.setSelectable(false);
Style style = new StyleImpl();
style.set(StyleAttributes.LAYOUT_CONSTRAINT, "");
style.set(StyleAttributes.PUNCTUATION_LEFT, true);
editorCell.getStyle().putAll(style);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteNode(prevNode, CellAction_DeleteNode.DeleteDirection.FORWARD));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteNode(prevNode, CellAction_DeleteNode.DeleteDirection.BACKWARD));
return editorCell;
}
@Override
protected void createInnerCells() {
try {
getCellFactory().pushCellContext();
getCellFactory().addCellContextHints(new String[]{"ObjectiefRecht.editor.Hints_ObjectiefRecht.Kort"});
getCellFactory().removeCellContextHints();
super.createInnerCells();
setInnerCellsContext();
} finally {
getCellFactory().popCellContext();
}
}
}
private EditorCell createConstant_feb60b_i0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_i0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_feb60b_j0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "Voorbeelden:");
editorCell.setCellId("Constant_feb60b_j0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_feb60b_k0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_k0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createRefNode_feb60b_l0a() {
SingleRoleCellProvider provider = new RechtsSubject_EditorBuilder_a.VoorbeeldenSingleRoleHandler_feb60b_l0a(myNode, MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x36e44840850477e5L, "Voorbeelden"), getEditorContext());
return provider.createCell();
}
private static class VoorbeeldenSingleRoleHandler_feb60b_l0a extends SingleRoleCellProvider {
@NotNull
private SNode myNode;
public VoorbeeldenSingleRoleHandler_feb60b_l0a(SNode ownerNode, SContainmentLink containmentLink, EditorContext context) {
super(containmentLink, context);
myNode = ownerNode;
}
@Override
@NotNull
public SNode getNode() {
return myNode;
}
protected EditorCell createChildCell(SNode child) {
EditorCell editorCell = getUpdateSession().updateChildNodeCell(child);
editorCell.setAction(CellActionType.DELETE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x36e44840850477e5L, "Voorbeelden"), child));
editorCell.setAction(CellActionType.BACKSPACE, new CellAction_DeleteSmart(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x36e44840850477e5L, "Voorbeelden"), child));
installCellInfo(child, editorCell);
return editorCell;
}
private void installCellInfo(SNode child, EditorCell editorCell) {
if (editorCell.getSubstituteInfo() == null || editorCell.getSubstituteInfo() instanceof DefaultSubstituteInfo) {
editorCell.setSubstituteInfo(new SChildSubstituteInfo(editorCell));
}
if (editorCell.getRole() == null) {
editorCell.setRole("Voorbeelden");
}
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
}
@Override
public EditorCell createCell() {
try {
getCellFactory().pushCellContext();
getCellFactory().addCellContextHints(new String[]{"ObjectiefRecht.editor.Hints_ObjectiefRecht.Tabel"});
return setCellContext(super.createCell());
} finally {
getCellFactory().popCellContext();
}
}
@Override
protected EditorCell createEmptyCell() {
getCellFactory().pushCellContext();
getCellFactory().setNodeLocation(new SNodeLocation.FromParentAndLink(getNode(), MetaAdapterFactory.getContainmentLink(0x8dc4b25f4c49400eL, 0xac370fd230db702cL, 0x611073d615228d0aL, 0x36e44840850477e5L, "Voorbeelden")));
try {
EditorCell editorCell = super.createEmptyCell();
editorCell.setCellId("empty_Voorbeelden");
installCellInfo(null, editorCell);
setCellContext(editorCell);
return editorCell;
} finally {
getCellFactory().popCellContext();
}
}
protected String getNoTargetText() {
return "<no Voorbeelden>";
}
}
private EditorCell createConstant_feb60b_m0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_m0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
private EditorCell createConstant_feb60b_n0a() {
EditorCell_Constant editorCell = new EditorCell_Constant(getEditorContext(), myNode, "");
editorCell.setCellId("Constant_feb60b_n0a");
Style style = new StyleImpl();
style.set(StyleAttributes.INDENT_LAYOUT_NEW_LINE, true);
editorCell.getStyle().putAll(style);
editorCell.setDefaultText("");
return editorCell;
}
}
| agpl-3.0 |
befair/soulShape | wp/soulshape.earth/wp-content/plugins/users-ultra/xooclasses/xoo.userultra.class.php | 112568 | <?php
class XooUserUltra
{
public $classes_array = array();
public $registration_fields;
public $login_fields;
public $fields;
public $allowed_inputs;
public $use_captcha = "no";
var $_aPostableTypes = array(
'post',
'page',
'attachment',
);
public function __construct()
{
$this->logged_in_user = 0;
$this->login_code_count = 0;
$this->current_page = $_SERVER['REQUEST_URI'];
if (isset($_GET['uultrasocialsignup']))
{
session_start();
$_SESSION['google_token'] = NULL;
/* get social links */
$this->social_login_links_openid();
}
}
public function plugin_init()
{
/*Load Main classes*/
$this->set_main_classes();
$this->load_classes();
/*Load Amin Classes*/
if (is_admin())
{
$this->set_admin_classes();
$this->load_classes();
}
//ini settings
$this->intial_settings();
}
public function set_main_classes()
{
$this->classes_array = array( "commmonmethods" =>"xoo.userultra.common" ,
"captchamodule" =>"xoo.userultra.captchamodules",
"htmlbuilder" =>"xoo.userultra.htmlbuilder" ,
"publisher" =>"xoo.userultra.publisher" ,
"activity" =>"xoo.userultra.activity" ,
"messaging" =>"xoo.userultra.messaging" ,
"recaptchalib" =>"xoo.userultra.recaptchalib",
"order" =>"xoo.userultra.order",
"subscribe" =>"xoo.userultra.newslettertool",
"paypal" =>"xoo.userultra.payment.paypal" ,
"social" =>"xoo.userultra.socials",
"shortocde" =>"xoo.userultra.shorcodes" ,
"login" =>"xoo.userultra.login" ,
"register" =>"xoo.userultra.register",
"mymessage" =>"xoo.userultra.mymessage" ,
"rating" =>"xoo.userultra.rating" ,
"statistc" =>"xoo.userultra.stat" ,
"photogallery" =>"xoo.userultra.photos" ,
"woocommerce" =>"xoo.userultra.woocommerce" ,
"userpanel" =>"xoo.userultra.user" );
}
public function pluginname_ajaxurl()
{
echo '<script type="text/javascript">var ajaxurl = "'. admin_url("admin-ajax.php") .'";
</script>';
}
public function intial_settings()
{
add_action( 'admin_notices', array(&$this, 'uultra_display_custom_message'));
add_action( 'wp_ajax_create_default_pages_auto', array( $this, 'create_default_pages_auto' ));
add_action( 'wp_ajax_hide_rate_message', array( $this, 'hide_rate_message' ));
add_action( 'wp_ajax_hide_proversion_message', array( $this, 'hide_proversion_message' ));
$this->include_for_validation = array('text','fileupload','textarea','select','radio','checkbox','password');
add_action('init', array(&$this, 'xoousers_load_textdomain'));
add_action('wp_enqueue_scripts', array(&$this, 'add_front_end_styles'), 9);
/* Remove bar except for admins */
add_action('init', array(&$this, 'userultra_remove_admin_bar'), 9);
/* Create Standar Fields */
add_action('init', array(&$this, 'xoousers_create_standard_fields'));
add_action('admin_init', array(&$this, 'xoousers_create_standard_fields'));
/*Create a generic profile page*/
add_action( 'init', array(&$this, 'create_initial_pages'), 9);
/*Setup redirection*/
add_action( 'wp_loaded', array(&$this, 'xoousersultra_redirect'), 9);
add_action( 'wp_head', array(&$this, 'pluginname_ajaxurl'));
add_action( 'wp_head', array(&$this, 'add_custom_css_style'));
$this->uultra_post_protection_logged_in();
}
// post protection by logged in users
function uultra_post_protection_logged_in()
{
if($this->get_option('uultra_loggedin_activated')=='1')
{
add_action( 'save_post', array( &$this, 'uultra_save_post_logged_in_protect' ), 97);
add_filter('the_posts', array(&$this, 'uultra_showPost'));
add_filter('get_pages', array(&$this, 'uultra_showPage'));
add_action( 'add_meta_boxes', array(&$this, 'uultra_post_protection_add_meta_box' ));
}
}
/**
* The function for the get_pages filter.
*
* @param array $aPages The pages.
*
* @return array
*/
public function uultra_showPage($aPages = array())
{
global $xoouserultra;
$aShowPages = array();
foreach ($aPages as $oPage)
{
if ($xoouserultra->get_option('uultra_loggedin_hide_complete_page') == 'yes' )
{
if ($this->checkAccessToPost($oPage->ID))
{
$aShowPages[] = $oPage;
}
} else {
if (!$this->checkAccessToPost($oPage->ID))
{
if ($xoouserultra->get_option('uultra_loggedin_hide_page_title') == 'yes')
{
$oPage->post_title =$xoouserultra->get_option('uultra_loggedin_page_title');
}
$oPage->post_content = $xoouserultra->get_option('uultra_loggedin_page_content');;
}
$aShowPages[] = $oPage;
}
}
$aPages = $aShowPages;
return $aPages;
}
/**
* The function for the the_posts filter.
*
* @param array $aPosts The posts.
*
* @return array
*/
public function uultra_showPost($aPosts = array())
{
global $xoouserultra;
$aShowPosts = array();
if (!is_feed() || ($this->get_option('uultra_loggedin_protect_feed') == 'yes' && is_feed()))
{
//echo "HERE ";
foreach ($aPosts as $iPostId)
{
if ($iPostId !== null)
{
$oPost = $this->_getPost($iPostId);
if ($oPost !== null)
{
$aShowPosts[] = $oPost;
}
}
}
$aPosts = $aShowPosts;
}
return $aPosts;
}
/**
* Modifies the content of the post by the given settings.
*
* @param object $oPost The current post.
*
* @return object|null
*/
protected function _getPost($oPost)
{
global $xoouserultra;
$sPostType = $oPost->post_type;
if ($sPostType != 'post' && $sPostType != 'page')
{
$sPostType = 'post';
} elseif ($sPostType != 'post' && $sPostType != 'page')
{
return $oPost;
}
if ($xoouserultra->get_option('uultra_loggedin_hide_complete_'.$sPostType.'') == 'yes' )
{
if ($this->checkAccessToPost($oPost->ID))
{
return $oPost;
}
} else {
if (!$this->checkAccessToPost($oPost->ID))
{
$oPost->isLocked = true;
$uultraPostContent = $xoouserultra->get_option('uultra_loggedin_'.$sPostType.'_content');
if ($xoouserultra->get_option('uultra_loggedin_hide_'.$sPostType.'_title') == 'yes')
{
$oPost->post_title =$xoouserultra->get_option('uultra_loggedin_'.$sPostType.'_title');
}
if ($xoouserultra->get_option('uultra_loggedin_allow_'.$sPostType.'_comments') == 'no')
{
$oPost->comment_status = 'close';
}
if ($xoouserultra->get_option('uultra_loggedin_post_content_before_more') == 'yes'
&& $sPostType == "post" && preg_match('/<!--more(.*?)?-->/', $oPost->post_content, $aMatches)
)
{
$oPost->post_content = explode($aMatches[0], $oPost->post_content, 2);
$uultraPostContent = $oPost->post_content[0] . " " . $uultraPostContent;
}
$oPost->post_content = stripslashes($uultraPostContent);
//$oPost->post_content = "Check here";
}
return $oPost;
}
return null;
}
public function checkAccessToPost($post_id)
{
global $xoouserultra;
//require_once(ABSPATH . 'wp-includes/pluggable.php');
require_once(ABSPATH. 'wp-admin/includes/user.php' );
$res = true;
$uultra_protect_logged_in = get_post_meta( $post_id, 'uultra_protect_logged_in' , true);
if ($uultra_protect_logged_in == 'yes' )
{
if(!is_user_logged_in())
{
$res = false;
}
}else{
$res = true;
}
return $res;
}
function uultra_save_post_logged_in_protect( $post_id )
{
// If this is just a revision, don't send the email.
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave($post_id) )
return;
$post = get_post($post_id);
if($post->post_status == 'trash' ){
return $post_id;
}
$aFormData = array();
if (isset($_POST['uultra_update_logged_in_access'])) {
$aFormData = $_POST;
} elseif (isset($_GET['uultra_update_logged_in_access'])) {
$aFormData = $_GET;
}
if (isset($aFormData['uultra_update_logged_in_access']))
{
$is_protected = $aFormData['uultra_protect_logged_in'];
update_post_meta($post_id, 'uultra_protect_logged_in', $is_protected);
}
}
function uultra_post_protection_add_meta_box()
{
$this->_aPostableTypes = array_merge($this->_aPostableTypes, get_post_types(array('publicly_queryable' => true), 'names'));
$this->_aPostableTypes = array_unique($this->_aPostableTypes);
$aPostableTypes = $this->getPostableTypes();
foreach ($aPostableTypes as $sPostableType)
{
add_meta_box('uultra_post_access_logged_in', 'Users Ultra Post Protection', array(&$this, 'editPostContent'), $sPostableType, 'side');
}
}
public function getPostableTypes()
{
return $this->_aPostableTypes;
}
public function editPostContent($oPost)
{
$iObjectId = $oPost->ID;
if (isset($_GET['attachment_id'])) {
$iObjectId = $_GET['attachment_id'];
} elseif (!isset($iObjectId)) {
$iObjectId = 0;
}
$oPost = get_post($iObjectId);
$sObjectType = $oPost->post_type;
$uultra_protect_logged_in = get_post_meta( $iObjectId, 'uultra_protect_logged_in' , true);
$html = '';
$html .= '<div class="uultra-protect-group-options"> ';
$html .= '<input type="hidden" name="uultra_update_logged_in_access" value="true" /> ';
if ($uultra_protect_logged_in=='yes')
{
$checked = 'checked="checked"';
}
$html .= ' <li>';
$html .= '<input type="checkbox" id="uultra_protect_logged_in" value="yes" name="uultra_protect_logged_in" '.$checked.' /> ';
$html .= ' <label for="uultra_protect_logged_in" class="selectit" style="display:inline;" >
'.__('Only Logged in Users','xoousers').'
</label>';
$html .= ' </li>';
$html .= ' </div>';
echo $html;
}
public function add_custom_css_style ()
{
$custom_css = $this->get_option('xoousersultra_custom_css');
$html = "";
if($custom_css!="" )
{
$html .= ' <style type="text/css">';
$html .= $custom_css;
$html .= ' </style>';
}
echo $html;
}
public function create_default_pages_auto ()
{
update_option('xoousersultra_auto_page_creation',1);
}
public function hide_rate_message ()
{
update_option('xoousersultra_already_rated_ultra',1);
}
public function hide_proversion_message ()
{
update_option('xoousersultra_pro_annuncement_1463',1);
}
public function get_pro_change_log ()
{
global $xoouserultra, $wpdb ;
require_once(ABSPATH . 'wp-includes/class-http.php');
require_once(ABSPATH . 'wp-includes/ms-functions.php');
$url = "http://usersultra.com/get_change_log_pro.php";
$response = wp_remote_post(
$url,
array(
'body' => array(
'd' => $domain,
'server_ip' => $server_add,
'sial_key' => $p,
'action' => 'validate',
)
)
);
$response = $response["body"];
return $response;
}
public function uultra_display_custom_message ()
{
//default pages created?
$my_account_page = get_option('xoousersultra_my_account_page');
$fresh_page_creation = get_option( 'xoousersultra_auto_page_creation' );
if($my_account_page=="" && $fresh_page_creation =="")
//if($fresh_page_creation =="")
{
$message = __('Thanks for installing Users Ultra. Do you need help?. Users Ultra can create the initial pages automatically. You just need to <a href="#" id="uultradmin-create-basic-fields">CLICK HERE</a> to start using Users Ultra. ', 'xoousers');
$this->uultra_fresh_install_message($message);
}
//Pro major 1.1.13 message
$uultra_pro_message_113 = get_option( 'xoousersultra_pro_annuncement_1463' );
if($uultra_pro_message_113=="" )
{
$message = __("<h2>Upgrade Now to Users Ultra Pro!. </h2> <p>Unique Widgetized user profile, add unlimited widgets, site-wide activity wall, add unlimited links within the user's dashboard. Integrating with third-party plugins by using shortcodes, friends, followers, following, user's wall, multiple profile layouts and many more amazing features.</p> <p> <a href='http://usersultra.com/' target='_blank' class='button button-secondary' >CLICK HERE TO FIND OUT MORE</a> </p> <a href='#' id='uultradmin-remove-proversionmessage'>Remove this message</a>", 'xoousers');
//$this->uultra_fresh_install_message($message);
}
//chekc my account link
$acc_link = $this->login->get_my_account_direct_link();
if($acc_link=="" )
{
echo '<div id="uultra-message" class="error"><p><strong>'.__("Users Ultra might be working wrong. We couldn't find the 'My Account' shortcode. Please click on settings tab and make sure that the My Account page has been set correctly. Then click on the 'save' button ","xoousers").'</strong></p></div>';
}
}
//display message
public function uultra_fresh_install_message ($message)
{
if ($errormsg)
{
echo '<div id="uultra-message" class="error">';
}else{
echo '<div id="uultra-message" class="updated fade">';
}
echo "<p><strong>$message</strong></p></div>";
}
public function uultra_uninstall ()
{
global $wpdb;
$delete_all_plugin_info = $this->get_option('uultra_delete_plugin_info_on_unistall');
if($delete_all_plugin_info=='yes')
{
$thetable = $wpdb->prefix."usersultra_stats_raw";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_stats";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_friends";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_likes";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_ajaxrating_vote";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_ajaxrating_votesummary";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_galleries";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_photos";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_photo_categories";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_photo_cat_rel";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_videos";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_packages";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_orders";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."users_ultra_pm";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_activity";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
//wall
$thetable = $wpdb->prefix."usersultra_wall";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
$thetable = $wpdb->prefix."usersultra_wall_replies";
$wpdb->query("DROP TABLE IF EXISTS $thetable");
//delete meta info
delete_option( 'usersultra_profile_fields' );
delete_option( 'userultra_default_user_tabs' );
delete_option( 'xoousersultra_my_account_page' );
delete_option( 'xoousersultra_auto_page_creation' );
delete_option( 'userultra_options' );
}
}
function userultra_remove_admin_bar()
{
if (!current_user_can('administrator') && !is_admin())
{
if ($this->get_option('hide_admin_bar')==1)
{
show_admin_bar(false);
}
}
}
public function get_logout_url ()
{
/*$defaults = array(
'redirect_to' => $this->current_page
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );*/
$redirect_to = $this->current_page;
return wp_logout_url($redirect_to);
}
public function custom_logout_page ($atts)
{
global $xoouserultra, $wp_rewrite ;
$wp_rewrite = new WP_Rewrite();
require_once(ABSPATH . 'wp-includes/link-template.php');
//require_once(ABSPATH . 'wp-includes/pluggable.php');
extract( shortcode_atts( array(
'redirect_to' => '',
), $atts ) );
/*$defaults = array(
'redirect_to' => $this->current_page
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );*/
//check redir
$account_page_id = get_option('xoousersultra_my_account_page');
$my_account_url = get_permalink($account_page_id);
if($redirect_to=="")
{
$redirect_to =$my_account_url;
}
$logout_url = wp_logout_url($redirect_to);
//quick patch =
$logout_url = str_replace("amp;","",$logout_url);
wp_redirect($logout_url);
//exit;
}
public function get_redirection_link ($module)
{
$url ="";
if($module=="profile")
{
//get profile url
$url = $this->get_option('profile_page_id');
}
return $url;
}
/*Setup redirection*/
public function xoousersultra_redirect()
{
global $pagenow;
/* Not admin */
if (!current_user_can('administrator')) {
$option_name = '';
// Check if current page is profile page
if('profile.php' == $pagenow)
{
// If user have selected to redirect backend profile page
if($this->get_option('redirect_backend_profile') == '1')
{
$option_name = 'profile_page_id';
}
}
// Check if current page is login or not
if('wp-login.php' == $pagenow && !isset($_REQUEST['action']))
{
if($this->get_option('redirect_backend_login') == '1')
{
$option_name = 'login_page_id';
}
}
if('wp-login.php' == $pagenow && isset($_REQUEST['action']) && $_REQUEST['action'] == 'register')
{
if($this->get_option('redirect_backend_registration') == '1')
{
$option_name = 'registration_page_id';
}
}
if($option_name != '')
{
if($this->get_option($option_name) > 0)
{
// Generating page url based on stored ID
$page_url = get_permalink($this->get_option($option_name));
// Redirect if page is not blank
if($page_url != '')
{
if($option_name == 'login_page_id' && isset($_GET['redirect_to']))
{
$url_data = parse_url($page_url);
$join_code = '/?';
if(isset($url_data['query']) && $url_data['query']!= '')
{
$join_code = '&';
}
$page_url= $page_url.$join_code.'redirect_to='.$_GET['redirect_to'];
}
wp_redirect($page_url);
exit;
}
}
}
}
}
public function create_initial_pages ()
{
$fresh_page_creation = get_option( 'xoousersultra_auto_page_creation' );
if($fresh_page_creation==1) //user wants to recreate pages
{
//create profile page
$login_page_id = $this->create_login_page();
//create registration page
$login_page_id = $this->create_register_page();
//Create Main Page
$main_page_id = $this->create_main_page();
//create profile page
$profile_page_id = $this->create_profile_page($main_page_id);
//directory page
$directory_page_id = $this->create_directory_page($main_page_id);
//pages created
update_option('xoousersultra_auto_page_creation',0);
$slug = $this->get_option("usersultra_slug"); // Profile Slug
$slug_login = $this->get_option("usersultra_login_slug"); //Login Slug
$slug_registration = $this->get_option("usersultra_registration_slug"); //Registration Slug
$slug_my_account = $this->get_option("usersultra_my_account_slug"); //My Account Slug
// this rule is used to display the registration page
add_rewrite_rule("$slug/$slug_registration",'index.php?pagename='.$slug.'/'.$slug_registration, 'top');
//this rules is for displaying the user's profiles
add_rewrite_rule("$slug/([^/]+)/?",'index.php?pagename='.$slug.'&uu_username=$matches[1]', 'top');
flush_rewrite_rules();
}else{
$slug = $this->get_option("usersultra_slug"); // Profile Slug
$slug_login = $this->get_option("usersultra_login_slug"); //Login Slug
$slug_registration = $this->get_option("usersultra_registration_slug"); //Registration Slug
$slug_my_account = $this->get_option("usersultra_my_account_slug"); //My Account Slug
// this rule is used to display the registration page
add_rewrite_rule("$slug/$slug_registration",'index.php?pagename='.$slug.'/'.$slug_registration, 'top');
//this rules is for displaying the user's profiles
add_rewrite_rule("$slug/([^/]+)/?",'index.php?pagename='.$slug.'&uu_username=$matches[1]', 'top');
//this rules is for displaying the user's profiles
add_rewrite_rule("([^/]+)/$slug/([^/]+)/?",'index.php?pagename='.$slug.'&uu_username=$matches[2]', 'top');
}
/* Setup query variables */
add_filter( 'query_vars', array(&$this, 'userultra_uid_query_var') );
}
//to be removed soon
public function create_rewrite_rules()
{
$slug = $this->get_option("usersultra_slug"); // Profile Slug
$slug_login = $this->get_option("usersultra_login_slug"); //Login Slug
$slug_registration = $this->get_option("usersultra_registration_slug"); //Registration Slug
$slug_my_account = $this->get_option("usersultra_my_account_slug"); //My Account Slug
// this rule is used to display the registration page
add_rewrite_rule("$slug/$slug_registration",'index.php?pagename='.$slug.'/'.$slug_registration, 'top');
//this rules is for displaying the user's profiles
add_rewrite_rule("$slug/([^/]+)/?",'index.php?pagename='.$slug.'&uu_username=$matches[1]', 'top');
//this rules is for displaying the user's profiles
add_rewrite_rule("([^/]+)/$slug/([^/]+)/?",'index.php?pagename='.$slug.'&uu_username=$matches[2]', 'top');
//this rules is for photos
flush_rewrite_rules();
}
/*Create profile page */
public function create_profile_page($parent)
{
if (!$this->get_option('profile_page_id'))
{
$slug = $this->get_option("usersultra_slug");
$new = array(
'post_title' => __('View Profile','xoousers'),
'post_type' => 'page',
'post_name' => $slug,
'post_content' => '[usersultra_profile]',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1
);
$new_page = wp_insert_post( $new, FALSE );
if (isset($new_page))
{
$current_option = get_option('userultra_options');
$page_data = get_post($new_page);
if(isset($page_data->guid))
{
//update settings
$this->userultra_set_option('profile_page_id',$new_page);
}
}
}
}
/*Create Directory page */
public function create_directory_page($parent)
{
if (!$this->get_option('directory_page_id'))
{
$slug = $this->get_option("usersultra_directory_slug");
$new = array(
'post_title' => __('Members Directory','xoousers'),
'post_type' => 'page',
'post_name' => $slug,
'post_content' =>"[usersultra_searchbox filters='country,age' ]
[usersultra_directory list_per_page=8 optional_fields_to_display='friend,social,country,description' pic_boder_type='rounded']",
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1
);
$new_page = wp_insert_post( $new, FALSE );
if (isset($new_page))
{
$current_option = get_option('userultra_options');
$page_data = get_post($new_page);
if(isset($page_data->guid))
{
//update settings
$this->userultra_set_option('directory_page_id',$new_page);
}
}
}
}
/*Create login page */
public function create_login_page()
{
if (!$this->get_option('login_page_id')) {
$slug = $this->get_option("usersultra_login_slug");
$new = array(
'post_title' => __('Login','xoousers'),
'post_type' => 'page',
'post_name' => $slug,
'post_content' => '[usersultra_login]',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1
);
$new_page = wp_insert_post( $new, FALSE );
if (isset($new_page))
{
$page_data = get_post($new_page);
if(isset($page_data->guid))
{
//update settings
$this->userultra_set_option('login_page_id',$new_page);
}
}
}
}
/*Create register page */
public function create_register_page()
{
if (!$this->get_option('registration_page_id')) {
//get slug
$slug = $this->get_option("usersultra_registration_slug");
$new = array(
'post_title' => __('Sign up','xoousers'),
'post_type' => 'page',
'post_name' => $slug,
'post_content' => '[usersultra_registration]',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1
);
$new_page = wp_insert_post( $new, FALSE );
if (isset($new_page))
{
$page_data = get_post($new_page);
if(isset($page_data->guid))
{
//update settings
$this->userultra_set_option('registration_page_id',$new_page);
}
}
}
}
/*Create My Account Page */
public function create_main_page()
{
if (!get_option('xoousersultra_my_account_page'))
{
//get slug
$slug = $this->get_option("usersultra_my_account_slug");
$new = array(
'post_title' => __('My Account','xoousers'),
'post_type' => 'page',
'post_name' => $slug,
'post_content' => '[usersultra_my_account]',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => 1
);
$new_page = wp_insert_post( $new, FALSE );
update_option('xoousersultra_my_account_page',$new_page);
}else{
$new_page=get_option('xoousersultra_my_account_page');
}
return $new_page;
}
public function userultra_uid_query_var( $query_vars )
{
$query_vars[] = 'uu_username';
$query_vars[] = 'searchuser';
$query_vars[] = 'uultra-page';
return $query_vars;
}
public function userultra_set_option($option, $newvalue)
{
$settings = get_option('userultra_options');
$settings[$option] = $newvalue;
update_option('userultra_options', $settings);
}
public function get_fname_by_userid($user_id)
{
$f_name = get_user_meta($user_id, 'first_name', true);
$l_name = get_user_meta($user_id, 'last_name', true);
$f_name = str_replace(' ', '_', $f_name);
$l_name = str_replace(' ', '_', $l_name);
$name = $f_name . '-' . $l_name;
return $name;
}
public function xoousers_create_standard_fields ()
{
/* Allowed input types */
$this->allowed_inputs = array(
'text' => __('Text','xoousers'),
'fileupload' => __('Image Upload','xoousers'),
'textarea' => __('Textarea','xoousers'),
'select' => __('Select Dropdown','xoousers'),
'radio' => __('Radio','xoousers'),
'checkbox' => __('Checkbox','xoousers'),
'password' => __('Password','xoousers'),
'datetime' => __('Date Picker','xoousers')
);
/* Core registration fields */
$set_pass = $this->get_option('set_password');
if ($set_pass)
{
$this->registration_fields = array(
50 => array(
'icon' => 'user',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'user_login',
'name' => __('Username','xoousers'),
'required' => 1
),
100 => array(
'icon' => 'envelope',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'user_email',
'name' => __('E-mail','xoousers'),
'required' => 1,
'can_hide' => 1,
),
150 => array(
'icon' => 'lock',
'field' => 'password',
'type' => 'usermeta',
'meta' => 'user_pass',
'name' => __('Password','xoousers'),
'required' => 1,
'can_hide' => 0,
'help' => __('Password must be at least 7 characters long. To make it stronger, use upper and lower case letters, numbers and symbols.','xoousers')
),
200 => array(
'icon' => 0,
'field' => 'password',
'type' => 'usermeta',
'meta' => 'user_pass_confirm',
'name' => __('Confirm Password','xoousers'),
'required' => 1,
'can_hide' => 0,
'help' => __('Type your password again.','xoousers')
),
250 => array(
'icon' => 0,
'field' => 'password_indicator',
'type' => 'usermeta'
)
);
} else {
$this->registration_fields = array(
50 => array(
'icon' => 'user',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'user_login',
'name' => __('Username','xoousers'),
'required' => 1
),
100 => array(
'icon' => 'envelope',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'user_email',
'name' => __('E-mail','xoousers'),
'required' => 1,
'can_hide' => 1,
'help' => __('A password will be e-mailed to you.','xoousers')
)
);
}
/* Core login fields */
$this->login_fields = array(
50 => array(
'icon' => 'user',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'user_login',
'name' => __('Username or Email','xoousers'),
'required' => 1
),
100 => array(
'icon' => 'lock',
'field' => 'password',
'type' => 'usermeta',
'meta' => 'login_user_pass',
'name' => __('Password','xoousers'),
'required' => 1
)
);
/* These are the basic profile fields */
$this->fields = array(
80 => array(
'position' => '50',
'type' => 'separator',
'name' => __('Profile Info','xoousers'),
'private' => 0,
'show_in_register' => 1,
'deleted' => 0
),
100 => array(
'position' => '100',
'icon' => 'user',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'first_name',
'name' => __('First Name','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'private' => 0,
'social' => 0,
'deleted' => 0
),
120 => array(
'position' => '101',
'icon' => 0,
'field' => 'text',
'type' => 'usermeta',
'meta' => 'last_name',
'name' => __('Last Name','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'private' => 0,
'social' => 0,
'deleted' => 0
),
130 => array(
'position' => '130',
'icon' => '0',
'field' => 'select',
'type' => 'usermeta',
'meta' => 'age',
'name' => __('Age','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'required' => 1,
'private' => 0,
'social' => 0,
'predefined_options' => 'age',
'deleted' => 0,
'allow_html' => 0
),
150 => array(
'position' => '150',
'icon' => 'user',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'display_name',
'name' => __('Display Name','xoousers'),
'can_hide' => 0,
'can_edit' => 1,
'show_in_register' => 1,
'private' => 0,
'social' => 0,
'required' => 1,
'deleted' => 0
),
170 => array(
'position' => '200',
'icon' => 'pencil',
'field' => 'textarea',
'type' => 'usermeta',
'meta' => 'brief_description',
'name' => __('Brief Description','xoousers'),
'can_hide' => 0,
'can_edit' => 1,
'show_in_register' => 1,
'private' => 0,
'social' => 0,
'deleted' => 0,
'allow_html' => 1
),
190 => array(
'position' => '200',
'icon' => 'pencil',
'field' => 'textarea',
'type' => 'usermeta',
'meta' => 'description',
'name' => __('About / Bio','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'private' => 0,
'social' => 0,
'deleted' => 0,
'allow_html' => 1
),
200 => array(
'position' => '200',
'icon' => '0',
'field' => 'select',
'type' => 'usermeta',
'meta' => 'country',
'name' => __('Country','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'required' => 1,
'private' => 0,
'social' => 0,
'predefined_options' => 'countries',
'deleted' => 0,
'allow_html' => 0
),
230 => array(
'position' => '250',
'type' => 'separator',
'name' => __('Contact Info','xoousers'),
'private' => 0,
'show_in_register' => 1,
'deleted' => 0
),
430 => array(
'position' => '400',
'icon' => 'link',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'user_url',
'name' => __('Website','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'required' => 0,
'private' => 0,
'social' => 0,
'deleted' => 0
),
470 => array(
'position' => '450',
'type' => 'separator',
'name' => __('Social Profiles','xoousers'),
'private' => 0,
'show_in_register' => 1,
'deleted' => 0
),
520 => array(
'position' => '500',
'icon' => 'facebook',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'facebook',
'name' => __('Facebook','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'required' => 0,
'show_in_register' => 1,
'private' => 0,
'social' => 1,
'tooltip' => __('Connect via Facebook','xoousers'),
'deleted' => 0
),
560 => array(
'position' => '510',
'icon' => 'twitter',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'twitter',
'name' => __('Twitter Username','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'required' => 0,
'show_in_register' => 1,
'private' => 0,
'social' => 1,
'tooltip' => __('Connect via Twitter','xoousers'),
'deleted' => 0
),
590 => array(
'position' => '520',
'icon' => 'google-plus',
'field' => 'text',
'type' => 'usermeta',
'meta' => 'googleplus',
'name' => __('Google+','xoousers'),
'can_hide' => 1,
'can_edit' => 1,
'show_in_register' => 1,
'private' => 0,
'required' => 0,
'social' => 1,
'tooltip' => __('Connect via Google+','xoousers'),
'deleted' => 0
),
600 => array(
'position' => '550',
'type' => 'separator',
'name' => __('Account Info','xoousers'),
'private' => 0,
'show_in_register' => 0,
'deleted' => 0
),
690 => array(
'position' => '600',
'icon' => 'lock',
'field' => 'password',
'type' => 'usermeta',
'meta' => 'user_pass',
'name' => __('New Password','xoousers'),
'can_hide' => 0,
'can_edit' => 1,
'private' => 1,
'social' => 0,
'deleted' => 0
),
720 => array(
'position' => '700',
'icon' => 0,
'field' => 'password',
'type' => 'usermeta',
'meta' => 'user_pass_confirm',
'name' => 0,
'can_hide' => 0,
'can_edit' => 1,
'private' => 1,
'social' => 0,
'deleted' => 0
)
);
/* Store default profile fields for the first time */
if (!get_option('usersultra_profile_fields'))
{
update_option('usersultra_profile_fields', $this->fields);
}
}
public function xoousers_update_field_value($option, $newvalue)
{
$fields = get_option('usersultra_profile_fields');
$fields[$option] = $newvalue;
update_option('usersultra_profile_fields', $settings);
}
public function xoousers_load_textdomain()
{
//load_plugin_textdomain( 'xoousers', false, xoousers_path.'/languages/');
}
function get_the_guid( $id = 0 )
{
$post = get_post($id);
return apply_filters('get_the_guid', $post->guid);
}
function load_classes()
{
foreach ($this->classes_array as $key => $class)
{
if (file_exists(xoousers_path."xooclasses/$class.php"))
{
require_once(xoousers_path."xooclasses/$class.php");
}
}
}
public function set_admin_classes()
{
$this->classes_array = array("xooadmin" =>"xoo.userultra.admin",
"adminshortcode" =>"xoo.userultra.adminshortcodes",
"woocommerce" =>"xoo.userultra.woocommerce"
);
}
/* register styles */
public function add_front_end_styles()
{
wp_enqueue_script( 'jquery-ui-datepicker' );
// Loading CSS and Script only when required
/* Tipsy script */
if (!wp_script_is('uultra_tipsy')) {
wp_register_script('uultra_tipsy', xoousers_url.'js/jquery.tipsy.js',array('jquery'));
wp_enqueue_script('uultra_tipsy');
}
/* Font Awesome */
wp_register_style( 'xoouserultra_font_awesome', xoousers_url.'css/css/font-awesome.min.css');
wp_enqueue_style('xoouserultra_font_awesome');
/* Main css file */
//wp_register_style( 'xoouserultra_css', xoousers_url.'templates/'.xoousers_template.'/css/xoouserultra.css');
//wp_enqueue_style('xoouserultra_css');
/* Custom style */
wp_register_style( 'xoouserultra_style', xoousers_url.'templates/'.xoousers_template.'/css/default.css');
wp_enqueue_style('xoouserultra_style');
/*Expandible*/
wp_register_script( 'xoouserultra_expandible_js', xoousers_url.'js/expandible.js',array('jquery'));
wp_enqueue_script('xoouserultra_expandible_js');
/*uploader*/
wp_enqueue_script('jquery-ui');
wp_enqueue_script('plupload-all');
wp_enqueue_script('jquery-ui-progressbar');
if($this->get_option('disable_default_lightbox')!=1)
{
//lightbox
//wp_register_style( 'xoouserultra_lightbox_css', xoousers_url.'js/lightbox/css/lightbox.css');
//wp_enqueue_style('xoouserultra_lightbox_css');
//wp_register_script( 'xoouserultra_lightboxjs', xoousers_url.'js/lightbox/js/lightbox-2.6.min.js',array('jquery'));
//wp_enqueue_script('xoouserultra_lightboxjs');
}
/*Validation Engibne JS*/
wp_register_script( 'form-validate-lang', xoousers_url.'js/languages/jquery.validationEngine-en.js',array('jquery'));
wp_enqueue_script('form-validate-lang');
wp_register_script('form-validate', xoousers_url.'js/jquery.validationEngine.js',array('jquery'));
wp_enqueue_script('form-validate');
/*Users JS*/
wp_register_script( 'uultra-front_js', xoousers_url.'js/uultra-front.js',array('jquery'));
wp_enqueue_script('uultra-front_js');
//front end style
$date_picker_array = array(
'closeText' => __('Done',"xoousers"),
'prevText' => __('Prev',"xoousers"),
'nextText' => __('Next',"xoousers"),
'currentText' => __('Today',"xoousers"),
'monthNames' => array(
'Jan' => __('January',"xoousers"),
'Feb' => __('February',"xoousers"),
'Mar' => __('March',"xoousers"),
'Apr' => __('April',"xoousers"),
'May' => __('May',"xoousers"),
'Jun' => __('June',"xoousers"),
'Jul' => __('July',"xoousers"),
'Aug' => __('August',"xoousers"),
'Sep' => __('September',"xoousers"),
'Oct' => __('October' ,"xoousers"),
'Nov' => __('November' ,"xoousers"),
'Dec' => __('December' ,"xoousers")
),
'monthNamesShort' => array(
'Jan' => __('Jan' ,"xoousers") ,
'Feb' => __('Feb' ,"xoousers"),
'Mar' => __('Mar' ,"xoousers"),
'Apr' => __('Apr' ,"xoousers"),
'May' => __('May' ,"xoousers"),
'Jun' => __('Jun' ,"xoousers"),
'Jul' => __('Jul' ,"xoousers"),
'Aug' => __('Aug' ,"xoousers"),
'Sep' => __('Sep' ,"xoousers"),
'Oct' =>__('Oct' ,"xoousers"),
'Nov' => __('Nov' ,"xoousers"),
'Dec' => __('Dec' ,"xoousers")
),
'dayNames' => array(
'Sun' => __('Sunday' ,"xoousers"),
'Mon' => __('Monday' ,"xoousers"),
'Tue' => __( 'Tuesday' ,"xoousers"),
'Wed' => __( 'Wednesday' ,"xoousers"),
'Thu' => __( 'Thursday' ,"xoousers"),
'Fri' => __('Friday' ,"xoousers"),
'Sat' => __('Saturday' ,"xoousers")
),
'dayNamesShort' => array(
'Sun' => __('Sun' ,"xoousers") ,
'Mon' => __('Mon' ,"xoousers"),
'Tue' => __('Tue' ,"xoousers"),
'Wed' => __('Wed' ,"xoousers"),
'Thu' => __('Thu' ,"xoousers"),
'Fri' =>__('Fri' ,"xoousers"),
'Sat' =>__('Sat' ,"xoousers")
),
'dayNamesMin' => array(
'Sun' => __('Su' ,"xoousers"),
'Mon' => __('Mo' ,"xoousers"),
'Tue' => __('Tu' ,"xoousers"),
'Wed' => __('We' ,"xoousers"),
'Thu' => __('Th' ,"xoousers"),
'Fri' => __('Fr' ,"xoousers"),
'Sat' => __('Sa' ,"xoousers")
),
'weekHeader' => 'Wk'
);
wp_localize_script('uultra-front_js', 'XOOUSERULTRADATEPICKER', $date_picker_array);
}
/* Display Front End Directory*/
public function show_users_directory( $atts )
{
return $this->userpanel->show_users_directory($atts);
}
/* Display Front End Mini Directory*/
public function show_users_directory_mini( $atts )
{
return $this->userpanel->show_users_directory_mini($atts);
}
/* Custom WP Query*/
public function get_results( $query )
{
$wp_user_query = new WP_User_Query($query);
return $wp_user_query;
}
/* Password Reset */
public function password_reset( $args=array() ) {
global $xoouserultra;
// Increasing Counter for Shortcode number
$this->login_code_count++;
// Check if redirect to is not set and redirect to is availble in URL
$default_redirect = $this->current_page;
if(isset($_GET['redirect_to']) && $_GET['redirect_to']!='')
$default_redirect = $_GET['redirect_to'];
/* Arguments */
$defaults = array(
'use_in_sidebar' => null,
'redirect_to' => $default_redirect
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
// Default set to no captcha
$this->captcha = 'no';
$sidebar_class = null;
if ($use_in_sidebar) $sidebar_class = 'xoouserultra-sidebar';
$display = null;
$display .= '<div class="xoouserultra-wrap xoouserultra-login '.$sidebar_class.'">
<div class="xoouserultra-inner xoouserultra-login-wrapper">';
$display .= '<div class="xoouserultra-head">';
$display .='<div class="xoouserultra-left">';
$display .='<div class="xoouserultra-field-name xoouserultra-field-name-wide login-heading" id="login-heading-'.$this->login_code_count.'">'.__('Password Reset','xoousers').'</div>';
$display .='</div>';
$display .='<div class="xoouserultra-right"></div><div class="xoouserultra-clear"></div>';
$display .= '</div>';
$display .='<div class="xoouserultra-main">';
/*Display errors*/
if (isset($_GET['resskey']) && $_GET['resskey']!="")
{
//check if valid
$valid = $xoouserultra->userpanel->get_user_with_key($_GET['resskey']);
if($valid)
{
$display .= $this->show_password_reset_form( $sidebar_class, $args, $_GET['resskey']);
}else{
$display .= '<p>'.__('Oops! The link is not correct! ', 'xoousers').'</p>';
}
}
$display .= '</div>
</div>
</div>';
return $display;
}
/* Show login forms */
public function show_password_reset_form( $sidebar_class=null, $args, $key)
{
global $xoousers_login, $xoousers_captcha_loader;
$display = null;
$display .= '<form action="" method="post" id="xoouserultra-passwordreset-form">';
$display .= '<input type="hidden" class="xoouserultra-input" name="uultra_reset_key" id="uultra_reset_key" value="'.$key.'"/>';
$meta="preset_password";
$meta_2="preset_password_2";
$placeholder = "";
$login_btn_class = "";
//field 1
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$display .= '<label class="xoouserultra-field-type" for="'.$meta.'">';
$display .= '<span>'.__('Type New Password:', 'xoousers').'</span></label>';
$display .= '<div class="xoouserultra-field-value">';
$display .= '<input type="password" class="xoouserultra-input" name="'.$meta.'" id="'.$meta.'" value="" '.$placeholder.' />';
$display .= '</div>';
$display .= '</div><div class="xoouserultra-clear"></div>';
//field 2
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$display .= '<label class="xoouserultra-field-type" for="'.$meta_2.'">';
$display .= '<span>'.__('Re-type Password:', 'xoousers').'</span></label>';
$display .= '<div class="xoouserultra-field-value">';
$display .= '<input type="password" class="xoouserultra-input" name="'.$meta_2.'" id="'.$meta_2.'" value="" '.$placeholder.' />';
$display .= '</div>';
$display .= '</div><div class="xoouserultra-clear"></div>';
$display .= '<div class="xoouserultra-clear"></div>';
$display .= '<input type="submit" name="xoouserultra-login" class="xoouserultra-button xoouserultra-reset-confirm'.$login_btn_class.'" value="'.__('Reset Password','xoousers').'" id="xoouserultra-reset-confirm-pass-btn" />';
$display .= '</br></br>';
$display.='<div class="xoouserultra-signin-noti-block" id="uultra-reset-p-noti-box"> </div>';
$display .= '</form>';
return $display;
}
/* Login Form on Front end */
public function login( $args=array() ) {
global $xoousers_login;
// Increasing Counter for Shortcode number
$this->login_code_count++;
// Check if redirect to is not set and redirect to is availble in URL
$default_redirect = $this->current_page;
if(isset($_GET['redirect_to']) && $_GET['redirect_to']!='')
$default_redirect = $_GET['redirect_to'];
/* Arguments */
$defaults = array(
'use_in_sidebar' => null,
'redirect_to' => $default_redirect,
'form_header_text' => __('Login','xoousers'),
'custom_text' => '',
'custom_registration_link' => '',
'disable_registration_link' => 'no'
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
// Default set to no captcha
$this->captcha = 'no';
if(isset($captcha))
$this->captcha = $captcha;
$sidebar_class = null;
if ($use_in_sidebar) $sidebar_class = 'xoouserultra-sidebar';
$display = null;
$display .= '<div class="xoouserultra-wrap xoouserultra-login '.$sidebar_class.'">
<div class="xoouserultra-inner xoouserultra-login-wrapper">';
$display .= '<div class="xoouserultra-head">';
$display .='<div class="xoouserultra-left">';
$display .='<div class="xoouserultra-field-name xoouserultra-field-name-wide login-heading" id="login-heading-'.$this->login_code_count.'">'.$form_header_text.'</div>';
$display .='</div>';
$display .='<div class="xoouserultra-right"></div><div class="xoouserultra-clear"></div>';
$display .= '</div>';
$display .='<div class="xoouserultra-main">';
$display .= $custom_text;
/*Display errors*/
if (isset($_POST['xoouserultra-login']))
{
$display .= $this->login->get_errors();
}
$display .= $this->show_login_form( $sidebar_class, $redirect_to , $args);
$display .= '</div>
</div>
</div>';
return $display;
}
/* Show login forms */
public function show_login_form( $sidebar_class=null, $redirect_to=null, $args)
{
global $xoousers_login, $xoousers_captcha_loader;
$atts = $args;
extract( shortcode_atts( array(
'custom_registration_link' => '',
'disable_registration_link' => 'no'
), $atts ) );
$display = null;
$display .= '<form action="" method="post" id="xoouserultra-login-form-'.$this->login_code_count.'">';
//get social sign up methods
$display .= $this->get_social_buttons(__("Sign in with",'xoousers' ),$args);
$display .='<h2>'.__("Sign in ",'xoousers' ).'</h2>';
foreach($this->login_fields as $key=>$field)
{
extract($field);
if ( $type == 'usermeta') {
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
/* Show the label */
$placeholder = '';
$icon_name = '';
$input_ele_class='';
if(!isset($required_text)){$required_text='';}
if (isset($this->login_fields[$key]['name']) && $name)
{
$display .= '<label class="xoouserultra-field-type" for="'.$meta.'">';
//icon
if (isset($this->login_fields[$key]['icon']) && $icon)
{
$display .= '<i class="fa fa-'.$icon.'"></i>';
} else {
$display .= '<i class="fa fa-none"></i>';
}
$display .= '<span>'.$name. ' '.$required_text.'</span></label>';
} else {
$display .= '<label class="xoouserultra-field-type"> </label>';
}
$display .= '<div class="xoouserultra-field-value">';
$display .=$icon_name;
switch($field) {
case 'textarea':
$display .= '<textarea class="xoouserultra-input'.$input_ele_class.'" name="'.$meta.'" id="'.$meta.'" '.$placeholder.'>'.$this->get_post_value($meta).'</textarea>';
break;
case 'text':
$display .= '<input type="text" class="xoouserultra-input'.$input_ele_class.'" name="'.$meta.'" id="'.$meta.'" value="'.$this->get_post_value($meta).'" '.$placeholder.' />';
if (isset($this->login_fields[$key]['help']) && $help != '') {
$display .= '<div class="xoouserultra-help">'.$help.'</div><div class="xoouserultra-clear"></div>';
}
break;
case 'password':
$display .= '<input type="password" class="xoouserultra-input'.$input_ele_class.'" name="'.$meta.'" id="'.$meta.'" value="" '.$placeholder.' />';
break;
}
if ($field == 'password') {
}
$display .= '</div>';
$display .= '</div><div class="xoouserultra-clear"></div>';
}
}
//$display.=$xoousers_captcha_loader->load_captcha($this->captcha);
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">
<label class="xoouserultra-field-type xoouserultra-field-type-'.$sidebar_class.'"> </label>
<div class="xoouserultra-field-value">';
if (isset($_POST['rememberme']) && $_POST['rememberme'] == 1)
{
$class = 'xoouserultra-icon-check';
} else {
$class = 'xoouserultra-icon-check-empty';
}
// this is the Forgot Pass Link
$forgot_pass = '<a href="#uultra-forgot-link" id="xoouserultra-forgot-pass-'.$this->login_code_count.'" class="xoouserultra-login-forgot-link" title="'.__('Forgot Password?','xoousers').'">'.__('Forgot Password?','xoousers').'</a>';
// this is the Register Link
$register_link = site_url('/wp-login.php?action=register');
if ($this->get_option('register_redirect') != '')
$register_link = $this->get_option('register_redirect');
//$register_link = '<a href="'.$register_link.'" class="xoouserultra-login-register-link">'.__('Register','xoousers').'</a>';
$register_link_url='';
if($disable_registration_link!='yes')
{
$register_link_url = ' | <a href="'.$register_link.'" class="xoouserultra-login-register-link">'.__('Register','xoousers').'</a>';
}
if($disable_registration_link!='yes' && $custom_registration_link!='')
{
$register_link_url = ' | <a href="'.$custom_registration_link.'" class="xoouserultra-login-register-link">'.__('Register','xoousers').'</a>';
}
$remember_me_class = '';
$login_btn_class = '';
if($sidebar_class != null)
{
$login_btn_class = ' in_sidebar';
$remember_me_class = ' in_sidebar_remember';
}
$display .= '<div class="xoouserultra-rememberme'.$remember_me_class.'">
<input type="checkbox" name="rememberme" id="rememberme_'.$this->login_code_count.'" value="0" /> <label for="rememberme_'.$this->login_code_count.'"><span></span>'.__('Remember me','xoousers').'</label>
</div>
<input type="submit" name="xoouserultra-login" class="xoouserultra-button xoouserultra-login'.$login_btn_class.'" value="'.__('Log In','xoousers').'" /><br />'.$forgot_pass.$register_link_url;
$display .= ' </div>
</div><div class="xoouserultra-clear"></div>';
$display .= '<input type="hidden" name="redirect_to" value="'.$redirect_to.'" />';
$display .= '</form>';
// this is the forgot password form
$forgot_pass = '';
$forgot_pass .= '<div class="xoouserultra-forgot-pass" id="xoouserultra-forgot-pass-holder">';
$forgot_pass .= "<div class='notimessage'>";
$forgot_pass .= "<div class='uupublic-ultra-warning'>".__(" A quick access link will be sent to your email that will let you get in your account and change your password. ", 'xoousers')."</div>";
$forgot_pass .= "</div>";
$forgot_pass .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$forgot_pass .= '<label class="xoouserultra-field-type" for="user_name_email-'.$this->login_code_count.'"><i class="fa fa-user"></i><span>'.__('Username or Email','xoousers').'</span></label>';
$forgot_pass .= '<div class="xoouserultra-field-value">';
$forgot_pass .= '<input type="text" class="xoouserultra-input" name="user_name_email" id="user_name_email" value=""></div>';
$forgot_pass .= '</div>';
$forgot_pass.='<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$forgot_pass.='<label class="xoouserultra-field-type xoouserultra-blank-lable"> </label>';
$forgot_pass.='<div class="xoouserultra-field-value">';
$forgot_pass.='<div class="xoouserultra-back-to-login">';
$forgot_pass.='<a href="javascript:void(0);" title="'.__('Back to Login','xoousers').'" id="xoouserultra-back-to-login-'.$this->login_code_count.'">'.__('Back to Login','xoousers').'</a> ';
$forgot_pass.='</div>';
$forgot_pass.='<input type="button" name="xoouserultra-forgot-pass" id="xoouserultra-forgot-pass-btn-confirm" class="xoouserultra-button xoouserultra-login" value="'.__('Send me Password','xoousers').'">';
$forgot_pass.='<div class="xoouserultra-signin-noti-block" id="uultra-signin-ajax-noti-box"> ';
$forgot_pass.='</div>';
$forgot_pass.='</div>';
$forgot_pass.='</div>';
$forgot_pass .= '</div>';
$display.=$forgot_pass;
return $display;
}
/* Show registration form */
function show_registration_form( $args=array() )
{
global $post, $xoousers_register;
// Loading scripts and styles only when required
/* Password Stregth Checker Script */
if(!wp_script_is('form-validate'))
{
/*Validation Engibne JS*/
$validate_strings = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ErrMsg' => array(
'similartousername' => __('Your password is too similar to your username.','xoousers'),
'mismatch' => __('Both passwords do not match.','xoousers'),
'tooshort' => __('Your password is too short.','xoousers'),
'veryweak' => __('Your password strength is too weak.','xoousers'),
'weak' => __('Your password strength weak.','xoousers'),
'usernamerequired' => __('Please provide username.','xoousers'),
'emailrequired' => __('Please provide email address.','xoousers'),
'validemailrequired' => __('Please provide valid email address.','xoousers'),
'usernameexists' => __('That username is already taken, please try a different one.','xoousers'),
'emailexists' => __('The email you entered is already registered. Please try a new email or log in to your existing account.','xoousers')
),
'MeterMsg' => array(
'similartousername' => __('Your password is too similar to your username.','xoousers'),
'mismatch' => __('Both passwords do not match.','xoousers'),
'tooshort' => __('Your password is too short.','xoousers'),
'veryweak' => __('Your password strength is too weak.','xoousers'),
'weak' => __('Your password strength weak.','xoousers'),
'good' => __('Good','xoousers'),
'strong' => __('Strong','xoousers')
),
'Err' => __('ERROR','xoousers')
);
wp_localize_script( 'form-validate', 'Validate', $validate_strings );
}
/* Arguments */
$defaults = array(
'use_in_sidebar' => null,
'form_header_text' => __('Sign Up','xoousers'),
'custom_text' => '',
'redirect_to' => null
);
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP );
$pic_class = 'xoouserultra-pic';
if(is_safari())
$pic_class = 'xoouserultra-pic safari';
// Default set to blank
$this->captcha = '';
$captpcha_status = $this->get_option("captcha_plugin");
if($captpcha_status!=""){
$this->captcha = $captpcha_status;
}
$sidebar_class = null;
if ($use_in_sidebar) $sidebar_class = 'xoouserultra-sidebar';
$display = null;
if(get_option('users_can_register') == '1')
{
$display .= '<div class="xoouserultra-wrap xoouserultra-registration '.$sidebar_class.'">
<div class="xoouserultra-inner">
<div class="xoouserultra-head">
<div class="xoouserultra-left">
<div class="'.$pic_class.'">';
if (isset($_POST['xoouserultra-register']) && $_POST['user_email'] != '' ) {
//$display .= $this->pic($_POST['user_email'], 50);
} else {
//$display .= $this->pic('john@doe.com', 50);
}
$display .= '</div>';
$display .= '<div class="xoouserultra-name">
<div class="xoouserultra-field-name xoouserultra-field-name-wide">';
$display .= $form_header_text;
$display .= '</div>
</div>';
$display .= '</div>';
$display .= '<div class="xoouserultra-right">';
$display .= '</div><div class="xoouserultra-clear"></div>
</div>
<div class="xoouserultra-main">';
$display .= $custom_text;
$display .= ' <div class="xoouserultra-errors" style="display:none;" id="pass_err_holder">
<span class="xoouserultra-error xoouserultra-error-block" id="pass_err_block">
<i class="xoouserultra-icon-remove"></i><strong>ERROR:</strong> '.__('Please enter a username.', 'xoousers').'
</span>
</div>
';
/*Display errors*/
if (isset($_POST['xoouserultra-register-form']))
{
$display .= $this->register->get_errors();
}
$display .= $this->display_the_registeration_form( $sidebar_class, $redirect_to, $args );
$display .= '</div>
</div>
</div>';
}else{
//the registration is disabled
$display .= '<div class="xoouserultra-wrap xoouserultra-registration '.$sidebar_class.'"><div class="xoouserultra-inner"><div class="xoouserultra-head">';
if($this->get_option('html_registration_disabled') != '')
{
$display.=$this->get_option('html_registration_disabled');
}else{
$display.=__('User registration is currently not allowed.','xoousers');
}
$display .= '</div></div></div>';
}
return $display;
}
/* This is the Registration Form */
function display_the_registeration_form( $sidebar_class=null, $redirect_to=null , $args)
{
global $xoousers_register, $predefined, $xoousers_captcha_loader;
$display = null;
//check if retype-password
$password_retype = $this->get_option("set_password_retype");
// Optimized condition and added strict conditions
if (!isset($xoousers_register->registered) || $xoousers_register->registered != 1)
{
$display .= '<form action="" method="post" id="xoouserultra-registration-form" enctype="multipart/form-data">';
$display .= '<div class="xoouserultra-seperator-requiredfields xoouserultra-edit xoouserultra-edit-show">'.__('Fields with (*) are required','xoousers').'</div>';
//get social sign up methods
$display .= $this->get_social_buttons(__("Sign up with",'xoousers'), $args);
$display .= '<div class="xoouserultra-field xoouserultra-seperator xoouserultra-edit xoouserultra-edit-show">'.__('Account Info','xoousers').'</div>';
/* These are the basic registrations fields */
foreach($this->registration_fields as $key=>$field)
{
extract($field);
if ( $type == 'usermeta') {
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
if(!isset($required))
$required = 0;
$required_class = '';
$required_text = '';
if($required == 1 && in_array($field, $this->include_for_validation))
{
$required_class = ' validate[required]';
$required_text = '(*)';
}
/* Show the label */
if (isset($this->registration_fields[$key]['name']) && $name)
{
$display .= '<label class="xoouserultra-field-type" for="'.$meta.'">';
if (isset($this->registration_fields[$key]['icon']) && $icon)
{
$display .= '<i class="fa fa-'.$icon.'"></i>';
} else {
$display .= '<i class="fa fa-none"></i>';
}
$tooltipip_class = '';
if (isset($array[$key]['tooltip']) && $tooltip)
{
$tooltipip_class = '<a href="#" class="uultra-tooltip" title="' . $tooltip . '" ><i class="fa fa-info-circle reg_tooltip"></i></a>';
}
$display .= '<span>'.$name. ' '.$required_text.' '.$tooltipip_class.'</span></label>';
} else {
$display .= '<label class="xoouserultra-field-type"> </label>';
}
$display .= '<div class="xoouserultra-field-value">';
switch($field) {
case 'textarea':
$display .= '<textarea placeholder="'.$name.'" class="'.$required_class.' xoouserultra-input" name="'.$meta.'" id="reg_'.$meta.'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'">'.$this->get_post_value($meta).'</textarea>';
break;
case 'text':
$display .= '<input placeholder="'.$name.'" type="text" class="'.$required_class.' xoouserultra-input" name="'.$meta.'" id="reg_'.$meta.'" value="'.$this->get_post_value($meta).'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'"/>';
if (isset($this->registration_fields[$key]['help']) && $help != '') {
$display .= '<div class="xoouserultra-help">'.$help.'</div><div class="xoouserultra-clear"></div>';
}
break;
case 'datetime':
$display .= '<input type="text" class="'.$required_class.' xoouserultra-input xoouserultra-datepicker" name="'.$meta.'" id="reg_'.$meta.'" value="'.$this->get_post_value($meta).'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'"/>';
if (isset($this->registration_fields[$key]['help']) && $help != '') {
$display .= '<div class="xoouserultra-help">'.$help.'</div><div class="xoouserultra-clear"></div>';
}
break;
case 'password':
$display .= '<input type="password" class="'.$required_class.' xoouserultra-input password" name="'.$meta.'" id="reg_'.$meta.'" value="" autocomplete="off" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'" />';
if (isset($this->registration_fields[$key]['help']) && $help != '') {
$display .= '<div class="xoouserultra-help">'.$help.'</div><div class="xoouserultra-clear"></div>';
}
break;
case 'password_indicator':
$display .= '<div class="password-meter"><div class="password-meter-message" id="password-meter-message"> </div></div>';
break;
}
/*User can hide this from public*/
if (isset($this->registration_fields[$key]['can_hide']) && $can_hide == 1)
{
/*$display .= '<div class="xoouserultra-hide-from-public">
<input type="checkbox" name="hide_'.$meta.'" id="hide_'.$meta.'" value="" /> <label for="checkbox1"><span></span>'.__('Hide from Public','xoousers').'</label>
</div>';*/
}
$display .= '</div>';
$display .= '</div><div class="xoouserultra-clear"></div>';
//re-type email
if($meta=='user_email' && $password_retype!='no')
{
$required_class = ' validate[required]';
$required_text = '(*)';
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$display .= '<label class="xoouserultra-field-type" for="user_email_2">';
$display .= '<i class="fa fa-envelope"></i>';
$display .= '<span>'.__('Re-type your email', 'xoousers').' '.$required_text.'</span></label>';
$display .= '<div class="xoouserultra-field-value">';
$display .= '<input type="text" class="'.$required_class.' xoouserultra-input" name="user_email_2" placeholder="'.__('Re-type your email', 'xoousers').'" id="reg_user_email_2" value="'.$this->get_post_value('user_email_2').'" title="Re-type your email." data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'"/>';
$display .= '</div>';
$display .= '</div><div class="xoouserultra-clear"></div>';
}
}
}
/* Get end of array */
$array = get_option('usersultra_profile_fields');
foreach($array as $key=>$field)
{
$exclude_array = array('user_pass', 'user_pass_confirm', 'user_email');
if(isset($field['meta']) && in_array($field['meta'], $exclude_array))
{
unset($array[$key]);
}
}
$i_array_end = end($array);
if(isset($i_array_end['position']))
{
$array_end = $i_array_end['position'];
if (isset($array[$array_end]['type']) && $array[$array_end]['type'] == 'seperator')
{
if(isset($array[$array_end]))
{
unset($array[$array_end]);
}
}
}
/*Display custom profile fields added by the user*/
foreach($array as $key => $field)
{
extract($field);
// WP 3.6 Fix
if(!isset($deleted))
$deleted = 0;
if(!isset($private))
$private = 0;
if(!isset($required))
$required = 0;
$required_class = '';
$required_text = '';
//if( $array[$key]['required'] == 1 && in_array($field, $this->include_for_validation))
if(isset($array[$key]['required']) && $array[$key]['required'] == 1 && in_array($field, $this->include_for_validation))
{
//if($required == 1 && in_array($field, $this->include_for_validation))
//{
$required_class = 'validate[required] ';
$required_text = '(*)';
}
/* This is a Fieldset seperator */
/* separator */
if ($type == 'separator' && $deleted == 0 && $private == 0 && isset($array[$key]['show_in_register']) && $array[$key]['show_in_register'] == 1)
{
$display .= '<div class="xoouserultra-field xoouserultra-seperator xoouserultra-edit xoouserultra-edit-show">'.$name.'</div>';
}
//this hack will be removed soon
if ($type == 'seperator' && $deleted == 0 && $private == 0 && isset($array[$key]['show_in_register']) && $array[$key]['show_in_register'] == 1)
{
$display .= '<div class="xoouserultra-field xoouserultra-seperator xoouserultra-edit xoouserultra-edit-show">'.$name.'</div>';
}
if ($type == 'usermeta' && $deleted == 0 && $private == 0 && isset($array[$key]['show_in_register']) && $array[$key]['show_in_register'] == 1)
{
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
/* Show the label */
if (isset($array[$key]['name']) && $name)
{
$display .= '<label class="xoouserultra-field-type" for="'.$meta.'">';
if (isset($array[$key]['icon']) && $icon) {
$display .= '<i class="fa fa-' . $icon . '"></i>';
} else {
$display .= '<i class="fa fa-icon-none"></i>';
}
$tooltipip_class = '';
if (isset($array[$key]['tooltip']) && $tooltip)
{
$tooltipip_class = '<a href="#" class="uultra-tooltip" title="' . $tooltip . '" ><i class="fa fa-info-circle reg_tooltip"></i></a>';
}
$display .= '<span>'.$name. ' '.$required_text.' '.$tooltipip_class.'</span></label>';
} else {
$display .= '<label class="xoouserultra-field-type"> </label>';
}
$display .= '<div class="xoouserultra-field-value">';
switch($field) {
case 'textarea':
$display .= '<textarea placeholder="'.$name.'" class="'.$required_class.' xoouserultra-input" name="'.$meta.'" id="'.$meta.'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'">'.$this->get_post_value($meta).'</textarea>';
break;
case 'text':
$display .= '<input placeholder="'.$name.'" type="text" class="'.$required_class.'xoouserultra-input" name="'.$meta.'" id="'.$meta.'" value="'.$this->get_post_value($meta).'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'"/>';
break;
case 'datetime':
$display .= '<input type="text" class="'.$required_class.' xoouserultra-input xoouserultra-datepicker" name="'.$meta.'" id="'.$meta.'" value="'.$this->get_post_value($meta).'" title="'.$name.'" />';
break;
case 'select':
if (isset($array[$key]['predefined_options']) && $array[$key]['predefined_options']!= '' && $array[$key]['predefined_options']!= '0' )
{
$loop = $this->commmonmethods->get_predifined( $array[$key]['predefined_options'] );
}elseif (isset($array[$key]['choices']) && $array[$key]['choices'] != '') {
//$loop = explode(PHP_EOL, $choices);
$loop = $this->uultra_one_line_checkbox_on_window_fix($choices);
}
if (isset($loop))
{
$display .= '<select class=" xoouserultra-input '.$required_class.'" name="'.$meta.'" id="'.$meta.'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'">';
foreach($loop as $option)
{
$option = trim($option);
$display .= '<option value="'.$option.'" '.selected( $this->get_post_value($meta), $option, 0 ).'>'.$option.'</option>';
}
$display .= '</select>';
}
$display .= '<div class="xoouserultra-clear"></div>';
break;
case 'radio':
if($required == 1 && in_array($field, $this->include_for_validation))
{
$required_class = "validate[required] radio ";
}
if (isset($array[$key]['choices']))
{
//$loop = explode(PHP_EOL, $choices);
$loop = $this->uultra_one_line_checkbox_on_window_fix($choices);
}
if (isset($loop) && $loop[0] != '')
{
$counter =0;
foreach($loop as $option)
{
if($counter >0)
$required_class = '';
$option = trim($option);
$display .= '<input type="radio" class="'.$required_class.'" title="'.$name.'" name="'.$meta.'" id="uultra_multi_radio_'.$meta.'_'.$counter.'" value="'.$option.'" '.checked( $this->get_post_value($meta), $option, 0 );
$display .= '/> <label for="uultra_multi_radio_'.$meta.'_'.$counter.'"><span></span>'.$option.'</label>';
$counter++;
}
}
$display .= '<div class="xoouserultra-clear"></div>';
break;
case 'checkbox':
if($required == 1 && in_array($field, $this->include_for_validation))
{
$required_class = "validate[required] checkbox ";
}
if (isset($array[$key]['choices']))
{
//$loop = explode(PHP_EOL, $choices);
$loop = $this->uultra_one_line_checkbox_on_window_fix($choices);
}
if (isset($loop) && $loop[0] != '')
{
$counter =0;
foreach($loop as $option)
{
if($counter >0)
$required_class = '';
$option = trim($option);
$display .= '<div class="xoouserultra-checkbox"><input type="checkbox" class="'.$required_class.'" title="'.$name.'" name="'.$meta.'[]" id="uultra_multi_box_'.$meta.'_'.$counter.'" value="'.$option.'" ';
if (is_array($this->get_post_value($meta)) && in_array($option, $this->get_post_value($meta) )) {
$display .= 'checked="checked"';
}
$display .= '/> <label for="uultra_multi_box_'.$meta.'_'.$counter.'"><span></span> '.$option.'</label> </div>';
$counter++;
}
}
$display .= '<div class="xoouserultra-clear"></div>';
break;
case 'fileupload':
if ($meta == 'user_pic')
{
$display .= '<input type="file" class="'.$required_class.'xoouserultra-input uultra-fileupload-field" name="'.$meta.'" style="display:block;" id="'.$meta.'" value="'.$this->get_post_value($meta).'" title="'.$name.'" data-errormessage-value-missing="'.__(' * This input is required!','xoousers').'"/>';
} //end if meta
break;
case 'password':
$display .= '<input type="password" class="xoouserultra-input'.$required_class.'" title="'.$name.'" name="'.$meta.'" id="'.$meta.'" value="'.$this->get_post_value($meta).'" />';
if ($meta == 'user_pass')
{
$display .= '<div class="xoouserultra-help">'.__('If you would like to change the password type a new one. Otherwise leave this blank.','xoousers').'</div>';
} elseif ($meta == 'user_pass_confirm') {
$display .= '<div class="xoouserultra-help">'.__('Type your new password again.','xoousers').'</div>';
}
break;
}
/*User can hide this from public*/
if (isset($array[$key]['can_hide']) && $can_hide == 1)
{
$display .= '<div class="xoouserultra-hide-from-public">
<input type="checkbox" name="hide_'.$meta.'" id="hide_'.$meta.'" value="" /> <label for="hide_'.$meta.'"><span></span>'.__('Hide from Public','xoousers').'</label>
</div>';
} elseif ($can_hide == 0 && $private == 0) {
}
//validation message
$display .= '</div>';
$display .= '</div><div class="xoouserultra-clear"></div>';
}
}
/*If we are using Paid Registration*/
if($this->get_option('registration_rules')==4)
{
$display .= '<div class="xoouserultra-field xoouserultra-seperator xoouserultra-edit xoouserultra-edit-show">'.__('Payment Information','xoousers').'</div>';
$display .= '<div class="xoouserultra-package-list">';
$display .= $this->paypal->get_packages();
$display .= '</div>';
}
/*If mailchimp*/
if($this->get_option('mailchimp_active')==1 && $this->get_option('mailchimp_api')!="")
{
//new mailchimp field
$mailchimp_text = stripslashes($this->get_option('mailchimp_text'));
$mailchimp_header_text = stripslashes($this->get_option('mailchimp_header_text'));
if($mailchimp_header_text==''){
$mailchimp_header_text = __('Receive Daily Updates ', 'xoousers');
}
//
$display .= '<div class="xoouserultra-field xoouserultra-seperator xoouserultra-edit xoouserultra-edit-show">'.$mailchimp_header_text.'</div>';
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$display .= '<div class="xoouserultra-clear"></div>';
$display .= '<label class="xoouserultra-field-type" for="'.$meta.'">';
$display .= '<span> </span></label>';
//$display .= '</label>';
$display .= '<div class="xoouserultra-field-value">';
$display .= '<input type="checkbox" title="'.$mailchimp_header_text.'" name="uultra-mailchimp-confirmation" id="uultra-mailchimp-confirmation" value="1" > <label for="uultra-mailchimp-confirmation"><span></span>'.$mailchimp_text.'</label></div>' ;
$display .= '<div class="xoouserultra-clear"></div>';
}
//terms and conditions
if($this->get_option('uultra_terms_and_conditions')=='yes')
{
$text_terms = stripslashes($this->get_option('uultra_terms_and_conditions_text'));
//
$display .= '<div class="xoouserultra-field xoouserultra-seperator xoouserultra-edit xoouserultra-edit-show">'.__('Terms & Conditions ', 'xoousers').'</div>';
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">';
$display .= '<div class="xoouserultra-clear"></div>';
$display .= '<label class="xoouserultra-field-type" for="'.$meta.'">';
$display .= '<span> </span></label>';
$display .= '<div class="xoouserultra-field-value">';
$display .= '<input type="checkbox" title="'.__('Terms & Conditions ', 'xoousers').'" name="uultra-terms-and-conditions-confirmation" id="uultra-terms-and-conditions-confirmation" value="1" class="validate[required]" > <label for="uultra-terms-and-conditions-confirmation"><span></span>'.$text_terms.'</label></div>' ;
$display .= '<div class="xoouserultra-clear"></div>';
}
$display.=$this->captchamodule->load_captcha($this->captcha);
$display .= '<div class="xoouserultra-clear"> </div>';
$display .= '<div class="xoouserultra-field xoouserultra-edit xoouserultra-edit-show">
<label class="xoouserultra-field-type xoouserultra-field-type-'.$sidebar_class.'"> </label>
<div class="xoouserultra-field-value">
<input type="hidden" name="xoouserultra-register-form" value="xoouserultra-register-form" />
<input type="submit" name="xoouserultra-register" id="xoouserultra-register-btn" class="xoouserultra-button" value="'.__('Register','xoousers').'" />
</div>
</div><div class="xoouserultra-clear"></div>';
if ($redirect_to != '' )
{
$display .= '<input type="hidden" name="redirect_to" value="'.$redirect_to.'" />';
}
$display .= '</form>';
}
return $display;
}
/**
* This has been added to avoid the window server issues
*/
public function uultra_one_line_checkbox_on_window_fix($choices)
{
if($this->uultra_if_windows_server()) //is window
{
$loop = array();
$loop = explode(",", $choices);
}else{ //not window
$loop = array();
$loop = explode(PHP_EOL, $choices);
}
return $loop;
}
public function uultra_if_windows_server()
{
$os = PHP_OS;
$os = strtolower($os);
$pos = strpos($os, "win");
if ($pos === false) {
//echo "NO, It's not windows";
return false;
} else {
//echo "YES, It's windows";
return true;
}
}
public function check_if_disabled_for_this_user($user_id, $module, $modules_custom_user, $modules_custom_user_id )
{
$res = false;
if(in_array($user_id,$modules_custom_user_id))
{
//the user is in the array list.
if(in_array($module,$modules_custom_user))
{
$res = true;
}
}
return $res;
}
/**
* Users Dashboard
*/
public function show_usersultra_my_account($atts )
{
global $wpdb, $current_user;
$user_id = get_current_user_id();
extract( shortcode_atts( array(
'disable' => '',
'disable_module_custom_user' => '', //modules separated by commas
'disable_module_user_id' => '' // users id separated by commas
), $atts ) );
$modules = array();
$modules = explode(',', $disable);
//modules, custom users
$modules_custom_user = array();
$modules_custom_user = explode(',', $disable_module_custom_user);
//modules, custom users id
$modules_custom_user_id = array();
$modules_custom_user_id = explode(',', $disable_module_user_id);
//turn on output buffering to capture script output
ob_start();
//include the specified file
require_once(xoousers_path.'/templates/'.xoousers_template."/dashboard.php");
//assign the file output to $content variable and clean buffer
$content = ob_get_clean();
return $content;
}
/**
* Display Minified Profile
*/
public function show_minified_profile($atts)
{
return $this->userpanel->show_minified_profile($atts);
}
/**
* Display Front Publisher
*/
public function show_front_publisher($atts)
{
return $this->publisher->show_front_publisher($atts);
}
/**
* Top Rated Photos
*/
public function show_top_rated_photos($atts)
{
return $this->photogallery->show_top_rated_photos($atts);
}
/**
* Top Rated Photos
*/
public function show_latest_photos($atts)
{
return $this->photogallery->show_latest_photos($atts);
}
/**
* Photo Grid
*/
public function show_photo_grid($atts)
{
return $this->photogallery->show_photo_grid($atts);
}
/**
* Featured Users
*/
public function show_featured_users($atts)
{
return $this->userpanel->show_featured_users($atts);
}
/**
* Promoted Users
*/
public function show_promoted_users($atts)
{
return $this->userpanel->show_promoted_users($atts);
}
/**
* Promoted Photos
*/
public function show_promoted_photos($atts)
{
return $this->photogallery->show_promoted_photos($atts);
}
/**
* Latest Users
*/
public function show_latest_users($atts)
{
return $this->userpanel->show_latest_users($atts);
}
/**
* Featured Users
*/
public function show_top_rated_users($atts)
{
return $this->userpanel->show_top_rated_users($atts);
}
/**
* Top Most Visited Users
*/
public function show_most_visited_users($atts)
{
return $this->userpanel->show_most_visited_users($atts);
}
/**
* Public Profile
*/
public function show_pulic_profile($atts)
{
return $this->userpanel->show_public_profile($atts);
}
/**
* Get Templates
*/
public function usersultra_get_template($template)
{
$display = "";
$display .= require_once(xoousers_path.'/templates/'.xoousers_template."/".$template.".php");
}
public function get_social_buttons ($action_text, $atts)
{
$display ="";
extract( shortcode_atts( array(
'social_conect' => '',
), $atts ) );
if($this->get_option('registration_rules')!=4) // Social media is not able when using paid registrations
{
$FACEBOOK_APPID = $this->get_option('social_media_facebook_app_id');
$FACEBOOK_SECRET = $this->get_option('social_media_facebook_secret');
$config = array();
$config['appId'] = $FACEBOOK_APPID;
$config['secret'] = $FACEBOOK_SECRET;
$web_url = site_url()."/";
$atleast_one = false;
if($this->get_option('social_media_fb_active')==1)
{
require_once(xoousers_path."libs/fbapi/src/facebook.php");
$atleast_one = true;
$facebook = new Facebook($config);
$params = array(
'scope' => 'public_profile, email',
'redirect_uri' => $web_url
);
$loginUrl = $facebook->getLoginUrl($params);
//Facebook
$display .='<div class="txt-center FacebookSignIn">
<a href="'.$loginUrl.'" class="btnuultra-facebook" >
<span class="uultra-icon-facebook"> <img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/facebook.png" ></span>'.$action_text.' Facebook </a>
</div>';
}
if($this->get_option('social_media_yahoo')==1)
{
$auth_url_yahoo = $web_url."?uultrasocialsignup=yahoo";
$atleast_one = true;
//Yahoo
$display .='<div class="txt-center YahooSignIn">
<a href="'.$auth_url_yahoo.'" class="btnuultra-yahoo" >
<span class="uultra-icon-yahoo"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/yahoo.png" ></span>'.$action_text.' Yahoo </a>
</div>';
}
if($this->get_option('social_media_google')==1)
{
//google
$auth_url_google = $web_url."?uultrasocialsignup=google";
$atleast_one = true;
//Google
$display .='<div class="txt-center GoogleSignIn">
<a href="'.$auth_url_google.'" class="btnuultra-google" >
<span class="uultra-icon-google"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/googleplus.png" ></span>'.$action_text.' Google </a>
</div>';
}
//instagram
if($this->get_option('instagram_connect')==1)
{
//instagram
$auth_url_google = $web_url."?uultrasocialsignup=instagram";
$atleast_one = true;
//Instagram
$display .='<div class="txt-center InstagramSignIn">
<a href="'.$auth_url_google.'" class="btnuultra-instagram" >
<span class="uultra-icon-instagram"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/instagram-icon.png" ></span>'.$action_text.' Instagram </a>
</div>';
}
if($this->get_option('yammer_connect')==1)
{
//google
$auth_url_google = $web_url."?uultrasocialsignup=yammer";
$atleast_one = true;
if($display_style=='minified')
{
//Google
$display .='
<a href="'.$auth_url_google.'" class="btnuultramini-yammer '.$rounded_class.'" >
<span class="uultra-icon-yammer"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/yammer.png" ></span> </a>
';
}else{
//Google
$display .='<div class="txt-center YammerSignIn">
<a href="'.$auth_url_google.'" class="btnuultra-yammer" >
<span class="uultra-icon-yammer"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/yammer.png" ></span>'.$action_text.' Yammer </a>
</div>';
}
}
if($this->get_option('twitter_connect')==1)
{
//google
$auth_url_google = $web_url."?uultrasocialsignup=twitter";
$atleast_one = true;
//Google
$display .='<div class="txt-center TwitterSignIn">
<a href="'.$auth_url_google.'" class="btnuultra-twitter" >
<span class="uultra-icon-twitter"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/twitter.png" ></span>'.$action_text.' Twitter </a>
</div>';
}
if($this->get_option('yammer_connect')==1)
{
//google
$auth_url_google = $web_url."?uultrasocialsignup=yammer";
$atleast_one = true;
//Google
$display .='<div class="txt-center YammerSignIn">
<a href="'.$auth_url_google.'" class="btnuultra-yammer" >
<span class="uultra-icon-yammer"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/yammer.png" ></span>'.$action_text.' Yammer </a>
</div>';
}
if($this->get_option('social_media_linked_active')==1)
{
$atleast_one = true;
if (!isset($_REQUEST['oauth_token']))
{
//$requestlink = $this->get_linkein_auth_link();
}
$requestlink = $web_url."?uultrasocialsignup=linkedin";
//LinkedIn
$display .='<div class="txt-center LinkedSignIn">
<a href="'.$requestlink.'" class="btnuultra-linkedin" >
<span class="uultra-icon-linkedin"><img src="'.xoousers_url.'templates/'.xoousers_template.'/img/socialicons/linkedin.png" ></span>'.$action_text.' LinkedIn </a>
</div>';
}
if($atleast_one)
{
$display .='<div class="xoouserultra-or-divider"> <div>or</div> </div>';
}
}
return $display;
}
/*This function loads basic google libraries*/
public function load_google()
{
if ( $this->get_option('social_media_google') == 1 && $this->get_option('google_client_id') && $this->get_option('google_client_secret') && $this->get_option('google_redirect_uri') )
{
require_once(xoousers_path."libs/google/src/Google/Client.php");
require_once(xoousers_path."libs/google/src/Google/Service/Plus.php");
require_once(xoousers_path."libs/google/src/Google/Service/Oauth2.php");
session_start();
$this->google = new Google_Client();
$this->google->setApplicationName("Authentication"); // Set your applicatio name
$this->google->setScopes('email'); // set scope during user login
$this->google->setClientId($this->get_option('google_client_id')); // paste the client id which you get from google API Console
$this->google->setClientSecret($this->get_option('google_client_secret')); // set the client secret
$this->google->setRedirectUri($this->get_option('google_redirect_uri')); // paste the redirect URI where you given in APi Console. You will get the Access Token here during login success
$this->google->setApprovalPrompt('auto');
$this->googleplus = new Google_Service_Plus($this->google);
$this->googleoauth2 = new Google_Service_Oauth2($this->google); // Call the OAuth2 class for get email address
if (isset($_SESSION['google_token']))
{
$this->google->setAccessToken($_SESSION['google_token']);
}
}
}
/*******************
Google auth url
********************/
public function get_google_auth_url()
{
//load google class
$google = $this->load_google();
$url = $this->google->createAuthUrl();
$authurl = isset( $url ) ? $url : '';
return $authurl;
}
/******************************************
Google auth
******************************************/
function google_authorize()
{
//require_once(ABSPATH . 'wp-includes/pluggable.php');
require_once(ABSPATH. 'wp-admin/includes/user.php' );
if ( $this->get_option('social_media_google') == 1 && $this->get_option('google_client_id') && $this->get_option('google_client_secret') && $this->get_option('google_redirect_uri') )
{
if( isset( $_GET['code'] ) && isset($_REQUEST['uultraplus']) && $_REQUEST['uultraplus'] == '1' ) {
//load google class
$google = $this->load_google();
if (isset($_SESSION['google_token']))
{
$gplus_access_token = $_SESSION['google_token'];
} else {
$google_token = $this->google->authenticate($_GET['code']);
$_SESSION['google_token'] = $google_token;
$gplus_access_token = $_SESSION['google_token'];
}
//check access token is set or not
if ( !empty( $gplus_access_token ) )
{
// capture data
$user_info = $this->googleplus->people->get('me');
//print_r($user_info );
$user_email = $this->googleoauth2->userinfo->get(); // to get email
$user_info['email'] = $user_email['email'];
//if user data get successfully
if (isset($user_info['id'])){
$data['user'] = $user_info;
//all data will assign to a session
$_SESSION['google_user_cache'] = $data;
//check if
$users = get_users(array(
'meta_key' => 'xoouser_ultra_google_id',
'meta_value' => $user_info['id'],
'meta_compare' => '='
));
if (isset($users[0]->ID) && is_numeric($users[0]->ID) )
{
$returning = $users[0]->ID;
$returning_user_login = $users[0]->user_login;
} else {
$returning = '';
}
// Authorize user
if (is_user_logged_in())
{
update_user_meta ($user_id, 'xoouser_ultra_google_id', $user_info['id']);
$this->login->login_registration_afterlogin();
} else {
//the user is NOT logged in
if ( $returning != '' )
{
$noactive = false;
/*If alreayd exists*/
$user = get_user_by('login',$returning_user_login);
$user_id =$user->ID;
if(!$this->login->is_active($user_id) && !is_super_admin($user_id))
{
$noactive = true;
}
if(!$noactive)
{
$secure = "";
//already exists then we log in
wp_set_auth_cookie( $user_id, true, $secure );
}
//redirect user
$this->login->login_registration_afterlogin();
} else if ($user_info['email'] != '' && email_exists($user_info['email'])) {
//user email exists then we have to sync
$user_id = email_exists( $user_info['email'] );
$user = get_userdata($user_id);
update_user_meta ($user_id, 'xoouser_ultra_google_id', $user_info['id']);
$u_user = $user->user_login;
$noactive = false;
/*If alreayd exists*/
$user = get_user_by('login',$u_user);
$user_id =$user->ID;
if(!$this->login->is_active($user_id) && !is_super_admin($user_id))
{
$noactive = true;
}
if(!$noactive)
{
$secure = "";
//already exists then we log in
wp_set_auth_cookie( $user_id, true, $secure );
}
//redirect user
$this->login->login_registration_afterlogin();
} else {
//this is a new client we have to create the account
$u_name = $this->get_social_services_name('google', $user_info);
$u_email = $user_info['email'];
//generat random password
$user_pass = wp_generate_password( 12, false);
$user_login = $this->unique_user('google', $user_info);
$user_login = sanitize_user ($user_login, true);
//Build user data
$user_data = array (
'user_login' => $user_login,
'display_name' => $u_name,
'user_email' => $u_email,
'user_pass' => $user_pass
);
// Create a new user
$user_id = wp_insert_user ($user_data);
update_user_meta ($user_id, 'xoouser_ultra_social_signup', 4);
update_user_meta ($user_id, 'xoouser_ultra_google_id', $user_info['id']);
update_user_meta ($user_id, 'first_name', $u_name);
update_user_meta ($user_id, 'display_name', $u_name);
$verify_key = $this->login->get_unique_verify_account_id();
update_user_meta ($user_id, 'xoouser_ultra_very_key', $verify_key);
$this->user_account_status($user_id);
//notify client
$this->messaging->welcome_email($u_email, $user_login, $user_pass);
$creds['user_login'] = sanitize_user($user_login);
$creds['user_password'] = $user_pass;
$creds['remember'] = 1;
$noactive = false;
if(!$this->login->is_active($user_id) && !is_super_admin($user_id))
{
$noactive = true;
}
if(!$noactive)
{
$user = wp_signon( $creds, false );
}
//redirect user
$this->login->login_registration_afterlogin();
}
}
}
}
}
}
}
function get_social_services_name($service=null,$form=null)
{
if ($service)
{
if ($service == 'google')
{
//print_r($form);
if (isset($form['name']) && is_array($form['name']))
{
$name = $form['name']['givenName'] . ' ' . $form['name']['familyName'];
$username = $name;
} elseif ( isset($form['displayName']) && !empty($form['displayName']) ) {
$username = $form['displayName'];
} else {
$username = $form['id'];
}
}
if ($service == 'twitter') {
if (isset($form['screen_name']) && !empty($form['screen_name']) ) {
$username = $form['screen_name'];
}
}
if ($service == 'vk') {
if (isset($form['screen_name']) && !empty($form['screen_name']) ) {
$username = $form['screen_name'];
} else {
$username = $form['uid'];
}
}
}
return $username;
}
/******************************************
friendly username
******************************************/
function clean_user($string){
$string = strtolower($string);
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
$string = preg_replace("/[\s-]+/", " ", $string);
$string = preg_replace("/[\s_]/", "_", $string);
return $string;
}
/******************************************
Make display_name unique
******************************************/
function unique_display_name($display_name){
$r = str_shuffle("0123456789");
$r1 = (int) $r[0];
$r2 = (int) $r[1];
$display_name = $display_name . $r1 . $r2;
return $display_name;
}
/******************************************
Make username unique
******************************************/
function unique_user($service=null,$form=null){
if ($service){
if ($service == 'google') {
if (isset($form['name']) && is_array($form['name'])) {
$name = $form['name']['givenName'] . ' ' . $form['name']['familyName'];
$username = $this->clean_user($name);
} elseif ( isset($form['displayName']) && !empty($form['displayName']) ) {
$username = $this->clean_user($form['displayName']);
} else {
$username = $form['id'];
}
}
if ($service == 'twitter') {
if (isset($form['screen_name']) && !empty($form['screen_name']) ) {
$username = $form['screen_name'];
}
}
if ($service == 'vk') {
if (isset($form['screen_name']) && !empty($form['screen_name']) ) {
$username = $form['screen_name'];
} else {
$username = $form['uid'];
}
}
}
// make sure username is unique
if (username_exists($username)){
$r = str_shuffle("0123456789");
$r1 = (int) $r[0];
$r2 = (int) $r[1];
$username = $username . $r1 . $r2;
}
if (username_exists($username)){
$r = str_shuffle("0123456789");
$r1 = (int) $r[0];
$r2 = (int) $r[1];
$username = $username . $r1 . $r2;
}
return $username;
}
/*---->> Set Account Status ****/
public function user_account_status($user_id)
{
// global $xoouserultra;
//check if login automatically
$activation_type= $this->get_option('registration_rules');
if($activation_type==1)
{
//automatic activation
update_user_meta ($user_id, 'usersultra_account_status', 'active');
}elseif($activation_type==2){
//email activation link
update_user_meta ($user_id, 'usersultra_account_status', 'pending');
}elseif($activation_type==3){
//manually approved
update_user_meta ($user_id, 'usersultra_account_status', 'pending_admin');
}
}
//special feature for yahoo and google
public function social_login_links_openid()
{
//require_once(ABSPATH . 'wp-includes/pluggable.php');
$web_url = site_url()."/";
if (isset($_GET['uultrasocialsignup']) && $_GET['uultrasocialsignup']=="yahoo")
{
require_once(xoousers_path."libs/openid/openid.php");
$openid_yahoo = new LightOpenID($web_url);
//yahoo
$openid_yahoo->identity = 'https://me.yahoo.com';
$openid_yahoo->required = array(
'namePerson',
'namePerson/first',
'namePerson/last',
'contact/email',
);
$openid_yahoo->returnUrl = $web_url;
$auth_url_yahoo = $openid_yahoo->authUrl();
wp_redirect($auth_url_yahoo);
exit;
}
}
public function get_linkein_auth_link ()
{
$requestlink ="";
//LinkedIn lib
require_once(xoousers_path."libs/linkedin/oauth/linkedinoauth.php");
$oauthstate = $this->get_linkedin_oauth_token();
$tokenpublic = $oauthstate['request_token'];
$to = new LinkedInOAuth($this->get_option('social_media_linkedin_api_public'), $this->get_option('social_media_linkedin_api_private'));
$requestlink = $to->getAuthorizeURL($tokenpublic, $this->get_current_url());
return $requestlink;
}
//used only once we've got a oauth_token and oauth_verifier
function get_linkedin_access_token($oauthstate)
{
require_once(xoousers_path."libs/linkedin/oauth/linkedinoauth.php");
$requesttoken = $oauthstate['request_token'];
$requesttokensecret = $oauthstate['request_token_secret'];
$urlaccessverifier = $_REQUEST['oauth_verifier'];
error_log("Creating API with $requesttoken, $requesttokensecret");
$to = new LinkedInOAuth(
$this->get_option('social_media_linkedin_api_public'),
$this->get_option('social_media_linkedin_api_private'),
$requesttoken,
$requesttokensecret
);
$tok = $to->getAccessToken($urlaccessverifier);
//print_r($tok);
$accesstoken = $tok['oauth_token'];
$accesstokensecret = $tok['oauth_token_secret'];
$oauthstate['access_token'] = $accesstoken;
$oauthstate['access_token_secret'] = $accesstokensecret;
return $oauthstate;
}
function get_linkedin_oauth_token()
{
session_start();
require_once(xoousers_path."libs/linkedin/oauth/linkedinoauth.php");
$oauthstate = $this->get_linkedin_oauth_state();
//echo "not set aut state";
error_log("No OAuth state found");
$to = new LinkedInOAuth($this->get_option('social_media_linkedin_api_public'), $this->get_option('social_media_linkedin_api_private'));
// This call can be unreliable for some providers if their servers are under a heavy load, so
// retry it with an increasing amount of back-off if there's a problem.
$maxretrycount = 1;
$retrycount = 0;
while ($retrycount<$maxretrycount)
{
$tok = $to->getRequestToken();
if (isset($tok['oauth_token'])&&
isset($tok['oauth_token_secret']))
break;
$retrycount += 1;
sleep($retrycount*5);
}
$tokenpublic = $tok['oauth_token'];
$tokenprivate = $tok['oauth_token_secret'];
$state = 'start';
// Create a new set of information, initially just containing the keys we need to make
// the request.
$oauthstate = array(
'request_token' => $tokenpublic,
'request_token_secret' => $tokenprivate,
'access_token' => '',
'access_token_secret' => '',
'state' => $state,
);
//SET IN DB TEMP TOKEN
$temp_user_session_id = session_id();
update_option('uultra_linkedin_'.$temp_user_session_id, $oauthstate);
$oauthstate = get_option('uultra_linkedin_'.$temp_user_session_id);
$this->set_linkedin_oauth_state($oauthstate);
return $oauthstate;
}
function get_linkedin_oauth_state()
{
if (empty($_SESSION['linkedinoauthstate']))
return null;
$result = $_SESSION['linkedinoauthstate'];
error_log("Found state ".print_r($result, true));
//print_r($_SESSION);
return $result;
}
// Updates the information about the user's progress through the oAuth process.
function set_linkedin_oauth_state($state)
{
error_log("Setting OAuth state to - ".print_r($state, true));
$_SESSION['linkedinoauthstate'] = $state;
}
public function get_current_url()
{
$result = 'http';
$script_name = "";
if(isset($_SERVER['REQUEST_URI']))
{
$script_name = $_SERVER['REQUEST_URI'];
}
else
{
$script_name = $_SERVER['PHP_SELF'];
if($_SERVER['QUERY_STRING']>' ')
{
$script_name .= '?'.$_SERVER['QUERY_STRING'];
}
}
if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on')
{
$result .= 's';
}
$result .= '://';
if($_SERVER['SERVER_PORT']!='80')
{
$result .= $_SERVER['HTTP_HOST'].':'.$_SERVER['SERVER_PORT'].$script_name;
}
else
{
$result .= $_SERVER['HTTP_HOST'].$script_name;
}
return $result;
}
/* get setting */
function get_option($option)
{
$settings = get_option('userultra_options');
if (isset($settings[$option]))
{
return $settings[$option];
}else{
return '';
}
}
/*Post value*/
function get_post_value($meta) {
if (isset($_POST['xoouserultra-register-form'])) {
if (isset($_POST[$meta]) ) {
return $_POST[$meta];
}
} else {
if (strstr($meta, 'country')) {
return 'United States';
}
}
}
}
?> | agpl-3.0 |
eBay-Opportunity-Hack-Chennai-2014/Chennai_Street_Fix | web/js/map-OpenLayers.js | 23447 | // This function might be passed either an OpenLayers.LonLat (so has
// lon and lat) or an OpenLayers.Geometry.Point (so has x and y)
function fixmystreet_update_pin(lonlat) {
lonlat.transform(
fixmystreet.map.getProjectionObject(),
new OpenLayers.Projection("EPSG:4326")
);
document.getElementById('fixmystreet.latitude').value = lonlat.lat || lonlat.y;
document.getElementById('fixmystreet.longitude').value = lonlat.lon || lonlat.x;
$.getJSON('/report/new/ajax', {
latitude: $('#fixmystreet\\.latitude').val(),
longitude: $('#fixmystreet\\.longitude').val()
}, function(data) {
if (data.error) {
if (!$('#side-form-error').length) {
$('<div id="side-form-error"/>').insertAfter($('#side-form'));
}
$('#side-form-error').html('<h1>' + translation_strings.reporting_a_problem + '</h1><p>' + data.error + '</p>').show();
$('#side-form').hide();
return;
}
$('#side-form, #site-logo').show();
$('#councils_text').html(data.councils_text);
$('#form_category_row').html(data.category);
if ( data.extra_name_info && !$('#form_fms_extra_title').length ) {
// there might be a first name field on some cobrands
var lb = $('#form_first_name').prev();
if ( lb.length === 0 ) { lb = $('#form_name').prev(); }
lb.before(data.extra_name_info);
}
});
if (!$('#side-form-error').is(':visible')) {
$('#side-form, #site-logo').show();
}
}
function fixmystreet_activate_drag() {
fixmystreet.drag = new OpenLayers.Control.DragFeature( fixmystreet.markers, {
onComplete: function(feature, e) {
fixmystreet_update_pin( feature.geometry.clone() );
}
} );
fixmystreet.map.addControl( fixmystreet.drag );
fixmystreet.drag.activate();
}
// Need to try and fake the 'centre' being 75% from the left
function fixmystreet_midpoint() {
var $content = $('.content'), mb = $('#map_box'),
q = ( $content.offset().left - mb.offset().left + $content.width() ) / 2,
mid_point = q < 0 ? 0 : q;
return mid_point;
}
function fixmystreet_zoomToBounds(bounds) {
if (!bounds) { return; }
var center = bounds.getCenterLonLat();
var z = fixmystreet.map.getZoomForExtent(bounds);
if ( z < 13 && $('html').hasClass('mobile') ) {
z = 13;
}
fixmystreet.map.setCenter(center, z);
if (fixmystreet.state_map && fixmystreet.state_map == 'full') {
fixmystreet.map.pan(-fixmystreet_midpoint(), -25, { animate: false });
}
}
function fms_markers_list(pins, transform) {
var markers = [];
for (var i=0; i<pins.length; i++) {
var pin = pins[i];
var loc = new OpenLayers.Geometry.Point(pin[1], pin[0]);
if (transform) {
// The Strategy does this for us, so don't do it in that case.
loc.transform(
new OpenLayers.Projection("EPSG:4326"),
fixmystreet.map.getProjectionObject()
);
}
var marker = new OpenLayers.Feature.Vector(loc, {
colour: pin[2],
size: pin[5] || 'normal',
id: pin[3],
title: pin[4] || ''
});
markers.push( marker );
}
return markers;
}
function fixmystreet_onload() {
if ( fixmystreet.area.length ) {
for (var i=0; i<fixmystreet.area.length; i++) {
var area = new OpenLayers.Layer.Vector("KML", {
strategies: [ new OpenLayers.Strategy.Fixed() ],
protocol: new OpenLayers.Protocol.HTTP({
url: "/mapit/area/" + fixmystreet.area[i] + ".kml?simplify_tolerance=0.0001",
format: new OpenLayers.Format.KML()
})
});
fixmystreet.map.addLayer(area);
if ( fixmystreet.area.length == 1 ) {
area.events.register('loadend', null, function(a,b,c) {
if ( fixmystreet.area_format ) {
area.styleMap.styles['default'].defaultStyle = fixmystreet.area_format;
}
fixmystreet_zoomToBounds( area.getDataExtent() );
});
}
}
}
var pin_layer_style_map = new OpenLayers.StyleMap({
'default': new OpenLayers.Style({
graphicTitle: "${title}",
graphicOpacity: 1,
graphicZIndex: 11,
backgroundGraphicZIndex: 10
})
});
pin_layer_style_map.addUniqueValueRules('default', 'size', {
'normal': {
externalGraphic: fixmystreet.pin_prefix + "pin-${colour}.png",
graphicWidth: 48,
graphicHeight: 64,
graphicXOffset: -24,
graphicYOffset: -64,
backgroundGraphic: fixmystreet.pin_prefix + "pin-shadow.png",
backgroundWidth: 60,
backgroundHeight: 30,
backgroundXOffset: -7,
backgroundYOffset: -30
},
'big': {
externalGraphic: fixmystreet.pin_prefix + "pin-${colour}-big.png",
graphicWidth: 78,
graphicHeight: 105,
graphicXOffset: -39,
graphicYOffset: -105,
backgroundGraphic: fixmystreet.pin_prefix + "pin-shadow-big.png",
backgroundWidth: 88,
backgroundHeight: 40,
backgroundXOffset: -10,
backgroundYOffset: -35
}
});
var pin_layer_options = {
rendererOptions: {
yOrdering: true
},
styleMap: pin_layer_style_map
};
if (fixmystreet.page == 'around') {
fixmystreet.bbox_strategy = fixmystreet.bbox_strategy || new OpenLayers.Strategy.BBOX({ ratio: 1 });
pin_layer_options.strategies = [ fixmystreet.bbox_strategy ];
pin_layer_options.protocol = new OpenLayers.Protocol.HTTP({
url: '/ajax',
params: fixmystreet.all_pins ? { all_pins: 1 } : { },
format: new OpenLayers.Format.FixMyStreet()
});
}
fixmystreet.markers = new OpenLayers.Layer.Vector("Pins", pin_layer_options);
fixmystreet.markers.events.register( 'loadend', fixmystreet.markers, function(evt) {
if (fixmystreet.map.popups.length) {
fixmystreet.map.removePopup(fixmystreet.map.popups[0]);
}
});
var markers = fms_markers_list( fixmystreet.pins, true );
fixmystreet.markers.addFeatures( markers );
function onPopupClose(evt) {
fixmystreet.select_feature.unselect(selectedFeature);
OpenLayers.Event.stop(evt);
}
if (fixmystreet.page == 'around' || fixmystreet.page == 'reports' || fixmystreet.page == 'my') {
fixmystreet.select_feature = new OpenLayers.Control.SelectFeature( fixmystreet.markers );
var selectedFeature;
fixmystreet.markers.events.register( 'featureunselected', fixmystreet.markers, function(evt) {
var feature = evt.feature, popup = feature.popup;
fixmystreet.map.removePopup(popup);
popup.destroy();
feature.popup = null;
});
fixmystreet.markers.events.register( 'featureselected', fixmystreet.markers, function(evt) {
var feature = evt.feature;
selectedFeature = feature;
var popup = new OpenLayers.Popup.FramedCloud("popup",
feature.geometry.getBounds().getCenterLonLat(),
null,
feature.attributes.title + "<br><a href=/report/" + feature.attributes.id + ">" + translation_strings.more_details + "</a>",
{ size: new OpenLayers.Size(0,0), offset: new OpenLayers.Pixel(0,-40) },
true, onPopupClose);
feature.popup = popup;
fixmystreet.map.addPopup(popup);
});
fixmystreet.map.addControl( fixmystreet.select_feature );
fixmystreet.select_feature.activate();
} else if (fixmystreet.page == 'new') {
fixmystreet_activate_drag();
}
fixmystreet.map.addLayer(fixmystreet.markers);
if ( fixmystreet.zoomToBounds ) {
fixmystreet_zoomToBounds( fixmystreet.markers.getDataExtent() );
}
$('#hide_pins_link').click(function(e) {
e.preventDefault();
var showhide = [
'Show pins', 'Hide pins',
'Dangos pinnau', 'Cuddio pinnau',
"Vis nåler", "Gjem nåler",
"Zeige Stecknadeln", "Stecknadeln ausblenden"
];
for (var i=0; i<showhide.length; i+=2) {
if (this.innerHTML == showhide[i]) {
fixmystreet.markers.setVisibility(true);
fixmystreet.select_feature.activate();
this.innerHTML = showhide[i+1];
} else if (this.innerHTML == showhide[i+1]) {
fixmystreet.markers.setVisibility(false);
fixmystreet.select_feature.deactivate();
this.innerHTML = showhide[i];
}
}
});
$('#all_pins_link').click(function(e) {
e.preventDefault();
fixmystreet.markers.setVisibility(true);
var texts = [
'en', 'Show old', 'Hide old',
'nb', 'Inkluder utdaterte problemer', 'Skjul utdaterte rapporter',
'cy', 'Cynnwys hen adroddiadau', 'Cuddio hen adroddiadau'
];
for (var i=0; i<texts.length; i+=3) {
if (this.innerHTML == texts[i+1]) {
this.innerHTML = texts[i+2];
fixmystreet.markers.protocol.options.params = { all_pins: 1 };
fixmystreet.markers.refresh( { force: true } );
lang = texts[i];
} else if (this.innerHTML == texts[i+2]) {
this.innerHTML = texts[i+1];
fixmystreet.markers.protocol.options.params = { };
fixmystreet.markers.refresh( { force: true } );
lang = texts[i];
}
}
if (lang == 'cy') {
document.getElementById('hide_pins_link').innerHTML = 'Cuddio pinnau';
} else if (lang == 'nb') {
document.getElementById('hide_pins_link').innerHTML = 'Gjem nåler';
} else {
document.getElementById('hide_pins_link').innerHTML = 'Hide pins';
}
});
}
$(function(){
// Set specific map config - some other JS included in the
// template should define this
set_map_config();
// Create the basics of the map
fixmystreet.map = new OpenLayers.Map(
"map", OpenLayers.Util.extend({
controls: fixmystreet.controls,
displayProjection: new OpenLayers.Projection("EPSG:4326")
}, fixmystreet.map_options)
);
// Need to do this here, after the map is created
if ($('html').hasClass('mobile')) {
if (fixmystreet.page == 'around') {
$('#fms_pan_zoom').css({ top: '2.75em' });
}
} else {
$('#fms_pan_zoom').css({ top: '4.75em' });
}
// Set it up our way
var layer;
if (!fixmystreet.layer_options) {
fixmystreet.layer_options = [ {} ];
}
for (var i=0; i<fixmystreet.layer_options.length; i++) {
fixmystreet.layer_options[i] = OpenLayers.Util.extend({
// This option is used by XYZ-based layers
zoomOffset: fixmystreet.zoomOffset,
// This option is used by FixedZoomLevels-based layers
minZoomLevel: fixmystreet.zoomOffset,
// This option is thankfully used by them both
numZoomLevels: fixmystreet.numZoomLevels
}, fixmystreet.layer_options[i]);
if (fixmystreet.layer_options[i].matrixIds) {
layer = new fixmystreet.map_type(fixmystreet.layer_options[i]);
} else {
layer = new fixmystreet.map_type("", fixmystreet.layer_options[i]);
}
fixmystreet.map.addLayer(layer);
}
if (!fixmystreet.map.getCenter()) {
var centre = new OpenLayers.LonLat( fixmystreet.longitude, fixmystreet.latitude );
centre.transform(
new OpenLayers.Projection("EPSG:4326"),
fixmystreet.map.getProjectionObject()
);
fixmystreet.map.setCenter(centre, fixmystreet.zoom || 3);
}
if (fixmystreet.state_map && fixmystreet.state_map == 'full') {
fixmystreet.map.pan(-fixmystreet_midpoint(), -25, { animate: false });
}
if (document.getElementById('mapForm')) {
var click = new OpenLayers.Control.Click();
fixmystreet.map.addControl(click);
click.activate();
}
$(window).hashchange(function(){
if (location.hash == '#report' && $('.rap-notes').is(':visible')) {
$('.rap-notes-close').click();
return;
}
if (location.hash && location.hash != '#') {
return;
}
// Okay, back to around view.
fixmystreet.bbox_strategy.activate();
fixmystreet.markers.refresh( { force: true } );
if ( fixmystreet.state_pins_were_hidden ) {
// If we had pins hidden when we clicked map (which had to show the pin layer as I'm doing it in one layer), hide them again.
$('#hide_pins_link').click();
}
fixmystreet.drag.deactivate();
$('#side-form').hide();
$('#side').show();
$('#sub_map_links').show();
//only on mobile
$('#mob_sub_map_links').remove();
$('.mobile-map-banner').html('<a href="/">' + translation_strings.home + '</a> ' + translation_strings.place_pin_on_map);
fixmystreet.page = 'around';
});
// Vector layers must be added onload as IE sucks
if ($.browser.msie) {
$(window).load(fixmystreet_onload);
} else {
fixmystreet_onload();
}
});
/* Overridding the buttonDown function of PanZoom so that it does
zoomTo(0) rather than zoomToMaxExtent()
*/
OpenLayers.Control.PanZoomFMS = OpenLayers.Class(OpenLayers.Control.PanZoom, {
onButtonClick: function (evt) {
var btn = evt.buttonElement;
switch (btn.action) {
case "panup":
this.map.pan(0, -this.getSlideFactor("h"));
break;
case "pandown":
this.map.pan(0, this.getSlideFactor("h"));
break;
case "panleft":
this.map.pan(-this.getSlideFactor("w"), 0);
break;
case "panright":
this.map.pan(this.getSlideFactor("w"), 0);
break;
case "zoomin":
case "zoomout":
case "zoomworld":
var mid_point = 0;
if (fixmystreet.state_map && fixmystreet.state_map == 'full') {
mid_point = fixmystreet_midpoint();
}
var size = this.map.getSize(),
xy = { x: size.w / 2 + mid_point, y: size.h / 2 };
switch (btn.action) {
case "zoomin":
this.map.zoomTo(this.map.getZoom() + 1, xy);
break;
case "zoomout":
this.map.zoomTo(this.map.getZoom() - 1, xy);
break;
case "zoomworld":
this.map.zoomTo(0, xy);
break;
}
}
}
});
/* Overriding Permalink so that it can pass the correct zoom to OSM */
OpenLayers.Control.PermalinkFMS = OpenLayers.Class(OpenLayers.Control.Permalink, {
_updateLink: function(alter_zoom) {
var separator = this.anchor ? '#' : '?';
var href = this.base;
if (href.indexOf(separator) != -1) {
href = href.substring( 0, href.indexOf(separator) );
}
var center = this.map.getCenter();
if ( center && fixmystreet.state_map && fixmystreet.state_map == 'full' ) {
// Translate the permalink co-ords so that 'centre' is accurate
var mid_point = fixmystreet_midpoint();
var p = this.map.getViewPortPxFromLonLat(center);
p.x += mid_point;
p.y += 25;
center = this.map.getLonLatFromViewPortPx(p);
}
var zoom = this.map.getZoom();
if ( alter_zoom ) {
zoom += fixmystreet.zoomOffset;
}
href += separator + OpenLayers.Util.getParameterString(this.createParams(center, zoom));
// Could use mlat/mlon here as well if we are on a page with a marker
if (this.anchor && !this.element) {
window.location.href = href;
}
else {
this.element.href = href;
}
},
updateLink: function() {
this._updateLink(0);
}
});
OpenLayers.Control.PermalinkFMSz = OpenLayers.Class(OpenLayers.Control.PermalinkFMS, {
updateLink: function() {
this._updateLink(1);
}
});
/* Pan data handler */
OpenLayers.Format.FixMyStreet = OpenLayers.Class(OpenLayers.Format.JSON, {
read: function(json, filter) {
if (typeof json == 'string') {
obj = OpenLayers.Format.JSON.prototype.read.apply(this, [json, filter]);
} else {
obj = json;
}
var current, current_near;
if (typeof(obj.current) != 'undefined' && (current = document.getElementById('current'))) {
current.innerHTML = obj.current;
}
if (typeof(obj.current_near) != 'undefined' && (current_near = document.getElementById('current_near'))) {
current_near.innerHTML = obj.current_near;
}
var markers = fms_markers_list( obj.pins, false );
return markers;
},
CLASS_NAME: "OpenLayers.Format.FixMyStreet"
});
/* Click handler */
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend(
{}, this.defaultHandlerOptions);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.trigger
}, this.handlerOptions);
},
trigger: function(e) {
var cobrand = $('meta[name="cobrand"]').attr('content');
if (typeof fixmystreet.nav_control != 'undefined') {
fixmystreet.nav_control.disableZoomWheel();
}
var lonlat = fixmystreet.map.getLonLatFromViewPortPx(e.xy);
if (fixmystreet.page == 'new') {
/* Already have a pin */
fixmystreet.markers.features[0].move(lonlat);
} else {
var markers = fms_markers_list( [ [ lonlat.lat, lonlat.lon, 'green' ] ], false );
fixmystreet.bbox_strategy.deactivate();
fixmystreet.markers.removeAllFeatures();
fixmystreet.markers.addFeatures( markers );
fixmystreet_activate_drag();
}
// check to see if markers are visible. We click the
// link so that it updates the text in case they go
// back
if ( ! fixmystreet.markers.getVisibility() ) {
fixmystreet.state_pins_were_hidden = true;
$('#hide_pins_link').click();
}
// Store pin location in form fields, and check coverage of point
fixmystreet_update_pin(lonlat);
// Already did this first time map was clicked, so no need to do it again.
if (fixmystreet.page == 'new') {
return;
}
fixmystreet.map.updateSize(); // might have done, and otherwise Firefox gets confused.
/* For some reason on IOS5 if you use the jQuery show method it
* doesn't display the JS validation error messages unless you do this
* or you cause a screen redraw by changing the phone orientation.
* NB: This has to happen after the call to show() */
if ( navigator.userAgent.match(/like Mac OS X/i)) {
document.getElementById('side-form').style.display = 'block';
}
$('#side').hide();
if (typeof heightFix !== 'undefined') {
heightFix('#report-a-problem-sidebar', '.content', 26);
}
// If we clicked the map somewhere inconvenient
var sidebar = $('#report-a-problem-sidebar');
if (sidebar.css('position') == 'absolute') {
var w = sidebar.width(), h = sidebar.height(),
o = sidebar.offset(),
$map_boxx = $('#map_box'), bo = $map_boxx.offset();
// e.xy is relative to top left of map, which might not be top left of page
e.xy.x += bo.left;
e.xy.y += bo.top;
// 24 and 64 is the width and height of the marker pin
if (e.xy.y <= o.top || (e.xy.x >= o.left && e.xy.x <= o.left + w + 24 && e.xy.y >= o.top && e.xy.y <= o.top + h + 64)) {
// top of the page, pin hidden by header;
// or underneath where the new sidebar will appear
lonlat.transform(
new OpenLayers.Projection("EPSG:4326"),
fixmystreet.map.getProjectionObject()
);
var p = fixmystreet.map.getViewPortPxFromLonLat(lonlat);
p.x -= ( o.left - bo.left + w ) / 2;
lonlat = fixmystreet.map.getLonLatFromViewPortPx(p);
fixmystreet.map.panTo(lonlat);
}
}
$('#sub_map_links').hide();
if ($('html').hasClass('mobile')) {
var $map_box = $('#map_box'),
width = $map_box.width(),
height = $map_box.height();
$map_box.append( '<p id="mob_sub_map_links">' + '<a href="#" id="try_again">' + translation_strings.try_again + '</a>' + '<a href="#ok" id="mob_ok">' + translation_strings.ok + '</a>' + '</p>' ).css({ position: 'relative', width: width, height: height, marginBottom: '1em' });
// Making it relative here makes it much easier to do the scrolling later
$('.mobile-map-banner').html('<a href="/">' + translation_strings.home + '</a> ' + translation_strings.right_place);
// mobile user clicks 'ok' on map
$('#mob_ok').toggle(function(){
//scroll the height of the map box instead of the offset
//of the #side-form or whatever as we will probably want
//to do this on other pages where #side-form might not be
$('html, body').animate({ scrollTop: height-60 }, 1000, function(){
$('#mob_sub_map_links').addClass('map_complete');
$('#mob_ok').text(translation_strings.map);
});
}, function(){
$('html, body').animate({ scrollTop: 0 }, 1000, function(){
$('#mob_sub_map_links').removeClass('map_complete');
$('#mob_ok').text(translation_strings.ok);
});
});
}
fixmystreet.page = 'new';
location.hash = 'report';
if ( typeof ga !== 'undefined' && cobrand == 'fixmystreet' ) {
ga('send', 'pageview', { 'page': '/map_click' } );
}
}
});
| agpl-3.0 |
pollopolea/core | lib/l10n/nl.js | 19116 | OC.L10N.register(
"lib",
{
"Cannot write into \"config\" directory!" : "Kan niet schrijven naar de \"config\" directory!",
"This can usually be fixed by giving the webserver write access to the config directory" : "Dit kan hersteld worden door de webserver schrijfrechten te geven op de de config directory",
"See %s" : "Zie %s",
"This can usually be fixed by %sgiving the webserver write access to the config directory%s." : "Dit kan hersteld worden door de webserver %sschrijfrechten te geven op de de config directory%s",
"Sample configuration detected" : "Voorbeeldconfiguratie gevonden",
"It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php" : "Blijkbaar is de voorbeeldconfiguratie gekopieerd. Dit kan uw installatie beschadigen en wordt niet dan ook ondersteund. Lees de documentatie voordat u wijzigingen aan config.php doorvoert",
"PHP %s or higher is required." : "PHP %s of hoger vereist.",
"PHP with a version lower than %s is required." : "PHP met een versie lager dan %s is vereist.",
"%sbit or higher PHP required." : "%sbit of hogere PHP vereist.",
"Following databases are supported: %s" : "De volgende databases worden ondersteund: %s",
"The command line tool %s could not be found" : "Commandoregel tool %s is niet gevonden",
"The library %s is not available." : "Library %s is niet beschikbaar.",
"Library %s with a version higher than %s is required - available version %s." : "Library %s met een versienummer hoger dan %s is vereist - beschikbare versie %s.",
"Library %s with a version lower than %s is required - available version %s." : "Library %s met een versienummer lager dan %s is vereist - beschikbare versie %s.",
"Following platforms are supported: %s" : "De volgende platformen worden ondersteund: %s",
"ownCloud %s or higher is required." : "ownCloud %s of hoger vereist.",
"ownCloud %s or lower is required." : "ownCloud %s of lager vereist.",
"Unknown filetype" : "Onbekend bestandsformaat",
"Invalid image" : "Ongeldige afbeelding",
"Avatar image is not square" : "Avatarafbeelding is niet vierkant",
"today" : "vandaag",
"yesterday" : "gisteren",
"_%n day ago_::_%n days ago_" : ["%n dag geleden","%n dagen geleden"],
"last month" : "vorige maand",
"_%n month ago_::_%n months ago_" : ["%n maand geleden","%n maanden geleden"],
"last year" : "vorig jaar",
"_%n year ago_::_%n years ago_" : ["%n jaar geleden","%n jaar geleden"],
"_%n hour ago_::_%n hours ago_" : ["%n uur geleden","%n uur geleden"],
"_%n minute ago_::_%n minutes ago_" : ["%n minuut geleden","%n minuten geleden"],
"seconds ago" : "seconden geleden",
"Module with id: %s does not exist. Please enable it in your apps settings or contact your administrator." : "Module met id: %s bestaat niet. Activeer het in uw apps instellingen, of neem contact op met uw beheerder.",
"Builtin" : "Ingebouwd",
"None" : "Geen",
"Username and password" : "Gebruikersnaam en wachtwoord",
"Username" : "Gebruikersnaam",
"Password" : "Wachtwoord",
"Log-in credentials, save in session" : "Inloggegevens, opslaan in sessie",
"Empty filename is not allowed" : "Een lege bestandsnaam is niet toegestaan",
"Dot files are not allowed" : "Punt bestanden zijn niet toegestaan",
"4-byte characters are not supported in file names" : "4-byte tekens in bestandsnamen worden niet ondersteund",
"File name is a reserved word" : "Bestandsnaam is een gereserveerd woord",
"File name contains at least one invalid character" : "De bestandsnaam bevat ten minste één verboden teken",
"File name is too long" : "De bestandsnaam is te lang",
"App directory already exists" : "App directory bestaat al",
"Can't create app folder. Please fix permissions. %s" : "Kan de app map niet aanmaken, Herstel de permissies. %s",
"Archive does not contain a directory named %s" : "Archief bevat geen directory genaamd %s",
"No source specified when installing app" : "Geen bron opgegeven bij installatie van de app",
"No href specified when installing app from http" : "Geen href opgegeven bij installeren van de app vanaf http",
"No path specified when installing app from local file" : "Geen pad opgegeven bij installeren van de app vanaf een lokaal bestand",
"Archives of type %s are not supported" : "Archiefbestanden van type %s niet ondersteund",
"Failed to open archive when installing app" : "Kon archiefbestand bij installatie van de app niet openen",
"App does not provide an info.xml file" : "De app heeft geen info.xml bestand",
"App cannot be installed because appinfo file cannot be read." : "App kan niet worden geïnstalleerd, omdat appinfo bestand niet gelezen kan worden.",
"Signature could not get checked. Please contact the app developer and check your admin screen." : "Handtekening kon niet worden geverifieerd. Nee contact op met de ontwikkelaar van de app en check uw beheerscherm.",
"App can't be installed because it is not compatible with this version of ownCloud" : "De app kan niet worden geïnstalleerd, omdat die niet compatible is met deze versie van ownCloud",
"App can't be installed because it contains the <shipped>true</shipped> tag which is not allowed for non shipped apps" : "De app kan niet worden geïnstalleerd, omdat het de <shipped>true</shipped> tag bevat die niet is toegestaan voor niet gepubliceerde apps",
"App can't be installed because the version in info.xml is not the same as the version reported from the app store" : "De app kan niet worden geïnstalleerd, omdat de versie in info.xml niet dezelfde is als de versie zoals die in de app store staat vermeld",
"Apps" : "Apps",
"General" : "Algemeen",
"Storage" : "Opslaglimiet",
"Security" : "Beveiliging",
"User Authentication" : "Gebruiker authenticatie",
"Encryption" : "Versleuteling",
"Workflows & Tags" : "Workflows & Tags",
"Sharing" : "Delen",
"Search" : "Zoeken",
"Help & Tips" : "Help & Tips",
"Additional" : "Extra",
"%s enter the database username and name." : "%s voer de database gebruikersnaam en naam in .",
"%s enter the database username." : "%s opgeven database gebruikersnaam.",
"%s enter the database name." : "%s opgeven databasenaam.",
"%s you may not use dots in the database name" : "%s er mogen geen puntjes in de databasenaam voorkomen",
"Oracle connection could not be established" : "Er kon geen verbinding met Oracle worden bereikt",
"Oracle username and/or password not valid" : "Oracle gebruikersnaam en/of wachtwoord ongeldig",
"DB Error: \"%s\"" : "DB Fout: \"%s\"",
"Offending command was: \"%s\"" : "Onjuiste commande was: \"%s\"",
"You need to enter either an existing account or the administrator." : "Geef of een bestaand account op of het beheerdersaccount.",
"Offending command was: \"%s\", name: %s, password: %s" : "Onjuiste commando was: \"%s\", naam: %s, wachtwoord: %s",
"PostgreSQL username and/or password not valid" : "PostgreSQL gebruikersnaam en/of wachtwoord ongeldig",
"%s is not supported and %s will not work properly on this platform. Use it at your own risk! " : "%s wordt niet ondersteund en %s zal niet goed werken op dit platform. Gebruik het op uw eigen risico!",
"For the best results, please consider using a GNU/Linux server instead." : "Voor het beste resultaat adviseren wij het gebruik van een GNU/Linux server.",
"It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. This will lead to problems with files over 4 GB and is highly discouraged." : "Het lijkt erop dat deze %s versie draait in een 32 bits PHP omgeving en dat open_basedir is geconfigureerd in php.ini. Dat zal leiden tot problemen met bestanden groter dan 4 GB en wordt dus sterk afgeraden.",
"Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP." : "Verwijder de open_basedir instelling in php.ini of schakel over op de 64bit PHP.",
"Set an admin username." : "Stel de gebruikersnaam van de beheerder in.",
"Set an admin password." : "Stel een beheerderswachtwoord in.",
"Can't create or write into the data directory %s" : "Kan niets creëren of wegschrijven in datadirectory %s",
"Invalid Federated Cloud ID" : "Ongeldige Federated Cloud ID",
"%s shared »%s« with you" : "%s deelde »%s« met u",
"%s via %s" : "%s via %s",
"Sharing %s failed, because the backend does not allow shares from type %i" : "Delen van %s is mislukt, omdat de share-backend niet toestaat om type %i te delen",
"Sharing %s failed, because the file does not exist" : "Delen van %s is mislukt, omdat het bestand niet bestaat",
"You are not allowed to share %s" : "U bent niet bevoegd om %s te delen",
"Sharing %s failed, because you can not share with yourself" : "Delen van %s is mislukt, omdat iemand niet met zichzelf kan delen",
"Sharing %s failed, because the user %s does not exist" : "Delen van %s is mislukt, omdat gebruiker %s niet bestaat",
"Sharing %s failed, because the user %s is not a member of any groups that %s is a member of" : "Delen van %s is mislukt, omdat gebruiker %s geen lid is van een groep waar %s lid van is",
"Sharing %s failed, because this item is already shared with %s" : "Delen van %s is mislukt, omdat het object al wordt gedeeld met %s",
"Sharing %s failed, because this item is already shared with user %s" : "Delen van %s is mislukt, omdat het object al wordt gedeeld met gebruiker %s",
"Sharing %s failed, because the group %s does not exist" : "Delen van %s is mislukt, omdat groep %s niet bestaat",
"Sharing %s failed, because %s is not a member of the group %s" : "Delen van %s is mislukt, omdat %s geen lid is van groep %s",
"You need to provide a password to create a public link, only protected links are allowed" : "U moet een wachtwoord verstrekken om een openbare koppeling te maken, alleen beschermde links zijn toegestaan",
"Sharing %s failed, because sharing with links is not allowed" : "Delen van %s is mislukt, omdat het delen met links niet is toegestaan",
"Not allowed to create a federated share with the same user" : "Het is niet toegestaan om een gefedereerde share met dezelfde gebruikersserver te maken",
"Sharing %s failed, could not find %s, maybe the server is currently unreachable." : "Delen van %s mislukt, kon %s niet vinden, misschien is de server niet bereikbaar.",
"Share type %s is not valid for %s" : "Delen van type %s is niet geldig voor %s",
"Setting permissions for %s failed, because the permissions exceed permissions granted to %s" : "Instellen van de permissies voor %s is mislukt, omdat de permissies hoger zijn dan de aan %s toegekende permissies",
"Setting permissions for %s failed, because the item was not found" : "Instellen van de permissies voor %s is mislukt, omdat het object niet is gevonden",
"Cannot set expiration date. Shares cannot expire later than %s after they have been shared" : "Kon vervaldatum niet instellen. Shares kunnen niet langer dan %s vervallen na het moment van delen",
"Cannot set expiration date. Expiration date is in the past" : "Kon vervaldatum niet instellen. De vervaldatum ligt in het verleden",
"Cannot clear expiration date. Shares are required to have an expiration date." : "Kon vervaldatum niet weghalen. Shares moeten een vervaldatum hebben.",
"Sharing backend %s must implement the interface OCP\\Share_Backend" : "Het share-backend %s moet de OCP\\Share_Backend interface implementeren",
"Sharing backend %s not found" : "Het share-backend %s is niet gevonden",
"Sharing backend for %s not found" : "Het share-backend voor %s is niet gevonden",
"Sharing failed, because the user %s is the original sharer" : "Delen mislukt, omdat gebruiker %s de originele deler is",
"Sharing %s failed, because the permissions exceed permissions granted to %s" : "Delen van %s is mislukt, omdat de rechten de aan %s toegekende autorisaties overschrijden",
"Sharing %s failed, because resharing is not allowed" : "Delen van %s is mislukt, omdat her-delen niet is toegestaan",
"Sharing %s failed, because the sharing backend for %s could not find its source" : "Delen van %s is mislukt, omdat de share-backend voor %s de bron niet kon vinden",
"Sharing %s failed, because the file could not be found in the file cache" : "Delen van %s is mislukt, omdat het bestand niet in de bestandscache kon worden gevonden",
"Cannot increase permissions of %s" : "Kan de rechten van %s niet verruimen",
"Files can't be shared with delete permissions" : "Bestanden kunnen niet worden gedeeld met verwijderrechten",
"Files can't be shared with create permissions" : "Bestanden kunnen niet worden gedeeld met creatie rechten",
"Expiration date is in the past" : "De vervaldatum ligt in het verleden",
"Cannot set expiration date more than %s days in the future" : "Kan vervaldatum niet verder dan %s dagen in de toekomst instellen",
"Could not find category \"%s\"" : "Kon categorie \"%s\" niet vinden",
"Only the following characters are allowed in a username: \"a-z\", \"A-Z\", \"0-9\", and \"_.@-'\"" : "Alleen de volgende tekens zijn toegestaan in een gebruikersnaam: \"a-z\", \"A-Z\", \"0-9\", en \"_.@-\"",
"A valid username must be provided" : "Er moet een geldige gebruikersnaam worden opgegeven",
"Username contains whitespace at the beginning or at the end" : "De gebruikersnaam bevat spaties aan het begin of eind",
"A valid password must be provided" : "Er moet een geldig wachtwoord worden opgegeven",
"The username is already being used" : "De gebruikersnaam bestaat al",
"Login canceled by app" : "Inloggen geannuleerd door app",
"User disabled" : "Gebruiker gedeactiveerd",
"Help" : "Help",
"Settings" : "Instellingen",
"Users" : "Gebruikers",
"App \"%s\" cannot be installed because the following dependencies are not fulfilled: %s" : "App \"%s\" kan niet worden geïnstalleerd, omdat de volgende afhankelijkheden niet zijn ingevuld: %s",
"A safe home for all your data" : "Een veilig thuis voor al uw gegevens",
"File is currently busy, please try again later" : "Bestandsverwerking bezig, probeer het later opnieuw",
"File cannot be read" : "Bestand kan niet worden gelezen",
"Application is not enabled" : "De applicatie is niet actief",
"Authentication error" : "Authenticatie fout",
"Token expired. Please reload page." : "Token verlopen. Herlaad de pagina.",
"Unknown user" : "Onbekende gebruiker",
"No database drivers (sqlite, mysql, or postgresql) installed." : "Geen database drivers (sqlite, mysql of postgres) geïnstalleerd.",
"Cannot write into \"config\" directory" : "Kan niet schrijven naar de \"config\" directory",
"Cannot create \"data\" directory" : "Kan de \"data\" directory niet aanmaken",
"This can usually be fixed by <a href=\"%s\" target=\"_blank\" rel=\"noreferrer\">giving the webserver write access to the root directory</a>." : "Dit kan worden hersteld door <a href=\"%s\" target=\"_blank\" rel=\"noreferrer\"> de webserver schrijfrechten te geven tot de hoofddirectory</a>.",
"Permissions can usually be fixed by %sgiving the webserver write access to the root directory%s." : "Dit kan hersteld worden door de webserver schrijfrechten te %s geven op de hoofddirectory %s.",
"Setting locale to %s failed" : "Instellen taal op %s mislukte",
"Please install one of these locales on your system and restart your webserver." : "Installeer één van de talen op uw systeem en herstart uw webserver.",
"Please ask your server administrator to install the module." : "Vraag uw beheerder om de module te installeren.",
"PHP module %s not installed." : "PHP module %s niet geïnstalleerd.",
"PHP setting \"%s\" is not set to \"%s\"." : "PHP instelling \"%s\" staat niet op \"%s\".",
"Adjusting this setting in php.ini will make ownCloud run again" : "Het in php.ini bijstellen hiervan laat ownCloud weer werken",
"mbstring.func_overload is set to \"%s\" instead of the expected value \"0\"" : "mbstring.func_overload is ingesteld op \"%s\" in plaats van op de verwachte waarde \"0\"",
"To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini" : "Om dit op te lossen stel <code>mbstring.func_overload</code> in op <code>0</code> in uw php.ini",
"libxml2 2.7.0 is at least required. Currently %s is installed." : "De laagste toegestane libxml2 versie is 2.7.0. Momenteel is %s is geïnstalleerd.",
"To fix this issue update your libxml2 version and restart your web server." : "Om dit te herstellen, moet u de libxml2 versie bijwerken en uw webserver herstarten.",
"PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible." : "PHP is blijkbaar zo ingesteld dat inline doc blokken worden gestript. Hierdoor worden verschillende kernmodules onbruikbaar.",
"This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Dit wordt vermoedelijk veroorzaakt door een cache/accelerator, zoals Zend OPcache of eAccelerator.",
"PHP modules have been installed, but they are still listed as missing?" : "PHP modules zijn geïnstalleerd, maar worden ze nog steeds als ontbrekend aangegeven?",
"Please ask your server administrator to restart the web server." : "Vraag uw beheerder de webserver opnieuw op te starten.",
"PostgreSQL >= 9 required" : "PostgreSQL >= 9 vereist",
"Please upgrade your database version" : "Werk uw database versie bij",
"Please change the permissions to 0770 so that the directory cannot be listed by other users." : "Wijzig de permissies in 0770 zodat de directory niet door anderen bekeken kan worden.",
"Your Data directory is readable by other users" : "Uw datadirectory is leesbaar voor andere gebruikers",
"Your Data directory must be an absolute path" : "Uw datadirectory moet een absoluut pad hebben",
"Check the value of \"datadirectory\" in your configuration" : "Controleer de waarde van \"datadirectory\" in uw configuratie",
"Your Data directory is invalid" : "Uw datadirectory is ongeldig",
"Please check that the data directory contains a file \".ocdata\" in its root." : "Verifieer dat de data directory een bestand \".ocdata\" in de hoofdmap heeft.",
"Could not obtain lock type %d on \"%s\"." : "Kon geen lock type %d krijgen op \"%s\".",
"Storage unauthorized. %s" : "Opslag niet toegestaan. %s",
"Storage incomplete configuration. %s" : "Incomplete opslagconfiguratie. %s",
"Storage connection error. %s" : "Opslagverbindingsfout. %s",
"Storage is temporarily not available" : "Opslag is tijdelijk niet beschikbaar",
"Storage connection timeout. %s" : "Opslagverbinding time-out. %s"
},
"nplurals=2; plural=(n != 1);");
| agpl-3.0 |
ComPlat/chemotion_ELN | app/packs/src/admin/MessagePublish.js | 2932 | import React from 'react';
import ReactDOM from 'react-dom';
import { FormGroup, ControlLabel, FormControl, Button, Panel } from 'react-bootstrap';
import Select from 'react-select';
import MessagesFetcher from '../components/fetchers/MessagesFetcher';
export default class MessagePublish extends React.Component {
constructor(props) {
super(props);
this.state = {
channels: [],
selectedChannel: null,
};
this.toggleChannelList = this.toggleChannelList.bind(this);
this.handleChannelChange = this.handleChannelChange.bind(this);
this.messageSend = this.messageSend.bind(this);
}
componentDidMount() {
this.toggleChannelList();
}
handleChannelChange(selectedChannel) {
if (selectedChannel) {
this.setState({ selectedChannel });
}
}
toggleChannelList() {
MessagesFetcher.fetchChannels(9)
.then((result) => {
const channels = result.channels.map(c =>
({ value: c.id, name: c.subject, label: c.subject }));
channels.sort((a, b) => (a.value - b.value));
this.setState({ channels });
});
}
messageSend() {
const { selectedChannel } = this.state;
if (!selectedChannel) {
alert('Please select channel!');
} else {
const params = {
channel_id: selectedChannel.value,
content: this.myMessage.value,
};
MessagesFetcher.createMessage(params)
.then((result) => {
this.myMessage.value = '';
alert('Message sent!');
});
}
}
render() {
const { selectedChannel, channels } = this.state;
return (
<div>
<Panel style={{ height: 'calc(100vh - 20px)' }}>
<Panel.Body>
<div className="col-md-3">
<ControlLabel>Channel</ControlLabel>
<Select
value={selectedChannel}
onChange={this.handleChannelChange}
options={channels}
placeholder="Select your channel"
autoFocus
/>
</div>
<div className="col-md-9">
<form>
<FormGroup controlId="formControlsTextarea">
<ControlLabel>Message</ControlLabel>
<FormControl componentClass="textarea" placeholder="message..." rows="20" inputRef={(ref) => { this.myMessage = ref; }} />
</FormGroup>
<Button
bsStyle="primary"
onClick={() => this.messageSend()}
>
Publish
<i className="fa fa-paper-plane" />
</Button>
</form>
</div>
</Panel.Body>
</Panel>
</div>
);
}
}
document.addEventListener('DOMContentLoaded', () => {
const domElement = document.getElementById('MsgPub');
if (domElement) { ReactDOM.render(<MsgPub />, domElement); }
});
| agpl-3.0 |
astrobin/astrobin | astrobin/static/astrobin/ckeditor/plugins/a11yhelp/dialogs/lang/et.js | 4924 | /**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'et', {
title: 'Hõlbustuste kasutamise juhised',
contents: 'Abi sisu. Selle dialoogi sulgemiseks vajuta ESC klahvi.',
legend: [
{
name: 'Üldine',
items: [
{
name: 'Redaktori tööriistariba',
legend: 'Tööriistaribale navigeerimiseks vajuta ${toolbarFocus}. Järgmisele või eelmisele tööriistagrupile liikumiseks vajuta TAB või SHIFT+TAB. Järgmisele või eelmisele tööriistaribale liikumiseks vajuta PAREMALE NOOLT või VASAKULE NOOLT. Vajuta TÜHIKUT või ENTERIT, et tööriistariba nupp aktiveerida.'
},
{
name: 'Redaktori dialoog',
legend:
'Dialoogi sees vajuta TAB, et liikuda järgmisele dialoogi elemendile, SHIFT+TAB, et liikuda tagasi, vajuta ENTER dialoogi kinnitamiseks, ESC dialoogi sulgemiseks. Kui dialoogil on mitu kaarti/sakki, pääseb kaartide nimekirjale ligi ALT+F10 klahvidega või TABi kasutades. Kui kaartide nimekiri on fookuses, saab järgmisele ja eelmisele kaardile vastavalt PAREMALE ja VASAKULE NOOLTEGA.'
},
{
name: 'Redaktori kontekstimenüü',
legend: 'Vajuta ${contextMenu} või RAKENDUSE KLAHVI, et avada kontekstimenüü. Siis saad liikuda järgmisele reale TAB klahvi või ALLA NOOLEGA. Eelmisele valikule saab liikuda SHIFT+TAB klahvidega või ÜLES NOOLEGA. Kirje valimiseks vajuta TÜHIK või ENTER. Alamenüü saab valida kui alammenüü kirje on aktiivne ja valida kas TÜHIK, ENTER või PAREMALE NOOL. Ülemisse menüüsse tagasi saab ESC klahvi või VASAKULE NOOLEGA. Menüü saab sulgeda ESC klahviga.'
},
{
name: 'Redaktori loetelu kast',
legend: 'Loetelu kasti sees saab järgmisele reale liikuda TAB klahvi või ALLANOOLEGA. Eelmisele reale saab liikuda SHIFT+TAB klahvide või ÜLESNOOLEGA. Kirje valimiseks vajuta TÜHIKUT või ENTERIT. Loetelu kasti sulgemiseks vajuta ESC klahvi.'
},
{
name: 'Redaktori elementide järjestuse riba',
legend: 'Vajuta ${elementsPathFocus} et liikuda asukoha ribal asuvatele elementidele. Järgmise elemendi nupule saab liikuda TAB klahviga või PAREMALE NOOLEGA. Eelmisele nupule saab liikuda SHIFT+TAB klahvi või VASAKULE NOOLEGA. Vajuta TÜHIK või ENTER, et valida redaktoris vastav element.'
}
]
},
{
name: 'Käsud',
items: [
{
name: 'Tühistamise käsk',
legend: 'Vajuta ${undo}'
},
{
name: 'Uuesti tegemise käsk',
legend: 'Vajuta ${redo}'
},
{
name: 'Rasvase käsk',
legend: 'Vajuta ${bold}'
},
{
name: 'Kursiivi käsk',
legend: 'Vajuta ${italic}'
},
{
name: 'Allajoonimise käsk',
legend: 'Vajuta ${underline}'
},
{
name: 'Lingi käsk',
legend: 'Vajuta ${link}'
},
{
name: 'Tööriistariba peitmise käsk',
legend: 'Vajuta ${toolbarCollapse}'
},
{
name: 'Ligipääs eelmisele fookuskohale',
legend: 'Vajuta ${accessPreviousSpace}, et pääseda ligi lähimale liigipääsematule fookuskohale enne kursorit, näiteks: kahe järjestikuse HR elemendi vahele. Vajuta kombinatsiooni uuesti, et pääseda ligi kaugematele kohtadele.'
},
{
name: 'Ligipääs järgmisele fookuskohale',
legend: 'Vajuta ${accessNextSpace}, et pääseda ligi lähimale liigipääsematule fookuskohale pärast kursorit, näiteks: kahe järjestikuse HR elemendi vahele. Vajuta kombinatsiooni uuesti, et pääseda ligi kaugematele kohtadele.'
},
{
name: 'Hõlbustuste abi',
legend: 'Vajuta ${a11yHelp}'
},
{
name: 'Asetamine tavalise tekstina',
legend: 'Vajuta ${pastetext}',
legendEdge: 'Vajuta ${pastetext}, siis ${paste}'
}
]
}
],
tab: 'Tabulaator',
pause: 'Paus',
capslock: 'Tõstulukk',
escape: 'Paoklahv',
pageUp: 'Leht üles',
pageDown: 'Leht alla',
leftArrow: 'Nool vasakule',
upArrow: 'Nool üles',
rightArrow: 'Nool paremale',
downArrow: 'Nool alla',
insert: 'Sisetamine',
leftWindowKey: 'Vasak Windowsi klahv',
rightWindowKey: 'Parem Windowsi klahv',
selectKey: 'Vali klahv',
numpad0: 'Numbriala 0',
numpad1: 'Numbriala 1',
numpad2: 'Numbriala 2',
numpad3: 'Numbriala 3',
numpad4: 'Numbriala 4',
numpad5: 'Numbriala 5',
numpad6: 'Numbriala 6',
numpad7: 'Numbriala 7',
numpad8: 'Numbriala 8',
numpad9: 'Numbriala 9',
multiply: 'Korrutus',
add: 'Pluss',
subtract: 'Miinus',
decimalPoint: 'Koma',
divide: 'Jagamine',
f1: 'F1',
f2: 'F2',
f3: 'F3',
f4: 'F4',
f5: 'F5',
f6: 'F6',
f7: 'F7',
f8: 'F8',
f9: 'F9',
f10: 'F10',
f11: 'F11',
f12: 'F12',
numLock: 'Numbrilukk',
scrollLock: 'Kerimislukk',
semiColon: 'Semikoolon',
equalSign: 'Võrdusmärk',
comma: 'Koma',
dash: 'Sidekriips',
period: 'Punkt',
forwardSlash: 'Kaldkriips',
graveAccent: 'Rõhumärk',
openBracket: 'Algussulg',
backSlash: 'Kurakaldkriips',
closeBracket: 'Lõpusulg',
singleQuote: 'Ülakoma'
} );
| agpl-3.0 |
lairdubois/lairdubois | src/Ladb/CoreBundle/Controller/Core/ResourceController.php | 489 | <?php
namespace Ladb\CoreBundle\Controller\Core;
use Symfony\Component\Routing\Annotation\Route;
use Ladb\CoreBundle\Controller\AbstractController;
use Ladb\CoreBundle\Handler\ResourceUploadHandler;
/**
* @Route("/resources")
*/
class ResourceController extends AbstractController {
/**
* @Route("/upload", name="core_resource_upload")
*/
public function uploadAction() {
$uploadHandler = $this->get(ResourceUploadHandler::NAME);
$uploadHandler->handle();
exit(0);
}
}
| agpl-3.0 |
chk1/openmensa | vendor/assets/javascripts/leaflet.markercluster.js | 74547 | /*
Leaflet.markercluster, Provides Beautiful Animated Marker Clustering functionality for Leaflet, a JS library for interactive maps.
https://github.com/Leaflet/Leaflet.markercluster
(c) 2012-2013, Dave Leaver, smartrak
*/
(function (window, document, undefined) {
/*
* L.MarkerClusterGroup extends L.FeatureGroup by clustering the markers contained within
*/
L.MarkerClusterGroup = L.FeatureGroup.extend({
options: {
maxClusterRadius: 80, //A cluster will cover at most this many pixels from its center
iconCreateFunction: null,
spiderfyOnMaxZoom: true,
showCoverageOnHover: true,
zoomToBoundsOnClick: true,
singleMarkerMode: false,
disableClusteringAtZoom: null,
// Setting this to false prevents the removal of any clusters outside of the viewpoint, which
// is the default behaviour for performance reasons.
removeOutsideVisibleBounds: true,
//Whether to animate adding markers after adding the MarkerClusterGroup to the map
// If you are adding individual markers set to true, if adding bulk markers leave false for massive performance gains.
animateAddingMarkers: false,
//Increase to increase the distance away that spiderfied markers appear from the center
spiderfyDistanceMultiplier: 1,
//Options to pass to the L.Polygon constructor
polygonOptions: {}
},
initialize: function (options) {
L.Util.setOptions(this, options);
if (!this.options.iconCreateFunction) {
this.options.iconCreateFunction = this._defaultIconCreateFunction;
}
this._featureGroup = L.featureGroup();
this._featureGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
this._nonPointGroup = L.featureGroup();
this._nonPointGroup.on(L.FeatureGroup.EVENTS, this._propagateEvent, this);
this._inZoomAnimation = 0;
this._needsClustering = [];
this._needsRemoving = []; //Markers removed while we aren't on the map need to be kept track of
//The bounds of the currently shown area (from _getExpandedVisibleBounds) Updated on zoom/move
this._currentShownBounds = null;
},
addLayer: function (layer) {
if (layer instanceof L.LayerGroup) {
var array = [];
for (var i in layer._layers) {
array.push(layer._layers[i]);
}
return this.addLayers(array);
}
//Don't cluster non point data
if (!layer.getLatLng) {
this._nonPointGroup.addLayer(layer);
return this;
}
if (!this._map) {
this._needsClustering.push(layer);
return this;
}
if (this.hasLayer(layer)) {
return this;
}
//If we have already clustered we'll need to add this one to a cluster
if (this._unspiderfy) {
this._unspiderfy();
}
this._addLayer(layer, this._maxZoom);
//Work out what is visible
var visibleLayer = layer,
currentZoom = this._map.getZoom();
if (layer.__parent) {
while (visibleLayer.__parent._zoom >= currentZoom) {
visibleLayer = visibleLayer.__parent;
}
}
if (this._currentShownBounds.contains(visibleLayer.getLatLng())) {
if (this.options.animateAddingMarkers) {
this._animationAddLayer(layer, visibleLayer);
} else {
this._animationAddLayerNonAnimated(layer, visibleLayer);
}
}
return this;
},
removeLayer: function (layer) {
//Non point layers
if (!layer.getLatLng) {
this._nonPointGroup.removeLayer(layer);
return this;
}
if (!this._map) {
if (!this._arraySplice(this._needsClustering, layer) && this.hasLayer(layer)) {
this._needsRemoving.push(layer);
}
return this;
}
if (!layer.__parent) {
return this;
}
if (this._unspiderfy) {
this._unspiderfy();
this._unspiderfyLayer(layer);
}
//Remove the marker from clusters
this._removeLayer(layer, true);
if (this._featureGroup.hasLayer(layer)) {
this._featureGroup.removeLayer(layer);
if (layer.setOpacity) {
layer.setOpacity(1);
}
}
return this;
},
//Takes an array of markers and adds them in bulk
addLayers: function (layersArray) {
var i, l, m,
onMap = this._map,
fg = this._featureGroup,
npg = this._nonPointGroup;
for (i = 0, l = layersArray.length; i < l; i++) {
m = layersArray[i];
//Not point data, can't be clustered
if (!m.getLatLng) {
npg.addLayer(m);
continue;
}
if (this.hasLayer(m)) {
continue;
}
if (!onMap) {
this._needsClustering.push(m);
continue;
}
this._addLayer(m, this._maxZoom);
//If we just made a cluster of size 2 then we need to remove the other marker from the map (if it is) or we never will
if (m.__parent) {
if (m.__parent.getChildCount() === 2) {
var markers = m.__parent.getAllChildMarkers(),
otherMarker = markers[0] === m ? markers[1] : markers[0];
fg.removeLayer(otherMarker);
}
}
}
if (onMap) {
//Update the icons of all those visible clusters that were affected
fg.eachLayer(function (c) {
if (c instanceof L.MarkerCluster && c._iconNeedsUpdate) {
c._updateIcon();
}
});
this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
}
return this;
},
//Takes an array of markers and removes them in bulk
removeLayers: function (layersArray) {
var i, l, m,
fg = this._featureGroup,
npg = this._nonPointGroup;
if (!this._map) {
for (i = 0, l = layersArray.length; i < l; i++) {
m = layersArray[i];
this._arraySplice(this._needsClustering, m);
npg.removeLayer(m);
}
return this;
}
for (i = 0, l = layersArray.length; i < l; i++) {
m = layersArray[i];
if (!m.__parent) {
npg.removeLayer(m);
continue;
}
this._removeLayer(m, true, true);
if (fg.hasLayer(m)) {
fg.removeLayer(m);
if (m.setOpacity) {
m.setOpacity(1);
}
}
}
//Fix up the clusters and markers on the map
this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
fg.eachLayer(function (c) {
if (c instanceof L.MarkerCluster) {
c._updateIcon();
}
});
return this;
},
//Removes all layers from the MarkerClusterGroup
clearLayers: function () {
//Need our own special implementation as the LayerGroup one doesn't work for us
//If we aren't on the map (yet), blow away the markers we know of
if (!this._map) {
this._needsClustering = [];
delete this._gridClusters;
delete this._gridUnclustered;
}
if (this._noanimationUnspiderfy) {
this._noanimationUnspiderfy();
}
//Remove all the visible layers
this._featureGroup.clearLayers();
this._nonPointGroup.clearLayers();
this.eachLayer(function (marker) {
delete marker.__parent;
});
if (this._map) {
//Reset _topClusterLevel and the DistanceGrids
this._generateInitialClusters();
}
return this;
},
//Override FeatureGroup.getBounds as it doesn't work
getBounds: function () {
var bounds = new L.LatLngBounds();
if (this._topClusterLevel) {
bounds.extend(this._topClusterLevel._bounds);
} else {
for (var i = this._needsClustering.length - 1; i >= 0; i--) {
bounds.extend(this._needsClustering[i].getLatLng());
}
}
//TODO: Can remove this isValid test when leaflet 0.6 is released
var nonPointBounds = this._nonPointGroup.getBounds();
if (nonPointBounds.isValid()) {
bounds.extend(nonPointBounds);
}
return bounds;
},
//Overrides LayerGroup.eachLayer
eachLayer: function (method, context) {
var markers = this._needsClustering.slice(),
i;
if (this._topClusterLevel) {
this._topClusterLevel.getAllChildMarkers(markers);
}
for (i = markers.length - 1; i >= 0; i--) {
method.call(context, markers[i]);
}
this._nonPointGroup.eachLayer(method, context);
},
//Returns true if the given layer is in this MarkerClusterGroup
hasLayer: function (layer) {
if (!layer) {
return false;
}
var i, anArray = this._needsClustering;
for (i = anArray.length - 1; i >= 0; i--) {
if (anArray[i] === layer) {
return true;
}
}
anArray = this._needsRemoving;
for (i = anArray.length - 1; i >= 0; i--) {
if (anArray[i] === layer) {
return false;
}
}
return !!(layer.__parent && layer.__parent._group === this) || this._nonPointGroup.hasLayer(layer);
},
//Zoom down to show the given layer (spiderfying if necessary) then calls the callback
zoomToShowLayer: function (layer, callback) {
var showMarker = function () {
if ((layer._icon || layer.__parent._icon) && !this._inZoomAnimation) {
this._map.off('moveend', showMarker, this);
this.off('animationend', showMarker, this);
if (layer._icon) {
callback();
} else if (layer.__parent._icon) {
var afterSpiderfy = function () {
this.off('spiderfied', afterSpiderfy, this);
callback();
};
this.on('spiderfied', afterSpiderfy, this);
layer.__parent.spiderfy();
}
}
};
if (layer._icon) {
callback();
} else if (layer.__parent._zoom < this._map.getZoom()) {
//Layer should be visible now but isn't on screen, just pan over to it
this._map.on('moveend', showMarker, this);
if (!layer._icon) {
this._map.panTo(layer.getLatLng());
}
} else {
this._map.on('moveend', showMarker, this);
this.on('animationend', showMarker, this);
this._map.setView(layer.getLatLng(), layer.__parent._zoom + 1);
layer.__parent.zoomToBounds();
}
},
//Overrides FeatureGroup.onAdd
onAdd: function (map) {
this._map = map;
var i, l, layer;
if (!isFinite(this._map.getMaxZoom())) {
throw "Map has no maxZoom specified";
}
this._featureGroup.onAdd(map);
this._nonPointGroup.onAdd(map);
if (!this._gridClusters) {
this._generateInitialClusters();
}
for (i = 0, l = this._needsRemoving.length; i < l; i++) {
layer = this._needsRemoving[i];
this._removeLayer(layer, true);
}
this._needsRemoving = [];
for (i = 0, l = this._needsClustering.length; i < l; i++) {
layer = this._needsClustering[i];
//If the layer doesn't have a getLatLng then we can't cluster it, so add it to our child featureGroup
if (!layer.getLatLng) {
this._featureGroup.addLayer(layer);
continue;
}
if (layer.__parent) {
continue;
}
this._addLayer(layer, this._maxZoom);
}
this._needsClustering = [];
this._map.on('zoomend', this._zoomEnd, this);
this._map.on('moveend', this._moveEnd, this);
if (this._spiderfierOnAdd) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
this._spiderfierOnAdd();
}
this._bindEvents();
//Actually add our markers to the map:
//Remember the current zoom level and bounds
this._zoom = this._map.getZoom();
this._currentShownBounds = this._getExpandedVisibleBounds();
//Make things appear on the map
this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, this._currentShownBounds);
},
//Overrides FeatureGroup.onRemove
onRemove: function (map) {
map.off('zoomend', this._zoomEnd, this);
map.off('moveend', this._moveEnd, this);
this._unbindEvents();
//In case we are in a cluster animation
this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
if (this._spiderfierOnRemove) { //TODO FIXME: Not sure how to have spiderfier add something on here nicely
this._spiderfierOnRemove();
}
//Clean up all the layers we added to the map
this._featureGroup.onRemove(map);
this._nonPointGroup.onRemove(map);
this._featureGroup.clearLayers();
this._map = null;
},
getVisibleParent: function (marker) {
var vMarker = marker;
while (vMarker !== null && !vMarker._icon) {
vMarker = vMarker.__parent;
}
return vMarker;
},
//Remove the given object from the given array
_arraySplice: function (anArray, obj) {
for (var i = anArray.length - 1; i >= 0; i--) {
if (anArray[i] === obj) {
anArray.splice(i, 1);
return true;
}
}
},
//Internal function for removing a marker from everything.
//dontUpdateMap: set to true if you will handle updating the map manually (for bulk functions)
_removeLayer: function (marker, removeFromDistanceGrid, dontUpdateMap) {
var gridClusters = this._gridClusters,
gridUnclustered = this._gridUnclustered,
fg = this._featureGroup,
map = this._map;
//Remove the marker from distance clusters it might be in
if (removeFromDistanceGrid) {
for (var z = this._maxZoom; z >= 0; z--) {
if (!gridUnclustered[z].removeObject(marker, map.project(marker.getLatLng(), z))) {
break;
}
}
}
//Work our way up the clusters removing them as we go if required
var cluster = marker.__parent,
markers = cluster._markers,
otherMarker;
//Remove the marker from the immediate parents marker list
this._arraySplice(markers, marker);
while (cluster) {
cluster._childCount--;
if (cluster._zoom < 0) {
//Top level, do nothing
break;
} else if (removeFromDistanceGrid && cluster._childCount <= 1) { //Cluster no longer required
//We need to push the other marker up to the parent
otherMarker = cluster._markers[0] === marker ? cluster._markers[1] : cluster._markers[0];
//Update distance grid
gridClusters[cluster._zoom].removeObject(cluster, map.project(cluster._cLatLng, cluster._zoom));
gridUnclustered[cluster._zoom].addObject(otherMarker, map.project(otherMarker.getLatLng(), cluster._zoom));
//Move otherMarker up to parent
this._arraySplice(cluster.__parent._childClusters, cluster);
cluster.__parent._markers.push(otherMarker);
otherMarker.__parent = cluster.__parent;
if (cluster._icon) {
//Cluster is currently on the map, need to put the marker on the map instead
fg.removeLayer(cluster);
if (!dontUpdateMap) {
fg.addLayer(otherMarker);
}
}
} else {
cluster._recalculateBounds();
if (!dontUpdateMap || !cluster._icon) {
cluster._updateIcon();
}
}
cluster = cluster.__parent;
}
delete marker.__parent;
},
_propagateEvent: function (e) {
if (e.layer instanceof L.MarkerCluster) {
e.type = 'cluster' + e.type;
}
this.fire(e.type, e);
},
//Default functionality
_defaultIconCreateFunction: function (cluster) {
var childCount = cluster.getChildCount();
var c = ' marker-cluster-';
if (childCount < 10) {
c += 'small';
} else if (childCount < 100) {
c += 'medium';
} else {
c += 'large';
}
return new L.DivIcon({ html: '<div><span>' + childCount + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
},
_bindEvents: function () {
var map = this._map,
spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
showCoverageOnHover = this.options.showCoverageOnHover,
zoomToBoundsOnClick = this.options.zoomToBoundsOnClick;
//Zoom on cluster click or spiderfy if we are at the lowest level
if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
this.on('clusterclick', this._zoomOrSpiderfy, this);
}
//Show convex hull (boundary) polygon on mouse over
if (showCoverageOnHover) {
this.on('clustermouseover', this._showCoverage, this);
this.on('clustermouseout', this._hideCoverage, this);
map.on('zoomend', this._hideCoverage, this);
map.on('layerremove', this._hideCoverageOnRemove, this);
}
},
_zoomOrSpiderfy: function (e) {
var map = this._map;
if (map.getMaxZoom() === map.getZoom()) {
if (this.options.spiderfyOnMaxZoom) {
e.layer.spiderfy();
}
} else if (this.options.zoomToBoundsOnClick) {
e.layer.zoomToBounds();
}
},
_showCoverage: function (e) {
var map = this._map;
if (this._inZoomAnimation) {
return;
}
if (this._shownPolygon) {
map.removeLayer(this._shownPolygon);
}
if (e.layer.getChildCount() > 2 && e.layer !== this._spiderfied) {
this._shownPolygon = new L.Polygon(e.layer.getConvexHull(), this.options.polygonOptions);
map.addLayer(this._shownPolygon);
}
},
_hideCoverage: function () {
if (this._shownPolygon) {
this._map.removeLayer(this._shownPolygon);
this._shownPolygon = null;
}
},
_hideCoverageOnRemove: function (e) {
if (e.layer === this) {
this._hideCoverage();
}
},
_unbindEvents: function () {
var spiderfyOnMaxZoom = this.options.spiderfyOnMaxZoom,
showCoverageOnHover = this.options.showCoverageOnHover,
zoomToBoundsOnClick = this.options.zoomToBoundsOnClick,
map = this._map;
if (spiderfyOnMaxZoom || zoomToBoundsOnClick) {
this.off('clusterclick', this._zoomOrSpiderfy, this);
}
if (showCoverageOnHover) {
this.off('clustermouseover', this._showCoverage, this);
this.off('clustermouseout', this._hideCoverage, this);
map.off('zoomend', this._hideCoverage, this);
map.off('layerremove', this._hideCoverageOnRemove, this);
}
},
_zoomEnd: function () {
if (!this._map) { //May have been removed from the map by a zoomEnd handler
return;
}
this._mergeSplitClusters();
this._zoom = this._map._zoom;
this._currentShownBounds = this._getExpandedVisibleBounds();
},
_moveEnd: function () {
if (this._inZoomAnimation) {
return;
}
var newBounds = this._getExpandedVisibleBounds();
this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, newBounds);
this._topClusterLevel._recursivelyAddChildrenToMap(null, this._zoom, newBounds);
this._currentShownBounds = newBounds;
return;
},
_generateInitialClusters: function () {
var maxZoom = this._map.getMaxZoom(),
radius = this.options.maxClusterRadius;
if (this.options.disableClusteringAtZoom) {
maxZoom = this.options.disableClusteringAtZoom - 1;
}
this._maxZoom = maxZoom;
this._gridClusters = {};
this._gridUnclustered = {};
//Set up DistanceGrids for each zoom
for (var zoom = maxZoom; zoom >= 0; zoom--) {
this._gridClusters[zoom] = new L.DistanceGrid(radius);
this._gridUnclustered[zoom] = new L.DistanceGrid(radius);
}
this._topClusterLevel = new L.MarkerCluster(this, -1);
},
//Zoom: Zoom to start adding at (Pass this._maxZoom to start at the bottom)
_addLayer: function (layer, zoom) {
var gridClusters = this._gridClusters,
gridUnclustered = this._gridUnclustered,
markerPoint, z;
if (this.options.singleMarkerMode) {
layer.options.icon = this.options.iconCreateFunction({
getChildCount: function () {
return 1;
},
getAllChildMarkers: function () {
return [layer];
}
});
}
//Find the lowest zoom level to slot this one in
for (; zoom >= 0; zoom--) {
markerPoint = this._map.project(layer.getLatLng(), zoom); // calculate pixel position
//Try find a cluster close by
var closest = gridClusters[zoom].getNearObject(markerPoint);
if (closest) {
closest._addChild(layer);
layer.__parent = closest;
return;
}
//Try find a marker close by to form a new cluster with
closest = gridUnclustered[zoom].getNearObject(markerPoint);
if (closest) {
var parent = closest.__parent;
if (parent) {
this._removeLayer(closest, false);
}
//Create new cluster with these 2 in it
var newCluster = new L.MarkerCluster(this, zoom, closest, layer);
gridClusters[zoom].addObject(newCluster, this._map.project(newCluster._cLatLng, zoom));
closest.__parent = newCluster;
layer.__parent = newCluster;
//First create any new intermediate parent clusters that don't exist
var lastParent = newCluster;
for (z = zoom - 1; z > parent._zoom; z--) {
lastParent = new L.MarkerCluster(this, z, lastParent);
gridClusters[z].addObject(lastParent, this._map.project(closest.getLatLng(), z));
}
parent._addChild(lastParent);
//Remove closest from this zoom level and any above that it is in, replace with newCluster
for (z = zoom; z >= 0; z--) {
if (!gridUnclustered[z].removeObject(closest, this._map.project(closest.getLatLng(), z))) {
break;
}
}
return;
}
//Didn't manage to cluster in at this zoom, record us as a marker here and continue upwards
gridUnclustered[zoom].addObject(layer, markerPoint);
}
//Didn't get in anything, add us to the top
this._topClusterLevel._addChild(layer);
layer.__parent = this._topClusterLevel;
return;
},
//Merge and split any existing clusters that are too big or small
_mergeSplitClusters: function () {
if (this._zoom < this._map._zoom) { //Zoom in, split
this._animationStart();
//Remove clusters now off screen
this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, this._zoom, this._getExpandedVisibleBounds());
this._animationZoomIn(this._zoom, this._map._zoom);
} else if (this._zoom > this._map._zoom) { //Zoom out, merge
this._animationStart();
this._animationZoomOut(this._zoom, this._map._zoom);
} else {
this._moveEnd();
}
},
//Gets the maps visible bounds expanded in each direction by the size of the screen (so the user cannot see an area we do not cover in one pan)
_getExpandedVisibleBounds: function () {
if (!this.options.removeOutsideVisibleBounds) {
return this.getBounds();
}
var map = this._map,
bounds = map.getBounds(),
sw = bounds._southWest,
ne = bounds._northEast,
latDiff = L.Browser.mobile ? 0 : Math.abs(sw.lat - ne.lat),
lngDiff = L.Browser.mobile ? 0 : Math.abs(sw.lng - ne.lng);
return new L.LatLngBounds(
new L.LatLng(sw.lat - latDiff, sw.lng - lngDiff, true),
new L.LatLng(ne.lat + latDiff, ne.lng + lngDiff, true));
},
//Shared animation code
_animationAddLayerNonAnimated: function (layer, newCluster) {
if (newCluster === layer) {
this._featureGroup.addLayer(layer);
} else if (newCluster._childCount === 2) {
newCluster._addToMap();
var markers = newCluster.getAllChildMarkers();
this._featureGroup.removeLayer(markers[0]);
this._featureGroup.removeLayer(markers[1]);
} else {
newCluster._updateIcon();
}
}
});
L.MarkerClusterGroup.include(!L.DomUtil.TRANSITION ? {
//Non Animated versions of everything
_animationStart: function () {
//Do nothing...
},
_animationZoomIn: function (previousZoomLevel, newZoomLevel) {
this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
},
_animationZoomOut: function (previousZoomLevel, newZoomLevel) {
this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel);
this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
},
_animationAddLayer: function (layer, newCluster) {
this._animationAddLayerNonAnimated(layer, newCluster);
}
} : {
//Animated versions here
_animationStart: function () {
this._map._mapPane.className += ' leaflet-cluster-anim';
this._inZoomAnimation++;
},
_animationEnd: function () {
if (this._map) {
this._map._mapPane.className = this._map._mapPane.className.replace(' leaflet-cluster-anim', '');
}
this._inZoomAnimation--;
this.fire('animationend');
},
_animationZoomIn: function (previousZoomLevel, newZoomLevel) {
var me = this,
bounds = this._getExpandedVisibleBounds(),
fg = this._featureGroup,
i;
//Add all children of current clusters to map and remove those clusters from map
this._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
var startPos = c._latlng,
markers = c._markers,
m;
if (!bounds.contains(startPos)) {
startPos = null;
}
if (c._isSingleParent() && previousZoomLevel + 1 === newZoomLevel) { //Immediately add the new child and remove us
fg.removeLayer(c);
c._recursivelyAddChildrenToMap(null, newZoomLevel, bounds);
} else {
//Fade out old cluster
c.setOpacity(0);
c._recursivelyAddChildrenToMap(startPos, newZoomLevel, bounds);
}
//Remove all markers that aren't visible any more
//TODO: Do we actually need to do this on the higher levels too?
for (i = markers.length - 1; i >= 0; i--) {
m = markers[i];
if (!bounds.contains(m._latlng)) {
fg.removeLayer(m);
}
}
});
this._forceLayout();
//Update opacities
me._topClusterLevel._recursivelyBecomeVisible(bounds, newZoomLevel);
//TODO Maybe? Update markers in _recursivelyBecomeVisible
fg.eachLayer(function (n) {
if (!(n instanceof L.MarkerCluster) && n._icon) {
n.setOpacity(1);
}
});
//update the positions of the just added clusters/markers
me._topClusterLevel._recursively(bounds, previousZoomLevel, newZoomLevel, function (c) {
c._recursivelyRestoreChildPositions(newZoomLevel);
});
//Remove the old clusters and close the zoom animation
setTimeout(function () {
//update the positions of the just added clusters/markers
me._topClusterLevel._recursively(bounds, previousZoomLevel, 0, function (c) {
fg.removeLayer(c);
c.setOpacity(1);
});
me._animationEnd();
}, 200);
},
_animationZoomOut: function (previousZoomLevel, newZoomLevel) {
this._animationZoomOutSingle(this._topClusterLevel, previousZoomLevel - 1, newZoomLevel);
//Need to add markers for those that weren't on the map before but are now
this._topClusterLevel._recursivelyAddChildrenToMap(null, newZoomLevel, this._getExpandedVisibleBounds());
//Remove markers that were on the map before but won't be now
this._topClusterLevel._recursivelyRemoveChildrenFromMap(this._currentShownBounds, previousZoomLevel, this._getExpandedVisibleBounds());
},
_animationZoomOutSingle: function (cluster, previousZoomLevel, newZoomLevel) {
var bounds = this._getExpandedVisibleBounds();
//Animate all of the markers in the clusters to move to their cluster center point
cluster._recursivelyAnimateChildrenInAndAddSelfToMap(bounds, previousZoomLevel + 1, newZoomLevel);
var me = this;
//Update the opacity (If we immediately set it they won't animate)
this._forceLayout();
cluster._recursivelyBecomeVisible(bounds, newZoomLevel);
//TODO: Maybe use the transition timing stuff to make this more reliable
//When the animations are done, tidy up
setTimeout(function () {
//This cluster stopped being a cluster before the timeout fired
if (cluster._childCount === 1) {
var m = cluster._markers[0];
//If we were in a cluster animation at the time then the opacity and position of our child could be wrong now, so fix it
m.setLatLng(m.getLatLng());
m.setOpacity(1);
} else {
cluster._recursively(bounds, newZoomLevel, 0, function (c) {
c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel + 1);
});
}
me._animationEnd();
}, 200);
},
_animationAddLayer: function (layer, newCluster) {
var me = this,
fg = this._featureGroup;
fg.addLayer(layer);
if (newCluster !== layer) {
if (newCluster._childCount > 2) { //Was already a cluster
newCluster._updateIcon();
this._forceLayout();
this._animationStart();
layer._setPos(this._map.latLngToLayerPoint(newCluster.getLatLng()));
layer.setOpacity(0);
setTimeout(function () {
fg.removeLayer(layer);
layer.setOpacity(1);
me._animationEnd();
}, 200);
} else { //Just became a cluster
this._forceLayout();
me._animationStart();
me._animationZoomOutSingle(newCluster, this._map.getMaxZoom(), this._map.getZoom());
}
}
},
//Force a browser layout of stuff in the map
// Should apply the current opacity and location to all elements so we can update them again for an animation
_forceLayout: function () {
//In my testing this works, infact offsetWidth of any element seems to work.
//Could loop all this._layers and do this for each _icon if it stops working
L.Util.falseFn(document.body.offsetWidth);
}
});
L.markerClusterGroup = function (options) {
return new L.MarkerClusterGroup(options);
};
L.MarkerCluster = L.Marker.extend({
initialize: function (group, zoom, a, b) {
L.Marker.prototype.initialize.call(this, a ? (a._cLatLng || a.getLatLng()) : new L.LatLng(0, 0), { icon: this });
this._group = group;
this._zoom = zoom;
this._markers = [];
this._childClusters = [];
this._childCount = 0;
this._iconNeedsUpdate = true;
this._bounds = new L.LatLngBounds();
if (a) {
this._addChild(a);
}
if (b) {
this._addChild(b);
}
},
//Recursively retrieve all child markers of this cluster
getAllChildMarkers: function (storageArray) {
storageArray = storageArray || [];
for (var i = this._childClusters.length - 1; i >= 0; i--) {
this._childClusters[i].getAllChildMarkers(storageArray);
}
for (var j = this._markers.length - 1; j >= 0; j--) {
storageArray.push(this._markers[j]);
}
return storageArray;
},
//Returns the count of how many child markers we have
getChildCount: function () {
return this._childCount;
},
//Zoom to the extents of this cluster
zoomToBounds: function () {
this._group._map.fitBounds(this._bounds);
},
getBounds: function () {
var bounds = new L.LatLngBounds();
bounds.extend(this._bounds);
return bounds;
},
_updateIcon: function () {
this._iconNeedsUpdate = true;
if (this._icon) {
this.setIcon(this);
}
},
//Cludge for Icon, we pretend to be an icon for performance
createIcon: function () {
if (this._iconNeedsUpdate) {
this._iconObj = this._group.options.iconCreateFunction(this);
this._iconNeedsUpdate = false;
}
return this._iconObj.createIcon();
},
createShadow: function () {
return this._iconObj.createShadow();
},
_addChild: function (new1, isNotificationFromChild) {
this._iconNeedsUpdate = true;
this._expandBounds(new1);
if (new1 instanceof L.MarkerCluster) {
if (!isNotificationFromChild) {
this._childClusters.push(new1);
new1.__parent = this;
}
this._childCount += new1._childCount;
} else {
if (!isNotificationFromChild) {
this._markers.push(new1);
}
this._childCount++;
}
if (this.__parent) {
this.__parent._addChild(new1, true);
}
},
//Expand our bounds and tell our parent to
_expandBounds: function (marker) {
var addedCount,
addedLatLng = marker._wLatLng || marker._latlng;
if (marker instanceof L.MarkerCluster) {
this._bounds.extend(marker._bounds);
addedCount = marker._childCount;
} else {
this._bounds.extend(addedLatLng);
addedCount = 1;
}
if (!this._cLatLng) {
// when clustering, take position of the first point as the cluster center
this._cLatLng = marker._cLatLng || addedLatLng;
}
// when showing clusters, take weighted average of all points as cluster center
var totalCount = this._childCount + addedCount;
//Calculate weighted latlng for display
if (!this._wLatLng) {
this._latlng = this._wLatLng = new L.LatLng(addedLatLng.lat, addedLatLng.lng);
} else {
this._wLatLng.lat = (addedLatLng.lat * addedCount + this._wLatLng.lat * this._childCount) / totalCount;
this._wLatLng.lng = (addedLatLng.lng * addedCount + this._wLatLng.lng * this._childCount) / totalCount;
}
},
//Set our markers position as given and add it to the map
_addToMap: function (startPos) {
if (startPos) {
this._backupLatlng = this._latlng;
this.setLatLng(startPos);
}
this._group._featureGroup.addLayer(this);
},
_recursivelyAnimateChildrenIn: function (bounds, center, maxZoom) {
this._recursively(bounds, 0, maxZoom - 1,
function (c) {
var markers = c._markers,
i, m;
for (i = markers.length - 1; i >= 0; i--) {
m = markers[i];
//Only do it if the icon is still on the map
if (m._icon) {
m._setPos(center);
m.setOpacity(0);
}
}
},
function (c) {
var childClusters = c._childClusters,
j, cm;
for (j = childClusters.length - 1; j >= 0; j--) {
cm = childClusters[j];
if (cm._icon) {
cm._setPos(center);
cm.setOpacity(0);
}
}
}
);
},
_recursivelyAnimateChildrenInAndAddSelfToMap: function (bounds, previousZoomLevel, newZoomLevel) {
this._recursively(bounds, newZoomLevel, 0,
function (c) {
c._recursivelyAnimateChildrenIn(bounds, c._group._map.latLngToLayerPoint(c.getLatLng()).round(), previousZoomLevel);
//TODO: depthToAnimateIn affects _isSingleParent, if there is a multizoom we may/may not be.
//As a hack we only do a animation free zoom on a single level zoom, if someone does multiple levels then we always animate
if (c._isSingleParent() && previousZoomLevel - 1 === newZoomLevel) {
c.setOpacity(1);
c._recursivelyRemoveChildrenFromMap(bounds, previousZoomLevel); //Immediately remove our children as we are replacing them. TODO previousBounds not bounds
} else {
c.setOpacity(0);
}
c._addToMap();
}
);
},
_recursivelyBecomeVisible: function (bounds, zoomLevel) {
this._recursively(bounds, 0, zoomLevel, null, function (c) {
c.setOpacity(1);
});
},
_recursivelyAddChildrenToMap: function (startPos, zoomLevel, bounds) {
this._recursively(bounds, -1, zoomLevel,
function (c) {
if (zoomLevel === c._zoom) {
return;
}
//Add our child markers at startPos (so they can be animated out)
for (var i = c._markers.length - 1; i >= 0; i--) {
var nm = c._markers[i];
if (!bounds.contains(nm._latlng)) {
continue;
}
if (startPos) {
nm._backupLatlng = nm.getLatLng();
nm.setLatLng(startPos);
if (nm.setOpacity) {
nm.setOpacity(0);
}
}
c._group._featureGroup.addLayer(nm);
}
},
function (c) {
c._addToMap(startPos);
}
);
},
_recursivelyRestoreChildPositions: function (zoomLevel) {
//Fix positions of child markers
for (var i = this._markers.length - 1; i >= 0; i--) {
var nm = this._markers[i];
if (nm._backupLatlng) {
nm.setLatLng(nm._backupLatlng);
delete nm._backupLatlng;
}
}
if (zoomLevel - 1 === this._zoom) {
//Reposition child clusters
for (var j = this._childClusters.length - 1; j >= 0; j--) {
this._childClusters[j]._restorePosition();
}
} else {
for (var k = this._childClusters.length - 1; k >= 0; k--) {
this._childClusters[k]._recursivelyRestoreChildPositions(zoomLevel);
}
}
},
_restorePosition: function () {
if (this._backupLatlng) {
this.setLatLng(this._backupLatlng);
delete this._backupLatlng;
}
},
//exceptBounds: If set, don't remove any markers/clusters in it
_recursivelyRemoveChildrenFromMap: function (previousBounds, zoomLevel, exceptBounds) {
var m, i;
this._recursively(previousBounds, -1, zoomLevel - 1,
function (c) {
//Remove markers at every level
for (i = c._markers.length - 1; i >= 0; i--) {
m = c._markers[i];
if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
c._group._featureGroup.removeLayer(m);
if (m.setOpacity) {
m.setOpacity(1);
}
}
}
},
function (c) {
//Remove child clusters at just the bottom level
for (i = c._childClusters.length - 1; i >= 0; i--) {
m = c._childClusters[i];
if (!exceptBounds || !exceptBounds.contains(m._latlng)) {
c._group._featureGroup.removeLayer(m);
if (m.setOpacity) {
m.setOpacity(1);
}
}
}
}
);
},
//Run the given functions recursively to this and child clusters
// boundsToApplyTo: a L.LatLngBounds representing the bounds of what clusters to recurse in to
// zoomLevelToStart: zoom level to start running functions (inclusive)
// zoomLevelToStop: zoom level to stop running functions (inclusive)
// runAtEveryLevel: function that takes an L.MarkerCluster as an argument that should be applied on every level
// runAtBottomLevel: function that takes an L.MarkerCluster as an argument that should be applied at only the bottom level
_recursively: function (boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel) {
var childClusters = this._childClusters,
zoom = this._zoom,
i, c;
if (zoomLevelToStart > zoom) { //Still going down to required depth, just recurse to child clusters
for (i = childClusters.length - 1; i >= 0; i--) {
c = childClusters[i];
if (boundsToApplyTo.intersects(c._bounds)) {
c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
}
}
} else { //In required depth
if (runAtEveryLevel) {
runAtEveryLevel(this);
}
if (runAtBottomLevel && this._zoom === zoomLevelToStop) {
runAtBottomLevel(this);
}
//TODO: This loop is almost the same as above
if (zoomLevelToStop > zoom) {
for (i = childClusters.length - 1; i >= 0; i--) {
c = childClusters[i];
if (boundsToApplyTo.intersects(c._bounds)) {
c._recursively(boundsToApplyTo, zoomLevelToStart, zoomLevelToStop, runAtEveryLevel, runAtBottomLevel);
}
}
}
}
},
_recalculateBounds: function () {
var markers = this._markers,
childClusters = this._childClusters,
i;
this._bounds = new L.LatLngBounds();
delete this._wLatLng;
for (i = markers.length - 1; i >= 0; i--) {
this._expandBounds(markers[i]);
}
for (i = childClusters.length - 1; i >= 0; i--) {
this._expandBounds(childClusters[i]);
}
},
//Returns true if we are the parent of only one cluster and that cluster is the same as us
_isSingleParent: function () {
//Don't need to check this._markers as the rest won't work if there are any
return this._childClusters.length > 0 && this._childClusters[0]._childCount === this._childCount;
}
});
L.DistanceGrid = function (cellSize) {
this._cellSize = cellSize;
this._sqCellSize = cellSize * cellSize;
this._grid = {};
this._objectPoint = { };
};
L.DistanceGrid.prototype = {
addObject: function (obj, point) {
var x = this._getCoord(point.x),
y = this._getCoord(point.y),
grid = this._grid,
row = grid[y] = grid[y] || {},
cell = row[x] = row[x] || [],
stamp = L.Util.stamp(obj);
this._objectPoint[stamp] = point;
cell.push(obj);
},
updateObject: function (obj, point) {
this.removeObject(obj);
this.addObject(obj, point);
},
//Returns true if the object was found
removeObject: function (obj, point) {
var x = this._getCoord(point.x),
y = this._getCoord(point.y),
grid = this._grid,
row = grid[y] = grid[y] || {},
cell = row[x] = row[x] || [],
i, len;
delete this._objectPoint[L.Util.stamp(obj)];
for (i = 0, len = cell.length; i < len; i++) {
if (cell[i] === obj) {
cell.splice(i, 1);
if (len === 1) {
delete row[x];
}
return true;
}
}
},
eachObject: function (fn, context) {
var i, j, k, len, row, cell, removed,
grid = this._grid;
for (i in grid) {
row = grid[i];
for (j in row) {
cell = row[j];
for (k = 0, len = cell.length; k < len; k++) {
removed = fn.call(context, cell[k]);
if (removed) {
k--;
len--;
}
}
}
}
},
getNearObject: function (point) {
var x = this._getCoord(point.x),
y = this._getCoord(point.y),
i, j, k, row, cell, len, obj, dist,
objectPoint = this._objectPoint,
closestDistSq = this._sqCellSize,
closest = null;
for (i = y - 1; i <= y + 1; i++) {
row = this._grid[i];
if (row) {
for (j = x - 1; j <= x + 1; j++) {
cell = row[j];
if (cell) {
for (k = 0, len = cell.length; k < len; k++) {
obj = cell[k];
dist = this._sqDist(objectPoint[L.Util.stamp(obj)], point);
if (dist < closestDistSq) {
closestDistSq = dist;
closest = obj;
}
}
}
}
}
}
return closest;
},
_getCoord: function (x) {
return Math.floor(x / this._cellSize);
},
_sqDist: function (p, p2) {
var dx = p2.x - p.x,
dy = p2.y - p.y;
return dx * dx + dy * dy;
}
};
/* Copyright (c) 2012 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Quickhull_(Javascript)?action=history&offset=20120410175256
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.
Retrieved from: http://en.literateprograms.org/Quickhull_(Javascript)?oldid=18434
*/
(function () {
L.QuickHull = {
getDistant: function (cpt, bl) {
var vY = bl[1].lat - bl[0].lat,
vX = bl[0].lng - bl[1].lng;
return (vX * (cpt.lat - bl[0].lat) + vY * (cpt.lng - bl[0].lng));
},
findMostDistantPointFromBaseLine: function (baseLine, latLngs) {
var maxD = 0,
maxPt = null,
newPoints = [],
i, pt, d;
for (i = latLngs.length - 1; i >= 0; i--) {
pt = latLngs[i];
d = this.getDistant(pt, baseLine);
if (d > 0) {
newPoints.push(pt);
} else {
continue;
}
if (d > maxD) {
maxD = d;
maxPt = pt;
}
}
return { 'maxPoint': maxPt, 'newPoints': newPoints };
},
buildConvexHull: function (baseLine, latLngs) {
var convexHullBaseLines = [],
t = this.findMostDistantPointFromBaseLine(baseLine, latLngs);
if (t.maxPoint) { // if there is still a point "outside" the base line
convexHullBaseLines =
convexHullBaseLines.concat(
this.buildConvexHull([baseLine[0], t.maxPoint], t.newPoints)
);
convexHullBaseLines =
convexHullBaseLines.concat(
this.buildConvexHull([t.maxPoint, baseLine[1]], t.newPoints)
);
return convexHullBaseLines;
} else { // if there is no more point "outside" the base line, the current base line is part of the convex hull
return [baseLine];
}
},
getConvexHull: function (latLngs) {
//find first baseline
var maxLat = false, minLat = false,
maxPt = null, minPt = null,
i;
for (i = latLngs.length - 1; i >= 0; i--) {
var pt = latLngs[i];
if (maxLat === false || pt.lat > maxLat) {
maxPt = pt;
maxLat = pt.lat;
}
if (minLat === false || pt.lat < minLat) {
minPt = pt;
minLat = pt.lat;
}
}
var ch = [].concat(this.buildConvexHull([minPt, maxPt], latLngs),
this.buildConvexHull([maxPt, minPt], latLngs));
return ch;
}
};
}());
L.MarkerCluster.include({
getConvexHull: function () {
var childMarkers = this.getAllChildMarkers(),
points = [],
hullLatLng = [],
hull, p, i;
for (i = childMarkers.length - 1; i >= 0; i--) {
p = childMarkers[i].getLatLng();
points.push(p);
}
hull = L.QuickHull.getConvexHull(points);
for (i = hull.length - 1; i >= 0; i--) {
hullLatLng.push(hull[i][0]);
}
return hullLatLng;
}
});
//This code is 100% based on https://github.com/jawj/OverlappingMarkerSpiderfier-Leaflet
//Huge thanks to jawj for implementing it first to make my job easy :-)
L.MarkerCluster.include({
_2PI: Math.PI * 2,
_circleFootSeparation: 25, //related to circumference of circle
_circleStartAngle: Math.PI / 6,
_spiralFootSeparation: 28, //related to size of spiral (experiment!)
_spiralLengthStart: 11,
_spiralLengthFactor: 5,
_circleSpiralSwitchover: 9, //show spiral instead of circle from this marker count upwards.
// 0 -> always spiral; Infinity -> always circle
spiderfy: function () {
if (this._group._spiderfied === this || this._group._inZoomAnimation) {
return;
}
var childMarkers = this.getAllChildMarkers(),
group = this._group,
map = group._map,
center = map.latLngToLayerPoint(this._latlng),
positions;
this._group._unspiderfy();
this._group._spiderfied = this;
//TODO Maybe: childMarkers order by distance to center
if (childMarkers.length >= this._circleSpiralSwitchover) {
positions = this._generatePointsSpiral(childMarkers.length, center);
} else {
center.y += 10; //Otherwise circles look wrong
positions = this._generatePointsCircle(childMarkers.length, center);
}
this._animationSpiderfy(childMarkers, positions);
},
unspiderfy: function (zoomDetails) {
/// <param Name="zoomDetails">Argument from zoomanim if being called in a zoom animation or null otherwise</param>
if (this._group._inZoomAnimation) {
return;
}
this._animationUnspiderfy(zoomDetails);
this._group._spiderfied = null;
},
_generatePointsCircle: function (count, centerPt) {
var circumference = this._group.options.spiderfyDistanceMultiplier * this._circleFootSeparation * (2 + count),
legLength = circumference / this._2PI, //radius from circumference
angleStep = this._2PI / count,
res = [],
i, angle;
res.length = count;
for (i = count - 1; i >= 0; i--) {
angle = this._circleStartAngle + i * angleStep;
res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
}
return res;
},
_generatePointsSpiral: function (count, centerPt) {
var legLength = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthStart,
separation = this._group.options.spiderfyDistanceMultiplier * this._spiralFootSeparation,
lengthFactor = this._group.options.spiderfyDistanceMultiplier * this._spiralLengthFactor,
angle = 0,
res = [],
i;
res.length = count;
for (i = count - 1; i >= 0; i--) {
angle += separation / legLength + i * 0.0005;
res[i] = new L.Point(centerPt.x + legLength * Math.cos(angle), centerPt.y + legLength * Math.sin(angle))._round();
legLength += this._2PI * lengthFactor / angle;
}
return res;
},
_noanimationUnspiderfy: function () {
var group = this._group,
map = group._map,
fg = group._featureGroup,
childMarkers = this.getAllChildMarkers(),
m, i;
this.setOpacity(1);
for (i = childMarkers.length - 1; i >= 0; i--) {
m = childMarkers[i];
fg.removeLayer(m);
if (m._preSpiderfyLatlng) {
m.setLatLng(m._preSpiderfyLatlng);
delete m._preSpiderfyLatlng;
}
if (m.setZIndexOffset) {
m.setZIndexOffset(0);
}
if (m._spiderLeg) {
map.removeLayer(m._spiderLeg);
delete m._spiderLeg;
}
}
}
});
L.MarkerCluster.include(!L.DomUtil.TRANSITION ? {
//Non Animated versions of everything
_animationSpiderfy: function (childMarkers, positions) {
var group = this._group,
map = group._map,
fg = group._featureGroup,
i, m, leg, newPos;
for (i = childMarkers.length - 1; i >= 0; i--) {
newPos = map.layerPointToLatLng(positions[i]);
m = childMarkers[i];
m._preSpiderfyLatlng = m._latlng;
m.setLatLng(newPos);
if (m.setZIndexOffset) {
m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
}
fg.addLayer(m);
leg = new L.Polyline([this._latlng, newPos], { weight: 1.5, color: '#222' });
map.addLayer(leg);
m._spiderLeg = leg;
}
this.setOpacity(0.3);
group.fire('spiderfied');
},
_animationUnspiderfy: function () {
this._noanimationUnspiderfy();
}
} : {
//Animated versions here
SVG_ANIMATION: (function () {
return document.createElementNS('http://www.w3.org/2000/svg', 'animate').toString().indexOf('SVGAnimate') > -1;
}()),
_animationSpiderfy: function (childMarkers, positions) {
var me = this,
group = this._group,
map = group._map,
fg = group._featureGroup,
thisLayerPos = map.latLngToLayerPoint(this._latlng),
i, m, leg, newPos;
//Add markers to map hidden at our center point
for (i = childMarkers.length - 1; i >= 0; i--) {
m = childMarkers[i];
//If it is a marker, add it now and we'll animate it out
if (m.setOpacity) {
m.setZIndexOffset(1000000); //Make these appear on top of EVERYTHING
m.setOpacity(0);
fg.addLayer(m);
m._setPos(thisLayerPos);
} else {
//Vectors just get immediately added
fg.addLayer(m);
}
}
group._forceLayout();
group._animationStart();
var initialLegOpacity = L.Path.SVG ? 0 : 0.3,
xmlns = L.Path.SVG_NS;
for (i = childMarkers.length - 1; i >= 0; i--) {
newPos = map.layerPointToLatLng(positions[i]);
m = childMarkers[i];
//Move marker to new position
m._preSpiderfyLatlng = m._latlng;
m.setLatLng(newPos);
if (m.setOpacity) {
m.setOpacity(1);
}
//Add Legs.
leg = new L.Polyline([me._latlng, newPos], { weight: 1.5, color: '#222', opacity: initialLegOpacity });
map.addLayer(leg);
m._spiderLeg = leg;
//Following animations don't work for canvas
if (!L.Path.SVG || !this.SVG_ANIMATION) {
continue;
}
//How this works:
//http://stackoverflow.com/questions/5924238/how-do-you-animate-an-svg-path-in-ios
//http://dev.opera.com/articles/view/advanced-svg-animation-techniques/
//Animate length
var length = leg._path.getTotalLength();
leg._path.setAttribute("stroke-dasharray", length + "," + length);
var anim = document.createElementNS(xmlns, "animate");
anim.setAttribute("attributeName", "stroke-dashoffset");
anim.setAttribute("begin", "indefinite");
anim.setAttribute("from", length);
anim.setAttribute("to", 0);
anim.setAttribute("dur", 0.25);
leg._path.appendChild(anim);
anim.beginElement();
//Animate opacity
anim = document.createElementNS(xmlns, "animate");
anim.setAttribute("attributeName", "stroke-opacity");
anim.setAttribute("attributeName", "stroke-opacity");
anim.setAttribute("begin", "indefinite");
anim.setAttribute("from", 0);
anim.setAttribute("to", 0.5);
anim.setAttribute("dur", 0.25);
leg._path.appendChild(anim);
anim.beginElement();
}
me.setOpacity(0.3);
//Set the opacity of the spiderLegs back to their correct value
// The animations above override this until they complete.
// If the initial opacity of the spiderlegs isn't 0 then they appear before the animation starts.
if (L.Path.SVG) {
this._group._forceLayout();
for (i = childMarkers.length - 1; i >= 0; i--) {
m = childMarkers[i]._spiderLeg;
m.options.opacity = 0.5;
m._path.setAttribute('stroke-opacity', 0.5);
}
}
setTimeout(function () {
group._animationEnd();
group.fire('spiderfied');
}, 200);
},
_animationUnspiderfy: function (zoomDetails) {
var group = this._group,
map = group._map,
fg = group._featureGroup,
thisLayerPos = zoomDetails ? map._latLngToNewLayerPoint(this._latlng, zoomDetails.zoom, zoomDetails.center) : map.latLngToLayerPoint(this._latlng),
childMarkers = this.getAllChildMarkers(),
svg = L.Path.SVG && this.SVG_ANIMATION,
m, i, a;
group._animationStart();
//Make us visible and bring the child markers back in
this.setOpacity(1);
for (i = childMarkers.length - 1; i >= 0; i--) {
m = childMarkers[i];
//Marker was added to us after we were spidified
if (!m._preSpiderfyLatlng) {
continue;
}
//Fix up the location to the real one
m.setLatLng(m._preSpiderfyLatlng);
delete m._preSpiderfyLatlng;
//Hack override the location to be our center
if (m.setOpacity) {
m._setPos(thisLayerPos);
m.setOpacity(0);
} else {
fg.removeLayer(m);
}
//Animate the spider legs back in
if (svg) {
a = m._spiderLeg._path.childNodes[0];
a.setAttribute('to', a.getAttribute('from'));
a.setAttribute('from', 0);
a.beginElement();
a = m._spiderLeg._path.childNodes[1];
a.setAttribute('from', 0.5);
a.setAttribute('to', 0);
a.setAttribute('stroke-opacity', 0);
a.beginElement();
m._spiderLeg._path.setAttribute('stroke-opacity', 0);
}
}
setTimeout(function () {
//If we have only <= one child left then that marker will be shown on the map so don't remove it!
var stillThereChildCount = 0;
for (i = childMarkers.length - 1; i >= 0; i--) {
m = childMarkers[i];
if (m._spiderLeg) {
stillThereChildCount++;
}
}
for (i = childMarkers.length - 1; i >= 0; i--) {
m = childMarkers[i];
if (!m._spiderLeg) { //Has already been unspiderfied
continue;
}
if (m.setOpacity) {
m.setOpacity(1);
m.setZIndexOffset(0);
}
if (stillThereChildCount > 1) {
fg.removeLayer(m);
}
map.removeLayer(m._spiderLeg);
delete m._spiderLeg;
}
group._animationEnd();
}, 200);
}
});
L.MarkerClusterGroup.include({
//The MarkerCluster currently spiderfied (if any)
_spiderfied: null,
_spiderfierOnAdd: function () {
this._map.on('click', this._unspiderfyWrapper, this);
if (this._map.options.zoomAnimation) {
this._map.on('zoomstart', this._unspiderfyZoomStart, this);
} else {
//Browsers without zoomAnimation don't fire zoomstart
this._map.on('zoomend', this._unspiderfyWrapper, this);
}
if (L.Path.SVG && !L.Browser.touch) {
this._map._initPathRoot();
//Needs to happen in the pageload, not after, or animations don't work in webkit
// http://stackoverflow.com/questions/8455200/svg-animate-with-dynamically-added-elements
//Disable on touch browsers as the animation messes up on a touch zoom and isn't very noticable
}
},
_spiderfierOnRemove: function () {
this._map.off('click', this._unspiderfyWrapper, this);
this._map.off('zoomstart', this._unspiderfyZoomStart, this);
this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
this._unspiderfy(); //Ensure that markers are back where they should be
},
//On zoom start we add a zoomanim handler so that we are guaranteed to be last (after markers are animated)
//This means we can define the animation they do rather than Markers doing an animation to their actual location
_unspiderfyZoomStart: function () {
if (!this._map) { //May have been removed from the map by a zoomEnd handler
return;
}
this._map.on('zoomanim', this._unspiderfyZoomAnim, this);
},
_unspiderfyZoomAnim: function (zoomDetails) {
//Wait until the first zoomanim after the user has finished touch-zooming before running the animation
if (L.DomUtil.hasClass(this._map._mapPane, 'leaflet-touching')) {
return;
}
this._map.off('zoomanim', this._unspiderfyZoomAnim, this);
this._unspiderfy(zoomDetails);
},
_unspiderfyWrapper: function () {
/// <summary>_unspiderfy but passes no arguments</summary>
this._unspiderfy();
},
_unspiderfy: function (zoomDetails) {
if (this._spiderfied) {
this._spiderfied.unspiderfy(zoomDetails);
}
},
_noanimationUnspiderfy: function () {
if (this._spiderfied) {
this._spiderfied._noanimationUnspiderfy();
}
},
//If the given layer is currently being spiderfied then we unspiderfy it so it isn't on the map anymore etc
_unspiderfyLayer: function (layer) {
if (layer._spiderLeg) {
this._featureGroup.removeLayer(layer);
layer.setOpacity(1);
//Position will be fixed up immediately in _animationUnspiderfy
layer.setZIndexOffset(0);
this._map.removeLayer(layer._spiderLeg);
delete layer._spiderLeg;
}
}
});
}(window, document));
| agpl-3.0 |
24eme/AVA | project/plugins/acVinTiragePlugin/lib/model/Tirage/Tirage.class.php | 9101 | <?php
/**
* Model for Tirage
*
*/
class Tirage extends BaseTirage implements InterfaceDeclarantDocument, InterfaceDeclaration, InterfacePieceDocument {
protected $declarant_document;
protected $piece_document = null;
public function __construct() {
parent::__construct();
$this->initDocuments();
}
public function __clone() {
parent::__clone();
$this->initDocuments();
}
protected function initDocuments() {
$this->declarant_document = new DeclarantDocument($this);
$this->piece_document = new PieceDocument($this);
}
public function constructId() {
$this->set('_id', 'TIRAGE-' . $this->identifiant . '-' . $this->campagne . $this->numero);
}
public function initDoc($identifiant, $campagne, $numero) {
$this->identifiant = $identifiant;
$this->campagne = $campagne;
$this->numero = $numero;
$this->updateCepages();
$this->getQualite();
}
public function storeDRFromDRev() {
$drev = $this->getDRev();
if(!$drev) {
return false;
}
if($drev->isAutomatique()) {
return false;
}
if(!$drev->hasDR()) {
return false;
}
$drContent = file_get_contents($drev->getAttachmentUri('DR.pdf'));
if(!$drContent) {
return false;
}
return $this->storeAsAttachment($drContent, "DR.pdf", "application/pdf");
}
public function hasDR() {
return $this->_attachments->exist('DR.pdf');
}
public function hasSV() {
return (($this->documents->exist(TirageDocuments::DOC_SV11)
&& ($this->documents->get(TirageDocuments::DOC_SV11)->statut) == TirageDocuments::STATUT_RECU)
||
($this->documents->exist(TirageDocuments::DOC_SV12)
&& ($this->documents->get(TirageDocuments::DOC_SV12)->statut) == TirageDocuments::STATUT_RECU)
);
}
public function getDRev() {
return DRevClient::getInstance()->find("DREV-".$this->identifiant."-".$this->campagne);
}
public function storeDeclarant() {
$this->declarant_document->storeDeclarant();
}
public function storeEtape($etape) {
$this->add('etape', $etape);
}
public function getConfiguration() {
return acCouchdbManager::getClient('Configuration')->retrieveConfiguration($this->campagne);
}
public function getConfigurationCepages() {
return $this->getConfiguration()->declaration->get('certification/genre/appellation_CREMANT/mention/lieu/couleur')->getProduitsFilter(_ConfigurationDeclaration::TYPE_DECLARATION_TIRAGE);
}
public function getEtablissementObject() {
return EtablissementClient::getInstance()->findByIdentifiant($this->identifiant);
}
public function validate($date = null) {
if(is_null($date)) {
$date = date('Y-m-d');
}
$this->validation = $date;
}
public function hasCompleteDocuments()
{
$complete = true;
foreach($this->getOrAdd('documents') as $document) {
if ($document->statut != DRevDocuments::STATUT_RECU) {
$complete = false;
break;
}
}
return $complete;
}
public function isValide() {
return $this->exist('validation') && $this->validation;
}
public function isPapier() {
return $this->exist('papier') && $this->get('papier');
}
public function isLectureSeule() {
return $this->exist('lecture_seule') && $this->get('lecture_seule');
}
public function isAutomatique() {
return $this->exist('automatique') && $this->get('automatique');
}
public function getValidation() {
return $this->_get('validation');
}
public function getValidationOdg() {
return $this->_get('validation_odg');
}
public function validateOdg() {
$this->validation_odg = date('Y-m-d');
}
public function updateCepages() {
$cepages = array();
foreach($this->getConfigurationCepages() as $cepage) {
$cepages[$cepage->getKey()] = $cepage->getLibelle();
}
sort($cepages);
foreach ($cepages as $keyCep => $libelle) {
$this->cepages->add($keyCep)->libelle = $libelle;
}
}
public function getDateMiseEnBouteilleDebutObject() {
if (!$this->date_mise_en_bouteille_debut) {
return null;
}
return new DateTime($this->date_mise_en_bouteille_debut);
}
public function getDateMiseEnBouteilleDebutFr() {
$date = $this->getDateMiseEnBouteilleDebutObject();
if (!$date) {
return null;
}
return $date->format('d/m/Y');
}
public function getDateMiseEnBouteilleFinObject() {
if (!$this->date_mise_en_bouteille_fin) {
return null;
}
return new DateTime($this->date_mise_en_bouteille_fin);
}
public function getDateMiseEnBouteilleFinFr() {
$date = $this->getDateMiseEnBouteilleFinObject();
if (!$date) {
return null;
}
return $date->format('d/m/Y');
}
public function isMillesimeAnnee() {
return preg_match("/^[0-9]{4}$/", $this->getMillesime());
}
public function setNumero($numero) {
return $this->_set('numero', sprintf("%02d", $numero));
}
public function isNegociant() {
$etblmt = $this->getEtablissementObject();
return ($etblmt->familles->exist('NEGOCIANT') && $etblmt->familles->get('NEGOCIANT'));
}
public function isCaveCooperative() {
$etblmt = $this->getEtablissementObject();
return ($etblmt->familles->exist('CAVE_COOPERATIVE') && $etblmt->familles->get('CAVE_COOPERATIVE'));
}
public function isViticulteur() {
return !($this>isNegociant()) && !($this->isCaveCooperative());
}
public function getQualite() {
$q = $this->_get('qualite');
if ($q) {
return $q;
}
$q = "Viticulteur-Manipulant total ou partiel";
if ($this->isCaveCooperative()) {
$q = "Cave coopérative";
}else if ($this->isNegociant()) {
$q = "Négociant";
}
$this->_set('qualite', $q);
return $q;
}
public function cleanDoc() {
$tobedeleted = array();
foreach ($this->composition as $k => $v) {
if (!$v->nombre) {
$tobedeleted[] = $k;
}
}
foreach($tobedeleted as $k) {
$this->composition->remove($k);
}
}
public function getCepagesSelectionnes() {
$cepagesSelectionnes = array();
foreach ($this->cepages as $cepageKey => $cepage) {
if($cepage->selectionne){
$cepagesSelectionnes[$cepageKey] = $cepage;
}
}
return $cepagesSelectionnes;
}
public function getVolumeTotalComposition() {
$sommeTotal = 0;
$contenances = sfConfig::get('app_contenances_bouteilles');
foreach ($this->composition as $compo){
$hectolitre = $contenances[$compo->contenance] / 10000;
$sommeTotal+=$compo->nombre * $hectolitre;
}
return $sommeTotal;
}
protected function doSave() {
$this->piece_document->generatePieces();
}
/**** PIECES ****/
public function getAllPieces() {
if ($this->date_mise_en_bouteille_fin) {
$date = new DateTime($this->date_mise_en_bouteille_fin);
$complement = $date->format('d/m/Y').' ';
} else {
$complement = '';
}
$complement .= ($this->isPapier())? '(Papier)' : '(Télédéclaration)';
return (!$this->getValidation())? array() : array(array(
'identifiant' => $this->getIdentifiant(),
'date_depot' => $this->getValidation(),
'libelle' => 'Déclaration de tirage Crémant '.$this->couleur_libelle.' '.$this->campagne.' - embouteillage jusqu\'au '.$complement,
'mime' => Piece::MIME_PDF,
'visibilite' => 1,
'source' => null
));
}
public function generatePieces() {
return $this->piece_document->generatePieces();
}
public function generateUrlPiece($source = null) {
return sfContext::getInstance()->getRouting()->generate('tirage_export_pdf', $this);
}
public static function getUrlVisualisationPiece($id, $admin = false) {
return sfContext::getInstance()->getRouting()->generate('tirage_visualisation', array('id' => $id));
}
public static function getUrlGenerationCsvPiece($id, $admin = false) {
return null;
}
public static function isVisualisationMasterUrl($admin = false) {
return true;
}
public static function isPieceEditable($admin = false) {
return false;
}
/**** FIN DES PIECES ****/
public function getCampagneDR() {
return preg_match('/^[0-9]+$/', $this->millesime) ? $this->millesime : $this->campagne;
}
}
| agpl-3.0 |
maestrano/processmaker | workflow/engine/methods/cases/debug_triggers.php | 2378 | <?php
if (isset( $_SESSION['TRIGGER_DEBUG']['info'] )) {
$aTriggers = $_SESSION['TRIGGER_DEBUG']['info'];
} else {
$aTriggers[0] = $_SESSION['TRIGGER_DEBUG'];
}
//print_r($aTriggers);die;
$triggersList = Array ();
$i = 0;
foreach ($aTriggers as $aTrigger) {
if ($aTrigger['NUM_TRIGGERS'] != 0) {
foreach ($aTrigger['TRIGGERS_NAMES'] as $index => $name) {
$triggersList[$i]['name'] = $name;
$triggersList[$i]['execution_time'] = strtolower( $aTrigger['TIME'] );
//$t_code = $aTrigger['TRIGGERS_VALUES'][$index]['TRI_WEBBOT'];
//$t_code = str_replace('"', '\'',$t_code);
//$t_code = addslashes($t_code);
//$t_code = Only1br($t_code);
//highlighting the trigger code using the geshi third party library
G::LoadThirdParty( 'geshi', 'geshi' );
$geshi = new GeSHi( $aTrigger['TRIGGERS_VALUES'][$index]['TRI_WEBBOT'], 'php' );
$geshi->enable_line_numbers( GESHI_FANCY_LINE_NUMBERS, 2 );
$geshi->set_line_style( 'background: #f0f0f0;' );
$triggersList[$i]['code'] = $geshi->parse_code(); //$aTrigger['TRIGGERS_VALUES'][$index]['TRI_WEBBOT'];
$i ++;
}
} else {
}
}
//print_r($_SESSION['TRIGGER_DEBUG']['ERRORS']); die;
$DEBUG_ERRORS = array_unique( $_SESSION['TRIGGER_DEBUG']['ERRORS'] );
foreach ($DEBUG_ERRORS as $error) {
if (isset( $error['ERROR'] ) and $error['ERROR'] != '') {
$triggersList[$i]['name'] = 'Error';
$triggersList[$i]['execution_time'] = 'error';
$triggersList[$i]['code'] = $error['ERROR'];
$i ++;
}
if (isset( $error['FATAL'] ) and $error['FATAL'] != '') {
$error['FATAL'] = str_replace( "<br />", "\n", $error['FATAL'] );
$tmp = explode( "\n", $error['FATAL'] );
$triggersList[$i]['name'] = isset( $tmp[0] ) ? $tmp[0] : 'Fatal Error in trigger';
$triggersList[$i]['execution_time'] = 'Fatal error';
$triggersList[$i]['code'] = $error['FATAL'];
$i ++;
}
}
/*echo '{total:5, data:[
{name:"trigger1", execution_time:"after"},
{name:"trigger2", execution_time:"before"},
{name:"trigger13", execution_time:"before"},
]}';
*/
$triggersRet->total = count( $triggersList );
$triggersRet->data = $triggersList;
echo G::json_encode( $triggersRet );
| agpl-3.0 |
mwwscott0/WoWAnalyzer | src/Parser/HolyPaladin/Modules/PaladinCore/BeaconHealOriginMatcher.js | 8527 | import SPELLS from 'common/SPELLS';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import BeaconTargets from './BeaconTargets';
import { BEACON_TRANSFERING_ABILITIES, BEACON_TYPES } from '../../Constants';
import LightOfDawn from './LightOfDawn';
const debug = false;
class BeaconHealOriginMatcher extends Module {
static dependencies = {
combatants: Combatants,
beaconTargets: BeaconTargets,
lightOfDawn: LightOfDawn,
};
on_byPlayer_heal(event) {
this.processForBeaconHealing(event);
}
healBacklog = [];
processForBeaconHealing(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.BEACON_OF_LIGHT.id) {
this.processBeaconHealing(event);
return;
}
const spellBeaconTransferFactor = BEACON_TRANSFERING_ABILITIES[spellId];
if (!spellBeaconTransferFactor) {
return;
}
const beaconTargets = this.beaconTargets;
let remainingBeaconTransfers = beaconTargets.numBeaconsActive;
if (beaconTargets.hasBeacon(event.targetID)) {
remainingBeaconTransfers -= 1;
debug && console.log(`${this.combatants.players[event.targetID].name} has beacon, remaining beacon transfers reduced by 1 and is now ${remainingBeaconTransfers}`);
}
if (remainingBeaconTransfers > 0) {
this.healBacklog.push({
...event,
spellBeaconTransferFactor,
remainingBeaconTransfers,
});
}
}
processBeaconHealing(beaconTransferEvent) {
// This should make it near impossible to match the wrong spells as we usually don't cast multiple heals within 500ms while the beacon transfer usually happens within 100ms
this.healBacklog = this.healBacklog.filter(healEvent => (this.owner.currentTimestamp - healEvent.timestamp) < 500);
if (debug) {
this.sanityChecker(beaconTransferEvent);
}
const matchedHeal = this.healBacklog[0];
if (!matchedHeal) {
console.error('No heal found for beacon transfer:', beaconTransferEvent);
return;
}
// console.log('Matched beacon transfer', beaconTransferEvent, 'to heal', matchedHeal);
this.owner.triggerEvent('beacon_heal', beaconTransferEvent, matchedHeal);
matchedHeal.remainingBeaconTransfers -= 1;
if (matchedHeal.remainingBeaconTransfers < 1) {
this.healBacklog.splice(0, 1);
}
}
get beaconType() {
return this.combatants.selected.lv100Talent;
}
/**
* Verify that the beacon transfer matches what we would expect. This isn't 100% reliable due to weird interactions with stuff like Blood Death Knights (Vampiric Blood and probably other things), and other healing received increasers.
*/
sanityChecker(beaconTransferEvent) {
const beaconTransferAmount = beaconTransferEvent.amount;
const beaconTransferAbsorbed = beaconTransferEvent.absorbed || 0;
const beaconTransferOverheal = beaconTransferEvent.overheal || 0;
const beaconTransferRaw = beaconTransferAmount + beaconTransferAbsorbed + beaconTransferOverheal;
const index = this.healBacklog.findIndex((healEvent) => {
const expectedBeaconTransfer = this.getExpectedBeaconTransfer(healEvent, beaconTransferEvent);
return Math.abs(expectedBeaconTransfer - beaconTransferRaw) <= 2; // allow for rounding errors on Blizzard's end
});
if (index === -1) {
// Here's a fun fact for you. Fury Warriors with the legendary "Kazzalax, Fujieda's Fury" (http://www.wowhead.com/item=137053/kazzalax-fujiedas-fury)
// get a 8% healing received increase for almost the entire fight (tooltip states it's 1%, this is a tooltip bug). What's messed up
// is that this healing increase doesn't beacon transfer. So we won't be able to recognize the heal in here since it's off by 8%, so
// this will be triggered. While I could implement code to track it, I chose not to because things would get way more complicated and
// fragile and the accuracy loss for not including this kind of healing is minimal. I expect other healing received increases likely
// also don't beacon transfer, but right now this isn't common. Fury warrior log:
// https://www.warcraftlogs.com/reports/TLQ14HfhjRvNrV2y/#view=events&type=healing&source=10&start=7614145&end=7615174&fight=39
console.error('Failed to match', beaconTransferEvent, 'to a heal. Healing backlog:', this.healBacklog, '-', (beaconTransferEvent.timestamp - this.owner.fight.start_time) / 1000, 'seconds into the fight');
this.healBacklog.forEach((healEvent, i) => {
const expectedBeaconTransfer = this.getExpectedBeaconTransfer(healEvent, beaconTransferEvent);
console.log(i, {
ability: healEvent.ability.name,
healEvent,
raw: healEvent.amount + (healEvent.absorbed || 0) + (healEvent.overheal || 0),
expectedBeaconTransfer,
actual: beaconTransferRaw,
difference: Math.abs(expectedBeaconTransfer - beaconTransferRaw),
beaconTransferFactor: this.getBeaconTransferFactor(healEvent),
spellBeaconTransferFactor: healEvent.spellBeaconTransferFactor,
});
});
} else if (index !== 0) {
const matchedHeal = this.healBacklog[index];
if (index !== 0) {
console.warn('Matched', beaconTransferEvent, 'to', matchedHeal, 'but it wasn\'t the first heal in the Backlog. Something is likely wrong.', this.healBacklog);
}
this.healBacklog.forEach((healEvent, i) => {
const expectedBeaconTransfer = this.getExpectedBeaconTransfer(healEvent, beaconTransferEvent);
console.log(i, {
ability: healEvent.ability.name,
healEvent,
raw: healEvent.amount + (healEvent.absorbed || 0) + (healEvent.overheal || 0),
expectedBeaconTransfer,
actual: beaconTransferRaw,
difference: Math.abs(expectedBeaconTransfer - beaconTransferRaw),
beaconTransferFactor: this.getBeaconTransferFactor(healEvent),
spellBeaconTransferFactor: healEvent.spellBeaconTransferFactor,
});
});
}
}
getBeaconTransferFactor(healEvent) {
let beaconFactor = 0.4;
// Light's Embrace (4PT2)
// What happens here are 2 situations:
// - Light of Dawn applies Light's Embrace, it acts a bit weird though since the FIRST heal from the cast does NOT get the increased beacon transfer, while all sebsequent heals do (even when the combatlog has't fired the Light's Embrace applybuff event yet). The first part checks for that. The combatlog looks different when the first heal is a self heal vs they're all on other people, but in both cases it always doesn't apply to the first LoD heal and does for all subsequent ones.
// - If a FoL or something else is cast right before the LoD, the beacon transfer may be delayed until after the Light's Embrace is applied. This beacon transfer does not appear to benefit. My hypothesis is that the server does healing and buffs async and there's a small lag between the processes, and I think 50ms should be about the time required.
const hasLightsEmbrace = (healEvent.ability.guid === SPELLS.LIGHT_OF_DAWN_HEAL.id && healEvent.lightOfDawnHealIndex > 0) || this.combatants.selected.hasBuff(SPELLS.LIGHTS_EMBRACE_BUFF.id, null, 0, 100);
if (hasLightsEmbrace) {
beaconFactor += 0.4;
}
if (this.beaconType === BEACON_TYPES.BEACON_OF_FATH) {
beaconFactor *= 0.8;
}
return beaconFactor;
}
getExpectedBeaconTransfer(healEvent, beaconTransferEvent) {
const amount = healEvent.amount;
const absorbed = healEvent.absorbed || 0;
const overheal = healEvent.overheal || 0;
let raw = amount + absorbed + overheal;
const healTargetId = healEvent.targetID;
const healCombatant = this.combatants.players[healTargetId];
if (healCombatant) {
if (healCombatant.hasBuff(SPELLS.PROTECTION_OF_TYR.id, healEvent.timestamp)) {
raw /= 1.15;
}
if (healCombatant.hasBuff(55233, healEvent.timestamp)) {
raw /= 1.3;
}
}
let expectedBeaconTransfer = Math.round(raw * this.getBeaconTransferFactor(healEvent) * healEvent.spellBeaconTransferFactor);
const beaconTargetId = beaconTransferEvent.targetID;
const beaconCombatant = this.combatants.players[beaconTargetId];
if (beaconCombatant) {
if (beaconCombatant.hasBuff(55233, healEvent.timestamp)) {
expectedBeaconTransfer *= 1.3;
}
}
return expectedBeaconTransfer;
}
}
export default BeaconHealOriginMatcher;
| agpl-3.0 |
PUMNL/nl.pum.expenseclaims | api/v3/ClaimLineLog/Get.php | 3724 | <?php
/**
* ClaimLineLog.Get API specification (optional)
* This is used for documentation and validation.
*
* @param array $spec description of fields supported by this API call
* @return void
* @see http://wiki.civicrm.org/confluence/display/CRM/API+Architecture+Standards
*/
function _civicrm_api3_claim_line_log_get_spec(&$spec) {
$spec['id'] = array(
'name' => 'id',
'title' => 'id',
'type' => CRM_Utils_Type::T_INT
);
$spec['claim_line_id'] = array(
'name' => 'claim_line_id',
'title' => 'claim_line_id',
'type' => CRM_Utils_Type::T_INT,
);
$spec['changed_by_id'] = array(
'name' => 'changed_by_id',
'title' => 'changed_by_id',
'type' => CRM_Utils_Type::T_INT,
);
$spec['changed_date'] = array(
'name' => 'changed_date',
'title' => 'changed_date',
'type' => CRM_Utils_Type::T_DATE
);
$spec['change_reason'] = array(
'name' => 'change_reason',
'title' => 'change_reason',
'type' => CRM_Utils_Type::T_STRING,
);
$spec['old_expense_date'] = array(
'name' => 'old_expense_date',
'title' => 'old_expense_date',
'type' => CRM_Utils_Type::T_DATE,
);
$spec['new_expense_date'] = array(
'name' => 'new_expense_date',
'title' => 'new_expense_date',
'type' => CRM_Utils_Type::T_DATE,
);
$spec['old_currency_id'] = array(
'name' => 'old_currency_id',
'title' => 'old_currency_id',
'type' => CRM_Utils_Type::T_INT,
);
$spec['new_currency_id'] = array(
'name' => 'new_currency_id',
'title' => 'new_currency_id',
'type' => CRM_Utils_Type::T_INT,
);
$spec['old_currency_amount'] = array(
'name' => 'old_currency_amount',
'title' => 'old_currency_amount',
'type' => CRM_Utils_Type::T_MONEY
);
$spec['new_currency_amount'] = array(
'name' => 'new_currency_amount',
'title' => 'new_currency_amount',
'type' => CRM_Utils_Type::T_MONEY
);
$spec['old_euro_amount'] = array(
'name' => 'old_euro_amount',
'title' => 'old_euro_amount',
'type' => CRM_Utils_Type::T_MONEY
);
$spec['new_euro_amount'] = array(
'name' => 'new_euro_amount',
'title' => 'new_euro_amount',
'type' => CRM_Utils_Type::T_MONEY
);
}
/**
* ClaimLineLog.Get API
*
* @param array $params
* @return array API result descriptor
* @see civicrm_api3_create_success
* @see civicrm_api3_create_error
* @throws API_Exception
*/
function civicrm_api3_claim_line_log_get($params) {
$result = CRM_Expenseclaims_BAO_ClaimLineLog::getValues($params);
foreach ($result as $resultId => $claimLineLog) {
if (isset($claimLineLog['old_currency_id'])) {
$sql = "SELECT name, full_name FROM civicrm_currency WHERE id = %1";
$currency = CRM_Core_DAO::executeQuery($sql, array(1 => array($claimLineLog['old_currency_id'], 'Integer')));
if ($currency->fetch()) {
$result[$resultId]['old_currency'] = $currency->name . ' (' . $currency->full_name . ')';
}
}
if (isset($claimLineLog['new_currency_id'])) {
$sql = "SELECT name, full_name FROM civicrm_currency WHERE id = %1";
$currency = CRM_Core_DAO::executeQuery($sql, array(1 => array($claimLineLog['new_currency_id'], 'Integer')));
if ($currency->fetch()) {
$result[$resultId]['new_currency'] = $currency->name . ' (' . $currency->full_name . ')';
}
}
if (isset($claimLineLog['changed_by_id'])) {
try {
$result[$resultId]['changed_by'] = civicrm_api3('Contact', 'getvalue', array(
'id' => $claimLineLog['changed_by_id'],
'return' => 'display_name'
));
} catch (CiviCRM_API3_Exception $ex) {}
}
}
return civicrm_api3_create_success($result, $params, 'ClaimLineLog', 'Get');
}
| agpl-3.0 |
ethanlim/MinorityViewport | Algorithms/MinorityViewportAlgo.cpp | 18976 | #include "MinorityViewportAlgo.h"
using namespace std;
namespace MinorityViewport{
MinorityViewportAlgo::MinorityViewportAlgo(Timer *curTime,ClientsList *clients)
:_curTime(curTime),_clients(clients)
{
//Create the global scene
this->_globalScene = new Scene(10,10,10,curTime);
}
MinorityViewportAlgo::~MinorityViewportAlgo(){
this->_mergethread->join();
}
unsigned int MinorityViewportAlgo::RegisterClient(string phyLocation, string ipAddr){
unsigned int clientId = this->_clients->AddClient(phyLocation,ipAddr);
this->ReportStatus("client id assigned - " + std::to_string(clientId));
return clientId;
}
string MinorityViewportAlgo::GetClientListing(){
string clientListing="";
clientListing += "{";
clientListing += "\"clients\":";
clientListing += "[";
for(unsigned int clientIdx=0;clientIdx<this->_clients->Size();clientIdx++){
MinorityViewport::Client *extractedClient = this->_clients->AtIdx(clientIdx);
clientListing += extractedClient->ToJSON();
if(clientIdx!=this->_clients->Size()-1){
clientListing+=",";
}
}
clientListing += "]";
clientListing += "}";
return clientListing;
}
void MinorityViewportAlgo::DeregisterClient(unsigned int clientId){
this->ReportStatus("client id deregistered - " + std::to_string(clientId));
Client *clientToBeRm = this->_clients->At(clientId);
map<string,Sensor*> allSensorsForClient = clientToBeRm->GetSensorsList();
this->_orderedSceneMutex.lock();
for(map<string,Sensor*>::iterator sensorToBeRm=allSensorsForClient.begin();
sensorToBeRm!=allSensorsForClient.end();
sensorToBeRm++){
Scene *scenePtr = sensorToBeRm->second->GetScene();
for(vector<Scene*>::iterator orderedSceneItr = this->_orderedScenes.begin();orderedSceneItr!=this->_orderedScenes.end();){
if(*orderedSceneItr==scenePtr){
orderedSceneItr = this->_orderedScenes.erase(orderedSceneItr);
}else{
++orderedSceneItr;
}
}
for(set<Scene*>::iterator sceneItr = this->_scenesSet.begin();sceneItr!=this->_scenesSet.end();){
if(*sceneItr==scenePtr){
sceneItr = this->_scenesSet.erase(sceneItr);
}else{
++sceneItr;
}
}
}
this->_orderedSceneMutex.unlock();
this->_clients->RemoveClient(clientId);
}
void MinorityViewportAlgo::RegisterSensors(unsigned int clientId,string rawSensorsList){
MinorityViewport::Client *extractedClient = this->_clients->At(clientId);
extractedClient->InitialSensorsList(rawSensorsList);
}
/**
* CalibrateSceneOrder
* Determine the order of scene based on their last skeleton observed time
* @return - true if scenes have been assigned with order
*/
bool MinorityViewportAlgo::CalibrateSceneOrder(){
this->RefreshScenesSet();
this->_orderedSceneMutex.lock();
this->_orderedScenes.clear();
this->_orderedSceneMutex.unlock();
unsigned int numOfCalibratedSceneRequired = this->_scenesSet.size();
unsigned int numOfCalibratedScene = 0;
for(set<Scene*>::const_iterator itr = this->_scenesSet.begin();itr!=this->_scenesSet.end();itr++){
Scene *scenePtr = *itr;
long lastSkeletonObserved = scenePtr->GetFirstSkeletonObservedTime_ms();
if(lastSkeletonObserved>0){
numOfCalibratedScene+=1;
}
}
if(numOfCalibratedScene<numOfCalibratedSceneRequired){
return false;
}
vector<long> sortedTimeStamp;
//Reset all scenes within the set
for(set<Scene*>::const_iterator itr = this->_scenesSet.begin();itr!=this->_scenesSet.end();itr++){
Scene *scenePtr = *itr;
scenePtr->SetOrdering(0);
sortedTimeStamp.push_back(scenePtr->GetFirstSkeletonObservedTime_ms());
}
sort(sortedTimeStamp.begin(),sortedTimeStamp.end());
unsigned int order = 1;
for(vector<long>::const_iterator sortedTimeStampItr = sortedTimeStamp.begin();sortedTimeStampItr!=sortedTimeStamp.end();sortedTimeStampItr++){
for(set<Scene*>::const_iterator sceneItr = this->_scenesSet.begin();sceneItr!=this->_scenesSet.end();sceneItr++){
Scene *scenePtr = *sceneItr;
if(scenePtr->GetFirstSkeletonObservedTime_ms()==*sortedTimeStampItr){
scenePtr->SetOrdering(order);
order+=1;
this->_orderedSceneMutex.lock();
this->_orderedScenes.push_back(scenePtr);
this->_orderedSceneMutex.unlock();
}
}
}
for(vector<Scene*>::iterator orderedSceneItr = this->_orderedScenes.begin();orderedSceneItr!=this->_orderedScenes.end();orderedSceneItr++)
{
Scene *scenePtr = *orderedSceneItr;
vector<Scene*>::iterator next, prev;
if(this->_orderedScenes.size()>1){
if(orderedSceneItr==this->_orderedScenes.begin()){
//First Scene
next = orderedSceneItr+1;
scenePtr->SetLeftRightScene(NULL,*next);
}else if(orderedSceneItr==this->_orderedScenes.end()-1)
{
//Last Scene
prev = orderedSceneItr-1;
scenePtr->SetLeftRightScene(*prev,NULL);
}else
{
//i scene i!=0 && i!=n
next = orderedSceneItr+1;
prev = orderedSceneItr-1;
scenePtr->SetLeftRightScene(*prev,*next);
}
}
}
this->_scenesSet.clear();
return true;
}
/**
* Calibrate the R & T from the two scenes
* At = RBt+T
* A is the reference frame
* B is the body frame
* R and T is the rotation and translation from B to A
* @return true if computation of R & T matrix is successful
*/
bool MinorityViewportAlgo::CalibrateScenes(unsigned int sceneAOrder,
string skeletonsA_json,
unsigned int sceneBOrder,
string skeletonsB_json)
{
bool calibrateSuccess = false;
Json::Value skeletonsARoot;
Json::Value skeletonsBRoot;
Json::Reader reader;
ofstream testOutputSensorAFile("A_calibration_data.txt");
ofstream testOutputSensorBFile("B_calibration_data.txt");
ofstream centroidAFile("A_centroid.txt");
ofstream centroidBFile("B_centroid.txt");
ofstream translationDataFile("T_calibration_data.txt");
ofstream rotationDataFile("R_calibration_data.txt");
if (this->_orderedScenes.size()>0&&reader.parse(skeletonsA_json,skeletonsARoot)&&reader.parse(skeletonsB_json,skeletonsBRoot))
{
Json::Value skeletonsA_JSON = skeletonsARoot["skeletons"];
Json::Value skeletonsB_JSON = skeletonsBRoot["skeletons"];
list<Skeleton> skeletonsA;
list<Skeleton> skeletonsB;
for(unsigned short skeleton=0;skeleton<skeletonsA_JSON.size();skeleton+=1){
Skeleton skeletonFromSceneA(skeletonsA_JSON[skeleton],0);
Skeleton skeletonFromSceneB(skeletonsB_JSON[skeleton],0);
/* Eliminate vectors which are not full sets of joints */
if(skeletonFromSceneA.checkFullSetOfJoints()&&skeletonFromSceneB.checkFullSetOfJoints()){
skeletonsA.push_front(skeletonFromSceneA);
skeletonsB.push_front(skeletonFromSceneB);
}
}
/* Regardless of Scene A or Scene B, Matrix A must be the reference frame here*/
Mat A,B; //nx3
Mat centroidA,centroidB; //1x3 (Verified with Matlab)
unsigned int bodyFrameOrder=0,refFrameOrder=0;
// A must always be the reference frame and B the body frame after this if condition
if(sceneAOrder<sceneBOrder){
//scene A is the reference frame
for(list<Skeleton>::iterator skeletonFromA=skeletonsA.begin();skeletonFromA!=skeletonsA.end();++skeletonFromA){
//nx3 vector matrix
A.push_back((*skeletonFromA).GetCompletePointsVectorMatrix(NULL,false)); //A
}
for(list<Skeleton>::iterator skeletonFromB=skeletonsB.begin();skeletonFromB!=skeletonsB.end();++skeletonFromB){
//nx3 vector matrix
B.push_back((*skeletonFromB).GetCompletePointsVectorMatrix(NULL,false)); //B
}
refFrameOrder = sceneAOrder;
bodyFrameOrder = sceneBOrder;
}else{
//scene B is the reference frame
for(list<Skeleton>::iterator skeletonFromB=skeletonsB.begin();skeletonFromB!=skeletonsB.end();++skeletonFromB){
//nx3 vector matrix
A.push_back((*skeletonFromB).GetCompletePointsVectorMatrix(NULL,false)); //A
}
for(list<Skeleton>::iterator skeletonFromA=skeletonsA.begin();skeletonFromA!=skeletonsA.end();++skeletonFromA){
//nx3 vector matrix
B.push_back((*skeletonFromA).GetCompletePointsVectorMatrix(NULL,false)); //B
}
refFrameOrder = sceneBOrder;
bodyFrameOrder = sceneAOrder;
}
//1x3
reduce(A,centroidA,0,1);
reduce(B,centroidB,0,1);
/* Log A,B and centroids */
A.convertTo(A, CV_64F);
B.convertTo(B, CV_64F);
for(unsigned int row=0;row<A.rows;row+=1){
testOutputSensorAFile << A.at<double>(row,0) << ",";
testOutputSensorAFile << A.at<double>(row,1) << ",";
testOutputSensorAFile << A.at<double>(row,2) ;
testOutputSensorAFile << endl;
testOutputSensorBFile << B.at<double>(row,0) << ",";
testOutputSensorBFile << B.at<double>(row,1) << ",";
testOutputSensorBFile << B.at<double>(row,2) ;
testOutputSensorBFile << endl;
}
testOutputSensorAFile.close();
testOutputSensorBFile.close();
centroidA.convertTo(centroidA, CV_64F);
centroidB.convertTo(centroidB, CV_64F);
centroidAFile<< centroidA.at<double>(0,0) << ",";
centroidAFile << centroidA.at<double>(0,1) << ",";
centroidAFile << centroidA.at<double>(0,2) ;
centroidBFile<< centroidB.at<double>(0,0) << ",";
centroidBFile << centroidB.at<double>(0,1) << ",";
centroidBFile << centroidB.at<double>(0,2) ;
centroidAFile.close();
centroidBFile.close();
/* End of Logging */
/* Construct the H matrix */
Mat centroidA_row = centroidA;
Mat centroidB_row = centroidB;
for(int row=0;row<A.rows-1;row++){
centroidA.push_back(centroidA_row);
centroidB.push_back(centroidB_row);
}
// A is the reference B is the body
// H = (B - repmat(centroid_B, N, 1))'*(A - repmat(centroid_A, N, 1));
Mat firstOperand;
subtract(B,centroidB,firstOperand,noArray(),CV_32F);
transpose(firstOperand,firstOperand);
Mat secondOperand;
subtract(A,centroidA,secondOperand,noArray(),CV_32F);
Mat H = firstOperand*secondOperand;
/* Perform SVD on H */
Mat U,S,Vt,Ut,V;
SVD::compute(H,S,U,Vt);
transpose(U,Ut);
transpose(Vt,V);
/* Compute the Rotation Matrix (3x3) (Verified with Matlab) */
Mat rotationMatrix=V*Ut;
/* Compute the Translation Matrix (3x1) */
Mat translationMatrix;
centroidB_row.convertTo(centroidB_row,CV_32F);
rotationMatrix.convertTo(rotationMatrix,CV_32F);
Mat centroidB_transpose;
transpose(centroidB_row,centroidB_transpose);
Mat temp = (-1*rotationMatrix)*centroidB_transpose;
Mat centroidA_transpose;
transpose(centroidA_row,centroidA_transpose);
add(temp,centroidA_transpose,translationMatrix,noArray(),CV_32F);
/* Assign to the R and T to the B scene */
Scene *bodyFrameScene = this->_orderedScenes.at(bodyFrameOrder-1);
bodyFrameScene->SetRAndT(rotationMatrix,translationMatrix);
/* Output to file for testing */
bodyFrameScene->GetRMatrix(&rotationDataFile,true);
bodyFrameScene->GetTMatrix(&translationDataFile,true);
Scene *refFrameScene = this->_orderedScenes.at(refFrameOrder-1);
bodyFrameScene->SetCalibration(true);
refFrameScene->SetCalibration(true);
calibrateSuccess = true;
}else{
calibrateSuccess = false;
}
return calibrateSuccess;
}
void MinorityViewportAlgo::ProcessSensorData(string sensorData){
Json::Value root;
Json::Reader reader;
if (!sensorData.empty()&&reader.parse(sensorData,root))
{
long timeStamp = root.get("TIME_STAMP","0").asDouble();
Json::Value skeletons_JSON = root["SENSOR_JSON"];
unsigned int numOfSkeletons = skeletons_JSON.size();
for(unsigned short skeletons=0;skeletons<numOfSkeletons;skeletons++){
MinorityViewport::Skeleton newSkeleton(skeletons_JSON[skeletons],timeStamp);
this->LoadSkeleton(newSkeleton);
}
}
}
void MinorityViewportAlgo::LoadSkeleton(Skeleton newSkeleton){
unsigned int clientId = newSkeleton.GetClientId();
string sensorId = newSkeleton.GetSensorId();
Client *client = this->_clients->At(clientId);
if(client!=NULL){
Sensor *sensor = client->ExtractSensor(sensorId);
sensor->UpdateScene(newSkeleton);
}
}
void MinorityViewportAlgo::MergeScenes(){
Mat R,T,Combi_R,Combi_T,transformedSkeletonMatrix;
long start=0,end=0;
double threshold = 0.04,diff_x=0,diff_y=0,diff_z=0;
unsigned int randomSkeletonId;
this->_globalScene->ManualClear();
//* Optimisation - remove mutex locks since only read and would affect real-time performance */
this->_orderedSceneMutex.lock();
vector<Scene*> orderedScenes = this->_orderedScenes;
this->_orderedSceneMutex.unlock();
/* Do the comparison with reference frame skeletons and discard skeletons as necessary */
if(orderedScenes.size()>0){
for(vector<Scene*>::reverse_iterator orderedSceneItr = orderedScenes.rbegin();orderedSceneItr!=orderedScenes.rend();orderedSceneItr++){
if((*orderedSceneItr)!=NULL&&(*orderedSceneItr)->GetCalibration()){
Combi_R = Mat::eye(3,3, CV_32F);
Combi_T = Mat(3,1, CV_32F,double(0));
Scene *leftScenePtr = (*orderedSceneItr)->GetLeftFrame();
map<unsigned short,Skeleton> currentSceneSkeletons = (*orderedSceneItr)->GetSkeletons();
randomSkeletonId = rand()%100;
for(vector<Scene*>::reverse_iterator prevSceneItr = orderedSceneItr;prevSceneItr!=orderedScenes.rend();prevSceneItr++){
if((*prevSceneItr)->GetLeftFrame()!=NULL){
R = (*prevSceneItr)->GetRMatrix(NULL,false); //3x3
T = (*prevSceneItr)->GetTMatrix(NULL,false); //3x1
Combi_R = Combi_R * R;
add(Combi_T,T,Combi_T,noArray(),CV_32F);
}
}
start=this->_curTime->GetTicks_ms();
if(leftScenePtr==NULL){
//This is the first scene => no transformation required
for(map<unsigned short,Skeleton>::iterator bodyFrameSkeleton=currentSceneSkeletons.begin();
bodyFrameSkeleton!=currentSceneSkeletons.end();
bodyFrameSkeleton++){
bodyFrameSkeleton->second.UnsetShared();
this->_globalScene->Update(randomSkeletonId,bodyFrameSkeleton->second);
}
}else {
map<unsigned short,Skeleton> leftFrameSkeletons = leftScenePtr->GetSkeletons();
if(leftFrameSkeletons.size()==0){
for(map<unsigned short,Skeleton>::iterator bodyFrameSkeleton=currentSceneSkeletons.begin();
bodyFrameSkeleton!=currentSceneSkeletons.end();
bodyFrameSkeleton++){
bodyFrameSkeleton->second.UnsetShared();
transformedSkeletonMatrix = this->TransformSkeletonMatrix(bodyFrameSkeleton->second.GetCompletePointsVectorMatrix(NULL,false),Combi_R,Combi_T);
bodyFrameSkeleton->second.ConvertVectorMatrixtoSkeletonPoints(transformedSkeletonMatrix);
this->_globalScene->Update(randomSkeletonId,bodyFrameSkeleton->second);
}
}else{
R = (*orderedSceneItr)->GetRMatrix(NULL,false); //3x3
T = (*orderedSceneItr)->GetTMatrix(NULL,false); //3x1
for(map<unsigned short,Skeleton>::iterator bodyFrameSkeleton=currentSceneSkeletons.begin();
bodyFrameSkeleton!=currentSceneSkeletons.end();
bodyFrameSkeleton++){
/* Transform all the skeletons within body frame to the left frame coordinates*/
Skeleton matchingSkeleton(bodyFrameSkeleton->second);
transformedSkeletonMatrix = this->TransformSkeletonMatrix(matchingSkeleton.GetCompletePointsVectorMatrix(NULL,false),R,T);
matchingSkeleton.ConvertVectorMatrixtoSkeletonPoints(transformedSkeletonMatrix);
/* Do comparison with the left scene skeletons */
for(map<unsigned short,Skeleton>::iterator refFrameSkeleton=leftFrameSkeletons.begin();
refFrameSkeleton!=leftFrameSkeletons.end();
refFrameSkeleton++){
/* Comparison */
diff_x = abs(refFrameSkeleton->second.pos_x-matchingSkeleton.pos_x);
diff_y = abs(refFrameSkeleton->second.pos_y-matchingSkeleton.pos_y);
diff_z = abs(refFrameSkeleton->second.pos_z-matchingSkeleton.pos_z);
if(diff_x<threshold||diff_y<threshold||diff_z<threshold){
//Deemed the same human appear in both left and right scene
//Eliminate the skeleton on the left scene that has the same coordinates as the cur scene skeleton's translated coordinates
leftScenePtr->Remove(refFrameSkeleton->first);
bodyFrameSkeleton->second.SetShared();
transformedSkeletonMatrix = this->TransformSkeletonMatrix(bodyFrameSkeleton->second.GetCompletePointsVectorMatrix(NULL,false),Combi_R,Combi_T);
bodyFrameSkeleton->second.ConvertVectorMatrixtoSkeletonPoints(transformedSkeletonMatrix);
this->_globalScene->Update(randomSkeletonId,bodyFrameSkeleton->second);
break;
}
}
}
}
}
end=this->_curTime->GetTicks_ms();
}
}
}
}
/**
* Implement the formulat
* A (3xn) = R(3x3)*B(3xn)+T(3xn)
*/
Mat MinorityViewportAlgo::TransformSkeletonMatrix(Mat bodyFramesSkeleton,Mat R, Mat T)
{
Mat Bt;
transpose(bodyFramesSkeleton,Bt); //3x21
Mat Tt;
transpose(T,Tt);
Mat TResized(Tt); //1x3
for(int col=0;col<Bt.cols-1;col+=1){
TResized.push_back(Tt); //21x3
}
transpose(TResized,TResized); //3x21
Mat RmulBt;
RmulBt = R*Bt; //3x21
Mat transformedMatrix; //3x21
add(RmulBt,TResized,transformedMatrix,noArray(),CV_32F);
transpose(transformedMatrix,transformedMatrix);
return transformedMatrix; //21x3
}
void MinorityViewportAlgo::RefreshScenesSet(){
this->_scenesSet.clear();
Client *clientPtr;
/* Load all sensors from clients into the unordered sceneset */
for(unsigned int client=0;client<this->_clients->Size();client+=1){
clientPtr = this->_clients->AtIdx(client);
map<string,Sensor*> sensors = clientPtr->GetSensorsList();
for(map<string,Sensor*>::iterator itr = sensors.begin();itr!=sensors.end();itr++)
{
Scene *scene = itr->second->GetScene();
this->_scenesSet.insert(scene);
}
}
}
Scene* MinorityViewportAlgo::GetGlobalScene(){
if(this->_orderedScenes.size()!=0){
this->MergeScenes();
return this->_globalScene;
}else{
return NULL;
}
}
Scene* MinorityViewportAlgo::GetLocalSceneBySensorId(string sensorId){
if(this->_clients->Size()>0){
Client *clientPtr;
for(unsigned int client=0;client<this->_clients->Size();client+=1){
clientPtr = this->_clients->AtIdx(client);
map<string,Sensor*> sensors = clientPtr->GetSensorsList();
for(map<string,Sensor*>::iterator itr = sensors.begin();itr!=sensors.end();itr++)
{
if(itr->first==sensorId){
return itr->second->GetScene();
}
}
}
}
return NULL;
}
void MinorityViewportAlgo::ReportStatus(string msg){
cout << "Viewport : " << msg << endl;
}
} | agpl-3.0 |
jcamins/biblionarrator | src/graphworker/tasks/mapper.js | 5920 | "use strict";
var environment = require('../../lib/environment'),
graphstore = environment.graphstore,
g = graphstore.g,
async = require('async');
module.exports = function (input, callback) {
var list = new g.ArrayList();
var recordtypes = new g.ArrayList();
input.depth = input.depth || 1;
var source = input.landmarks || input.records;
if (source) {
async.series({
records: function (cb) {
g.start(source).copySplit(g._().out().in(), g._().in().out()).fairMerge().groupCount().cap().orderMap(g.Tokens.decr).range(0, input.size).aggregate(list).toJSON(cb);
},
recordtypes: function (cb) {
cb();
//g.start(list.iteratorSync()).out('recordtype').property('key').toJSON(cb);
},
paths: function (cb) {
g.start(source).copySplit(g._().inE().outV().outE().inV(), g._().outE().inV().inE().outV()).fairMerge().retain(list).path('{it->it.id}', '{it->it.inV.next().id + "^" + it.label}', '{it->it.id}', '{it->it.inV.next().id + "^" + it.label}', '{it->it.id}').toJSON(cb);
}
}, function (err, res) {
var records = res.records;
g.start(source).copySplit(g._().out().in(), g._().in().out()).fairMerge().groupCount().cap().orderMap(g.Tokens.decr).range(0, input.size).aggregate(list).iterate(function () {
var edges = [ ];
var recmap = { };
records = records || [ ];
records.forEach(function (rec, index) {
records[index].recordtype = recordtypes[index] || '';
records[index].weight = 0;
recmap[rec._id] = index;
});
var edgeparts;
var needed = { };
var newedge;
var edgemap = { };
res.paths = res.paths || [ ];
res.paths.forEach(function (path) {
edgeparts = path[1].split('^');
edgeparts[0] = parseInt(edgeparts[0], 10);
newedge = { _inV: edgeparts[0], _label: edgeparts[1], _outV: edgeparts[0] === path[0] ? path[2] : path[0] };
if (typeof edgemap[newedge._inV + '^' + newedge._label + '^' + newedge._outV] === 'undefined') {
edges.push(newedge);
}
edgeparts = path[3].split('^');
edgeparts[0] = parseInt(edgeparts[0], 10);
newedge = { _inV: edgeparts[0], _label: edgeparts[1], _outV: edgeparts[0] === path[2] ? path[4] : path[2] };
if (typeof edgemap[newedge._inV + '^' + newedge._label + '^' + newedge._outV] === 'undefined') {
edges.push(newedge);
}
if (typeof recmap[path[0]] === 'undefined') {
needed[path[0]] = true;
}
if (typeof recmap[path[2]] === 'undefined') {
needed[path[2]] = true;
}
if (typeof recmap[path[4]] === 'undefined') {
needed[path[4]] = true;
}
});
if (typeof input.landmarks !== 'undefined') {
input.landmarks.forEach(function (landmark) {
if (typeof recmap[landmark] === 'undefined') {
needed[landmark] = true;
}
});
}
var finishProcessing = function (err, res) {
if (typeof input.landmarks !== 'undefined') {
input.landmarks.forEach(function (landmark) {
if (recmap[landmark] && records[recmap[landmark]]) records[recmap[landmark]].landmark = true;
});
}
var removes = [ ];
for (var ii = 0; ii < edges.length; ii++) {
edges[ii].source = recmap[edges[ii]._inV];
edges[ii].target = recmap[edges[ii]._outV];
if (typeof edges[ii].source === 'undefined' || typeof edges[ii].target === 'undefined') {
removes.unshift(ii);
} else {
records[recmap[edges[ii]._inV]].weight += 1;
records[recmap[edges[ii]._outV]].weight += 1;
}
}
removes.forEach(function (ii) {
edges.splice(ii, 1);
});
callback({ records: records, recmap: recmap, edges: edges, landmarks: input.landmarks });
};
if (Object.keys(needed).length > 0) {
recordtypes = new g.ArrayList();
g.start(Object.keys(needed)).as('records').out('recordtype').property('key').store(recordtypes).optional('records').toJSON(function (err, newrecords) {
g.toJSON(recordtypes, function(err, recordtypes) {
newrecords = newrecords || [ ];
newrecords.forEach(function (newrecord, index) {
newrecord.recordtype = recordtypes[index] || '';
newrecord.weight = 0;
recmap[newrecord._id] = records.push(newrecord) - 1;
});
finishProcessing();
});
});
} else {
finishProcessing();
}
});
});
} else {
callback({ records: [ ], recmap: { }, edges: [ ], landmarks: [ ] });
}
};
module.exports.message = 'map';
| agpl-3.0 |
wujf/rethinkdb | src/rdb_protocol/datum_stream.cc | 45289 | // Copyright 2010-2013 RethinkDB, all rights reserved.
#include "rdb_protocol/datum_stream.hpp"
#include <map>
#include "boost_utils.hpp"
#include "rdb_protocol/batching.hpp"
#include "rdb_protocol/env.hpp"
#include "rdb_protocol/func.hpp"
#include "rdb_protocol/term.hpp"
#include "rdb_protocol/val.hpp"
#include "utils.hpp"
#include "debug.hpp"
namespace ql {
// RANGE/READGEN STUFF
rget_response_reader_t::rget_response_reader_t(
const counted_t<real_table_t> &_table,
bool _use_outdated,
scoped_ptr_t<readgen_t> &&_readgen)
: table(_table),
use_outdated(_use_outdated),
started(false), shards_exhausted(false),
readgen(std::move(_readgen)),
active_range(readgen->original_keyrange()),
items_index(0) { }
void rget_response_reader_t::add_transformation(transform_variant_t &&tv) {
r_sanity_check(!started);
transforms.push_back(std::move(tv));
}
void rget_response_reader_t::accumulate(env_t *env, eager_acc_t *acc,
const terminal_variant_t &tv) {
r_sanity_check(!started);
started = shards_exhausted = true;
batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env);
read_t read = readgen->terminal_read(transforms, tv, batchspec);
result_t res = do_read(env, std::move(read)).result;
acc->add_res(env, &res);
}
std::vector<datum_t> rget_response_reader_t::next_batch(env_t *env,
const batchspec_t &batchspec) {
started = true;
if (!load_items(env, batchspec)) {
return std::vector<datum_t>();
}
r_sanity_check(items_index < items.size());
std::vector<datum_t> res;
switch (batchspec.get_batch_type()) {
case batch_type_t::NORMAL: // fallthru
case batch_type_t::NORMAL_FIRST: // fallthru
case batch_type_t::TERMINAL: {
res.reserve(items.size() - items_index);
for (; items_index < items.size(); ++items_index) {
res.push_back(std::move(items[items_index].data));
}
} break;
case batch_type_t::SINDEX_CONSTANT: {
ql::datum_t sindex = std::move(items[items_index].sindex_key);
store_key_t key = std::move(items[items_index].key);
res.push_back(std::move(items[items_index].data));
items_index += 1;
bool maybe_more_with_sindex = true;
while (maybe_more_with_sindex) {
for (; items_index < items.size(); ++items_index) {
if (sindex.has()) {
r_sanity_check(items[items_index].sindex_key.has());
if (items[items_index].sindex_key != sindex) {
break; // batch is done
}
} else {
r_sanity_check(!items[items_index].sindex_key.has());
if (items[items_index].key != key) {
break;
}
}
res.push_back(std::move(items[items_index].data));
rcheck_datum(
res.size() <= env->limits().array_size_limit(), base_exc_t::GENERIC,
strprintf("Too many rows (> %zu) with the same value "
"for index `%s`:\n%s",
env->limits().array_size_limit(),
opt_or(readgen->sindex_name(), "").c_str(),
// This is safe because you can't have duplicate
// primary keys, so they will never exceed the
// array limit.
sindex.trunc_print().c_str()));
}
if (items_index >= items.size()) {
// If we consumed the whole batch without finding a new sindex,
// we might have more rows with the same sindex in the next
// batch, which we promptly load.
maybe_more_with_sindex = load_items(env, batchspec);
} else {
maybe_more_with_sindex = false;
}
}
} break;
default: unreachable();
}
if (items_index >= items.size()) { // free memory immediately
items_index = 0;
std::vector<rget_item_t> tmp;
tmp.swap(items);
}
shards_exhausted = (res.size() == 0) ? true : shards_exhausted;
return res;
}
bool rget_response_reader_t::is_finished() const {
return shards_exhausted && items_index >= items.size();
}
rget_read_response_t rget_response_reader_t::do_read(env_t *env, const read_t &read) {
read_response_t res;
table->read_with_profile(env, read, &res, use_outdated);
auto rget_res = boost::get<rget_read_response_t>(&res.response);
r_sanity_check(rget_res != NULL);
if (auto e = boost::get<exc_t>(&rget_res->result)) {
throw *e;
}
return std::move(*rget_res);
}
rget_reader_t::rget_reader_t(
const counted_t<real_table_t> &_table,
bool _use_outdated,
scoped_ptr_t<readgen_t> &&_readgen)
: rget_response_reader_t(_table, _use_outdated, std::move(_readgen)) { }
void rget_reader_t::accumulate_all(env_t *env, eager_acc_t *acc) {
r_sanity_check(!started);
started = true;
batchspec_t batchspec = batchspec_t::all();
read_t read = readgen->next_read(active_range, transforms, batchspec);
rget_read_response_t resp = do_read(env, std::move(read));
auto rr = boost::get<rget_read_t>(&read.read);
auto final_key = !reversed(rr->sorting) ? store_key_t::max() : store_key_t::min();
r_sanity_check(resp.last_key == final_key);
r_sanity_check(!resp.truncated);
shards_exhausted = true;
acc->add_res(env, &resp.result);
}
std::vector<rget_item_t> rget_reader_t::do_range_read(
env_t *env, const read_t &read) {
rget_read_response_t res = do_read(env, read);
auto rr = boost::get<rget_read_t>(&read.read);
r_sanity_check(rr);
const key_range_t &rng = rr->sindex? rr->sindex->region.inner : rr->region.inner;
// We need to do some adjustments to the last considered key so that we
// update the range correctly in the case where we're reading a subportion
// of the total range.
store_key_t *key = &res.last_key;
if (*key == store_key_t::max() && !reversed(rr->sorting)) {
if (!rng.right.unbounded) {
*key = rng.right.key;
bool b = key->decrement();
r_sanity_check(b);
}
} else if (*key == store_key_t::min() && reversed(rr->sorting)) {
*key = rng.left;
}
shards_exhausted = readgen->update_range(&active_range, res.last_key);
grouped_t<stream_t> *gs = boost::get<grouped_t<stream_t> >(&res.result);
// groups_to_batch asserts that underlying_map has 0 or 1 elements, so it is
// correct to declare that the order doesn't matter.
return groups_to_batch(gs->get_underlying_map(grouped::order_doesnt_matter_t()));
}
bool rget_reader_t::load_items(env_t *env, const batchspec_t &batchspec) {
started = true;
if (items_index >= items.size() && !shards_exhausted) { // read some more
items_index = 0;
items = do_range_read(
env, readgen->next_read(active_range, transforms, batchspec));
// Everything below this point can handle `items` being empty (this is
// good hygiene anyway).
while (boost::optional<read_t> read = readgen->sindex_sort_read(
active_range, items, transforms, batchspec)) {
std::vector<rget_item_t> new_items = do_range_read(env, *read);
if (new_items.size() == 0) {
break;
}
rcheck_datum(
(items.size() + new_items.size()) <= env->limits().array_size_limit(),
base_exc_t::GENERIC,
strprintf("Too many rows (> %zu) with the same "
"truncated key for index `%s`. "
"Example value:\n%s\n"
"Truncated key:\n%s",
env->limits().array_size_limit(),
opt_or(readgen->sindex_name(), "").c_str(),
items[items.size() - 1].sindex_key.trunc_print().c_str(),
key_to_debug_str(items[items.size() - 1].key).c_str()));
items.reserve(items.size() + new_items.size());
std::move(new_items.begin(), new_items.end(), std::back_inserter(items));
}
readgen->sindex_sort(&items);
}
if (items_index >= items.size()) {
shards_exhausted = true;
}
return items_index < items.size();
}
intersecting_reader_t::intersecting_reader_t(
const counted_t<real_table_t> &_table,
bool _use_outdated,
scoped_ptr_t<readgen_t> &&_readgen)
: rget_response_reader_t(_table, _use_outdated, std::move(_readgen)) { }
void intersecting_reader_t::accumulate_all(env_t *env, eager_acc_t *acc) {
r_sanity_check(!started);
started = true;
batchspec_t batchspec = batchspec_t::all();
read_t read = readgen->next_read(active_range, transforms, batchspec);
rget_read_response_t resp = do_read(env, std::move(read));
auto final_key = store_key_t::max();
r_sanity_check(resp.last_key == final_key);
r_sanity_check(!resp.truncated);
shards_exhausted = true;
acc->add_res(env, &resp.result);
}
bool intersecting_reader_t::load_items(env_t *env, const batchspec_t &batchspec) {
started = true;
while (items_index >= items.size() && !shards_exhausted) { // read some more
std::vector<rget_item_t> unfiltered_items = do_intersecting_read(
env, readgen->next_read(active_range, transforms, batchspec));
if (unfiltered_items.empty()) {
shards_exhausted = true;
} else {
items_index = 0;
items.clear();
items.reserve(unfiltered_items.size());
for (size_t i = 0; i < unfiltered_items.size(); ++i) {
r_sanity_check(unfiltered_items[i].key.size() > 0);
store_key_t pkey(ql::datum_t::extract_primary(unfiltered_items[i].key));
if (processed_pkeys.count(pkey) == 0) {
if (processed_pkeys.size() >= env->limits().array_size_limit()) {
throw ql::exc_t(ql::base_exc_t::GENERIC,
"Array size limit exceeded during geospatial index "
"traversal.", NULL);
}
processed_pkeys.insert(pkey);
items.push_back(std::move(unfiltered_items[i]));
}
}
}
}
return items_index < items.size();
}
std::vector<rget_item_t> intersecting_reader_t::do_intersecting_read(
env_t *env, const read_t &read) {
rget_read_response_t res = do_read(env, read);
auto gr = boost::get<intersecting_geo_read_t>(&read.read);
r_sanity_check(gr);
const key_range_t &rng = gr->sindex.region.inner;
// We need to do some adjustments to the last considered key so that we
// update the range correctly in the case where we're reading a subportion
// of the total range.
store_key_t *key = &res.last_key;
if (*key == store_key_t::max()) {
if (!rng.right.unbounded) {
*key = rng.right.key;
bool b = key->decrement();
r_sanity_check(b);
}
}
shards_exhausted = readgen->update_range(&active_range, res.last_key);
grouped_t<stream_t> *gs = boost::get<grouped_t<stream_t> >(&res.result);
// groups_to_batch asserts that underlying_map has 0 or 1 elements, so it is
// correct to declare that the order doesn't matter.
return groups_to_batch(gs->get_underlying_map(grouped::order_doesnt_matter_t()));
}
readgen_t::readgen_t(
const std::map<std::string, wire_func_t> &_global_optargs,
std::string _table_name,
profile_bool_t _profile,
sorting_t _sorting)
: global_optargs(_global_optargs),
table_name(std::move(_table_name)),
profile(_profile),
sorting(_sorting) { }
bool readgen_t::update_range(key_range_t *active_range,
const store_key_t &last_key) const {
if (!reversed(sorting)) {
active_range->left = last_key;
} else {
active_range->right = key_range_t::right_bound_t(last_key);
}
// TODO: mixing these non-const operations INTO THE CONDITIONAL is bad, and
// confused me (mlucy) for a while when I tried moving some stuff around.
if (!reversed(sorting)) {
if (!active_range->left.increment()
|| (!active_range->right.unbounded
&& (active_range->right.key < active_range->left))) {
return true;
}
} else {
r_sanity_check(!active_range->right.unbounded);
if (!active_range->right.key.decrement()
|| active_range->right.key < active_range->left) {
return true;
}
}
return active_range->is_empty();
}
rget_readgen_t::rget_readgen_t(
const std::map<std::string, wire_func_t> &_global_optargs,
std::string _table_name,
const datum_range_t &_original_datum_range,
profile_bool_t _profile,
sorting_t _sorting)
: readgen_t(_global_optargs, std::move(_table_name), _profile, _sorting),
original_datum_range(_original_datum_range) { }
read_t rget_readgen_t::next_read(
const key_range_t &active_range,
const std::vector<transform_variant_t> &transforms,
const batchspec_t &batchspec) const {
return read_t(next_read_impl(active_range, transforms, batchspec), profile);
}
// TODO: this is how we did it before, but it sucks.
read_t rget_readgen_t::terminal_read(
const std::vector<transform_variant_t> &transforms,
const terminal_variant_t &_terminal,
const batchspec_t &batchspec) const {
rget_read_t read = next_read_impl(original_keyrange(), transforms, batchspec);
read.terminal = _terminal;
return read_t(read, profile);
}
primary_readgen_t::primary_readgen_t(
const std::map<std::string, wire_func_t> &global_optargs,
std::string table_name,
datum_range_t range,
profile_bool_t profile,
sorting_t sorting)
: rget_readgen_t(global_optargs, std::move(table_name), range, profile, sorting) { }
scoped_ptr_t<readgen_t> primary_readgen_t::make(
env_t *env,
std::string table_name,
datum_range_t range,
sorting_t sorting) {
return scoped_ptr_t<readgen_t>(
new primary_readgen_t(
env->get_all_optargs(),
std::move(table_name),
range,
env->profile(),
sorting));
}
rget_read_t primary_readgen_t::next_read_impl(
const key_range_t &active_range,
const std::vector<transform_variant_t> &transforms,
const batchspec_t &batchspec) const {
return rget_read_t(
region_t(active_range),
global_optargs,
table_name,
batchspec,
transforms,
boost::optional<terminal_variant_t>(),
boost::optional<sindex_rangespec_t>(),
sorting);
}
// We never need to do an sindex sort when indexing by a primary key.
boost::optional<read_t> primary_readgen_t::sindex_sort_read(
UNUSED const key_range_t &active_range,
UNUSED const std::vector<rget_item_t> &items,
UNUSED const std::vector<transform_variant_t> &transforms,
UNUSED const batchspec_t &batchspec) const {
return boost::optional<read_t>();
}
void primary_readgen_t::sindex_sort(UNUSED std::vector<rget_item_t> *vec) const {
return;
}
key_range_t primary_readgen_t::original_keyrange() const {
return original_datum_range.to_primary_keyrange();
}
boost::optional<std::string> primary_readgen_t::sindex_name() const {
return boost::optional<std::string>();
}
sindex_readgen_t::sindex_readgen_t(
const std::map<std::string, wire_func_t> &global_optargs,
std::string table_name,
const std::string &_sindex,
datum_range_t range,
profile_bool_t profile,
sorting_t sorting)
: rget_readgen_t(global_optargs, std::move(table_name), range, profile, sorting),
sindex(_sindex) { }
scoped_ptr_t<readgen_t> sindex_readgen_t::make(
env_t *env,
std::string table_name,
const std::string &sindex,
datum_range_t range,
sorting_t sorting) {
return scoped_ptr_t<readgen_t>(
new sindex_readgen_t(
env->get_all_optargs(),
std::move(table_name),
sindex,
range,
env->profile(),
sorting));
}
class sindex_compare_t {
public:
explicit sindex_compare_t(sorting_t _sorting)
: sorting(_sorting) { }
bool operator()(const rget_item_t &l, const rget_item_t &r) {
r_sanity_check(l.sindex_key.has() && r.sindex_key.has());
// We don't have to worry about v1.13.x because there's no way this is
// running inside of a secondary index function. Also, in case you're
// wondering, it's okay for this ordering to be different from the buggy
// secondary index key ordering that existed in v1.13. It was different in
// v1.13 itself. For that, we use the last_key value in the
// rget_read_response_t.
return reversed(sorting)
? l.sindex_key.compare_gt(reql_version_t::LATEST, r.sindex_key)
: l.sindex_key.compare_lt(reql_version_t::LATEST, r.sindex_key);
}
private:
sorting_t sorting;
};
void sindex_readgen_t::sindex_sort(std::vector<rget_item_t> *vec) const {
if (vec->size() == 0) {
return;
}
if (sorting != sorting_t::UNORDERED) {
std::stable_sort(vec->begin(), vec->end(), sindex_compare_t(sorting));
}
}
rget_read_t sindex_readgen_t::next_read_impl(
const key_range_t &active_range,
const std::vector<transform_variant_t> &transforms,
const batchspec_t &batchspec) const {
return rget_read_t(
region_t::universe(),
global_optargs,
table_name,
batchspec,
transforms,
boost::optional<terminal_variant_t>(),
sindex_rangespec_t(sindex, region_t(active_range), original_datum_range),
sorting);
}
boost::optional<read_t> sindex_readgen_t::sindex_sort_read(
const key_range_t &active_range,
const std::vector<rget_item_t> &items,
const std::vector<transform_variant_t> &transforms,
const batchspec_t &batchspec) const {
if (sorting != sorting_t::UNORDERED && items.size() > 0) {
const store_key_t &key = items[items.size() - 1].key;
if (datum_t::key_is_truncated(key)) {
std::string skey = datum_t::extract_secondary(key_to_unescaped_str(key));
key_range_t rng = active_range;
if (!reversed(sorting)) {
// We construct a right bound that's larger than the maximum
// possible row with this truncated sindex but smaller than the
// minimum possible row with a larger sindex.
rng.right = key_range_t::right_bound_t(
store_key_t(skey + std::string(MAX_KEY_SIZE - skey.size(), 0xFF)));
} else {
// We construct a left bound that's smaller than the minimum
// possible row with this truncated sindex but larger than the
// maximum possible row with a smaller sindex.
rng.left = store_key_t(skey);
}
if (rng.right.unbounded || rng.left < rng.right.key) {
return read_t(
rget_read_t(
region_t::universe(),
global_optargs,
table_name,
batchspec.with_new_batch_type(batch_type_t::SINDEX_CONSTANT),
transforms,
boost::optional<terminal_variant_t>(),
sindex_rangespec_t(
sindex,
region_t(key_range_t(rng)),
original_datum_range),
sorting),
profile);
}
}
}
return boost::optional<read_t>();
}
key_range_t sindex_readgen_t::original_keyrange() const {
return original_datum_range.to_sindex_keyrange();
}
boost::optional<std::string> sindex_readgen_t::sindex_name() const {
return sindex;
}
intersecting_readgen_t::intersecting_readgen_t(
const std::map<std::string, wire_func_t> &global_optargs,
std::string table_name,
const std::string &_sindex,
const datum_t &_query_geometry,
profile_bool_t profile)
: readgen_t(global_optargs, std::move(table_name), profile, sorting_t::UNORDERED),
sindex(_sindex),
query_geometry(_query_geometry) { }
scoped_ptr_t<readgen_t> intersecting_readgen_t::make(
env_t *env,
std::string table_name,
const std::string &sindex,
const datum_t &query_geometry) {
return scoped_ptr_t<readgen_t>(
new intersecting_readgen_t(
env->get_all_optargs(),
std::move(table_name),
sindex,
query_geometry,
env->profile()));
}
read_t intersecting_readgen_t::next_read(
const key_range_t &active_range,
const std::vector<transform_variant_t> &transforms,
const batchspec_t &batchspec) const {
return read_t(next_read_impl(active_range, transforms, batchspec), profile);
}
read_t intersecting_readgen_t::terminal_read(
const std::vector<transform_variant_t> &transforms,
const terminal_variant_t &_terminal,
const batchspec_t &batchspec) const {
intersecting_geo_read_t read =
next_read_impl(original_keyrange(), transforms, batchspec);
read.terminal = _terminal;
return read_t(read, profile);
}
intersecting_geo_read_t intersecting_readgen_t::next_read_impl(
const key_range_t &active_range,
const std::vector<transform_variant_t> &transforms,
const batchspec_t &batchspec) const {
return intersecting_geo_read_t(
region_t::universe(),
global_optargs,
table_name,
batchspec,
transforms,
boost::optional<terminal_variant_t>(),
sindex_rangespec_t(sindex, region_t(active_range), datum_range_t::universe()),
query_geometry);
}
boost::optional<read_t> intersecting_readgen_t::sindex_sort_read(
UNUSED const key_range_t &active_range,
UNUSED const std::vector<rget_item_t> &items,
UNUSED const std::vector<transform_variant_t> &transforms,
UNUSED const batchspec_t &batchspec) const {
// Intersection queries don't support sorting
return boost::optional<read_t>();
}
void intersecting_readgen_t::sindex_sort(UNUSED std::vector<rget_item_t> *vec) const {
// No sorting required for intersection queries, since they don't
// support any specific ordering.
}
key_range_t intersecting_readgen_t::original_keyrange() const {
// This is always universe for intersection reads.
// The real query is in the query geometry.
return datum_range_t::universe().to_sindex_keyrange();
}
boost::optional<std::string> intersecting_readgen_t::sindex_name() const {
return sindex;
}
scoped_ptr_t<val_t> datum_stream_t::run_terminal(
env_t *env, const terminal_variant_t &tv) {
scoped_ptr_t<eager_acc_t> acc(make_eager_terminal(tv));
accumulate(env, acc.get(), tv);
return acc->finish_eager(backtrace(), is_grouped(), env->limits());
}
scoped_ptr_t<val_t> datum_stream_t::to_array(env_t *env) {
scoped_ptr_t<eager_acc_t> acc = make_to_array(env->reql_version());
accumulate_all(env, acc.get());
return acc->finish_eager(backtrace(), is_grouped(), env->limits());
}
// DATUM_STREAM_T
counted_t<datum_stream_t> datum_stream_t::slice(size_t l, size_t r) {
return make_counted<slice_datum_stream_t>(l, r, this->counted_from_this());
}
counted_t<datum_stream_t> datum_stream_t::indexes_of(counted_t<const func_t> f) {
return make_counted<indexes_of_datum_stream_t>(f, counted_from_this());
}
counted_t<datum_stream_t> datum_stream_t::ordered_distinct() {
return make_counted<ordered_distinct_datum_stream_t>(counted_from_this());
}
datum_stream_t::datum_stream_t(const protob_t<const Backtrace> &bt_src)
: pb_rcheckable_t(bt_src), batch_cache_index(0), grouped(false) {
}
void datum_stream_t::add_grouping(transform_variant_t &&tv,
const protob_t<const Backtrace> &bt) {
check_not_grouped("Cannot call `group` on the output of `group` "
"(did you mean to `ungroup`?).");
grouped = true;
add_transformation(std::move(tv), bt);
}
void datum_stream_t::check_not_grouped(const char *msg) {
rcheck(!is_grouped(), base_exc_t::GENERIC, msg);
}
std::vector<datum_t>
datum_stream_t::next_batch(env_t *env, const batchspec_t &batchspec) {
DEBUG_ONLY_CODE(env->do_eval_callback());
if (env->interruptor->is_pulsed()) {
throw interrupted_exc_t();
}
// Cannot mix `next` and `next_batch`.
r_sanity_check(batch_cache_index == 0 && batch_cache.size() == 0);
check_not_grouped("Cannot treat the output of `group` as a stream "
"(did you mean to `ungroup`?).");
try {
return next_batch_impl(env, batchspec);
} catch (const datum_exc_t &e) {
rfail(e.get_type(), "%s", e.what());
unreachable();
}
}
datum_t datum_stream_t::next(
env_t *env, const batchspec_t &batchspec) {
profile::starter_t("Reading element from datum stream.", env->trace);
if (batch_cache_index >= batch_cache.size()) {
r_sanity_check(batch_cache_index == 0);
batch_cache = next_batch(env, batchspec);
if (batch_cache_index >= batch_cache.size()) {
return datum_t();
}
}
r_sanity_check(batch_cache_index < batch_cache.size());
datum_t d = std::move(batch_cache[batch_cache_index++]);
if (batch_cache_index >= batch_cache.size()) {
// Free the vector as soon as we're done with it. This also keeps the
// assert in `next_batch` happy.
batch_cache_index = 0;
std::vector<datum_t> tmp;
tmp.swap(batch_cache);
}
return d;
}
bool datum_stream_t::batch_cache_exhausted() const {
return batch_cache_index >= batch_cache.size();
}
void eager_datum_stream_t::add_transformation(
transform_variant_t &&tv, const protob_t<const Backtrace> &bt) {
ops.push_back(make_op(tv));
transforms.push_back(std::move(tv));
update_bt(bt);
}
eager_datum_stream_t::done_t eager_datum_stream_t::next_grouped_batch(
env_t *env, const batchspec_t &bs, groups_t *out) {
r_sanity_check(out->size() == 0);
while (out->size() == 0) {
std::vector<datum_t> v = next_raw_batch(env, bs);
if (v.size() == 0) {
return done_t::YES;
}
(*out)[datum_t()] = std::move(v);
for (auto it = ops.begin(); it != ops.end(); ++it) {
(**it)(env, out, datum_t());
}
}
return done_t::NO;
}
void eager_datum_stream_t::accumulate(
env_t *env, eager_acc_t *acc, const terminal_variant_t &) {
batchspec_t bs = batchspec_t::user(batch_type_t::TERMINAL, env);
// I'm guessing reql_version doesn't matter here, but why think about it? We use
// th env's reql_version.
groups_t data(optional_datum_less_t(env->reql_version()));
while (next_grouped_batch(env, bs, &data) == done_t::NO) {
(*acc)(env, &data);
}
}
void eager_datum_stream_t::accumulate_all(env_t *env, eager_acc_t *acc) {
groups_t data(optional_datum_less_t(env->reql_version()));
done_t done = next_grouped_batch(env, batchspec_t::all(), &data);
(*acc)(env, &data);
if (done == done_t::NO) {
done_t must_be_yes = next_grouped_batch(env, batchspec_t::all(), &data);
r_sanity_check(data.size() == 0);
r_sanity_check(must_be_yes == done_t::YES);
}
}
std::vector<datum_t>
eager_datum_stream_t::next_batch_impl(env_t *env, const batchspec_t &bs) {
groups_t data(optional_datum_less_t(env->reql_version()));
next_grouped_batch(env, bs, &data);
return groups_to_batch(&data);
}
datum_t eager_datum_stream_t::as_array(env_t *env) {
if (is_grouped() || !is_array()) {
return datum_t();
}
datum_array_builder_t arr(env->limits());
batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env);
{
profile::sampler_t sampler("Evaluating stream eagerly.", env->trace);
datum_t d;
while (d = next(env, batchspec), d.has()) {
arr.add(d);
sampler.new_sample();
}
}
return std::move(arr).to_datum();
}
// LAZY_DATUM_STREAM_T
lazy_datum_stream_t::lazy_datum_stream_t(
scoped_ptr_t<reader_t> &&_reader,
const protob_t<const Backtrace> &bt_src)
: datum_stream_t(bt_src),
current_batch_offset(0),
reader(std::move(_reader)) { }
void lazy_datum_stream_t::add_transformation(transform_variant_t &&tv,
const protob_t<const Backtrace> &bt) {
reader->add_transformation(std::move(tv));
update_bt(bt);
}
void lazy_datum_stream_t::accumulate(
env_t *env, eager_acc_t *acc, const terminal_variant_t &tv) {
reader->accumulate(env, acc, tv);
}
void lazy_datum_stream_t::accumulate_all(env_t *env, eager_acc_t *acc) {
reader->accumulate_all(env, acc);
}
std::vector<datum_t>
lazy_datum_stream_t::next_batch_impl(env_t *env, const batchspec_t &batchspec) {
// Should never mix `next` with `next_batch`.
r_sanity_check(current_batch_offset == 0 && current_batch.size() == 0);
return reader->next_batch(env, batchspec);
}
bool lazy_datum_stream_t::is_exhausted() const {
return reader->is_finished() && batch_cache_exhausted();
}
bool lazy_datum_stream_t::is_cfeed() const {
return false;
}
bool lazy_datum_stream_t::is_infinite() const {
return false;
}
array_datum_stream_t::array_datum_stream_t(datum_t _arr,
const protob_t<const Backtrace> &bt_source)
: eager_datum_stream_t(bt_source), index(0), arr(_arr) { }
datum_t array_datum_stream_t::next(env_t *env, const batchspec_t &bs) {
return ops_to_do() ? datum_stream_t::next(env, bs) : next_arr_el();
}
datum_t array_datum_stream_t::next_arr_el() {
return index < arr.arr_size() ? arr.get(index++) : datum_t();
}
bool array_datum_stream_t::is_exhausted() const {
return index >= arr.arr_size();
}
bool array_datum_stream_t::is_cfeed() const {
return false;
}
bool array_datum_stream_t::is_infinite() const {
return false;
}
std::vector<datum_t>
array_datum_stream_t::next_raw_batch(env_t *env, const batchspec_t &batchspec) {
std::vector<datum_t> v;
batcher_t batcher = batchspec.to_batcher();
profile::sampler_t sampler("Fetching array elements.", env->trace);
datum_t d;
while (d = next_arr_el(), d.has()) {
batcher.note_el(d);
v.push_back(std::move(d));
if (batcher.should_send_batch()) {
break;
}
sampler.new_sample();
}
return v;
}
bool array_datum_stream_t::is_array() const {
return !is_grouped();
}
// INDEXED_SORT_DATUM_STREAM_T
indexed_sort_datum_stream_t::indexed_sort_datum_stream_t(
counted_t<datum_stream_t> stream,
std::function<bool(env_t *, // NOLINT(readability/casting)
profile::sampler_t *,
const datum_t &,
const datum_t &)> _lt_cmp)
: wrapper_datum_stream_t(stream), lt_cmp(_lt_cmp), index(0) { }
std::vector<datum_t>
indexed_sort_datum_stream_t::next_raw_batch(env_t *env, const batchspec_t &batchspec) {
std::vector<datum_t> ret;
batcher_t batcher = batchspec.to_batcher();
profile::sampler_t sampler("Sorting by index.", env->trace);
while (!batcher.should_send_batch()) {
if (index >= data.size()) {
if (ret.size() > 0
&& batchspec.get_batch_type() == batch_type_t::SINDEX_CONSTANT) {
// Never read more than one SINDEX_CONSTANT batch if we need to
// return an SINDEX_CONSTANT batch.
return ret;
}
index = 0;
data = source->next_batch(
env, batchspec.with_new_batch_type(batch_type_t::SINDEX_CONSTANT));
if (index >= data.size()) {
return ret;
}
std::stable_sort(data.begin(), data.end(),
std::bind(lt_cmp, env, &sampler, ph::_1, ph::_2));
}
for (; index < data.size() && !batcher.should_send_batch(); ++index) {
batcher.note_el(data[index]);
ret.push_back(std::move(data[index]));
}
}
return ret;
}
// ORDERED_DISTINCT_DATUM_STREAM_T
ordered_distinct_datum_stream_t::ordered_distinct_datum_stream_t(
counted_t<datum_stream_t> _source) : wrapper_datum_stream_t(_source) { }
std::vector<datum_t>
ordered_distinct_datum_stream_t::next_raw_batch(env_t *env, const batchspec_t &bs) {
std::vector<datum_t> ret;
profile::sampler_t sampler("Ordered distinct.", env->trace);
while (ret.size() == 0) {
std::vector<datum_t> v = source->next_batch(env, bs);
if (v.size() == 0) break;
for (auto &&el : v) {
if (!last_val.has() || last_val != el) {
last_val = el;
ret.push_back(std::move(el));
}
sampler.new_sample();
}
}
return ret;
}
// INDEXES_OF_DATUM_STREAM_T
indexes_of_datum_stream_t::indexes_of_datum_stream_t(counted_t<const func_t> _f,
counted_t<datum_stream_t> _source)
: wrapper_datum_stream_t(_source), f(_f), index(0) {
guarantee(f.has() && source.has());
}
std::vector<datum_t>
indexes_of_datum_stream_t::next_raw_batch(env_t *env, const batchspec_t &bs) {
std::vector<datum_t> ret;
profile::sampler_t sampler("Finding indexes_of eagerly.", env->trace);
while (ret.size() == 0) {
std::vector<datum_t> v = source->next_batch(env, bs);
if (v.size() == 0) {
break;
}
for (auto it = v.begin(); it != v.end(); ++it, ++index) {
if (f->filter_call(env, *it, counted_t<const func_t>())) {
ret.push_back(datum_t(static_cast<double>(index)));
}
sampler.new_sample();
}
}
return ret;
}
// SLICE_DATUM_STREAM_T
slice_datum_stream_t::slice_datum_stream_t(
uint64_t _left, uint64_t _right, counted_t<datum_stream_t> _src)
: wrapper_datum_stream_t(_src), index(0), left(_left), right(_right) { }
changefeed::keyspec_t slice_datum_stream_t::get_change_spec() {
if (left == 0) {
changefeed::keyspec_t subspec = source->get_change_spec();
auto *rspec = boost::get<changefeed::keyspec_t::range_t>(&subspec.spec);
if (rspec != NULL) {
std::copy(transforms.begin(), transforms.end(),
std::back_inserter(rspec->transforms));
return changefeed::keyspec_t(
changefeed::keyspec_t::limit_t{std::move(*rspec), right},
std::move(subspec.table),
std::move(subspec.table_name));
}
}
return wrapper_datum_stream_t::get_change_spec();
}
std::vector<datum_t>
slice_datum_stream_t::next_raw_batch(env_t *env, const batchspec_t &batchspec) {
if (left >= right || index >= right) {
return std::vector<datum_t>();
}
batcher_t batcher = batchspec.to_batcher();
profile::sampler_t sampler("Slicing eagerly.", env->trace);
std::vector<datum_t> ret;
while (index < left) {
sampler.new_sample();
std::vector<datum_t> v =
source->next_batch(env, batchspec.with_at_most(right - index));
if (v.size() == 0) {
return ret;
}
index += v.size();
if (index > right) {
v.resize(v.size() - (index - right));
index = right;
}
if (index > left) {
auto start = v.end() - (index - left);
for (auto it = start; it != v.end(); ++it) {
batcher.note_el(*it);
}
ret.reserve(index - left);
std::move(start, v.end(), std::back_inserter(ret));
}
}
while (index < right && !batcher.should_send_batch()) {
sampler.new_sample();
std::vector<datum_t> v =
source->next_batch(env, batchspec.with_at_most(right - index));
if (v.size() == 0) {
return ret;
}
index += v.size();
if (index > right) {
v.resize(v.size() - (index - right));
index = right;
}
for (const auto &d : v) {
batcher.note_el(d);
}
ret.reserve(ret.size() + v.size());
std::move(v.begin(), v.end(), std::back_inserter(ret));
}
r_sanity_check(index >= left);
r_sanity_check(index <= right);
return ret;
}
bool slice_datum_stream_t::is_exhausted() const {
return (left >= right || index >= right || source->is_exhausted())
&& batch_cache_exhausted();
}
bool slice_datum_stream_t::is_cfeed() const {
return source->is_cfeed();
}
bool slice_datum_stream_t::is_infinite() const {
return source->is_infinite() && right == std::numeric_limits<size_t>::max();
}
// UNION_DATUM_STREAM_T
void union_datum_stream_t::add_transformation(transform_variant_t &&tv,
const protob_t<const Backtrace> &bt) {
for (auto it = streams.begin(); it != streams.end(); ++it) {
(*it)->add_transformation(transform_variant_t(tv), bt);
}
update_bt(bt);
}
void union_datum_stream_t::accumulate(
env_t *env, eager_acc_t *acc, const terminal_variant_t &tv) {
for (auto it = streams.begin(); it != streams.end(); ++it) {
(*it)->accumulate(env, acc, tv);
}
}
void union_datum_stream_t::accumulate_all(env_t *env, eager_acc_t *acc) {
for (auto it = streams.begin(); it != streams.end(); ++it) {
(*it)->accumulate_all(env, acc);
}
}
bool union_datum_stream_t::is_array() const {
for (auto it = streams.begin(); it != streams.end(); ++it) {
if (!(*it)->is_array()) {
return false;
}
}
return true;
}
datum_t union_datum_stream_t::as_array(env_t *env) {
if (!is_array()) {
return datum_t();
}
datum_array_builder_t arr(env->limits());
batchspec_t batchspec = batchspec_t::user(batch_type_t::TERMINAL, env);
{
profile::sampler_t sampler("Evaluating stream eagerly.", env->trace);
datum_t d;
while (d = next(env, batchspec), d.has()) {
arr.add(d);
sampler.new_sample();
}
}
return std::move(arr).to_datum();
}
bool union_datum_stream_t::is_exhausted() const {
for (auto it = streams.begin(); it != streams.end(); ++it) {
if (!(*it)->is_exhausted()) {
return false;
}
}
return batch_cache_exhausted();
}
bool union_datum_stream_t::is_cfeed() const {
return is_cfeed_union;
}
bool union_datum_stream_t::is_infinite() const {
return is_infinite_union;
}
std::vector<datum_t>
union_datum_stream_t::next_batch_impl(env_t *env, const batchspec_t &batchspec) {
for (; streams_index < streams.size(); ++streams_index) {
std::vector<datum_t> batch
= streams[streams_index]->next_batch(env, batchspec);
if (batch.size() != 0 || streams[streams_index]->is_cfeed()) {
return batch;
}
}
return std::vector<datum_t>();
}
// RANGE_DATUM_STREAM_T
range_datum_stream_t::range_datum_stream_t(bool _is_infinite_range,
int64_t _start,
int64_t _stop,
const protob_t<const Backtrace> &bt_source)
: eager_datum_stream_t(bt_source),
is_infinite_range(_is_infinite_range),
start(_start),
stop(_stop) { }
std::vector<datum_t>
range_datum_stream_t::next_raw_batch(env_t *, const batchspec_t &batchspec) {
rcheck(!is_infinite_range
|| batchspec.get_batch_type() == batch_type_t::NORMAL
|| batchspec.get_batch_type() == batch_type_t::NORMAL_FIRST,
base_exc_t::GENERIC,
"Cannot use an infinite stream with an aggregation function (`reduce`, `count`, etc.) or coerce it to an array.");
std::vector<datum_t> batch;
// 500 is picked out of a hat for latency, primarily in the Data Explorer. If you
// think strongly it should be something else you're probably right.
batcher_t batcher = batchspec.with_at_most(500).to_batcher();
while (!is_exhausted()) {
double next = safe_to_double(start++);
// `safe_to_double` returns NaN on error, which signals that `start` is larger
// than 2^53 indicating we've reached the end of our infinite stream. This must
// be checked before creating a `datum_t` as that does a similar check on
// construction.
rcheck(risfinite(next), base_exc_t::GENERIC,
"`range` out of safe double bounds.");
batch.emplace_back(next);
batcher.note_el(batch.back());
if (batcher.should_send_batch()) {
break;
}
}
return batch;
}
bool range_datum_stream_t::is_exhausted() const {
return !is_infinite_range && start >= stop && batch_cache_exhausted();
}
// MAP_DATUM_STREAM_T
map_datum_stream_t::map_datum_stream_t(std::vector<counted_t<datum_stream_t> > &&_streams,
counted_t<const func_t> &&_func,
const protob_t<const Backtrace> &bt_src)
: eager_datum_stream_t(bt_src), streams(std::move(_streams)), func(std::move(_func)),
is_array_map(true), is_cfeed_map(false), is_infinite_map(true) {
for (const auto &stream : streams) {
is_array_map &= stream->is_array();
is_cfeed_map |= stream->is_cfeed();
is_infinite_map &= stream->is_infinite();
}
}
std::vector<datum_t>
map_datum_stream_t::next_raw_batch(env_t *env, const batchspec_t &batchspec) {
rcheck(!is_infinite_map
|| batchspec.get_batch_type() == batch_type_t::NORMAL
|| batchspec.get_batch_type() == batch_type_t::NORMAL_FIRST,
base_exc_t::GENERIC,
"Cannot use an infinite stream with an aggregation function (`reduce`, `count`, etc.) or coerce it to an array.");
std::vector<datum_t> batch;
batcher_t batcher = batchspec.to_batcher();
std::vector<datum_t> args;
args.reserve(streams.size());
// We need a separate batchspec for the streams to prevent calling `stream->next`
// with a `batch_type_t::TERMINAL` on an infinite stream.
batchspec_t batchspec_inner = batchspec_t::default_for(batch_type_t::NORMAL);
while (!is_exhausted()) {
args.clear(); // This prevents allocating a new vector every iteration.
for (const auto &stream : streams) {
args.push_back(stream->next(env, batchspec_inner));
}
datum_t datum = func->call(env, args)->as_datum();
batcher.note_el(datum);
batch.push_back(std::move(datum));
if (batcher.should_send_batch()) {
break;
}
}
return batch;
}
bool map_datum_stream_t::is_exhausted() const {
for (const auto &stream : streams) {
if (stream->is_exhausted()) {
return batch_cache_exhausted();
}
}
return false;
}
vector_datum_stream_t::vector_datum_stream_t(
const protob_t<const Backtrace> &bt_source,
std::vector<datum_t> &&_rows,
boost::optional<ql::changefeed::keyspec_t> &&_changespec) :
eager_datum_stream_t(bt_source),
rows(std::move(_rows)),
index(0),
changespec(std::move(_changespec)) { }
datum_t vector_datum_stream_t::next(
env_t *env, const batchspec_t &bs) {
if (ops_to_do()) {
return datum_stream_t::next(env, bs);
}
return next_impl(env);
}
datum_t vector_datum_stream_t::next_impl(env_t *) {
if (index < rows.size()) {
return std::move(rows[index++]);
} else {
return datum_t();
}
}
std::vector<datum_t> vector_datum_stream_t::next_raw_batch(
env_t *env, const batchspec_t &bs) {
std::vector<datum_t> v;
batcher_t batcher = bs.to_batcher();
datum_t d;
while (d = next_impl(env), d.has()) {
batcher.note_el(d);
v.push_back(std::move(d));
if (batcher.should_send_batch()) {
break;
}
}
return v;
}
bool vector_datum_stream_t::is_exhausted() const {
return index == rows.size();
}
bool vector_datum_stream_t::is_cfeed() const {
return false;
}
bool vector_datum_stream_t::is_array() const {
return false;
}
bool vector_datum_stream_t::is_infinite() const {
return false;
}
changefeed::keyspec_t vector_datum_stream_t::get_change_spec() {
if (static_cast<bool>(changespec)) {
return *changespec;
} else {
rfail(base_exc_t::GENERIC, "%s", "Cannot call `changes` on this stream.");
}
}
} // namespace ql
| agpl-3.0 |
MartinHaeusler/chronos | org.chronos.benchmarks/src/test/java/org/chronos/benchmarks/chronosphere/itlandscape/ItLandscapeBenchmark.java | 19806 | package org.chronos.benchmarks.chronosphere.itlandscape;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.chronos.benchmarks.util.BenchmarkUtils;
import org.chronos.chronodb.api.Order;
import org.chronos.chronodb.internal.api.ChronoDBConfiguration;
import org.chronos.chronodb.internal.util.ChronosBackend;
import org.chronos.chronodb.test.base.AllBackendsTest.DontRunWithBackend;
import org.chronos.chronodb.test.base.InstantiateChronosWith;
import org.chronos.chronograph.internal.api.configuration.ChronoGraphConfiguration;
import org.chronos.chronosphere.api.ChronoSphere;
import org.chronos.chronosphere.api.ChronoSphereTransaction;
import org.chronos.chronosphere.api.query.Direction;
import org.chronos.chronosphere.emf.api.ChronoEObject;
import org.chronos.chronosphere.emf.internal.util.EMFUtils;
import org.chronos.chronosphere.internal.api.ChronoSphereInternal;
import org.chronos.chronosphere.test.base.AllChronoSphereBackendsTest;
import org.chronos.common.test.junit.categories.PerformanceTest;
import org.chronos.common.test.utils.Statistic;
import org.chronos.common.test.utils.TimeStatistics;
import org.eclipse.emf.ecore.*;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Category(PerformanceTest.class)
@DontRunWithBackend({ChronosBackend.INMEMORY, ChronosBackend.JDBC, ChronosBackend.MAPDB, ChronosBackend.TUPL})
public class ItLandscapeBenchmark extends AllChronoSphereBackendsTest {
// =================================================================================================================
// ROOT CAUSE ANALYSIS
// =================================================================================================================
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "500000")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "100")
@InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE")
@InstantiateChronosWith(property = ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, value = "off")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void rootCauseAnalysis() throws Exception {
ChronoSphereInternal sphere = this.setUpChronoSphereITLandscape();
System.gc();
System.gc();
System.gc();
// Root Cause Analysis
Statistic rcaStats = new Statistic();
System.out.println("BEGINNING WARMUP");
// warmup
for (int i = 0; i < 10; i++) {
this.runRootCauseAnalysis(sphere);
}
System.out.println("WARMUP COMPLETE");
// actual benchmark runs
for (int i = 0; i < 10; i++) {
rcaStats.addSample(this.runRootCauseAnalysis(sphere));
}
// print the results
System.out.println("RCA: " + new TimeStatistics(rcaStats).toCSV());
System.out.println("RCA Samples: " + new TimeStatistics(rcaStats).getRuntimes());
}
private long runRootCauseAnalysis(final ChronoSphereInternal sphere) {
try (ChronoSphereTransaction tx = sphere.tx()) {
EClass service = tx.getEClassBySimpleName("Service");
EClass virtualHost = tx.getEClassBySimpleName("VirtualHost");
EClass physicalMachine = tx.getEClassBySimpleName("PhysicalMachine");
EClass application = tx.getEClassBySimpleName("Application");
EReference hostRunsOn = EMFUtils.getEReference(virtualHost, "runsOn");
EReference appRunsOn = EMFUtils.getEReference(application, "runsOn");
EReference dependsOn = EMFUtils.getEReference(service, "dependsOn");
List<EObject> services = tx.find().startingFromInstancesOf(service).toList();
Collections.shuffle(services);
TimeStatistics statistics = new TimeStatistics();
long sum = 0;
for (int i = 0; i < 1000; i++) {
EObject s = services.get(i);
statistics.beginRun();
Set<EObject> result = tx.find()
.startingFromEObject(s)
.eGet(dependsOn).eGet(appRunsOn)
.closure(hostRunsOn).isInstanceOf(physicalMachine, false)
.toSet();
statistics.endRun();
sum += result.size();
}
System.out.println("ROOT CAUSE ANALYSIS");
System.out.println(" Time: " + statistics.getTotalTime() + "ms");
System.out.println(" Hits: " + sum);
return statistics.getTotalTime();
}
}
// =================================================================================================================
// IMPACT ANALYSIS
// =================================================================================================================
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "500000")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "100")
@InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE")
@InstantiateChronosWith(property = ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, value = "off")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void impactAnalysis() throws Exception {
ChronoSphereInternal sphere = this.setUpChronoSphereITLandscape();
System.gc();
System.gc();
System.gc();
// Impact Analysis
Statistic imaStats = new Statistic();
System.out.println("BEGINNING WARMUP");
// warmup
for (int i = 0; i < 10; i++) {
this.runImpactAnalysis(sphere);
}
System.out.println("WARMUP COMPLETE");
// actual benchmark runs
for (int i = 0; i < 10; i++) {
imaStats.addSample(this.runImpactAnalysis(sphere));
}
// print the results
System.out.println("IMA: " + new TimeStatistics(imaStats).toCSV());
System.out.println("IMA Samples: " + new TimeStatistics(imaStats).getRuntimes());
}
private long runImpactAnalysis(final ChronoSphereInternal sphere) {
try (ChronoSphereTransaction tx = sphere.tx()) {
EClass service = tx.getEClassBySimpleName("Service");
EClass virtualHost = tx.getEClassBySimpleName("VirtualHost");
EClass physicalMachine = tx.getEClassBySimpleName("PhysicalMachine");
EClass application = tx.getEClassBySimpleName("Application");
EReference hostRunsOn = EMFUtils.getEReference(virtualHost, "runsOn");
EReference appRunsOn = EMFUtils.getEReference(application, "runsOn");
EReference dependsOn = EMFUtils.getEReference(service, "dependsOn");
List<EObject> machines = tx.find().startingFromInstancesOf(physicalMachine).toList();
Collections.shuffle(machines);
TimeStatistics statistics = new TimeStatistics();
long sum = 0;
for (int i = 0; i < 10; i++) {
EObject s = machines.get(i);
statistics.beginRun();
Set<EObject> result = tx.find()
.startingFromEObject(s)
// TODO: this query only considers App-[runsOn]->VirtualHost-[runsOn]->PhysicalMachine.
// This query currently ignores the [App]-[runsOn]->PhysicalMachine relationship.
.closure(hostRunsOn, Direction.INCOMING)
.eGetInverse(appRunsOn)
.eGetInverse(dependsOn)
.toSet();
statistics.endRun();
sum += result.size();
}
System.out.println("IMPACT ANALYSIS");
System.out.println(" Time: " + statistics.getTotalTime() + "ms");
System.out.println(" Hits: " + sum);
return statistics.getTotalTime();
}
}
// =================================================================================================================
// FIND BY NAME
// =================================================================================================================
private static final List<String> PHYSICAL_MACHINE_BASE_NAMES =
ImmutableList.of(
"IBM Power S822",
"IBM Power S814",
"IBM Power S824",
"IBM Power 710",
"IBM Power 720",
"Lenovo x440",
"Lenovo ThinkSystem SN550",
"Lenovo ThinkSystem SN850",
"Lenovo ThinkSystem SR950",
"Lenovo ThinkSystem SR860",
"Lenovo ThinkSystem x880",
"Lenovo ThinkSystem x480",
"HPE ProLiant BL460c",
"HPE ProLiant BL660c",
"HPE ProLiant WS460c",
"HPE ProLiant DL385",
"HPE ProLiant XL190r"
);
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "500000")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "100")
@InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE")
@InstantiateChronosWith(property = ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, value = "off")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void findByName() throws Exception {
ChronoSphereInternal sphere = this.setUpChronoSphereITLandscape();
// Find By Name
Statistic fbnStats = new Statistic();
System.out.println("BEGINNING WARMUP");
// warmup
for (int i = 0; i < 10; i++) {
this.runFindByName(sphere);
}
System.out.println("WARMUP COMPLETE");
// actual benchmark runs
for (int i = 0; i < 10; i++) {
fbnStats.addSample(this.runFindByName(sphere));
}
// print the results
System.out.println("FBN: " + new TimeStatistics(fbnStats).toCSV());
System.out.println("FBN Samples: " + new TimeStatistics(fbnStats).getRuntimes());
}
private long runFindByName(final ChronoSphereInternal sphere) {
try (ChronoSphereTransaction tx = sphere.tx()) {
EClass physicalMachine = tx.getEClassBySimpleName("PhysicalMachine");
EAttribute name = EMFUtils.getEAttribute(physicalMachine, "name");
TimeStatistics statistics = new TimeStatistics();
long sum = 0;
for (int i = 0; i < 100; i++) {
String randomName = BenchmarkUtils.getRandomEntryOf(PHYSICAL_MACHINE_BASE_NAMES);
int number = BenchmarkUtils.randomBetween(0, 100);
randomName += " " + number;
statistics.beginRun();
Set<EObject> result = tx.find()
.startingFromInstancesOf(physicalMachine)
.has(name, randomName)
.toSet();
statistics.endRun();
sum += result.size();
}
System.out.println("FIND BY NAME");
System.out.println(" Time: " + statistics.getTotalTime() + "ms");
System.out.println(" Hits: " + sum);
return statistics.getTotalTime();
}
}
// =================================================================================================================
// ASSETS OVER TIME
// =================================================================================================================
@Test
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHING_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.CACHE_MAX_SIZE, value = "500000")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_ENABLED, value = "true")
@InstantiateChronosWith(property = ChronoDBConfiguration.QUERY_CACHE_MAX_SIZE, value = "100")
@InstantiateChronosWith(property = ChronoDBConfiguration.COMMIT_CONFLICT_RESOLUTION_STRATEGY, value = "OVERWRITE_WITH_SOURCE")
@InstantiateChronosWith(property = ChronoDBConfiguration.DUPLICATE_VERSION_ELIMINATION_MODE, value = "off")
@InstantiateChronosWith(property = ChronoGraphConfiguration.TRANSACTION_CHECK_ID_EXISTENCE_ON_ADD, value = "false")
public void assetsOverTime() throws Exception {
ChronoSphereInternal sphere = this.setUpChronoSphereITLandscape();
int additionsPerDay = 300;
int deletionsPerDay = 50;
List<String> eObjectIdsInHead = sphere.tx()
.find()
.startingFromAllEObjects()
.toStream()
.map(it -> (ChronoEObject) it)
.map(ChronoEObject::getId)
.distinct()
.collect(Collectors.toList());
long minTimestamp = sphere.getNow();
// simulate one year of changes
System.out.println("Simulating 1 year of changes...");
for (int day = 1; day <= 365; day++) {
ChronoSphereTransaction dayTransaction = sphere.tx();
EClass physicalMachine = dayTransaction.getEClassBySimpleName("PhysicalMachine");
EClass virtualMachine = dayTransaction.getEClassBySimpleName("VirtualMachine");
EClass service = dayTransaction.getEClassBySimpleName("Service");
EClass cluster = dayTransaction.getEClassBySimpleName("Cluster");
EClass application = dayTransaction.getEClassBySimpleName("Application");
List<EClass> eClasses = Lists.newArrayList(physicalMachine, virtualMachine, service, cluster, application);
List<String> newEObjectIds = Lists.newArrayList();
// create the elements
for (int addition = 0; addition < additionsPerDay; addition++) {
EClass eClass = BenchmarkUtils.getRandomEntryOf(eClasses);
ChronoEObject eObject = (ChronoEObject) dayTransaction.createAndAttach(eClass);
newEObjectIds.add(eObject.getId());
}
// delete some other elements
for (int deletion = 0; deletion < deletionsPerDay; deletion++) {
String randomId = BenchmarkUtils.getRandomEntryOf(eObjectIdsInHead);
ChronoEObject eObject = dayTransaction.getEObjectById(randomId);
eObjectIdsInHead.remove(eObject.getId());
dayTransaction.delete(eObject, false);
}
eObjectIdsInHead.addAll(newEObjectIds);
dayTransaction.commit();
System.out.println("Completed Simulation of Day " + day);
}
// assets over time
Statistic aotStats = new Statistic();
System.out.println("BEGINNING WARMUP");
// warmup
for (int i = 0; i < 10; i++) {
this.runAssetsOverTime(sphere, i, minTimestamp);
}
System.out.println("WARMUP COMPLETE");
// actual benchmark runs
for (int i = 0; i < 10; i++) {
aotStats.addSample(this.runAssetsOverTime(sphere, i + 5, minTimestamp));
}
// print the results
System.out.println("AOT: " + new TimeStatistics(aotStats).toCSV());
System.out.println("AOT Samples: " + new TimeStatistics(aotStats).getRuntimes());
}
private long runAssetsOverTime(ChronoSphere sphere, int commitIndexOffset, long minTimestamp) {
long now = sphere.getNow();
TimeStatistics statistics = new TimeStatistics();
long sum = 0;
// retrieve the last 365 commits
List<Long> commits = Lists.newArrayList(sphere.getCommitTimestampsPaged(minTimestamp, now, 365, 0, Order.ASCENDING));
for (int month = 0; month < 12; month++) {
int commitIndex = month * 30 + commitIndexOffset;
long commitTimestamp = commits.get(commitIndex);
try (ChronoSphereTransaction tx = sphere.tx(commitTimestamp)) {
EClass service = tx.getEClassBySimpleName("Service");
statistics.beginRun();
long count = tx.find().startingFromInstancesOf(service).count();
statistics.endRun();
sum += count;
}
}
// print the results
System.out.println("ASSETS OVER TIME");
System.out.println(" Time: " + statistics.getTotalTime() + "ms");
System.out.println(" Hits: " + sum);
return statistics.getTotalTime();
}
// =================================================================================================================
// HELPER METHODS
// =================================================================================================================
private ChronoSphereInternal setUpChronoSphereITLandscape() throws IOException {
final List<EPackage> ePackages;
{
String path = "ecoremodels/itlandscape.ecore";
InputStream stream = this.getClass().getClassLoader().getResourceAsStream(path);
String ecoreContents = IOUtils.toString(stream, StandardCharsets.UTF_8);
ePackages = EMFUtils.readEPackagesFromXMI(ecoreContents);
}
ChronoSphereInternal sphere = this.getChronoSphere();
sphere.getEPackageManager().registerOrUpdateEPackages(ePackages);
try (ChronoSphereTransaction tx = sphere.tx()) {
EAttribute name = tx.getEAttributeByQualifiedName("itlandscape::Element#name");
sphere.getIndexManager().createIndexOn(name);
tx.commit();
}
System.out.println("IT-Landscape Ecore metamodel loaded.");
final String xmiContent;
{
String path = "ecoremodels/ITLandscape200k.xmi";
InputStream stream = this.getClass().getClassLoader().getResourceAsStream(path);
xmiContent = IOUtils.toString(stream, StandardCharsets.UTF_8);
}
System.out.println("XMI loaded to string.");
try (ChronoSphereTransaction tx = sphere.tx()) {
Set<EPackage> packs = tx.getEPackages();
List<EObject> eObjectsFromXMI = EMFUtils.readEObjectsFromXMI(xmiContent, packs);
System.out.println("EObjects loaded from XMI");
long timeBeforeLoad = System.currentTimeMillis();
tx.attach(eObjectsFromXMI);
tx.commit();
long timeAfterLoad = System.currentTimeMillis();
System.out.println("Loading the 200k ITLandscape XMI took " + (timeAfterLoad - timeBeforeLoad) + "ms.");
}
return sphere;
}
}
| agpl-3.0 |
jdpage/caesura | caesura/server/web/server.py | 3455 | """HTTP server component.
"""
__author__ = "Jonathan David Page"
__copyright__ = "Copyright 2014, Jonathan David Page"
import logging
import asyncio
from aiohttp.server import ServerHttpProtocol
import aiohttp
import time
from werkzeug.routing import Map, Rule, NotFound, RequestRedirect
from . import api
logger = logging.getLogger(__name__)
# goal: select all five iron tracks
# GET /metadata/tracks?group.name=Five+Iron+Frenzy
# goal: select Black Sabbath albums with Dio singing
# GET /metadata/albums?group.name=Black+Sabbath&group.singer.name_contains=Dio
# goal: select GY!BE releases from after they moved the exclamation point
# GET /metadata/releases?group.under_name=Godspeed+You%21+Black+Emperor
# searchable endpoints:
# groups
# people
# albums
# releases
# songs
# tracks
# quantifiers:
# under_
# all_
# any_
# some_
# no_
# matches:
# _is
# _contains
# _in
class WebRouter(ServerHttpProtocol):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.api_root = '/'
self.url_map = Map([
Rule('/',
endpoint=api.ServerInfoEndpoint),
Rule('/paged_query',
endpoint=api.PagedQueryEndpoint),
Rule('/metadata',
endpoint=api.MetadataInfoEndpoint),
Rule('/metadata/groups',
endpoint=api.GroupCollectionEndpoint),
Rule('/metadata/groups/<int:id>',
endpoint=api.GroupEndpoint),
Rule('/metadata/people',
endpoint=api.PeopleCollectionEndpoint),
Rule('/metadata/people/<int:id>',
endpoint=api.PeopleEndpoint),
Rule('/metadata/albums',
endpoint=api.AlbumCollectionEndpoint),
Rule('/metadata/albums/<int:id>',
endpoint=api.AlbumEndpoint),
Rule('/metadata/songs',
endpoint=api.SongCollectionEndpoint),
Rule('/metadata/songs/<int:id>',
endpoint=api.SongEndpoint),
Rule('/metadata/tracks',
endpoint=api.TrackCollectionEndpoint),
Rule('/metadata/tracks/<int:id>',
endpoint=api.TrackEndpoint),
Rule('/audio',
endpoint=api.AudioCollectionEndpoint),
Rule('/audio/<audio_name>.<format>',
endpoint=api.AudioEndpoint),
Rule('/users',
endpoint=api.UserCollectionEndpoint),
Rule('/users/<user_id>',
endpoint=api.UserEndpoint),
Rule('/users/<user_id>/playlists',
endpoint=api.PlaylistCollectionEndpoint),
Rule('/users/<user_id>/playlists/<pl_id>',
endpoint=api.PlaylistEndpoint),
Rule('/users/<user_id>/playlists/<pl_id>/<entry_id>',
endpoint=api.PlaylistEntryEndpoint)
])
@asyncio.coroutine
def handle_request(self, message, payload):
now = time.time()
urls = self.url_map.bind(message.headers['HOST'], self.api_root)
try:
endpoint_type, path_args = urls.match(message.path)
except NotFound:
endpoint_type, path_args = api.NotFoundEndpoint, {}
endpoint = endpoint_type(self)
response = yield from endpoint.handle(path_args, message, payload)
self.log_access(message, None, response, time.time() - now)
| agpl-3.0 |
veo-labs/openveo-core | app/client/admin/js/ov/ApplicationController.js | 6218 | 'use strict';
(function(app) {
/**
* Defines the user controller for the user page.
*/
function ApplicationController($scope, $filter, entityService, scopes) {
var entityType = 'applications';
/**
* Translates name and description of each scope.
*/
function translateScopes() {
angular.forEach($scope.scopes, function(value) {
value.name = $filter('translate')(value.name);
value.description = $filter('translate')(value.description);
});
}
/**
* Removes a list of applications.
*
* @param {Array} selected The list of application ids to remove
* @param {Function} reload The reload Function to force reloading the table
*/
function removeRows(selected, reload) {
entityService.removeEntities(entityType, null, selected.join(','))
.then(function() {
$scope.$emit('setAlert', 'success', $filter('translate')('CORE.APPLICATIONS.REMOVE_SUCCESS'), 4000);
reload();
});
}
/**
* Saves application.
*
* @param {Object} application The application to save
* @return {Promise} Promise resolving when application has been saved
*/
function saveApplication(application) {
return entityService.updateEntity(entityType, null, application.id, {
name: application.name,
scopes: application.scopes
});
}
/**
* Adds an application.
*
* @param {Object} application The application to add
* @return {Promise} Promise resolving when application has been added
*/
function addApplication(application) {
return entityService.addEntities(entityType, null, [application]);
}
$scope.scopes = scopes.data.scopes;
translateScopes();
/*
*
* RIGHTS
*
*/
$scope.rights = {};
$scope.rights.add = $scope.checkAccess('core-add-' + entityType);
$scope.rights.edit = $scope.checkAccess('core-update-' + entityType);
$scope.rights.delete = $scope.checkAccess('core-delete-' + entityType);
/*
*
* DATATABLE
*/
var scopeDataTable = $scope.tableContainer = {};
scopeDataTable.entityType = entityType;
scopeDataTable.filterBy = [
{
key: 'query',
value: '',
label: $filter('translate')('CORE.APPLICATIONS.QUERY_FILTER')
}
];
scopeDataTable.header = [{
key: 'name',
name: $filter('translate')('CORE.APPLICATIONS.NAME_COLUMN'),
class: ['col-xs-11']
},
{
key: 'action',
name: $filter('translate')('CORE.UI.ACTIONS_COLUMN'),
class: ['col-xs-1']
}];
scopeDataTable.actions = [{
label: $filter('translate')('CORE.UI.REMOVE'),
warningPopup: true,
condition: function(row) {
return $scope.rights.delete && !row.locked && !row.saving;
},
callback: function(row, reload) {
removeRows([row.id], reload);
},
global: function(selected, reload) {
removeRows(selected, reload);
}
}];
/*
* FORM
*/
var scopeEditForm = $scope.editFormContainer = {};
scopeEditForm.model = {};
scopeEditForm.entityType = entityType;
scopeEditForm.init = function(row) {
scopeEditForm.fields[1].templateOptions.message = row.id;
scopeEditForm.fields[2].templateOptions.message = row.secret;
};
scopeEditForm.fields = [
{
key: 'name',
type: 'horizontalEditableInput',
templateOptions: {
label: $filter('translate')('CORE.APPLICATIONS.ATTR_NAME'),
required: true
}
},
{
noFormControl: true,
type: 'emptyrow',
templateOptions: {
label: $filter('translate')('CORE.APPLICATIONS.ATTR_ID'),
message: ''
}
},
{
noFormControl: true,
type: 'emptyrow',
templateOptions: {
label: $filter('translate')('CORE.APPLICATIONS.ATTR_SECRET'),
message: ''
}
}
];
if ($scope.scopes.length != 0)
scopeEditForm.fields.push(
{
key: 'scopes',
type: 'horizontalEditableMultiCheckbox',
templateOptions: {
label: $filter('translate')('CORE.APPLICATIONS.ATTR_SCOPES'),
options: $scope.scopes,
valueProperty: 'id',
labelProperty: 'name'
}
}
);
scopeEditForm.conditionEditDetail = function(row) {
return $scope.rights.edit && !row.locked;
};
scopeEditForm.onSubmit = function(model) {
return saveApplication(model);
};
/*
* FORM Add user
*
*/
var scopeAddForm = $scope.addFormContainer = {};
scopeAddForm.model = {};
scopeAddForm.fields = [
{
// the key to be used in the model values
// so this will be bound to vm.user.username
key: 'name',
type: 'horizontalInput',
templateOptions: {
label: $filter('translate')('CORE.APPLICATIONS.FORM_ADD_NAME'),
required: true,
description: $filter('translate')('CORE.APPLICATIONS.FORM_ADD_NAME_DESC')
}
}
];
if ($scope.scopes.length == 0)
scopeAddForm.fields.push({
noFormControl: true,
template: '<p>' + $filter('translate')('CORE.APPLICATIONS.NO_APPLICATIONS') + '</p>'
});
else
scopeAddForm.fields.push({
key: 'scopes',
type: 'horizontalMultiCheckbox',
templateOptions: {
label: $filter('translate')('CORE.APPLICATIONS.FORM_ADD_SCOPES'),
required: false,
options: $scope.scopes,
valueProperty: 'id',
labelProperty: 'name',
description: $filter('translate')('CORE.APPLICATIONS.FORM_ADD_SCOPES_DESC')
},
expressionProperties: {
'templateOptions.disabled': '!model.name' // disabled when username is blank
}
});
scopeAddForm.onSubmit = function(model) {
return addApplication(model);
};
}
app.controller('ApplicationController', ApplicationController);
ApplicationController.$inject = ['$scope', '$filter', 'entityService', 'scopes'];
})(angular.module('ov'));
| agpl-3.0 |
swalladge/hit326-project | src/Model/Entity/OpeningHour.php | 687 | <?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
/**
* OpeningHour Entity
*
* @property int $id
* @property int $weekday
* @property string $start_time
* @property string $end_time
*/
class OpeningHour extends Entity
{
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
* be mass assigned. For security purposes, it is advised to set '*' to false
* (or remove it), and explicitly make individual fields accessible as needed.
*
* @var array
*/
protected $_accessible = [
'*' => true,
'id' => false
];
}
| agpl-3.0 |
StartupdotSC/Lemyr | app/models/user_status.rb | 453 | class UserStatus < ActiveRecord::Base
belongs_to :user
belongs_to :checkin_status
attr_accessible :checkin, :checkin_status_id, :comment, :user_id, :user
def self.get_currently_checked_in()
checkins = []
User.where("last_status_id IS NOT NULL").each do |u|
status = UserStatus.find(u.last_status_id)
checkins << status if status.checkin
end
checkins
end
def display_name
checkin_status.label
end
end
| agpl-3.0 |
RojavaCrypto/libbitcoin-c | include/bitcoin/bitcoin/c/internal/chain/script/operation.hpp | 1576 | /**
* Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_C_INTERNAL_CHAIN_SCRIPT_OPERATION_HPP
#define LIBBITCOIN_C_INTERNAL_CHAIN_SCRIPT_OPERATION_HPP
#include <bitcoin/bitcoin/c/chain/script/operation.h>
#include <vector>
#include <bitcoin/bitcoin/chain/script/operation.hpp>
#include <bitcoin/bitcoin/c/internal/utility/vector.hpp>
BC_DECLARE_VECTOR_INTERNAL(operation_stack, bc_operation_t,
libbitcoin::chain::operation::stack);
extern "C" {
struct bc_operation_t
{
libbitcoin::chain::operation* obj;
};
} // extern C
// C++ convenience functions
bc_script_pattern_t bc_script_pattern_to_ctype(
libbitcoin::chain::script_pattern value);
libbitcoin::chain::script_pattern bc_script_pattern_from_ctype(
bc_script_pattern_t value);
#endif
| agpl-3.0 |
Vauxoo/stock-logistics-warehouse | stock_request_kanban/tests/test_inventory_kanban.py | 4353 | # Copyright 2017 Creu Blanca
# Copyright 2017 Eficent Business and IT Consulting Services, S.L.
# License LGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from .base_test import TestBaseKanban
class TestKanban(TestBaseKanban):
def setUp(self):
super().setUp()
self.main_company = self.env.ref('base.main_company')
self.route = self.env['stock.location.route'].create({
'name': 'Transfer',
'product_categ_selectable': False,
'product_selectable': True,
'company_id': self.main_company.id,
'sequence': 10,
})
self.product = self.env['product.product'].create({
'name': 'Product',
'route_ids': [(4, self.route.id)],
'company_id': False,
})
self.product_2 = self.env['product.product'].create({
'name': 'Product 2',
'route_ids': [(4, self.route.id)],
'company_id': False,
})
self.kanban_1 = self.env['stock.request.kanban'].create({
'product_id': self.product.id,
'product_uom_id': self.product.uom_id.id,
'product_uom_qty': 1,
})
self.kanban_2 = self.env['stock.request.kanban'].create({
'product_id': self.product.id,
'product_uom_id': self.product.uom_id.id,
'product_uom_qty': 1,
})
self.kanban_3 = self.env['stock.request.kanban'].create({
'product_id': self.product_2.id,
'product_uom_id': self.product.uom_id.id,
'product_uom_qty': 1,
})
def test_inventory_warehouse(self):
inventory = self.env['stock.inventory.kanban'].create({
'warehouse_ids': [(4, self.kanban_1.warehouse_id.id)],
})
inventory.start_inventory()
self.assertIn(self.kanban_1, inventory.kanban_ids)
self.assertIn(self.kanban_1, inventory.missing_kanban_ids)
def test_inventory_location(self):
inventory = self.env['stock.inventory.kanban'].create({
'location_ids': [(4, self.kanban_1.location_id.id)],
})
inventory.start_inventory()
self.assertIn(self.kanban_1, inventory.kanban_ids)
self.assertIn(self.kanban_1, inventory.missing_kanban_ids)
def test_inventory_product(self):
inventory = self.env['stock.inventory.kanban'].create({
'product_ids': [(4, self.product.id)],
})
inventory.start_inventory()
self.assertIn(self.kanban_1, inventory.kanban_ids)
self.assertNotIn(self.kanban_3, inventory.kanban_ids)
self.assertIn(self.kanban_1, inventory.missing_kanban_ids)
self.assertEqual(inventory.state, 'in_progress')
wizard = self.env['wizard.stock.inventory.kanban'].with_context(
default_inventory_kanban_id=inventory.id
).create({})
self.pass_code(wizard, self.kanban_3.name)
self.assertEqual(wizard.status_state, 1)
self.pass_code(wizard, self.kanban_1.name)
self.assertEqual(wizard.status_state, 0)
self.assertNotIn(self.kanban_1, inventory.missing_kanban_ids)
self.assertIn(self.kanban_1, inventory.scanned_kanban_ids)
self.pass_code(wizard, self.kanban_1.name)
self.assertEqual(wizard.status_state, 1)
self.assertNotIn(self.kanban_1, inventory.missing_kanban_ids)
self.assertIn(self.kanban_1, inventory.scanned_kanban_ids)
inventory.finish_inventory()
self.assertEqual(inventory.state, 'finished')
inventory.close_inventory()
self.assertEqual(inventory.state, 'closed')
def test_cancel_inventory(self):
inventory = self.env['stock.inventory.kanban'].create({
'product_ids': [(4, self.product.id)],
})
inventory.start_inventory()
self.assertIn(self.kanban_1, inventory.kanban_ids)
self.assertNotIn(self.kanban_3, inventory.kanban_ids)
self.assertIn(self.kanban_1, inventory.missing_kanban_ids)
self.assertEqual(inventory.state, 'in_progress')
inventory.cancel()
self.assertEqual(inventory.state, 'cancelled')
inventory.to_draft()
self.assertEqual(inventory.state, 'draft')
self.assertFalse(inventory.kanban_ids)
self.assertFalse(inventory.scanned_kanban_ids)
| agpl-3.0 |
strongswan/strongTNC | apps/swid/migrations/0003_tag_version.py | 479 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('packages', '__first__'),
('swid', '0002_rename_to_version_str'),
]
operations = [
migrations.AddField(
model_name='tag',
name='version',
field=models.ForeignKey(to='packages.Version', null=True, on_delete=models.CASCADE),
),
]
| agpl-3.0 |
helloimcasper/GalaxyEmulator | galaxy.core/habbolib/catalog/CatalogPage.cs | 4592 | using System.Collections.Generic;
namespace galaxy.core.habbolib.catalog
{
public class CatalogPage
{
private int _id;
private int _parentId;
private string _caption;
private string _pageLink;
private int _icon;
private int _minRank;
private int _minVIP;
private bool _visible;
private bool _enabled;
private string _template;
private List<string> _pageStrings1;
private List<string> _pageStrings2;
private Dictionary<int, CatalogItem> _items;
private Dictionary<int, CatalogItem> _itemOffers;
public CatalogPage(int Id, int ParentId, string Enabled, string Caption, string PageLink, int Icon, int MinRank, int MinVIP,
string Visible, string Template, string PageStrings1, string PageStrings2, Dictionary<int, CatalogItem> Items, ref Dictionary<int, int> flatOffers)
{
this._id = Id;
this._parentId = ParentId;
this._enabled = Enabled.ToLower() == "1" ? true : false;
this._caption = Caption;
this._pageLink = PageLink;
this._icon = Icon;
this._minRank = MinRank;
this._minVIP = MinVIP;
this._visible = Visible.ToLower() == "1" ? true : false;
this._template = Template;
foreach (string Str in PageStrings1.Split('|'))
{
if (this._pageStrings1 == null) { this._pageStrings1 = new List<string>(); }
this._pageStrings1.Add(Str);
}
foreach (string Str in PageStrings2.Split('|'))
{
if (this._pageStrings2 == null) { this._pageStrings2 = new List<string>(); }
this._pageStrings2.Add(Str);
}
this._items = Items;
this._itemOffers = new Dictionary<int, CatalogItem>();
foreach (int i in flatOffers.Keys)
{
if (flatOffers[i] == Id)
{
foreach (CatalogItem item in _items.Values)
{
if (item.offerID == i)
{
if (!_itemOffers.ContainsKey(i))
_itemOffers.Add(i, item);
}
}
}
}
}
public int Id
{
get { return this._id; }
set { this._id = value; }
}
public int ParentId
{
get { return this._parentId; }
set { this._parentId = value; }
}
public bool Enabled
{
get { return this._enabled; }
set { this._enabled = value; }
}
public string Caption
{
get { return this._caption; }
set { this._caption = value; }
}
public string PageLink
{
get { return this._pageLink; }
set { this._pageLink = value; }
}
public int Icon
{
get { return this._icon; }
set { this._icon = value; }
}
public int MinimumRank
{
get { return this._minRank; }
set { this._minRank = value; }
}
public int MinimumVIP
{
get { return this._minVIP;}
set { this._minVIP = value; }
}
public bool Visible
{
get { return this._visible; }
set { this._visible = value; }
}
public string Template
{
get { return this._template; }
set { this._template = value; }
}
public List<string> PageStrings1
{
get { return this._pageStrings1; }
private set { this._pageStrings1 = value; }
}
public List<string> PageStrings2
{
get { return this._pageStrings2; }
private set { this._pageStrings2 = value; }
}
public Dictionary<int, CatalogItem> Items
{
get { return this._items; }
private set { this._items = value; }
}
public Dictionary<int, CatalogItem> ItemOffers
{
get { return this._itemOffers; }
private set { this._itemOffers = value; }
}
public CatalogItem GetItem(int pId)
{
if (this._items.ContainsKey(pId))
return (CatalogItem)this._items[pId];
return null;
}
}
} | agpl-3.0 |
precog/labcoat-legacy | js/ace/mode/css_worker.js | 4644 | /*
* _ _ _
* | | | | | |
* | | __ _| |__ ___ ___ __ _| |_ Labcoat (R)
* | |/ _` | '_ \ / __/ _ \ / _` | __| Powerful development environment for Quirrel.
* | | (_| | |_) | (_| (_) | (_| | |_ Copyright (C) 2010 - 2013 SlamData, Inc.
* |_|\__,_|_.__/ \___\___/ \__,_|\__| All Rights Reserved.
*
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version
* 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. 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 AJAX.ORG B.V. 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.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var Mirror = require("../worker/mirror").Mirror;
var CSSLint = require("./css/csslint").CSSLint;
var Worker = exports.Worker = function(sender) {
Mirror.call(this, sender);
this.setTimeout(400);
this.ruleset = null;
this.setDisabledRules("ids");
this.setInfoRules("adjoining-classes|qualified-headings|zero-units|gradients|import|outline-none");
};
oop.inherits(Worker, Mirror);
(function() {
this.setInfoRules = function(ruleNames) {
if (typeof ruleNames == "string")
ruleNames = ruleNames.split("|");
this.infoRules = lang.arrayToMap(ruleNames);
this.doc.getValue() && this.deferredUpdate.schedule(100);
};
this.setDisabledRules = function(ruleNames) {
if (!ruleNames) {
this.ruleset = null;
} else {
if (typeof ruleNames == "string")
ruleNames = ruleNames.split("|");
var all = {};
CSSLint.getRules().forEach(function(x){
all[x.id] = true;
});
ruleNames.forEach(function(x) {
delete all[x];
});
this.ruleset = all;
}
this.doc.getValue() && this.deferredUpdate.schedule(100);
};
this.onUpdate = function() {
var value = this.doc.getValue();
var infoRules = this.infoRules;
var result = CSSLint.verify(value, this.ruleset);
this.sender.emit("csslint", result.messages.map(function(msg) {
return {
row: msg.line - 1,
column: msg.col - 1,
text: msg.message,
type: infoRules[msg.rule.id] ? "info" : msg.type
}
}));
};
}).call(Worker.prototype);
});
| agpl-3.0 |
Netsend/mastersync | lib/versioned_system.js | 34264 | /**
* Copyright 2014 Netsend.
*
* This file is part of Mastersync.
*
* Mastersync 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.
*
* Mastersync 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 Mastersync. If not, see <https://www.gnu.org/licenses/>.
*/
'use strict';
// sys
var util = require('util');
var EE = require('events').EventEmitter;
var spawn = require('child_process').spawn;
// npm
var async = require('async');
var mongodb = require('mongodb');
var BSON = mongodb.BSON;
var chroot = require('chroot');
var User = require('mongo-bcrypt-user');
var keyFilter = require('object-key-filter');
// lib
var VersionedCollection = require('./versioned_collection');
var Replicator = require('./replicator');
var OplogReader = require('./oplog_reader');
var authRequest = require('./auth_request');
var pushRequest = require('./push_request');
var pullRequest = require('./pull_request');
var noop = function() {};
/**
* VersionedSystem
*
* Track configured versioned collections. Monitor local changes via the
* oplog and fetch and merge new items from configured remotes.
*
* @param {mongodb.Collection} oplogColl oplog collection (capped collection)
* @param {Object} [opts] additional options
*
* Options
* usersDb {String} in which database user accounts are stored. By default, the
* database in the auth request is used.
* usersCollName {String, default users} collection that contains all user
* accounts
* usersColl {Object} collection that contains all user accounts, implements
* find etc.
* replicationDb {String} in which database replication configs are stored. By
* default, the database in the auth request is used.
* replicationCollName {String, default replication} collection that contains
* all replication configs
* replicationColl {Object} collection that contains all replication configs,
* implements find etc.
* log {Object, default console} log object that contains debug2, debug, info,
* notice, warning, err, crit and emerg functions. Uses console.log and
* console.error by default.
*/
function VersionedSystem(oplogColl, opts) {
if (!(oplogColl instanceof mongodb.Collection)) { throw new TypeError('oplogColl must be a mongdb.Collection'); }
if (typeof opts !== 'undefined') {
if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
if (typeof opts.usersDb !== 'undefined' && typeof opts.usersDb !== 'string') { throw new TypeError('opts.usersDb must be a string'); }
if (typeof opts.usersCollName !== 'undefined' && typeof opts.usersCollName !== 'string') { throw new TypeError('opts.usersCollName must be a string'); }
if (typeof opts.usersColl !== 'undefined' && typeof opts.usersColl !== 'object') { throw new TypeError('opts.usersColl must be an object'); }
if (typeof opts.usersColl !== 'undefined' && typeof opts.usersCollName !== 'undefined') {
throw new TypeError('opts.usersColl and opts.usersCollName are mutually exclusive');
}
if (typeof opts.usersColl !== 'undefined' && typeof opts.usersDb !== 'undefined') {
throw new TypeError('opts.usersColl and opts.usersDb are mutually exclusive');
}
if (typeof opts.replicationDb !== 'undefined' && typeof opts.replicationDb !== 'string') { throw new TypeError('opts.replicationDb must be a string'); }
if (typeof opts.replicationCollName !== 'undefined' && typeof opts.replicationCollName !== 'string') { throw new TypeError('opts.replicationCollName must be a string'); }
if (typeof opts.replicationColl !== 'undefined' && typeof opts.replicationColl !== 'object') { throw new TypeError('opts.replicationColl must be an object'); }
if (typeof opts.replicationColl !== 'undefined' && typeof opts.replicationCollName !== 'undefined') {
throw new TypeError('opts.replicationColl and opts.replicationCollName are mutually exclusive');
}
if (typeof opts.replicationColl !== 'undefined' && typeof opts.replicationDb !== 'undefined') {
throw new TypeError('opts.replicationColl and opts.replicationDb are mutually exclusive');
}
if (typeof opts.log !== 'undefined' && typeof opts.log !== 'object') { throw new TypeError('opts.log must be an object'); }
}
EE.call(this);
this._oplogColl = oplogColl;
this._oplogDb = this._oplogColl.db;
this._options = opts || {};
this._usersDb = this._options.usersDb;
if (this._options.usersColl) {
this._usersColl = this._options.usersColl;
} else {
this._usersCollName = this._options.usersCollName || 'users';
}
this._replicationDb = this._options.replicationDb;
if (this._options.replicationColl) {
this._replicationColl = this._options.replicationColl;
} else {
this._replicationCollName = this._options.replicationCollName || 'replication';
}
this._log = this._options.log || {
emerg: console.error,
alert: console.error,
crit: console.error,
err: console.error,
warning: console.log,
notice: console.log,
info: console.log,
debug: console.log,
debug2: console.log,
getFileStream: noop,
getErrorStream: noop,
close: noop
};
this._vces = {};
this._oplogReaders = {};
}
util.inherits(VersionedSystem, EE);
module.exports = VersionedSystem;
/**
* Fork each VC and send initial request containing database parameters, VC config
* and an optional chroot config. Then connect an oplog reader to each vce.
*
* @param {Object} vces object containing vcexec configs
* @param {Boolean, default true} follow object containing vcexec configs
* @param {Function} cb This will be called as soon as all VCs are initialized.
* First parameter will be an error object or null. Second
* parameter will be an object with oplog readers for each
* vce.
*/
VersionedSystem.prototype.initVCs = function initVCs(vces, follow, cb) {
if (typeof vces !== 'object') { throw new TypeError('vces must be an object'); }
if (typeof follow === 'function') {
cb = follow;
follow = true;
}
if (typeof follow === 'undefined' || follow === null) {
follow = true;
}
if (typeof follow !== 'boolean') { throw new TypeError('follow must be a boolean'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var that = this;
var error;
async.eachSeries(Object.keys(vces), function(dbName, cb2) {
async.eachSeries(Object.keys(vces[dbName]), function(collectionName, cb3) {
var ns = dbName + '.' + collectionName;
if (that._vces[ns]) {
error = new Error('vce already initialized');
that._log.err('vs vce error', ns, error);
cb3(error);
return;
}
if (that._oplogReaders[ns]) {
error = new Error('vce already has an oplog reader associated');
that._log.err('vs vce error', ns, error);
cb3(error);
return;
}
// load versioned collection exec config
var vceCfg = vces[dbName][collectionName];
// ensure database and collection name
vceCfg.dbName = vceCfg.dbName || dbName;
vceCfg.collectionName = vceCfg.collectionName || collectionName;
vceCfg.tailable = follow;
that._startVC(vceCfg, function(err, vce, or) {
if (err) { cb3(err); return; }
// register vc and or
that._vces[ns] = vce;
that._oplogReaders[ns] = or;
//vc.fixConsistency(vceCfg.dbName, cb3);
cb3();
});
}, cb2);
}, function(err) {
if (err) { cb(err); return; }
cb(null, that._oplogReaders);
});
};
/**
* Return stats of all collections.
*
* @param {Boolean} [extended, default false] whether to add _m3._ack counts
* @param {Array} [nsList, default this._vces] list of namespaces
* @param {Function} cb The first parameter will contain either an Error object or
* null. The second parameter is an object with collection
* info.
*
* extended object:
* ack {Number} the number of documents where _m3._ack = true
*/
VersionedSystem.prototype.info = function info(opts, cb) {
if (typeof opts === 'function') {
cb = opts;
opts = undefined;
}
if (typeof opts !== 'undefined') {
if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
if (typeof opts.extended !== 'undefined' && typeof opts.extended !== 'boolean') { throw new TypeError('extended must be a boolean'); }
if (typeof opts.nsList !== 'undefined' && !Array.isArray(opts.nsList)) { throw new TypeError('nsList must be an array'); }
}
opts = opts || {};
// default values
if (typeof opts.extended === 'undefined') { opts.extended = false; }
if (typeof opts.nsList === 'undefined') { opts.nsList = Object.keys(this._vces); }
var extended = opts.extended;
var nsList = opts.nsList;
var that = this;
var result = {};
async.each(nsList, function(key, cb2) {
var dbName = key.split('.')[0];
var collectionName = key.split('.').slice(1).join();
var collection = that._oplogDb.db(dbName).collection(collectionName);
var snapshotCollection = that._oplogDb.db(dbName).collection('m3.' + collectionName);
collection.stats(function(err, resultCollection) {
if (err) {
if (err.message !== 'ns not found' && !/^Collection .* not found/.test(err.message)) {
cb2(err);
return;
}
resultCollection = {};
}
result[key] = { collection: resultCollection };
snapshotCollection.stats(function(err, resultSnapshotCollection) {
if (err) {
if (err.message !== 'ns not found' && !/^Collection .* not found/.test(err.message)) {
cb2(err);
return;
}
resultSnapshotCollection = {};
}
result[key].snapshotCollection = resultSnapshotCollection;
if (extended) {
snapshotCollection.count({ '_m3._ack': true }, function(err, count) {
if (err) { cb2(err); return; }
result[key].extended = { ack: count };
cb2();
});
} else {
cb2();
}
});
});
}, function(err) {
cb(err, result);
});
};
/**
* Send a pull request to a versioned collection.
*
* Adds the following options to the PR based on a replication config:
* [filter]: {Object}
* [hooks]: {Array}
* [hooksOpts]: {Object}
* [offset]: {String}
*
* @param {String} ns namespace of the versioned collection
* @param {Object} pullRequest pull request to send
* @param {Function} cb callback is called once the PR is sent
*
* A pull request should have the following structure:
* {
* username: {String}
* password: {String}
* database: {String}
* collection: {String}
* [path]: {String}
* [host]: {String} // defaults to 127.0.0.1
* [port]: {Number} // defaults to 2344
* }
*/
VersionedSystem.prototype.sendPR = function sendPR(ns, pullReq, cb) {
if (typeof ns !== 'string') { throw new TypeError('ns must be a string'); }
if (typeof pullReq !== 'object') { throw new TypeError('pullReq must be an object'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
if (typeof pullReq.username !== 'string') { throw new TypeError('pullReq.username must be a string'); }
if (typeof pullReq.password !== 'string') { throw new TypeError('pullReq.password must be a string'); }
if (typeof pullReq.database !== 'string') { throw new TypeError('pullReq.database must be a string'); }
if (typeof pullReq.collection !== 'string') { throw new TypeError('pullReq.collection must be a string'); }
var localDb, localColl;
var parts = ns.split('.');
if (parts.length <= 1) { throw new Error('ns must contain at least a database name and a collection name separated by a dot'); }
localDb = parts[0];
localColl = parts.slice(1).join('.');
var that = this;
var error;
if (typeof this._vces[ns] !== 'object') {
error = 'no versioned collection found for this combination of database and collection';
that._log.err('vs sendPR', ns, error);
throw new Error(error);
}
if (!pullRequest.valid(pullReq)) { throw new Error('invalid pull request'); }
// filter password out request
function debugReq(req) {
return keyFilter(req, ['password']);
}
// set replication config collection
var replicationDb;
var replicationColl;
if (this._replicationColl) {
replicationColl = this._replicationColl;
} else {
if (this._replicationDb) {
replicationDb = this._oplogDb.db(this._replicationDb);
} else {
replicationDb = this._oplogDb.db(localDb);
}
replicationColl = replicationDb.collection(this._replicationCollName);
}
// search for import replication config for the remote using the remote name
Replicator.fetchFromDb(replicationColl, 'import', pullReq.database, function(err, replCfg) {
if (err) { cb(err); return; }
// check if requested collection is imported
if (!replCfg.collections[localColl]) {
error = 'requested collection has no import replication config';
that._log.err('vs sendPR', ns, error);
cb(new Error(error));
return;
}
replCfg = replCfg.collections[localColl];
// set extra hook and other options on pull request
pullReq.hooksOpts = pullReq.hooksOpts || {};
if (replCfg.filter) { pullReq.filter = replCfg.filter; }
if (replCfg.hooks) { pullReq.hooks = replCfg.hooks; }
if (pullReq.offset) { pullReq.offset = pullReq.offset; }
// set hooksOpts with all keys but the pre-configured ones
Object.keys(replCfg).forEach(function(key) {
if (!~['filter', 'hooks', 'hooksOpts', 'offset'].indexOf(key)) {
pullReq.hooksOpts[key] = replCfg[key];
}
});
if (!pullRequest.valid(pullReq)) {
that._log.err('vs sendPR unable to construct a valid pull request %j', debugReq(pullReq));
cb(new Error('unable to construct a valid pull request'));
return;
}
that._log.info('vs sendPR pull request forwarded %j', debugReq(pullReq));
// now send this pull request to the appropriate versioned collection
that._vces[ns].send(pullReq);
});
};
/**
* Chroot this process.
*
* @param {String} user user to drop privileges to
* @param {Object} [opts] options
*
* Options
* path {String, default "/var/empty"} new root
*/
VersionedSystem.prototype.chroot = function (user, opts) {
if (typeof user !== 'string') { throw new TypeError('user must be a string'); }
opts = opts || {};
if (typeof opts !== 'object') { throw new TypeError('opts must be an object'); }
var newPath = opts.path || '/var/empty';
chroot(newPath, user);
this._log.info('vs: changed root and user to', newPath, user);
};
/**
* Fork a pre-auth server that handles incoming push requests. Verify password,
* find replication config and pass a push request to the appropriate versioned
* collection.
*
* Note: chroots right after pre-auth server is started
*
* @param {String} user username to drop privileges to
* @param {String} newRoot new root path
* @param {Object} preauthCfg configuration object send to preauth process
* @param {Function} cb First parameter will be an Error object or null.
*
* preauthCfg:
* {
* logCfg: {Object} // log configuration object, child.stdout
* { // will be mapped to file and child.stderr
* // wil be mapped to error or file
* [console] {Boolean, default: false} whether to log to the console
* [file] {String|Number|Object} log all messages to this file,
* // either a filename, file descriptor or
* // writable stream.
* [error] {String|Number|Object} extra file to log errors only, either a
* // filename, file descriptor or writable stream.
* [mask] {Number, default NOTICE} set a minimum priority for "file"
* [silence] {Boolean, default false} whether to suppress logging or not
* }
*
* [serverConfig]:
* {
* [host]: {String} // defaults to 127.0.0.1
* [port]: {Number} // defaults to 2344
* [path]: {String} // defaults to /tmp/ms-2344.sock
*
* [chrootConfig]:
* {
* [user]: {String} // defaults to "nobody"
* [newRoot]: {String} // defaults to /var/empty
* }
* }
*
* @void
*/
VersionedSystem.prototype.listen = function listen(user, newRoot, preauthCfg, cb) {
if (typeof user !== 'string') { throw new TypeError('user must be a string'); }
if (typeof newRoot !== 'string') { throw new TypeError('newRoot must be a string'); }
if (typeof preauthCfg !== 'object') { throw new TypeError('preauthCfg must be an object'); }
if (typeof preauthCfg.logCfg !== 'object') { throw new TypeError('preauthCfg.logCfg must be an object'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var that = this;
if (!Object.keys(this._vces).length) { throw new TypeError('run initVCs first'); }
// filter password out request
function debugReq(req) {
return keyFilter(req, ['password']);
}
function connErrorHandler(conn, e) {
try {
var error = { error: 'invalid auth request' };
that._log.err('vs listen %j', conn.address(), error, e);
conn.write(BSON.serialize(error));
conn.destroy();
} catch(err) {
that._log.err('vs listen connection write or disconnect error', err);
}
}
// handle incoming authentication requests
function handleMessage(req, conn) {
that._log.info('vs listen %d %d %j', conn.bytesRead, conn.bytesWritten, conn.address());
if (!authRequest.valid(req)) {
that._log.err('vs listen invalid auth request %j', debugReq(req));
connErrorHandler(conn, new Error('invalid auth request'));
return;
}
// verify credentials and lookup replication config
that._verifyAuthRequest(req, function(err, replCfg) {
if (err) {
that._log.err('vs listen auth request %j, err %j', debugReq(req), err);
connErrorHandler(conn, err);
return;
}
// create a push request from the auth request and replication config
var pushReq = {
hooksOpts: {}
};
if (replCfg.filter) { pushReq.filter = replCfg.filter; }
if (replCfg.hooks) { pushReq.hooks = replCfg.hooks; }
if (req.offset) { pushReq.offset = req.offset; }
// set hooksOpts with all keys but the pre-configured ones
Object.keys(replCfg).forEach(function(key) {
if (!~['filter', 'hooks', 'hooksOpts', 'offset'].indexOf(key)) {
pushReq.hooksOpts[key] = replCfg[key];
}
});
// some export hooks need the name of the destination
pushReq.hooksOpts.to = { databaseName: req.username };
if (!pushRequest.valid(pushReq)) {
that._log.err('vs listen unable to construct a valid push request %j, req: %j', pushReq, debugReq(req));
connErrorHandler(conn, new Error('unable to construct a valid push request'));
return;
}
var ns = req.database + '.' + req.collection;
that._log.info('vs listen push request forwarded %j', debugReq(pushReq));
// now send this push request and connection to the appropriate versioned collection
that._vces[ns].send(pushReq, conn);
});
}
that._log.info('vs listen preauthCfg %j', preauthCfg);
that._log.info('vs listen forking preauth');
var stdio = ['pipe', 'pipe', 'pipe', 'ipc'];
// use fd 4 if a file stream is opened
if (preauthCfg.logCfg.file) {
stdio[4] = preauthCfg.logCfg.file.fd;
preauthCfg.logCfg.file = 4;
}
// use fd 5 if an error stream is opened
if (preauthCfg.logCfg.error) {
stdio[5] = preauthCfg.logCfg.error.fd;
preauthCfg.logCfg.error = 5;
}
// open preauth server
var preauth = spawn(process.execPath, [__dirname + '/preauth_exec'], {
cwd: '/',
env: {},
stdio: stdio
});
preauth.stdout.pipe(process.stdout);
preauth.stderr.pipe(process.stderr);
this.chroot(user, { path: newRoot });
// send initial config after preauth is ready to receive messages
preauth.once('message', function(msg) {
if (msg !== 'init') {
that._log.err('vs listen expected message "init"', msg);
cb(new Error('expected first message to be "init"'));
return;
}
that._log.info('vs listen "init" received');
preauth.send(preauthCfg);
preauth.once('message', function(msg) {
if (msg !== 'listen') {
that._log.err('vs listen expected message "listen"', msg);
cb(new Error('expected second message to be "listen"'));
return;
}
that._log.info('vs listen "listen" received');
preauth.on('message', handleMessage);
cb();
});
});
this._preauth = preauth;
};
/**
* Stop oplog reader and close db.
*
* @param {Function} cb First parameter will be an Error object or null.
*/
VersionedSystem.prototype.stop = function stop(cb) {
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var that = this;
var tasks = [];
var ors = Object.keys(this._oplogReaders);
ors.forEach(function(key) {
var or = that._oplogReaders[key];
tasks.push(function(cb2) {
that._log.notice('closing oplog reader', key);
or.on('end', cb2);
or.close();
});
});
async.series(tasks, cb);
};
/**
* Stop pre-auth server, vc exec instances (not catching SIGTERM).
*
* @param {Function} cb First parameter will be an Error object or null.
*/
VersionedSystem.prototype.stopTerm = function stopTerm(cb) {
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var that = this;
var tasks = [];
var vces = Object.keys(this._vces);
this._log.notice('vs stopTerm vces', vces);
vces.forEach(function(key) {
var vce = that._vces[key];
tasks.push(function(cb2) {
that._log.notice('closing vce', key);
vce.on('close', function() {
that._log.notice('vs stopTerm closed vce', key);
cb2();
});
vce.kill();
});
});
if (this._preauth) {
tasks.push(function(cb2) {
that._preauth.on('close', function(err) {
if (err) { cb2(err); return; }
that._log.notice('preauth closed');
cb2();
});
that._preauth.kill();
});
}
async.series(tasks, function(err) {
if (err) { cb(err); return; }
that.stop(cb);
});
};
/////////////////////
//// PRIVATE API ////
/////////////////////
/**
* Start and initialize a versioned collection. Return the forked child when it's
* ready to accept pull and push requests.
*
* @param {Object} config versioned collection exec config
* @param {Function} cb First parameter will be an error object or null, second
* parameter will be the forked child on success.
*
* vc exec config:
* {
* dbName: {String}
* collectionName: {String}
* size: {Number} // size of the snapshot in MB which will be
* // converted to B
* logCfg: {Object} // log configuration object, child.stdout
* // will be mapped to file and child.stderr
* // wil be mapped to error or file
* [hookPaths]: {Array, default [hooks, local/hooks]} // list of paths to
* // load hooks from
* [dbPort]: {Number} // defaults to 27017
* [dbUser]: {String}
* [dbPass]: {String}
* [adminDb]: {String}
* [any VersionedCollection options]
* [chrootUser]: {String} // defaults to "nobody"
* [chrootNewRoot]: {String} // defaults to /var/empty
* [tailable]: {Boolean}
* }
*/
VersionedSystem.prototype._startVC = function _startVC(config, cb) {
if (typeof config !== 'object' || config === null) { throw new TypeError('config must be an object'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
if (typeof config.dbName !== 'string') { throw new TypeError('config.dbName must be a string'); }
if (typeof config.collectionName !== 'string') { throw new TypeError('config.collectionName must be a string'); }
if (typeof config.size !== 'number') { throw new TypeError('config.size must be a number'); }
if (typeof config.logCfg !== 'object') { throw new TypeError('config.logCfg must be an object'); }
if (config.size <= 0) { throw new Error('config.size must be larger than 0'); }
// convert the config size from MB to B
config.size = config.size * 1024 * 1024;
config.hookPaths = config.hookPaths || ['hooks', 'local/hooks'];
var ns = config.dbName + '.' + config.collectionName;
var that = this;
that._log.info('vs _startVC forking:', ns);
var stdio = ['pipe', 'pipe', 'pipe', 'ipc'];
// use fd 4 if a file stream is opened
if (config.logCfg.file) {
stdio[4] = config.logCfg.file.fd;
config.logCfg.file = 4;
}
// use fd 5 if an error stream is opened
if (config.logCfg.error) {
stdio[5] = config.logCfg.error.fd;
config.logCfg.error = 5;
}
var vce = spawn(process.execPath, [__dirname + '/versioned_collection_exec'], {
cwd: '/',
env: {},
stdio: stdio
});
vce.stdout.pipe(process.stdout);
vce.stderr.pipe(process.stderr);
var phase = null;
vce.on('error', function(err) {
that._log.err('vs _startVC error', ns, err);
// callback if not in listen mode yet
if (phase !== 'listen') {
cb(err);
}
});
vce.once('close', function(code, sig) {
that._log.notice('vs _startVC close', ns, code, sig);
// callback if not in listen mode yet
if (phase !== 'listen') {
cb(new Error('abnormal termination'));
}
});
vce.once('exit', function(code, sig) {
that._log.notice('vs _startVC exit', ns, code, sig);
// callback if not in listen mode yet
if (phase !== 'listen') {
cb(new Error('abnormal termination'));
}
});
// send db, vc and log config after vce is ready to receive messages
vce.once('message', function(msg) {
if (msg !== 'init') {
that._log.err('vs _startVC expected message "init"', ns, msg);
cb(new Error('expected first message to be "init"'));
return;
}
phase = 'init';
that._log.info('vs _startVC "init" received', ns);
vce.send(config);
// wait for the child to send the "listen" message, and start sending oplog items
vce.once('message', function(msg) {
if (msg !== 'listen') {
that._log.err('vs _startVC expected message "listen"', ns, msg);
cb(new Error('expected second message to be "listen"'));
return;
}
that._log.info('vs _startVC "listen" received', ns);
phase = 'listen';
// setup oplog connection to this vce
that._ensureSnapshotAndOplogOffset(config, function(err, offset) {
if (err) { cb(err); return; }
var opts = {
tailable: config.tailable,
offset: offset,
log: that._log
};
var or = new OplogReader(that._oplogColl, ns, opts);
or.pipe(vce.stdin);
// cb with vce and or
cb(null, vce, or);
});
});
});
};
/**
* If the snapshot is empty, get the latest oplog item as offset, otherwise use
* maxOplogPointer or Timestamp(0, 0);
*
* @param {Object} cfg versioned collection configuration object
* @param {Function} cb Called when oplog is connected to the vce. First parameter
* will be an error object or null.
*
* A versioned collection configuration object should have the following structure:
* {
* dbName: {String}
* collectionName: {String}
* size: {Number}
* [any VersionedCollection options]
* }
*/
VersionedSystem.prototype._ensureSnapshotAndOplogOffset = function _ensureSnapshotAndOplogOffset(cfg, cb) {
if (typeof cfg !== 'object') { throw new TypeError('cfg must be an object'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
if (typeof cfg.dbName !== 'string') { throw new TypeError('cfg.dbName must be a string'); }
if (typeof cfg.collectionName !== 'string') { throw new TypeError('cfg.collectionName must be a string'); }
if (typeof cfg.size !== 'number') { throw new TypeError('cfg.size must be a number'); }
var opts = {
log: this._log,
localPerspective: cfg.localPerspective,
versionKey: cfg.versionKey,
remotes: cfg.remotes
};
var vc = new VersionedCollection(this._oplogDb.db(cfg.dbName), cfg.collectionName, opts);
var that = this;
var error;
var oplogOffset;
// get oldest item from oplog
this._oplogColl.findOne({}, { sort: { $natural: 1 } }, function(err, oldestOplogItem) {
if (err) { cb(err); return; }
if (!oldestOplogItem) {
error = new Error('no oplog item found');
that._log.err(vc.ns, error);
cb(error);
return;
}
// get newest item from oplog
that._oplogColl.findOne({}, { sort: { $natural: -1 } }, function(err, newestOplogItem) {
if (err) { cb(err); return; }
that._log.info('vs _ensureSnapshotAndOplogOffset oplog span', oldestOplogItem.ts, newestOplogItem.ts);
vc._snapshotCollection.count(function(err, items) {
if (err) { return cb(err); }
// get max oplog pointer from snapshot
vc.maxOplogPointer(function(err, snapshotOffset) {
if (err) { cb(err); return; }
if (!snapshotOffset && items) {
error = new Error('vc contains snapshots but no oplog pointer');
that._log.err(vc.ns, error);
cb(error);
return;
}
// if found, use it, but warn if it's outside the current range of the oplog
if (snapshotOffset) {
if (snapshotOffset.lessThan(oldestOplogItem.ts) || snapshotOffset.greaterThan(newestOplogItem.ts)) {
that._log.warning('oplog pointer outside current oplog range', snapshotOffset, oldestOplogItem.ts, newestOplogItem.ts);
}
oplogOffset = snapshotOffset;
} else if (!items) {
// if snapshot is empty, use newest oplog item
oplogOffset = newestOplogItem.ts;
}
vc.ensureSnapshotCollection(cfg.size, function(err) {
if (err) { cb(err); return; }
cb(null, oplogOffset);
});
});
});
});
});
};
/**
* Verify an auth request, and if valid, pass back the replication config.
*
* @param {Object} req auth request
* @param {Function} cb First parameter will be an error object or null. Second
* parameter will be a replication config if valid.
*/
VersionedSystem.prototype._verifyAuthRequest = function _verifyAuthRequest(req, cb) {
if (typeof req !== 'object') { throw new TypeError('req must be an object'); }
if (typeof cb !== 'function') { throw new TypeError('cb must be a function'); }
var that = this;
var error;
var ns = req.database + '.' + req.collection;
if (!this._vces[ns]) {
error = 'invalid credentials';
that._log.err('vs _verifyAuthRequest not a versioned collection:', ns, error);
process.nextTick(function() {
cb(new Error(error));
});
return;
}
// set user account collection
var usersDb;
var usersColl;
if (this._usersColl) {
usersColl = this._usersColl;
} else {
if (this._usersDb) {
usersDb = this._oplogDb.db(this._usersDb);
} else {
usersDb = this._oplogDb.db(req.database);
}
usersColl = usersDb.collection(this._usersCollName);
}
// set replication config collection
var replicationDb;
var replicationColl;
if (this._replicationColl) {
replicationColl = this._replicationColl;
} else {
if (this._replicationDb) {
replicationDb = this._oplogDb.db(this._replicationDb);
} else {
replicationDb = this._oplogDb.db(req.database);
}
replicationColl = replicationDb.collection(this._replicationCollName);
}
// do a lookup in the database
User.find(usersColl, req.username, req.database, function(err, user) {
if (err) { cb(err); return; }
if (!user) {
error = 'invalid credentials';
that._log.err('vs _verifyAuthRequest user not found', ns, error);
cb(new Error(error));
return;
}
that._log.info('vs _verifyAuthRequest %s user found %j', ns, user);
user.verifyPassword(req.password, function(err, valid) {
if (err) { cb(err); return; }
if (!valid) {
error = 'invalid credentials';
that._log.err('vs _verifyAuthRequest', ns, error);
cb(new Error(error));
return;
}
that._log.info('vs successfully authenticated', req.username);
// search for export replication config for the remote using the username
Replicator.fetchFromDb(replicationColl, 'export', req.username, function(err, replCfg) {
if (err) { cb(err); return; }
// check if requested collection is exported
if (!replCfg.collections[req.collection]) {
error = 'requested collection not exported';
that._log.err('vs createDataRequest', ns, error);
cb(error);
return;
}
cb(null, replCfg.collections[req.collection]);
});
});
});
};
| agpl-3.0 |
fronteerio/grasshopper | node_modules/gh-core/lib/api.js | 8346 | /**
* Copyright (c) 2015 "Fronteer LTD"
* Grasshopper Event Engine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var AdminsDAO = require('gh-admins/lib/internal/dao');
var AuthAPI = require('gh-auth');
var ConfigAPI = require('gh-config');
var DocsAPI = require('gh-docs');
var StatsdAPI = require('gh-statsd');
var UsersAPI = require('gh-users');
var DB = require('./db');
var Logger = require('./logger');
var Modules = require('./modules');
var Server = require('./server');
var Signature = require('./signature');
var log = Logger.logger('gh-core/api');
// The Express server for the global admin server
var globalAdminServer = module.exports.globalAdminServer = null;
// The Express server for apps
var appServer = module.exports.appServer = null;
/**
* Initialize the application
*
* @param {Object} config The application configuration
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error object, if any
*/
var init = module.exports.init = function(config, callback) {
// Apply global utilities
require('./globals');
// Initialize the logger
Logger.refreshLogConfiguration(config.log);
// Set up application-level error handler
process.on('uncaughtException', function(err) {
log().error({
'err': err
}, 'An uncaught exception was raised to the application.');
});
// Initialize the signature logic
Signature.init(config.signing);
// Initialize the statsd API
StatsdAPI.init(config.statsd);
// Connect to the database
DB.init(config, function(err) {
if (err) {
return callback(err);
}
// Ensure the default global administrator exists
_ensureDefaultGlobalAdministrator(function(err) {
if (err) {
return callback(err);
}
// Initialise the modules lister. It will cache a list of
// all the Grasshopper modules in the application container
Modules.init(function(err) {
if (err) {
return callback(err);
}
// Initialise the config api
ConfigAPI.init(function(err) {
if (err) {
return callback(err);
}
// Initialise the users api
UsersAPI.init(function(err) {
if (err) {
return callback(err);
}
// Initialise the Pattern listener
require('gh-series/lib/internal/listener');
// Intitialise the Express servers
return _initialiseExpressServers(config, callback);
});
});
});
});
});
};
/**
* Ensure that the default global administrator account exists. If no such
* account exists, one will be created
*
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error object, if any
* @api private
*/
var _ensureDefaultGlobalAdministrator = function(callback) {
// Ensure that the default global administrator exists
var defaultGlobalAdmin = {
'username': 'administrator',
'password': 'administrator',
'displayName': 'Global Admin'
};
AdminsDAO.getGlobalAdminByUsername(defaultGlobalAdmin.username, function(err, globalAdmin) {
if (err && err.code !== 404) {
return callback(err);
}
// Create the default global administrator if they don't exist yet
var needsGlobalAdmin = (err && err.code === 404);
_.ghIf(needsGlobalAdmin, AdminsDAO.createGlobalAdmin, defaultGlobalAdmin.username, defaultGlobalAdmin.password, defaultGlobalAdmin.displayName, function(err, globalAdmin) {
if (err) {
log().error({'err': err}, 'Failed to create the default global administrator');
return callback(err);
}
return callback();
});
});
};
/**
* Initialise the global admin and app Express servers, initialise the REST API endpoint
* and cache the REST API documentation
*
* @param {Object} config The application configuration
* @param {Function} callback Standard callback function
* @param {Object} callback.err An error object, if any
* @api private
*/
var _initialiseExpressServers = function(config, callback) {
// Initialise the Express servers
module.exports.globalAdminServer = Server.setUpServer(config.servers.adminPort, config);
module.exports.appServer = Server.setUpServer(config.servers.appsPort, config);
// Initialise the REST router wrapper
module.exports.globalAdminRouter = Server.setupRouter(module.exports.globalAdminServer);
module.exports.appRouter = Server.setupRouter(module.exports.appServer);
var ghModules = Modules.getAvailableModules();
// Check if a `rest.js` file exists in the `lib` folder in each
// module. If such a file exists, we require it. This allows other
// modules to add in their own set of REST apis
_.each(ghModules, function(module) {
var restFile = path.join(__dirname, '../..', module, '/lib/rest.js');
if (fs.existsSync(restFile)) {
log().debug({'module': module}, 'Trying to register REST apis');
require(module + '/lib/rest');
}
});
log().info('All REST APIs have been initialized');
// Initialize the Passport authentication strategies
AuthAPI.init(config);
/*!
* Add middleware that will check if the user has accepted the Terms and Conditions, if enabled.
* If the user hasn't accepted the Terms and Conditions, all POST requests (excluding whitelisted post requests) will be prevented.
*/
module.exports.appServer.use(function(req, res, next) {
// The Terms and Conditions middleware is only applicable on logged in users who
// try to interact with the system excluding a set of whitelisted endpoints
if (!_.contains(['GET', 'HEAD'], req.method) && UsersAPI.needsToAcceptTermsAndConditions(req.ctx) && _requiresTermsAndConditions(req.path)) {
return res.status(419).send('You need to accept the Terms and Conditions before you can interact with this application');
}
return next();
});
Server.postInitialize(module.exports.globalAdminServer, module.exports.globalAdminRouter);
Server.postInitialize(module.exports.appServer, module.exports.appRouter);
/*!
* Called when all the modules have been documented
*/
var moduleDocumented = _.after(ghModules.length, function() {
// Add the models to all the api resources
DocsAPI.addModelsToResources();
log().info('All REST APIs have been documented');
return callback();
});
// Document each module's REST APIs
_.each(ghModules, function(module) {
DocsAPI.documentModule(module, moduleDocumented);
});
};
/**
* Check if a URL requires the Terms and Conditions to be accepted
*
* @param {String} url The URL to check
* @return {Boolean} `true` if the user hasto accept the Terms and Conditions in order to POST to this url, `false` otherwise
* @api private
*/
var _requiresTermsAndConditions = function(url) {
return !(url.indexOf('/api/auth') === 0 || url.indexOf('/api/users') === 0);
};
| agpl-3.0 |
vivekdevrari/litecrm | cache-old/smarty/templates_c/%%E1^E11^E112718D%%en_us.DetailView.tpl.php | 5146 | <?php /* Smarty version 2.6.29, created on 2016-10-17 16:35:45
compiled from include/SugarFields/Fields/Address/en_us.DetailView.tpl */ ?>
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
smarty_core_load_plugins(array('plugins' => array(array('function', 'sugarvar_connector', 'include/SugarFields/Fields/Address/en_us.DetailView.tpl', 55, false),)), $this); ?>
{*
/*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
* SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
* Copyright (C) 2011 - 2014 Salesagility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
********************************************************************************/
*}
<table border='0' cellpadding='0' cellspacing='0' width='100%'>
<tr>
<td width='99%'>
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_street" value="{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_street.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}">
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_city" value="{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_city.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}">
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_state" value="{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_state.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}">
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_country" value="{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_country.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}">
<input type="hidden" class="sugar_field" id="<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_postalcode" value="{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_postalcode.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}">
{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_street.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}<br>
{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_city.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br} {$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_state.value|escape:'html_entity_decode'|strip_tags|url2html|nl2br} {$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_postalcode.value|escape:'html_entity_decode'|strip_tags|url2html|nl2br}<br>
{$fields.<?php echo $this->_tpl_vars['displayParams']['key']; ?>
_address_country.value|escape:'html_entity_decode'|escape:'html'|url2html|nl2br}
</td>
<?php if (! empty ( $this->_tpl_vars['displayParams']['enableConnectors'] )): ?>
<td class="dataField">
<?php echo smarty_function_sugarvar_connector(array('view' => 'DetailView'), $this);?>
</td>
<?php endif; ?>
<td class='dataField' width='1%'>
{$custom_code_<?php echo $this->_tpl_vars['displayParams']['key']; ?>
}
</td>
</tr>
</table> | agpl-3.0 |